body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p><strong>Overview</strong><br />
After playing a while with the ECS implementation of the Unity engine and liking it very much I decided to try recreate it as a challenge. As part of this challenge I need a way of storing the components grouped by entity; I solved this by creating a container called a <code>Chunk</code>.</p>
<p>Unity uses archetypes to group components together and stores these components in pre-allocated chunks of fixed size.</p>
<p>I made a simple design of my implementation as clarification:</p>
<p><a href="https://i.stack.imgur.com/cZW3F.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cZW3F.jpg" alt="implementation diagram" /></a></p>
<p>Here <code>Archetype</code> is a linked list of chunks; the chunks contain arrays of all the components that make the archetype - in this case Comp1, Comp2 and Comp3. Once a chunk is full a new chunk is allocated and can be filled up and so on.</p>
<p>The chunk itself is implemented like this:</p>
<p><a href="https://i.stack.imgur.com/8NIgG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8NIgG.jpg" alt="chunk diagram" /></a></p>
<p>With this solution I can store the components grouped by entity while making optimal use of storage and cache because the components are tightly packed in an array. Because of the indirection provided by the array of indices I am able to delete any component and move the rest of the components down to make sure there aren't any holes.</p>
<p><strong>Questions</strong><br />
I have some items I'd like feedback on in order to improve myself</p>
<ul>
<li>Is the code clear and concise?</li>
<li>Are there any obvious performance improvements?</li>
<li>Because this is my first somewhat deep-dive in templates, are there any STL solutions I could've used that I have missed?</li>
</ul>
<p><strong>Code</strong></p>
<ul>
<li>chunk.h<br />
Contains the container.</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "utils.h"
#include "entity.h"
#include <cstdint>
#include <tuple>
template<size_t Capacity, typename ...Components>
class chunk
{
public:
struct index
{
uint16_t id;
uint16_t index;
uint16_t next;
};
chunk()
:
m_enqueue(Capacity - 1),
m_dequeue(0),
m_object_count(0)
{
static_assert((Capacity & (Capacity - 1)) == 0, "number should be power of 2");
for (uint16_t i = 0; i < Capacity; i++)
{
m_indices[i].id = i;
m_indices[i].next = i + 1;
}
}
const uint16_t add()
{
index& index = m_indices[m_dequeue];
m_dequeue = index.next;
index.id += m_new_id;
index.index = m_object_count++;
return index.id;
}
void remove(uint16_t id)
{
index& index = m_indices[id & m_index_mask];
tuple_utils<Components...>::tuple_array<Capacity, Components...>::remove_item(index.index, m_object_count, m_items);
m_indices[id & m_index_mask].index = index.index;
index.index = USHRT_MAX;
m_indices[m_enqueue].next = id & m_index_mask;
m_enqueue = id & m_index_mask;
}
template<typename... ComponentParams>
constexpr void assign(uint16_t id, ComponentParams&... value)
{
static_assert(arg_types<Components...>::contain_args<ComponentParams...>::value, "Component type does not exist on entity");
index& index = m_indices[id & m_index_mask];
tuple_utils<Components...>::tuple_array<Capacity, ComponentParams...>::assign_item(index.index, m_object_count, m_items, value...);
}
template<typename T>
constexpr T& get_component_data(uint16_t id)
{
static_assert(arg_types<Components...>::contain_type<T>::value, "Component type does not exist on entity");
index& index = m_indices[id & m_index_mask];
return std::get<T[Capacity]>(m_items)[index.index];
}
inline const bool contains(uint16_t id) const
{
const index& index = m_indices[id & m_index_mask];
return index.id == id && index.index != USHRT_MAX;
}
inline const uint32_t get_count() const
{
return m_object_count;
}
static constexpr uint16_t get_capacity()
{
return Capacity;
}
private:
static constexpr uint16_t m_index_mask = Capacity - 1;
static constexpr uint16_t m_new_id = m_index_mask + 1;
uint16_t m_enqueue;
uint16_t m_dequeue;
uint16_t m_object_count;
index m_indices[Capacity] = {};
std::tuple<Components[Capacity]...> m_items;
};
</code></pre>
<ul>
<li>utils.h<br />
Contains utility functions for templates used by the chunk class.</li>
</ul>
<pre class="lang-cpp prettyprint-override"><code>// utils.h
#pragma once
#include <tuple>
#include <type_traits>
#include <algorithm>
// get total size of bytes from argumant pack
template<typename First, typename... Rest>
struct args_size
{
static constexpr size_t value = args_size<First>::value + args_size<Rest...>::value;
};
template <typename T>
struct args_size<T>
{
static constexpr size_t value = sizeof(T);
};
template<typename... Args>
struct arg_types
{
//check if variadic template contains types of Args
template<typename First, typename... Rest>
struct contain_args
{
static constexpr bool value = std::disjunction<std::is_same<First, Args>...>::value ?
std::disjunction<std::is_same<First, Args>...>::value :
contain_args<Rest...>::value;
};
template <typename Last>
struct contain_args<Last>
{
static constexpr bool value = std::disjunction<std::is_same<Last, Args>...>::value;
};
//check if variadic template contains type of T
template <typename T>
struct contain_type : std::disjunction<std::is_same<T, Args>...> {};
};
template<typename... Args>
struct tuple_utils
{
// general operations on arrays inside tuple
template<size_t Size, typename First, typename... Rest>
struct tuple_array
{
static constexpr void remove_item(size_t index, size_t count, std::tuple<Args[Size]...>& p_tuple)
{
First& item = std::get<First[Size]>(p_tuple)[index];
item = std::get<First[Size]>(p_tuple)[--count];
tuple_array<Size, Rest...>::remove_item(index, count, p_tuple);
}
static constexpr void assign_item(size_t index, size_t count, std::tuple<Args[Size]...>& p_tuple, const First& first, const Rest&... rest)
{
std::get<First[Size]>(p_tuple)[index] = first;
tuple_array<Size, Rest...>::assign_item(index, count, p_tuple, rest...);
}
};
template <size_t Size, typename Last>
struct tuple_array<Size, Last>
{
static constexpr void remove_item(size_t index, size_t count, std::tuple<Args[Size]...>& p_tuple)
{
Last& item = std::get<Last[Size]>(p_tuple)[index];
item = std::get<Last[Size]>(p_tuple)[--count];
}
static constexpr void assign_item(size_t index, size_t count, std::tuple<Args[Size]...>& p_tuple, const Last& last)
{
std::get<Last[Size]>(p_tuple)[index] = last;
}
};
};
</code></pre>
<p><strong>Usage</strong></p>
<pre class="lang-cpp prettyprint-override"><code> auto ch = new chunk<2 * 2, TestComponent1, TestComponent2>();
auto id1 = ch->add();
auto id2 = ch->add();
auto contains = ch->contains(id1);
ch->assign(id1, TestComponent2{ 5 });
ch->assign(id2, TestComponent1{ 2 });
ch->remove(id1);
</code></pre>
<p><strong>Tests</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "chunk.h"
#define CATCH_CONFIG_MAIN
#include "catch.h"
struct TestComponent1
{
int i;
};
struct TestComponent2
{
int j;
};
struct TestComponent3
{
char t;
};
SCENARIO("Chunk can be instantiated")
{
GIVEN("A Capacity of 4 * 4 and 3 component types as template parameters")
{
chunk<4 * 4, TestComponent1, TestComponent2, TestComponent3> testChunk;
THEN("Chunk has Capacity of 4 * 4 and is empty")
{
REQUIRE(testChunk.get_capacity() == 4 * 4);
REQUIRE(testChunk.get_count() == 0);
}
}
}
SCENARIO("Items can be added and removed from chunk")
{
GIVEN("A Capacity of 4 * 4 and 3 component types as template parameters")
{
chunk<4 * 4, TestComponent1, TestComponent2, TestComponent3> testChunk;
auto entityId = 0;
WHEN("Entity is added to chunk")
{
entityId = testChunk.add();
THEN("Chunk contains entity with id")
{
REQUIRE(testChunk.contains(entityId));
REQUIRE(testChunk.get_count() == 1);
}
}
WHEN("Entity is removed from chunk")
{
testChunk.remove(entityId);
THEN("Chunk does not contain entity with id")
{
REQUIRE(!testChunk.contains(entityId));
REQUIRE(testChunk.get_count() == 0);
}
}
}
}
SCENARIO("Items can be given a value")
{
GIVEN("A Capacity of 4 * 4 and 3 component types as template parameters with one entity")
{
// prepare
chunk<4 * 4, TestComponent1, TestComponent2, TestComponent3> testChunk;
auto entity = testChunk.add();
auto value = 5;
WHEN("entity is given a type TestComponent2 with a value of 5")
{
testChunk.assign(entity, TestComponent2{ value });
THEN("entity has component of type TestComponent2 with value of 5")
{
auto component = testChunk.get_component_data<TestComponent2>(entity);
REQUIRE(component.j == value);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T15:48:01.357",
"Id": "491357",
"Score": "0",
"body": "is there any tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T15:54:41.287",
"Id": "491361",
"Score": "0",
"body": "@Sugar I have added some unit tests"
}
] |
[
{
"body": "<p>This answer about the use of <code>inline</code>:</p>\n<p><a href=\"https://stackoverflow.com/a/29796839/313768\">https://stackoverflow.com/a/29796839/313768</a></p>\n<p>is very educational; in particular</p>\n<blockquote>\n<p>Another way to mark a function as inline is to define (not just declare) it directly in a class definition. Such a function is inline automatically, even without the inline keyword.</p>\n</blockquote>\n<p>There's no advantage to explicitly declaring <code>inline</code> where you've done it. Trust your compiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:26:31.310",
"Id": "491371",
"Score": "3",
"body": "Trust :-) Just accept your compiler is better than you at its one job (unless you happen to be a compiler engineer, then its your job to make that shit work). ;-) Comming from a compiler background humans are horrible at understanding what is best to \"function\"-inline (just horrible). You may think you know but you don't (unless you are a compiler engineer and have the handful of extra tools you need to compiler the million other ways and verify)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T16:44:58.610",
"Id": "250432",
"ParentId": "250421",
"Score": "3"
}
},
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is the code clear and concise?</p>\n</blockquote>\n<p>That's definitely a yes.</p>\n<blockquote>\n<p>Are there any obvious performance improvements?</p>\n</blockquote>\n<p>That is hard to say. For generic use, I think it will do just fine. However, if the components are very small, the overhead of <code>m_indices</code> might become noticable. A bitmask to mark which elements are in use might be better then. Also, there might be access patterns that could benefit from a different implementation. If you add a lot of entities, then use the entities, then delete all of them and start over, you wasted cycles keeping track of the indices. But again, for generic use it looks fine. Use a profiling tool like <a href=\"https://en.wikipedia.org/wiki/Perf_(Linux)\" rel=\"nofollow noreferrer\">Linux's perf tools</a> to measure performance bottlenecks, and if you see you spend a lot of cycles in the member functions of <code>class chunk</code>, you can then decide whether another approach might be better.</p>\n<blockquote>\n<p>Because this is my first somewhat deep-dive in templates, are there any STL solutions I could've used that I have missed?</p>\n</blockquote>\n<p>The list-of-chunks looks a lot like what <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a> does. You could use a <code>std::deque</code> in your <code>class archetype</code>, and not have a <code>class chunk</code>. The only issue is that <code>std::deque</code> hides the chunks it uses internally from you. So you if you go this way, you probably cannot initialize the indices like you did in <code>class chunk</code>, but have to do this in a more dynamic way.</p>\n<h1>Assert that you don't overflow <code>uint16_t</code> variables</h1>\n<p>The template parameter <code>Capacity</code> is a <code>size_t</code>, but you use <code>uint16_t</code> indices. Add a <code>static_assert()</code> to ensure you don't overflow the index variables. Note: <a href=\"https://en.cppreference.com/w/cpp/language/static_assert\" rel=\"nofollow noreferrer\"><code>static_assert()</code></a>s are declarations, not statements, so you don't have to put them inside a member function.</p>\n<h1>Add runtime <code>assert()</code>s</h1>\n<p>Apart from compile-time checks, it might also be useful to add run-time checks to ensure errors are caught early in debug builds. For example, in <code>Chunk::add()</code> you should <code>assert(m_object_count < Capacity)</code>.</p>\n<h1>Consider combining <code>add()</code> and <code>assign()</code></h1>\n<p>When reading your code, I was wondering why <code>add()</code> and <code>remove()</code> looked so different. Adding a new entity is apparently a two-step process: first you call <code>add()</code> to reserve an ID, and then you <code>assign()</code> values to the components of that ID. Why not make this a one-step process?</p>\n<h1>High bits in IDs</h1>\n<p>You seem to be using the high bits as a kind of generation counter. Is this doing anything useful? If <code>Capacity</code> is set to 65536, then there are no high bits left, so you can't be relying on this. I would avoid this altogether, this way you can remove <code>m_index_mask</code>, <code>m_new_id</code> and all the <code>& m_index_mask</code> operations.</p>\n<h1>Try to make your class look and act like STL containers</h1>\n<p>The standard library containers all have a similar interface; you only have to learn it once and you can apply this knowledge on all the containers it provides. It helps if you follow the same conventions, so you don't have to learn and use different terms for your classes. Mostly, it's just renaming a few member functions:</p>\n<ul>\n<li><code>add()</code> -> <code>insert()</code> (just like <code>std::set</code>)</li>\n<li><code>remove()</code> -> <code>erase()</code></li>\n<li><code>get_component_data()</code> -> <code>get()</code> (just like <code>std::tuple</code>)</li>\n<li><code>get_count()</code> -> <code>size()</code></li>\n<li><code>get_capacity()</code> -> <code>capacity()</code></li>\n</ul>\n<p>You also might want to add some functions commonly found in STL containers, such as <code>empty()</code> and <code>clear()</code>. Most importantly, I assume you want to loop over all entities at some point and call a function on each of them. For this, it helps if you add iterators to this class, so they can be used in range-based <code>for</code>-loops, in STL algorithms, and makes it easy to interact with anything else that supports iterators.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T07:51:49.983",
"Id": "491600",
"Score": "0",
"body": "Thanks for your excellent feedback, lots to think about. I get the feedback on the Indices being overhead but it allows me to access items by id in o(1), without it I would not be able to couple an entity id to and index in the component array and would getting items by id become o(n). In cases of multiple insert and deletion it would indeed cost cycles so I think I need to check what will be the most common operation, I have failed to see an solution providing optimal performance in both cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:18:26.550",
"Id": "491601",
"Score": "1",
"body": "@RickNijhuis Keep in mind that O(1) is only faster than O(N) for \"large enough\" values of N. On modern CPUs, you can get the first empty position in a 64-bit bitmask with a [single instruction](https://en.wikipedia.org/wiki/Find_first_set)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:44:39.277",
"Id": "491607",
"Score": "0",
"body": "@G.SIiepen I already know the first empty position though, this because the component arrays are tightly packed(the count of items + 1). In order to keep it like that I can't rely on using an index as entity id because the index of components can change if another component is deleted, this in order to keep the arrays tightly packed. I am not sure if I misunderstood your comment but I don't think I can use a bitmask to link an entity id to the index of components belonging to that entity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:49:30.330",
"Id": "491608",
"Score": "0",
"body": "I do think the struct index array m_indices can be changed to an plain array of integers, this will reduce some of the memory cost per entity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T09:28:14.453",
"Id": "491612",
"Score": "0",
"body": "@RickNijhuis You could consider making index and entity ID the same. With bitmasks, skipping over unused indices is very fast. If your chunks only contain up to 64 entities, then I think using a bitmask will certainly improve performance, but whether it is worth it depends on the rest of the application. For chunks with much more entities in them, your approach might still be the fastest. But the only way to be sure is to measure both approaches with a realistic workload."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:14:58.970",
"Id": "250437",
"ParentId": "250421",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250437",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T14:35:44.707",
"Id": "250421",
"Score": "5",
"Tags": [
"c++",
"entity-component-system"
],
"Title": "Storage container for components of entities (ECS)"
}
|
250421
|
<p>I'm developing a fully AJAX community WP theme that comes with a lot of custom queries.</p>
<p>Everything is fine, there is no bug but recently but I had a few clients that have a huge database and my theme started to kill the CPU. I wonder how can I make it run faster.</p>
<h3>What this code is doing?</h3>
<p>This code is trying to get posts that contains only have "comment" type comments (comment_type="comment") AND approved ones.</p>
<p><strong>database information:</strong> Mysql - mariaDB</p>
<p><strong>table name I'm trying to get result</strong> - wp_comments</p>
<p><strong>how many data that table have -</strong> 380.000 (380K) comments</p>
<p><strong>query's raw output time on phpmyadmin (w/o php) -</strong> 0.23 seconds</p>
<p><strong>time to get this data on front end -</strong> 0.85-90 seconds</p>
<p><strong>JS Code that calls function</strong></p>
<pre><code> function lfload(page) {
$("#sol-load").css("opacity","0.75");
document.cookie = "lf= popular; expires = Fri, 31 Dec 9999 23:59:59 GMT; path=/";
document.cookie = "popular_page = " + page + "; expires = Fri, 31 Dec 9999 23:59:59 GMT; path=/";
var xhr = new XMLHttpRequest();
xhr.open("POST", bilgi.tema_url + '/admin-ajax.php', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
document.getElementById("sol-load").innerHTML = this.response;
$("#sol-load").css("opacity","1");
}
}
xhr.send("action=popular_ajax");
}
</code></pre>
<p><strong>PHP Code to get data</strong></p>
<pre><code>function popular_ajax()
{
global $wpdb;
// getting latest page from cookie
if (isset($_COOKIE["popular_page"]) AND
$_COOKIE["popular_page"] != 0) {
$latest_sent_page_no = intval($_COOKIE["popular_page"]);
} elseif (!isset($_COOKIE["popular_page"]) OR
$_COOKIE["popular_page"] == 0) {
$latest_sent_page_no = 1;
}
$page = $latest_sent_page_no;
$cur_page = $page;
$page -= 1;
$per_page = 20;
$start = $page * $per_page;
$count_limiti = $per_page*50;
// tried to limit count
//query to make it more faster but did'nt work
// count how many page exists to use it for pagination
$count = $wpdb->get_var("SELECT COUNT(DISTINCT comment_post_ID)
FROM ".$wpdb->prefix."comments
USE INDEX (left_frame_index)
WHERE comment_approved = 1
AND comment_type = 'comment'
LIMIT $count_limiti");
$sorgu = $wpdb->get_results("SELECT DISTINCT comment_post_ID
FROM ".$wpdb->prefix."comments
USE INDEX (left_frame_index)
WHERE comment_approved = 1
AND comment_type = 'comment'
GROUP BY comment_post_ID
ORDER BY MAX(comment_date)
DESC LIMIT $start, $per_page");
// GET DATA FROM SQL
foreach($sorgu as $goflying2){
// Çıktı bölgesi
$msg .= "<li class='has-border-bottom'><a class='pr-0 pl-0 pt-1
pb-2 is-size-8'
href='". get_permalink($goflying2->comment_post_ID) ."'
title='".get_the_title($goflying2->comment_post_ID)."'>
".get_the_title($goflying2->comment_post_ID)."<span class='badge'>
" .clean_comment_count_wo_newbies($goflying2->comment_post_ID).
"</span></a></li>";
}
wp_reset_postdata();
// SAY THERE IS NO DATA IF ITS EMPTY
if ($count == 0) {
echo '<div class="tag has-text-centered has-fullwidth">
<a class="pr-0 pl-0 pt-2 pb-2 is-size-8 has-text-dark">
'.__("gündemimiz boş...", 'hype-community').'</a></div>';
exit;
}
// PAGINATOIN STARTING HERE
$no_of_paginations = ceil($count / $per_page);
$start_loop = 1;
$end_loop = $no_of_paginations;
//conditional pagination
if ($cur_page > 1) {
$pre = $cur_page - 1;
$pag_container .= "
<button onclick='gundemNav(this)' value='$pre' class='button is-small'>
<i class='fa fa-angle-left' aria-hidden='true'></i>
</button>
";
}
$pag_container .= "
<div class='dropdown is-hoverable has-fullwidth'>
<button class='button is-small ml-3 mr-3 dropdown-trigger
has-fullwidth' aria-haspopup='true' aria-controls='dropdown-menu5'>
<span>$cur_page</span>
<span class='icon'>
<i class='fa fa-caret-down'></i>
</span>
</button>
".'<div class="dropdown-menu" id="dropdown-menu5" role="menu">
<div class="dropdown-content">';
// tried to limit for loop
if ($end_loop > 50) {
$end_loop = 50;
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
// loop to print all page numbers
if ($cur_page == $i) {
$pag_container .= "<a value='$i' class='dropdown-item
is-active'>$i</a>";
} else {
$pag_container .= "<a onclick='gundemNav(this)' value='$i'
class='dropdown-item'>$i</a>";
}
}
$pag_container = $pag_container . "
</div></div>
</div>";
if ($cur_page < $no_of_paginations) {
//conditional pagination output
$nex = $cur_page + 1;
$pag_container .= "
<button onclick='gundemNav(this)' value='$nex' class='button is-small'>
<i class='fa fa-angle-right' aria-hidden='true'></i>
</button>
";
}
if ($no_of_paginations == 1) {
//conditional pagination output
print '<aside class="menu"><ul class="menu-list">' . $msg .
'</ul></aside>';
} elseif ($cur_page == 1 and $no_of_paginations >= 2) {
//conditional pagination output
print '<aside class="menu"><ul class="menu-list">' . $msg .
'</ul></aside>';
echo '
<button onclick="gundemNav(this)" value="'. $nex .'"
class="button is-small is-bg-blue has-text-white is-fullwidth mt-3">
<span class="icon">
<i class="fa fa-book" aria-hidden="true"></i>
</span>
<strong>'.__("fazlasını yükle", 'hype-community').'</strong>
</button>
';
} elseif ($cur_page != 1 and $no_of_paginations > 1) {
//conditional pagination output
echo
'<div class="has-text-centered is-flex mb-3">'.$pag_container .
'</div>'. // pagination
'<aside class="menu"><ul class="menu-list">' . $msg .
'</ul></aside>'; // content that called from wpdb get results
}
// kill ajax
exit;
}
</code></pre>
<p><strong>INDEX I used in this query</strong></p>
<pre><code>left_frame_index -> commenst_post_ID, comment_date, comment_approved, comment_type
</code></pre>
<p>How can I make it run faster, be more stable? Is there something wrong with my SQL code or PHP code? This code is really killing the CPU...</p>
<p>Without this index, query is around 0.5 seconds (phpymyadmin exec. time. 1.5 seconds when calling with AJAX).</p>
<p>sorry for my bad English! ^_^</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T15:52:49.190",
"Id": "491360",
"Score": "1",
"body": "Please, format long lines to fit in one screen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T17:04:35.067",
"Id": "491368",
"Score": "0",
"body": "hello! yes, sorry. I formatted my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T03:07:46.663",
"Id": "491392",
"Score": "0",
"body": "Why do you tell the queries to use a specific index? Databases are usualy smart enough to decide on their own what index to use if any to get the best performance for any given query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T03:36:51.020",
"Id": "491394",
"Score": "0",
"body": "tbh I wanted to be sure but I was trying to fix this query last 10 hours. Now my query working exec time 0.056 seconds. But IDK when I'm trying spamming this ajax button with my mouse; my cpu goes crayz. I set a transient to count query (deleting it with new comments) but cpu still get hurts when I'm spamming it.\n\nBut I switched to twentynineteen theme and spammed my f5 @home page and cpu went to %60 70 again. This makes me think everything is OK with my code but there is a problem with my hosting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:47:13.197",
"Id": "491428",
"Score": "0",
"body": "You're using both `DISTINCT comment_post_ID` and `GROUP BY comment_post_ID` in your query. Either one will be enough. I doubt this will affect CPU usage, but it is worth testing which variant is performs best. See also: https://stackoverflow.com/questions/581521/whats-faster-select-distinct-or-group-by-in-mysql"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T09:19:08.377",
"Id": "510323",
"Score": "0",
"body": "I see 4 probles 1. For pagination -> `LIMIT` and `OFFSET`, 2. Free result after sql (free memory) query `$result->free();` 3. `DISTINCT` and `GROUP BY` - use `DISTINCT` or `GROUP BY`. 4 Security html output (XSS - problem)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T09:26:20.333",
"Id": "510324",
"Score": "0",
"body": "And `SELECT COUNT(DISTINCT` gives you a one number, you don't need to use pagination:)"
}
] |
[
{
"body": "<h1>Overall comments</h1>\n<p>Overall I’d say that the practice of sending HTML in an AJAX response and using that to directly set the content of a DOM element is an antiquated practice, and <a href=\"https://labs.f-secure.com/blog/getting-real-with-xss/\" rel=\"nofollow noreferrer\">could be an XSS avenue</a>. While the practice of <a href=\"https://softwareengineering.stackexchange.com/questions/140036/is-it-a-good-idea-to-do-ui-100-in-javascript-and-provide-data-through-an-api\">sending data from the API and having the front end code construct the HTML dynamically may have been a new construct eight years ago</a> it is much more common in today’s web.</p>\n<h1>Improving speed of code to lookup posts</h1>\n<p>To answer your question "<em>How can I make it more faster, more stable.</em>" it looks like there is a query to get IDs for each post, and then in the loop to create list items, there are calls to <code>get_permalink()</code>, <code>get_the_title()</code> and <code>clean_comment_count_wo_newbies()</code>. Do those function calls run queries against the database? If so, that would likely be the bottleneck. Ideally the code would run a single query to get all the information needed - e.g. IDs, titles, comment counts, etc. Remember that DB queries <strong>are expensive</strong> so it is best to minimize the number of queries needed.</p>\n<h1>JavaScript</h1>\n<h2>DOM Access</h2>\n<p>The code looks up the element with id <em>sol-load</em> three times within a few lines. It would be wise to cache those lookups, since they can be expensive.</p>\n<p><a href=\"https://i.stack.imgur.com/ybMID.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ybMID.jpg\" alt=\"bridge toll\" /></a></p>\n<blockquote>\n<p><em>”...DOM access is actually pretty costly - I think of it like if I have a bridge - like two pieces of land with a toll bridge, and the JavaScript engine is on one side, and the DOM is on the other, and every time I want to access the DOM from the JavaScript engine, I have to pay that toll”</em><br>\n - John Hrvatin, Microsoft, MIX09, in <a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">this talk <em>Building High Performance Web Applications and Sites</em></a> at 29:38, also cited in the <a href=\"https://books.google.com/books?id=ED6ph4WEIoQC&pg=PA36&lpg=PA36&dq=John+Hrvatin+%22DOM%22&source=bl&ots=2Wrd5G2ceJ&sig=pjK9cf9LGjlqw1Z6Hm6w8YrWOio&hl=en&sa=X&ved=2ahUKEwjcmZ7U_eDeAhVMGDQIHSfUAdoQ6AEwAnoECAgQAQ#v=onepage&q=John%20Hrvatin%20%22DOM%22&f=false\" rel=\"nofollow noreferrer\">O'Reilly <em>Javascript</em> book by Nicholas C Zakas Pg 36</a>, as well as mentioned in <a href=\"https://www.learnsteps.com/javascript-increase-performance-by-handling-dom-with-care/\" rel=\"nofollow noreferrer\">this post</a></p>\n</blockquote>\n<pre><code>const solLoad = $("#sol-load");\n</code></pre>\n<h2>AJAX</h2>\n<p>The front end code uses jQuery to access DOM elements yet the AJAX code uses vanilla XHR mechanisms. The jQuery AJAX methods like <a href=\"https://api.jquery.com/jQuery.get/\" rel=\"nofollow noreferrer\"><code>$.get()</code></a> and <a href=\"https://api.jquery.com/jQuery.post/\" rel=\"nofollow noreferrer\"><code>$.post()</code></a> could be used to simplify the code. Actually <a href=\"https://api.jquery.com/load/\" rel=\"nofollow noreferrer\"><code>.load()</code></a> can be used to simplify the code dramatically -</p>\n<p>I haven't tested this but this should be what would be needed:</p>\n<pre><code>solLoad.load(bilgi.tema_url + '/admin-ajax.php', {action: 'popular_ajax'}, \n solLoad.css.bind(solLoad, "opacity", 1));\n</code></pre>\n<h2>Inline event handlers</h2>\n<p>There are event handlers registered within the HTML code - e.g.</p>\n<blockquote>\n<pre><code><button onclick='gundemNav(this)'\n</code></pre>\n</blockquote>\n<p>It is better to register event handlers within the JavaScript (e.g. using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>button.addEventListener</code></a> (can be done when element is created or after is is selected via DOM) for multiple reasons:</p>\n<ol>\n<li>The logic can be separated from the markup - if multiple teammates worked on the project then one could work on the JavaScript while the other could work on the HTML independently.</li>\n<li>Such handlers can pollute the global namespace which can lead <a href=\"https://stackoverflow.com/a/59539045/1575353\">to strange behavior</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T05:46:24.730",
"Id": "252503",
"ParentId": "250424",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>SELECT COUNT(DISTINCT comment_post_ID)\n FROM ".$wpdb->prefix."comments USE INDEX (left_frame_index)\n WHERE comment_approved = 1\n AND comment_type = 'comment'\n LIMIT $count_limit\n</code></pre>\n</blockquote>\n<p>Needs a better index; see the below.</p>\n<p>Do NOT compare a VARCHAR (such as <code>comment_approved</code>) with a numeric literal (such as <code>1</code>), the index cannot be used. Put quotes around <code>"1"</code> or <code>'1'</code>.</p>\n<p>Get rid of the "index hint"; it may be hurting more than helping.</p>\n<p>Why no <code>ORDER BY</code>? A limit without an order-by give you "random" rows.</p>\n<p>Oops, the real problem is that the query generates only 1 row, so there is no use in having a <code>LIMIT</code>. Keep the <code>DISTINCT</code>; toss the <code>LIMIT</code>.</p>\n<blockquote>\n<pre><code>SELECT DISTINCT comment_post_ID\n FROM ".$wpdb->prefix."comments USE INDEX (left_frame_index)\n WHERE comment_approved = 1\n AND comment_type = 'comment'\n GROUP BY comment_post_ID\n ORDER BY MAX(comment_date) DESC\n LIMIT $start, $per_page\n</code></pre>\n</blockquote>\n<p>See above, plus</p>\n<p>Don't mix <code>GROUP BY</code> and <code>DISTINCT</code>. Use only the <code>GROUP BY</code>.</p>\n<p>This query needs a different index (use the specified order):</p>\n<pre><code>INDEX(comment_type, comment_approved, comment_post_ID, comment_date)\n</code></pre>\n<p>I suspect this query is not giving you what you expect? Please describe in English what the goal is.</p>\n<p>Pagination via <code>OFFSET</code> has problems. See <a href=\"http://mysql.rjweb.org/doc.php/pagination\" rel=\"nofollow noreferrer\">http://mysql.rjweb.org/doc.php/pagination</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T06:31:03.867",
"Id": "258829",
"ParentId": "250424",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T14:57:09.163",
"Id": "250424",
"Score": "3",
"Tags": [
"javascript",
"php",
"jquery",
"mysql",
"wordpress"
],
"Title": "Wordpress Ajax Custom Query - High CPU LOAD"
}
|
250424
|
<p>Quite simply, this is my base class for Xamarin forms, everything is fully working, but it's getting a bit too long and feels a bit like it can be improved, especially the network bit could be handled differently.</p>
<p>Anyone have any idea how I can split this up?</p>
<pre><code>/// <summary> The startup class for the cross-platform project </summary>
public partial class App
{
/// <summary> The container for all our dependency injections. </summary>
private static TinyIoCContainer _container;
/// <summary> Handles pop up and other alerts </summary>
private readonly IDialogService _dialogService;
public static Double ScreenHeight { get; set; }
public static Double ScreenWidth { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="App" /> class.
/// This is the start up method of the entire application along with it's corresponding start up method in the native
/// platform.
/// </summary>
public App()
{
InitializeComponent();
// Register for connectivity changes, be sure to unsubscribe when finished
Connectivity.ConnectivityChanged += ConnectivityChanged;
// Enables Experimental features
Device.SetFlags(new[] {"Markup_Experimental", "Brush_Experimental", "Shapes_Experimental"});
// Retrieve token
var token = GetTokenAsync().Result;
#if DEBUG
EnableDebugRainbows(false);
RegisterDependencies(true);
GlobalSetting.Instance.UpdateRunMode(true, token);
#else
RegisterDependencies(false);
GlobalSetting.Instance.UpdateRunMode(true, token);
#endif
_dialogService = TinyIoCContainer.Current.Resolve<IDialogService>();
// Start navigation, do this last
InitNavigation();
SetDeviceHeightAndWidth();
}
private void SetDeviceHeightAndWidth()
{
// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Width (in pixels)
var width = mainDisplayInfo.Width;
// Width (in xamarin.forms units)
var xamarinWidth = width / mainDisplayInfo.Density;
// Height (in pixels)
var height = mainDisplayInfo.Height;
// Screen density
var density = mainDisplayInfo.Density;
ScreenWidth = xamarinWidth;
}
/// <summary> Called when the application starts. </summary>
protected override void OnStart()
{
// Initialize AppCenter
AppCenter.Start(
""",
typeof(Analytics),
typeof(Crashes));
}
/// <summary> Gets the token from secure storage in app </summary>
/// <returns> returns token as a string </returns>
private static async Task<string> GetTokenAsync()
{
try
{
var oauthToken = await SecureStorage.GetAsync("AuthAccessToken").ConfigureAwait(false);
return oauthToken;
}
catch (Exception exception)
{
// Possible that device doesn't support secure storage on device.
Debug.WriteLine(exception);
throw new Exception();
}
}
/// <summary> Applies Debug Coloring to UI if enabled </summary>
private void EnableDebugRainbows(bool shouldUseDebugRainbows)
{
Resources.Add(new Style(typeof(ContentPage))
{
ApplyToDerivedTypes = true, Setters = {new Setter {Property = DebugRainbow.ShowColorsProperty, Value = shouldUseDebugRainbows}}
});
}
/// <summary> Registers our dependency services. </summary>
public static void RegisterDependencies(bool inDebugMode)
{
// 1. Create a new Tiny Ioc container
_container = TinyIoCContainer.Current;
// 2. Register Services - by default, TinyIoC will register interface registrations as singletons.
_container.Register<IRequestProvider, RequestProvider>();
_container.Register<ISettingsService, SettingsService>();
_container.Register<IAuthenticationService, AuthenticationService>();
_container.Register<IDialogService, DialogService>();
if (inDebugMode)
{
_container.Register<IFormsService, FormsMockService>();
_container.Register<IJobsService, JobsMockService>();
_container.Register<IMediaService, MediaFileMockService>();
GlobalSetting.InDebugMode = true;
}
else
{
_container.Register<IFormsService, FormService>();
_container.Register<IJobsService, JobsService>();
_container.Register<IMediaService, MediaFileService>();
GlobalSetting.InDebugMode = false;
}
}
/// <summary> Decides where user will be redirected to, if logged in already skip login. </summary>
private void InitNavigation()
{
var navigationHelper = new ShellNavigationHelper();
var currentAssembly = Assembly.GetExecutingAssembly();
navigationHelper.RegisterViewsInAssembly(currentAssembly);
TinyIoCContainer.Current.Register<INavigationHelper>(navigationHelper);
foreach (var type in currentAssembly.ExportedTypes.Where(x => x.IsSubclassOf(typeof(ViewModelBase))))
{
TinyIoCContainer.Current.Register(type);
}
foreach (var type in currentAssembly.ExportedTypes.Where(x => x.IsSubclassOf(typeof(Page))))
{
TinyIoCContainer.Current.Register(type);
}
Resolver.SetResolver(new TinyIoCResolver());
var token = GlobalSetting.Instance.AuthToken;
// If no token go to login page, else go to main page
if (string.IsNullOrEmpty(token))
{
MainPage = new LoginPage();
}
else
{
MainPage = new AppShell();
}
}
/// <summary> Called when the application is resumed, after being sent to the background. </summary>
protected override void OnResume()
{
Connectivity.ConnectivityChanged += ConnectivityChanged;
}
/// <summary> Called each time the application goes to the background. </summary>
protected override void OnSleep()
{
Connectivity.ConnectivityChanged -= ConnectivityChanged;
}
/// <summary> Show a toast at bottom when connectivity is lost </summary>
/// <param name="sender"> The sender. </param>
/// <param name="eventArgs"> The eventArgs hold the connectivity information </param>
private void ConnectivityChanged(object sender, ConnectivityChangedEventArgs eventArgs)
{
var access = eventArgs.NetworkAccess;
var netStatus = CheckNetAccess(access);
_dialogService.ShowAlertAsync(netStatus, "Internet", "OK");
var profiles = eventArgs.ConnectionProfiles;
var internetType = CheckInternetType(profiles);
_dialogService.ShowAlertAsync(internetType, "Internet Type", "OK");
}
private static string CheckInternetType(IEnumerable<ConnectionProfile> profiles)
{
var connectionProfiles = profiles.ToList();
return connectionProfiles.Contains(ConnectionProfile.WiFi)
? connectionProfiles.FirstOrDefault().ToString()
: "No Wifi";
}
private static string CheckNetAccess(NetworkAccess access)
{
return access switch
{
NetworkAccess.Internet => "Local and internet access",
NetworkAccess.Local => "Local network access only",
NetworkAccess.ConstrainedInternet => "Limited internet access",
NetworkAccess.None => "No connectivity is available",
NetworkAccess.Unknown => "Unable to determine internet connectivity",
_ => throw new ArgumentOutOfRangeException(nameof(access), access, null)
};
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Re-entrance</h2>\n<p>I don't think that these:</p>\n<pre><code> private static TinyIoCContainer _container;\n public static Double ScreenHeight { get; set; }\n public static Double ScreenWidth { get; set; }\n</code></pre>\n<p>should be static. Particularly for the purposes of unit testing, these should simply be instance properties on your <code>App</code>. The feasibility of this might be limited by an external contract for <code>RegisterDependencies</code> that I don't understand, mind you.</p>\n<h2>Implicit types</h2>\n<p><code>var</code> is over-used, here. The usual policy I recommend is that - if a type is obvious, such as the case of an object being constructed and then assigned, <code>var</code> is fine; like this:</p>\n<pre><code>var navigationHelper = new ShellNavigationHelper();\n</code></pre>\n<p>But, for something like this:</p>\n<pre><code>var netStatus = CheckNetAccess(access);\n</code></pre>\n<p>Can you tell, just by looking at this line, the type of <code>netStatus</code>? No. Part of self-documenting code is making this more legible to others, and to yourself in a few weeks, by adding explicit types. An added benefit is that it will catch a certain category of regressions if the expected type changes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:17:00.057",
"Id": "491422",
"Score": "0",
"body": "I was thinking more in line of how to split up the networking code and didn't even consider those improvements, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T16:34:04.157",
"Id": "250431",
"ParentId": "250428",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T16:03:34.073",
"Id": "250428",
"Score": "1",
"Tags": [
"c#",
"xaml",
"xamarin"
],
"Title": "App.xaml.cs Startup Code Refactoring"
}
|
250428
|
<p>I trying to implement Huffman Codes on C. And, since my previous attempt failed, I decided to approach the issue more responsibly. So I'm asking for feedback on my implementation of the priority queue on C. First of all, the design of structures and interfaces is important to me! Also, how easy would it be to implement a Huffman tree using this structure? And of course, what about decomposition?</p>
<p><em>priority_queue.h</em></p>
<pre><code>#ifndef PRIORITY_QUEUE
#define PRIORITY_QUEUE
#include <stdlib.h>
struct pq_node {
unsigned long frequency;
struct pq_node *parent; //Pointers for Huffman tree
struct pq_node *left;
struct pq_node *right;
char symbol;
};
struct priority_queue {
struct pq_node *heap_on_array;
size_t size;
size_t capacity;
};
void init_queue(struct priority_queue **pq, size_t capacity);
void shift_up(struct priority_queue **pq, int i); // i - index
void shift_down(struct priority_queue **pq, size_t i); // i - index
struct pq_node extract_min(struct priority_queue **pq);
void insert(struct priority_queue **pq, char symbol);
void insert_element(struct priority_queue **pq, char symbol, unsigned long frequency);
void node_swap(struct pq_node *first, struct pq_node *second);
</code></pre>
<p><em>priority_queue.c</em></p>
<pre><code>#include "priority_queue.h"
void init_queue(struct priority_queue **pq, size_t capacity)
{
(*pq) = malloc(sizeof(struct priority_queue));
(*pq)->heap_on_array = malloc(sizeof(struct pq_node) * capacity);
(*pq)->capacity = capacity;
(*pq)->size = 0;
};
void shift_up(struct priority_queue **pq, int i)
{
while ((*pq)->heap_on_array[i].frequency < (*pq)->heap_on_array[(i-1)/2].frequency)
{
node_swap(&((*pq)->heap_on_array[i]), &((*pq)->heap_on_array[(i-1)/2]));
i = (i - 1) / 2;
}
}
void shift_down(struct priority_queue **pq, size_t i)
{
while ((2 * i + 1) < (*pq)->size)
{
size_t left = 2 * i + 1;
size_t right = 2 * i + 2;
size_t j = left;
if((right < (*pq)->size) && ((*pq)->heap_on_array[right].frequency < (*pq)->heap_on_array[left].frequency))
{
j = right;
}
if((*pq)->heap_on_array[i].frequency <= (*pq)->heap_on_array[j].frequency)
{
break;
}
node_swap(&((*pq)->heap_on_array[i]), &((*pq)->heap_on_array[j]));
i = j;
}
}
struct pq_node extract_min(struct priority_queue **pq)
{
struct pq_node tmp = (*pq)->heap_on_array[0];
(*pq)->heap_on_array[0] = (*pq)->heap_on_array[(*pq)->size - 1];
(*pq)->size--;
shift_down(pq, 0);
return tmp;
}
void insert(struct priority_queue **pq, char symbol)
{
for(size_t i = 0; i < (*pq)->size; ++i)
{
if((*pq)->heap_on_array[i].symbol == symbol)
{
(*pq)->heap_on_array[i].frequency++;
shift_down(pq, i);
return;
}
}
if((*pq)->size == (*pq)->capacity)
{
(*pq)->heap_on_array = reallocarray((*pq)->heap_on_array, (*pq)->size * 2, sizeof(struct pq_node));
(*pq)->capacity = (*pq)->capacity * 2;
}
(*pq)->size++;
(*pq)->heap_on_array[(*pq)->size - 1].symbol = symbol;
(*pq)->heap_on_array[(*pq)->size - 1].frequency = 1;
shift_up(pq, (*pq)->size - 1);
}
void insert_element(struct priority_queue **pq, char symbol, unsigned long frequency)
{
for(size_t i = 0; i < (*pq)->size; ++i)
{
if((*pq)->heap_on_array[i].symbol == symbol)
{
(*pq)->heap_on_array[i].frequency = frequency;
shift_down(pq, i);
return;
}
}
if((*pq)->size == (*pq)->capacity)
{
(*pq)->heap_on_array = reallocarray((*pq)->heap_on_array, (*pq)->size * 2, sizeof(struct pq_node));
(*pq)->capacity = (*pq)->capacity * 2;
}
(*pq)->size++;
(*pq)->heap_on_array[(*pq)->size - 1].symbol = symbol;
(*pq)->heap_on_array[(*pq)->size - 1].frequency = frequency;
shift_up(pq, (*pq)->size - 1);
}
void node_swap(struct pq_node *first, struct pq_node *second)
{
struct pq_node tmp = *first;
*first = *second;
*second = tmp;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Avoid double pointers. They are absolutely unwarranted in all the functions (except <code>init</code>, but see below).</p>\n</li>\n<li><p>Prefer returning a value to a side effect. In the client code, which I presume is along the lines of</p>\n<pre><code> struct priority_queue * pq;\n init_queue(&pq, capacity);\n</code></pre>\n<p>I have to read the source of <code>init_queue</code> to see that there is a side effect of modifying the parameter I passed. Compare it to a clear assignment:</p>\n<pre><code> struct priority_queue * pq;\n pq = init_queue(capacity);\n</code></pre>\n</li>\n<li><p>Always test what <code>malloc</code> returns, and return <code>NULL</code> immediately if it fails. Ditto for <code>reallocarray</code>.</p>\n<p>Also, the blind</p>\n<pre><code> (*pq)->heap_on_array = reallocarray((*pq)->heap_on_array, (*pq)->size * 2, sizeof(struct pq_node));\n</code></pre>\n<p>leads to a memory leak in case of failure: the pointer to the original block is lost, and it cannot be <code>free</code>d. Typically one would</p>\n<pre><code> temp = reallocarray(...);\n if (temp == NULL) {\n // handle_error, e.g. free(pq->heap_on_array);\n return;\n }\n pq->heap_on_array = temp;\n</code></pre>\n</li>\n<li><p>No naked loops. Every loop implements an important algorithm, and deserves a name. In your case, the initial loop of <code>insert_*</code> is surely</p>\n<pre><code> pq_node * find(priority_queue * pq, char symbol);\n</code></pre>\n</li>\n<li><p>DRY. <code>insert</code> and <code>insert_element</code> are suspiciously similar. The only difference is in treating <code>frequency</code>. The common functionality shall be factored out into a function.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T20:20:24.683",
"Id": "491380",
"Score": "0",
"body": "thanks for your answer, can you say more about the design of structures. Is them well-designed or not? Because structures is the main thing in all programms."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T19:31:14.360",
"Id": "250442",
"ParentId": "250438",
"Score": "4"
}
},
{
"body": "<p>in function:</p>\n<pre><code>void init_queue(struct priority_queue **pq, size_t capacity)\n</code></pre>\n<p>after the final closing brace '}' there is a semicolon ';'. This results in the compiler outputting:</p>\n<pre><code>untitled1.c:41:2: warning: ISO C does not allow extra ‘;’ outside of a function [-Wpedantic]\n</code></pre>\n<p>There are also some warnings about implicit conversions.</p>\n<p>When compiling, always enable the warnings, then fix those warnings.</p>\n<p>for <code>gcc</code>, at a minimum use:</p>\n<pre><code>-Wall -Wextra -Wconversion -pedantic -std=gnu11 \n</code></pre>\n<p>Note: other compilers use different options to produce the same results.</p>\n<p>the file: <code>priority_queue.h</code> is missing the statement:</p>\n<pre><code>#endif\n</code></pre>\n<p>at the end of the file. So it does not compile!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T20:25:47.967",
"Id": "250483",
"ParentId": "250438",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:45:55.503",
"Id": "250438",
"Score": "2",
"Tags": [
"c",
"compression",
"priority-queue"
],
"Title": "Priority queue implementation on C. (For Huffman Coding)"
}
|
250438
|
<p><strong>Introduction</strong></p>
<p>I have released a small a <a href="https://github.com/billguastalla/wavereader" rel="nofollow noreferrer">WAVE file reader</a> with a mutex/lock-based caching mechanism, as a header-only library. The general purpose of the library is to read WAVE files into floating points, in a way that handles repeated sequential requests for audio data without hanging on disk reads.</p>
<p>I am looking for some criticism of the code but also of the structure of the project.</p>
<ul>
<li>Is there anything unsafe about the code, or is there any misuse of language constructs?</li>
<li>Does the project provide everything you would expect from a public-facing library?</li>
</ul>
<p><strong>Code</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <vector>
#include <string>
#include <mutex>
#include <thread>
#include <iostream>
#include <istream>
#include <set>
constexpr size_t WAV_HEADER_DEFAULT_SIZE = 44u;
//! Wave header
/*!
Reads and stores the wave header in the same way it appears in the WAV file.
*/
struct WAV_HEADER
{
/*!
* Read the first 44 bytes of the input stream into the header.
*/
bool read(std::istream& s)
{
if (s.good())
{
s.seekg(0u);
s.read(&m_0_headerChunkID[0], 4);
s.read((char*)&m_4_chunkSize, 4);
s.read(&m_8_format[0], 4);
s.read(&m_12_subchunk1ID[0], 4);
s.read((char*)&m_16_subchunk1Size, 4);
s.read((char*)&m_20_audioFormat, 2);
s.read((char*)&m_22_numChannels, 2);
s.read((char*)&m_24_sampleRate, 4);
s.read((char*)&m_28_byteRate, 4);
s.read((char*)&m_32_bytesPerBlock, 2);
s.read((char*)&m_34_bitsPerSample, 2);
s.read(&m_36_dataSubchunkID[0], 4);
s.read((char*)&m_40_dataSubchunkSize, 4);
}
return s.good();
}
/*!
* Checks whether the header is in a format that can be read by waveread
*/
bool valid() const
{
return (std::string{ &m_0_headerChunkID[0],4u } == std::string{ "RIFF" }) && // RIFF
std::string{ &m_8_format[0],4u } == std::string{ "WAVE" } && // WAVE format
m_16_subchunk1Size == 16 &&// PCM, with no extra parameters in file
m_20_audioFormat == 1 && // uncompressed
m_32_bytesPerBlock == (m_22_numChannels * (m_34_bitsPerSample / 8)) && // block align matches # channels and bit depth
(
(m_34_bitsPerSample == 8) ||
(m_34_bitsPerSample == 16) ||
(m_34_bitsPerSample == 24) ||
(m_34_bitsPerSample == 32) // available bit depths
);
}
/*!
* Clear all data in the header setting values to 0 or "nil\0"
*/
void clear()
{
auto cpy = [](char from[4], char to[4]) // since strcpy is deprecated on windows and strcpy_s absent on *nix.
{
for (size_t i{ 0u }; i < 4u; ++i)
to[i] = from[i];
};
char none[4]{ "nil" };
cpy(none, m_0_headerChunkID);
m_4_chunkSize = 0;
cpy(none, m_8_format);
cpy(none, m_12_subchunk1ID);
m_16_subchunk1Size = 0;
m_20_audioFormat = 0;
m_22_numChannels = 0;
m_24_sampleRate = 0;
m_28_byteRate = 0;
m_32_bytesPerBlock = 0;
m_34_bitsPerSample = 0;
cpy(none, m_36_dataSubchunkID);
m_40_dataSubchunkSize = 0;
}
/*!
* Samples per channel
*/
int samples() const { return (m_40_dataSubchunkSize / ((m_22_numChannels * m_34_bitsPerSample) / 8)); }
char m_0_headerChunkID[4]; /*!< Header chunk ID */
int32_t m_4_chunkSize; /*!< Chunk size*/
char m_8_format[4]; /*!< Format */
char m_12_subchunk1ID[4]; /*!< Subchunk ID */
int16_t m_16_subchunk1Size; /*!< Subchunk size*/
int16_t m_20_audioFormat; /*!< Audio format */
int16_t m_22_numChannels; /*!< Number of channels*/
int32_t m_24_sampleRate; /*!< Sample rate of a single channel */
int32_t m_28_byteRate; /*!< Number of bytes per sample*/
int16_t m_32_bytesPerBlock; /*!< Number of bytes per block (where a block is a single sample from each channel)*/
int16_t m_34_bitsPerSample; /*!< Bits per sample */
char m_36_dataSubchunkID[4]; /*!< Detailed description after the member */
int32_t m_40_dataSubchunkSize; /*!< Detailed description after the member */
};
static_assert(sizeof(WAV_HEADER) == WAV_HEADER_DEFAULT_SIZE, "WAV File header is not the expected size.");
//! Wave reader
/*!
Reads audio from an input stream.
*/
class Waveread
{
public:
//! Constructor
/*!
* \param stream the input stream
* \param cacheSize the size of the cache. This should usually be a reasonable multiple of the size of the set of samples you expect to read each time you call audio().
* \param cacheExtensionThreshold Within interval [0,1]. When a caller gets audio, how far into the cache should the caller go before the cache is triggered to be extended?
*/
Waveread(
std::unique_ptr<std::istream>&& stream,
size_t cacheSize = 1048576u,
double cacheExtensionThreshold = 0.5
)
:
m_stream{ stream.release() },
m_header{},
m_data{},
m_dataMutex{},
m_cachePos{ 0u },
m_opened{ false },
m_cacheSize{ cacheSize }, // 1MB == 1048576u
m_cacheExtensionThreshold{ cacheExtensionThreshold }
{
if (m_cacheExtensionThreshold < 0.0)
m_cacheExtensionThreshold = 0.0;
else if (m_cacheExtensionThreshold > 1.0)
m_cacheExtensionThreshold = 1.0;
m_header.clear();
}
Waveread(const Waveread&) = delete;
Waveread& operator=(const Waveread&) = delete;
//! Move Constructor
/*!
* \param other Another waveread object. The move constructor enables the placement of waveread objects in containers using std::move().
* For instance you can do:
* Waveread a{stream};
* std::vector<Waveread> readers;
* readers.push_back(std::move(a))
* a is now unusable, but the vector now contains the wavereader.
*/
Waveread(Waveread&& other) noexcept
:
m_stream{ },
m_header{ },
m_data{ },
m_dataMutex{},
m_cachePos{ other.m_cachePos },
m_opened{ other.m_opened },
m_cacheSize{ other.m_cacheSize },
m_cacheExtensionThreshold{ other.m_cacheExtensionThreshold }
{
std::lock_guard<std::mutex> l{ other.m_dataMutex };
m_data = other.m_data;
m_header = other.m_header;
m_stream.reset(other.m_stream.release());
}
//! Reset
/*!
* Resets the wavereader, clearing all data.
* \param stream a new std::istream to read a wave file from.
*/
void reset(std::unique_ptr<std::istream>&& stream)
{
std::lock_guard<std::mutex> lock{ m_dataMutex };
m_stream = std::move(stream);
m_data.clear();
m_header.clear();
m_cachePos = 0u;
m_opened = false;
}
//! Open
/*!
* Loads the wave header from file, and fills the cache from the start.
*/
bool open()
{
if (!m_opened)
{
m_header.read(*m_stream.operator->());
if (m_header.valid())
{
m_opened = true;
load(0u, m_cacheSize);
return true;
}
else
return false; // we couldn't open it
}
return true; // we didn't open it, but it was already opened.
}
//! Close
/*!
* Closes the wavereader.
*/
void close()
{
std::lock_guard<std::mutex> lock{ m_dataMutex };
m_stream->seekg(0u);
m_data.clear();
m_header.clear();
m_cachePos = 0u;
m_opened = false;
}
//! Audio
/*!
* Get interleaved floating point audio samples in the interval (-1.f,1.f).
* \param startSample index of first sample desired
* \param sampleCount number of samples needed including first sample
* \param channels Which channels would you like to retrieve. Zero-indexed. If channels are out of bounds, then their modulus with the channel count will be taken. This means if you ask for channels {0,1} from a mono file, you will retrieve two copies of the mono channel, interleaved.
* \param stride for each channel, when getting samples, skip every n samples where n == stride.
* \param interleaved determines how samples are ordered: true provides {C1S1, C2S1, ..., CMS1, C1S2, C2S2, ..., CMS2} false provides {C1S1, C1S2, ..., C1SN, C2S1, C2S2, ..., C2S2, ...}
*/
std::vector<float> audio(
size_t startSample,
size_t sampleCount,
std::set<int> channels = std::set<int>{ 0,1 },
size_t stride = 0u,
bool interleaved = true
)
{
if (!open())
return std::vector<float>{};
size_t startSample_ch_bit{ startSample * m_header.m_32_bytesPerBlock };
size_t sampleCount_ch_bit{ sampleCount * m_header.m_32_bytesPerBlock };
if ((startSample_ch_bit + sampleCount_ch_bit) >= (size_t)m_header.m_40_dataSubchunkSize) // case1: out of bounds of file
{
if (startSample_ch_bit >= (size_t)m_header.m_40_dataSubchunkSize) // case1A: read starts out of bounds
return std::vector<float>{};
else // case1B: read starts within bounds, ends out of bounds
{
load(startSample_ch_bit, m_header.m_40_dataSubchunkSize - startSample_ch_bit);
return samples(0u, m_header.m_40_dataSubchunkSize - startSample_ch_bit, channels, stride, interleaved);
}
}
else if (startSample_ch_bit >= m_cachePos &&
(startSample_ch_bit + sampleCount_ch_bit) <= (m_cachePos + m_data.size())) // case2: within cache
{
std::vector<float> result{ samples(startSample_ch_bit - m_cachePos, sampleCount_ch_bit, channels, stride,interleaved) };
if (startSample_ch_bit > (m_cachePos + (size_t)(m_data.size() * m_cacheExtensionThreshold))) // case2A: approaching end of cache
{
std::thread extendBuffer{ &Waveread::load,this,m_cachePos + (size_t)(m_cacheSize * m_cacheExtensionThreshold), m_cacheSize };
extendBuffer.detach();
}
return result;
}
else // case3: within file, outside of cache
{
if (load(startSample_ch_bit, m_cacheSize > sampleCount_ch_bit ? m_cacheSize : sampleCount_ch_bit)) // load samplecount or cachesize, whichever is greater.
return samples(0u, sampleCount_ch_bit, channels, stride, interleaved);
else
return std::vector<float>{};
}
}
//! Get header file
const WAV_HEADER& header() const { return m_header; }
//! Get size of cache
const size_t& cacheSize() const { return m_cacheSize; }
//! Get start position of cache
const size_t& cachePos() const { return m_cachePos; }
//! Has the file been opened
const bool& opened() const { return m_opened; }
//! Get cache extension threshold: this is the fraction of the cache that is read before it is extended.
const double& cacheExtensionThreshold() const { return m_cacheExtensionThreshold; }
//! Set cache extension threshold. Does not extend the cache until audio() has been called. Function will halt until the last load operation has finished.
void setCacheExtensionThreshold(const double& cacheExtensionThreshold)
{
std::lock_guard<std::mutex> l{ m_dataMutex };
m_cacheExtensionThreshold = cacheExtensionThreshold;
}
//! Set cache size. Does not extend the cache until audio() has been called. Function will halt until the last load operation has finished.
void setCacheSize(const size_t& csize)
{
std::lock_guard<std::mutex> l{ m_dataMutex };
m_cacheSize = csize;
}
private:
//! Load data into the cache
bool load(size_t pos, size_t size) // method will offset read by header size
{
std::lock_guard<std::mutex> lock{ m_dataMutex };
size_t truncatedSize{ (pos + size) < (size_t)m_header.m_40_dataSubchunkSize
? size : (size_t)m_header.m_40_dataSubchunkSize - pos };
if (pos < (size_t)m_header.m_40_dataSubchunkSize)
{
m_stream->seekg(((std::streampos)pos + (std::streampos)sizeof(WAV_HEADER))); // add header size
m_data.resize(truncatedSize);
if (m_stream->good())
{
m_stream->read(reinterpret_cast<char*>(&m_data[0]), truncatedSize);
m_cachePos = pos;
m_stream->clear(std::iostream::eofbit);
return m_stream->good();
}
}
return false;
}
//! Transform cached bytes into floats.
/*!
* \param posInCache
* \param size
* \param channels
* \param stride
* \param interleaved
*/
std::vector<float> samples(
size_t posInCache,
size_t size,
std::set<int> channels = std::set<int>{},
size_t stride = 0u,
bool interleaved = true) // posInCache is pos relative to cachepos.
{
std::vector<float> result{};
if (
(posInCache + size) <= m_data.size() && // if caller is not overshooting the cache
!channels.empty() // if caller has provided channels
)
{
std::lock_guard<std::mutex> lock{ m_dataMutex };
size_t bpc{ m_header.m_32_bytesPerBlock / (size_t)m_header.m_22_numChannels }; // bytes per channel
if (interleaved)
switch (m_header.m_34_bitsPerSample)
{
case 8: // unsigned 8-bit
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
for (auto ch : channels)
{
// NOTE: (a) see narrow_cast<T>(var) (b) addition defined in C++ as: T operator+(const T &a, const T2 &b);
// EXCEPTIONS: Integer types smaller than int are promoted when an operation is performed on them.
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
result.emplace_back((float)
(m_data[i + cho] - 128) // unsigned, so offset by 2^7
/ (128.f)); // divide by 2^7
}
}
break;
case 16: // signed 16-bit
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
result.emplace_back((float)
((m_data[i + cho]) |
(m_data[i + 1u + cho] << 8))
/ (32768.f)); // divide by 2^15
}
}
break;
case 24: // signed 24-bit
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
// 24-bit is different to others: put the value into a 32-bit int with zeros at the (LSB) end
result.emplace_back((float)
((m_data[i + cho] << 8) |
(m_data[i + 1u + cho] << 16) |
(m_data[i + 2u + cho] << 24))
/ (2147483648.f)); // divide by 2^31
}
}
break;
case 32: // signed 32-bit
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
result.emplace_back((float)
(m_data[i + cho] |
(m_data[i + 1u + cho] << 8) |
(m_data[i + 2u + cho] << 16) |
(m_data[i + 3u + cho] << 24))
/ (2147483648.f)); // signed, so divide by 2^31
}
}
break;
default:
break;
}
else
switch (m_header.m_34_bitsPerSample)
{
case 8: // unsigned 8-bit
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
// NOTE: (a) see narrow_cast<T>(var) (b) addition defined in C++ as: T operator+(const T &a, const T2 &b);
// EXCEPTIONS: Integer types smaller than int are promoted when an operation is performed on them.
result.emplace_back((float)
(m_data[i + cho] - 128) // unsigned, so offset by 2^7
/ (128.f)); // divide by 2^7
}
}
break;
case 16: // signed 16-bit
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
result.emplace_back((float)
((m_data[i + cho]) |
(m_data[i + 1u + cho] << 8))
/ (32768.f)); // divide by 2^15
}
}
break;
case 24: // signed 24-bit
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
// 24-bit is different to others: put the value into a 32-bit int with zeros at the (LSB) end
result.emplace_back((float)
((m_data[i + cho] << 8) |
(m_data[i + 1u + cho] << 16) |
(m_data[i + 2u + cho] << 24))
/ (2147483648.f)); // divide by 2^31
}
}
break;
case 32: // signed 32-bit
for (auto ch : channels)
{
size_t cho{ (ch % m_header.m_22_numChannels) * bpc };
for (size_t i{ posInCache }; i < (posInCache + size); i += (m_header.m_32_bytesPerBlock * (1u + stride)))
{
result.emplace_back((float)
(m_data[i + cho] |
(m_data[i + 1u + cho] << 8) |
(m_data[i + 2u + cho] << 16) |
(m_data[i + 3u + cho] << 24))
/ (2147483648.f)); // signed, so divide by 2^31
}
}
break;
default:
break;
}
}
return result;
}
bool m_opened; /*!< Has the file been opened */
std::unique_ptr<std::istream> m_stream; /*!< Input stream */
WAV_HEADER m_header; /*!< Holds structure of header when opened, used in subsequent operations. */
std::vector<uint8_t> m_data;/*!< Cached data holding part of the data chunk of the WAV file. */
std::mutex m_dataMutex; /*!< Mutex to lock data when buffer is being extended */
size_t m_cachePos; /*!< At what point, from the start of the data chunk (i.e. cachePos == idx - 44u), does the cached data in m_data begin at. */
size_t m_cacheSize; /*!< How big should the cache (all channels) be in bytes */
double m_cacheExtensionThreshold; /*!< Within interval [0,1]. When a caller gets audio, how far into the cache should the caller go before the cache is triggered to be extended? */
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<pre class=\"lang-cpp prettyprint-override\"><code> s.read(&m_0_headerChunkID[0], 4);\n s.read((char*)&m_4_chunkSize, 4);\n s.read(&m_8_format[0], 4);\n s.read(&m_12_subchunk1ID[0], 4);\n s.read((char*)&m_16_subchunk1Size, 4);\n s.read((char*)&m_20_audioFormat, 2);\n s.read((char*)&m_22_numChannels, 2);\n s.read((char*)&m_24_sampleRate, 4);\n s.read((char*)&m_28_byteRate, 4);\n s.read((char*)&m_32_bytesPerBlock, 2);\n s.read((char*)&m_34_bitsPerSample, 2);\n s.read(&m_36_dataSubchunkID[0], 4);\n s.read((char*)&m_40_dataSubchunkSize, 4);\n</code></pre>\n<p>You're assuming endianness.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T10:00:57.407",
"Id": "491404",
"Score": "5",
"body": "is this supposed to be a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T17:39:17.227",
"Id": "491442",
"Score": "1",
"body": "@AryanParekh yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T18:26:57.867",
"Id": "491449",
"Score": "2",
"body": "While you are technically correct that endianness is assumed in this code, I would argue that this is a non-issue; there are hardly any CPU architectures in use anymore that are big-endian, and in the posted code, `valid()` will actually return `false` if the code is compiled for big-endian and a little-endian file is read."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T19:31:03.573",
"Id": "250441",
"ParentId": "250440",
"Score": "1"
}
},
{
"body": "<h1>Ensure correct order of constructor member initializers</h1>\n<p>My compiler warns me that in the constructors of <code>Waveread</code>, <code>m_cachePos</code> and <code>m_opened</code> are initialized in the wrong order. The order of the constructor initializer list should match the order in which the member variables are declared, otherwise they might be initialized in a different order than you specify, which could be a problem if they depend on each other in some way.</p>\n<p>I would also prefer using default member initializers to initialize those member variables that don't depend on the arguments passed to the constructors. So for example:</p>\n<pre><code>Waveread(\n std::unique_ptr<std::istream>&& stream,\n size_t cacheSize = 1048576u,\n double cacheExtensionThreshold = 0.5\n):\n m_stream{ stream.release() },\n m_cacheSize{ cacheSize},\n m_cacheExtensionThreshold{ cacheExtensionThreshold }\n{\n ...\n}\n\n...\n\nprivate:\n bool m_opened{};\n std::unique_ptr<std::istream> m_stream;\n WAV_HEADER m_header{};\n std::vector<uint8_t> m_data{};\n std::mutex m_dataMutex{};\n size_t m_cachePos{};\n size_t m_cacheSize;\n double m_cacheExtensionThreshold;\n};\n</code></pre>\n<h1>Are you sure your mutexes are locked correctly?</h1>\n<p>If you really want multiple threads to be able to access the same instance of <code>class Wavereader</code>, then you better be prepared for them to access the instance at the same time in the most inconvenient places. For example, what happens if two members call <code>open()</code> simultaneously? It might happen that both see that <code>m_opened</code> is <code>false</code>, then they both call <code>m_header.read(...)</code>, and likely one of them will read the actual header, the other will read data after right after the header. In what order will <code>m_header.valid()</code> be called? When will <code>m_opened = true</code> be set? There are many combinations, there's at least one where <code>m_opened()</code> will be set to <code>true</code> and the function will return <code>true</code>, but the values in <code>m_header</code> will be garbage.</p>\n<p>Either always lock the mutex when doing anything with member variables, or don't have any mutex in your class and leave it up to the callers to handle concurrent access.</p>\n<h1>Do you really need to cache yourself?</h1>\n<blockquote>\n<p>The general purpose of the library is to read WAVE files into floating points, in a way that handles repeated sequential requests for audio data without hanging on disk reads.</p>\n</blockquote>\n<p>Virtually all operating systems that you run on desktop computers and servers already have sophisticated cache mechanisms to handle repeated access to the same data on disks. So you are duplicating what the OS already does for you.</p>\n<p>If you do lots of small reads, then there is some virtue in doing caching in your code, because it will avoid the overhead of system calls. However, if this is a concern, then it is probably even better to use <a href=\"https://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"noreferrer\">memory-mapping</a> to map the whole WAV file into memory.</p>\n<h1>Avoid repetition</h1>\n<p>Whenever you are repeating the same thing twice or more times, you should immediately start to find some way to avoid the repetition. This can be done by using <code>for</code>-loops or creating functions, or perhaps reorganizing the code a bit.</p>\n<p>In <code>audio()</code>, there are three cases being handled separately, but I think this can be simplified by first checking how much data has to be loaded in the cache, then convert <code>startSample</code> into the correct offset into the cache, and once that is done, you can do a single <code>return samples(...)</code> statement:</p>\n<pre><code>std::vector<float> audio(...) {\n ...\n size_t offset;\n bool load_ok;\n\n if (/* out of bounds */) {\n load_ok = load(startSample_ch_bit, m_header.m_40_dataSubchunkSize - startSample_ch_bit);\n offset = 0;\n } else if (/* within cache */) {\n load_ok = true; // Everything has already been loaded\n offset = startSample_ch_bit - m_cachePos;\n } else /* within file, outside cache */ {\n load_ok = load(startSample_ch_bit, m_cacheSize > sampleCount_ch_bit ? m_cacheSize : sampleCount_ch_bit));\n offset = 0;\n }\n\n if (load_ok)\n return samples(offset, sampleCount_ch_bit, channels, stride, interleaved);\n else\n return {};\n}\n</code></pre>\n<p>In <code>samples()</code>, you have a lot of repetition handling the different sample formats. Try to create a generic function that can convert arbitrarily sized integers. Let the compiler worry about optimizing it. Then just write the code to handle the different ways of channel interleaving. For example:</p>\n<pre><code>static float convert_sample(const uint8_t *data, size_t len) {\n // Initialize a 32-bit integer with ones or zero bits,\n // depending on whether we need to sign-extend the input data\n int32_t value;\n\n if (len > 1 && data[len - 1] & 0x80)\n value = -1;\n else\n value = 0;\n \n // Copy the input data into value, assuming everything is little-endian \n memcpy(&value, data, len);\n\n // Return it as a float scaled between -1.0 and 1.0\n return static_cast<float>(value) / (1 << (len * 8 - 1)) - (len > 1 ? 0 : 0.5);\n}\n\n...\n\nstd::vector<float> samples() {\n ...\n const size_t sample_len = header.m_34_bitsPerSample / 8);\n\n if (interleaved) {\n for (size_t i{ posInCache }; ...) {\n for (auto ch: channels) {\n size_t cho{...}; \n result.emplace_back(convert_sample(&m_data[i + cho], sample_len);\n }\n }\n } else {\n for (auto ch: channels) {\n for (size_t i{ posInCache }; ...) {\n size_t cho{...}; \n result.emplace_back(convert_sample(&m_data[i + cho], sample_len);\n }\n }\n }\n \n return result;\n}\n</code></pre>\n<h1>Avoid unnecessary floating point math</h1>\n<p>Don't write <code>(size_t)(m_cacheSize * 0.5)</code>, write <code>m_cacheSize / 2</code>. The answer should be the same, and if it isn't, it's because on 64-bit machines, a <code>double</code> has less precision than a <code>size_t</code>, and with large enough values this will become noticable. Also, it's quite costly to convert an integer to a <code>double</code> and back; not only do you waste some CPU cycles converting between the two, it might cause an interrupt where the operating system has to restore the FPU state after a lazy FPU context switch (not really an issue in your code since you already convert samples to <code>float</code> in <code>samples()</code>, but just so you know).</p>\n<h1>Don't create throwaway threads</h1>\n<p>I was wondering why you needed locking at all, but then I spotted this in <code>audio()</code>:</p>\n<pre><code>std::thread extendBuffer{ &Waveread::load,this,m_cachePos + (size_t)(m_cacheSize * 0.5), m_cacheSize };\nextendBuffer.detach();\n</code></pre>\n<p>You are creating threads here, but don't care what they are doing and detaching them immediately. But what if I am calling <code>audio()</code> in quick succession, with <code>startSample()</code> wildly varying at each call? Maybe there are two threads that want to read audio from different places, and they each call <code>load()</code> in turn? If reading data from disk was really so slow that you need the caching, then this will potentially create a large amount of threads that are slowing down the system, and potentially causing the wrong data being in the cache at the time it will be used. It is in fact possible that you create a thread to extend the buffer, but it will not start immediately, and then immediately there is another call to <code>audio()</code>, which will hit case 1 or case 3, which will call <code>load()</code>, and then between that call to <code>load()</code> and the call to <code>samples()</code>, the background thread will execute its <code>load()</code>. That means <code>samples()</code> will read from the wrong data.</p>\n<p>It's hard to reason about threads you no longer have any control over. I would just trust the operating system, it already performs caching for you, and will likely read ahead for you as well.</p>\n<h1>Avoid using a <code>std::set</code> for <code>channels</code></h1>\n<p>A <code>std::set</code> is quite an expensive data structure to use to pass the desired <code>channels</code> to <code>audio()</code>: it allocates memory on the heap and builds a balanced tree of nodes. Furthermore, you pass it by value so a copy has to be made. A better datastructure would be a <a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"noreferrer\"><code>std::bitset</code></a>, but unfortunately it needs to know its size up front, and since WAV files support up to 65535 channels, that is not great. Another option would be a <a href=\"https://en.cppreference.com/w/cpp/container/vector_bool\" rel=\"noreferrer\"><code>std::vector<bool></code></a>. Be sure to pass these structures by <code>const</code> reference:</p>\n<pre><code>std::vector<float> audio(\n size_t startSample, \n size_t sampleCount, \n const std::vector<bool> &channels = {true, true},\n size_t stride = 0u, \n bool interleaved = true\n) {\n ...\n}\n</code></pre>\n<p>To iterate over them, you would do something like:</p>\n<pre><code>for (size_t ch = 0; ch < channels.size(); ++ch) {\n if (channels[ch]) {\n size_t cho{ (ch % ...) };\n ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T20:53:36.667",
"Id": "491466",
"Score": "1",
"body": "Very nice review! having a competition in the monthly ranks xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:40:04.250",
"Id": "493288",
"Score": "0",
"body": "Thank you this is really good stuff. The most humbling thing is realising that the OS does probably make caching redundant. I'll benchmark and then implement the advice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T20:03:10.020",
"Id": "250482",
"ParentId": "250440",
"Score": "5"
}
},
{
"body": "<p><strong><code>WAV_HEADER</code>:</strong></p>\n<pre><code>bool read(std::istream& s)\n{\n if (s.good())\n {\n s.seekg(0u);\n s.read(&m_0_headerChunkID[0], 4);\n s.read((char*)&m_4_chunkSize, 4);\n s.read(&m_8_format[0], 4);\n s.read(&m_12_subchunk1ID[0], 4);\n s.read((char*)&m_16_subchunk1Size, 4);\n s.read((char*)&m_20_audioFormat, 2);\n s.read((char*)&m_22_numChannels, 2);\n s.read((char*)&m_24_sampleRate, 4);\n s.read((char*)&m_28_byteRate, 4);\n s.read((char*)&m_32_bytesPerBlock, 2);\n s.read((char*)&m_34_bitsPerSample, 2);\n s.read(&m_36_dataSubchunkID[0], 4);\n s.read((char*)&m_40_dataSubchunkSize, 4);\n }\n return s.good();\n}\n</code></pre>\n<p>Hmm. It would be more conventional to make this an <code>istream& operator>>(istream&, WAV_HEADER& header);</code></p>\n<p>I don't think we need to check if the stream is <code>good()</code> before reading. We just do the read, and let the stream handle the errors (it'll set failbit or throw if necessary).</p>\n<p>Seeking to the start of the stream inside this function may cause problems in some cases (e.g. a wave file embedded in a larger file). It is probably better to require that the input stream is positioned at the start of the wave format when passed in to the reader.</p>\n<hr />\n<pre><code>void clear() { ... }\n</code></pre>\n<p>This should probably just be the class constructor.</p>\n<hr />\n<p><strong><code>Waveread</code>:</strong></p>\n<pre><code>Waveread(\n std::unique_ptr<std::istream>&& stream,\n size_t cacheSize = 1048576u,\n double cacheExtensionThreshold = 0.5\n)\n :\n m_stream{ stream.release() },\n m_header{},\n m_data{},\n m_dataMutex{},\n m_cachePos{ 0u },\n m_opened{ false },\n m_cacheSize{ cacheSize }, // 1MB == 1048576u\n m_cacheExtensionThreshold{ cacheExtensionThreshold }\n{\n if (m_cacheExtensionThreshold < 0.0)\n m_cacheExtensionThreshold = 0.0;\n else if (m_cacheExtensionThreshold > 1.0)\n m_cacheExtensionThreshold = 1.0;\n\n m_header.clear();\n}\n</code></pre>\n<p>While it might be safer to take the stream as a <code>unique_ptr</code>, it is a fiddle for the user compared to taking a reference to the stream. (Either is fine... just something to consider).</p>\n<p>We could take the <code>std::unique_ptr<></code> by value (there's no need to require the r-value reference) and <code>std::move</code> it into <code>m_stream</code>. (These are really just semantic differences though).</p>\n<p>With C++17 we can do <code>m_cacheExtensionThreshold{ std::clamp(cacheExtensionThreshold, 0.0, 1.0) }</code>. Without it, we might define our own <code>clamp</code> utility function for neatness.</p>\n<p>Having to call <code>m_header.clear()</code> here as a separate step again suggests making it the <code>WAV_HEADER</code> constructor.</p>\n<hr />\n<pre><code>Waveread(Waveread&& other) noexcept\n</code></pre>\n<p>Consider supporting move assignment, since we have move construction.</p>\n<hr />\n<pre><code>void reset(std::unique_ptr<std::istream>&& stream)\n</code></pre>\n<p>If we support move assignment, we don't need this function, as we could do something like: <code>oldWaveRead = Waveread(std::move(newStream));</code></p>\n<hr />\n<pre><code>bool open()\n{\n if (!m_opened)\n {\n m_header.read(*m_stream.operator->());\n if (m_header.valid())\n {\n m_opened = true;\n load(0u, m_cacheSize);\n return true;\n }\n else\n return false; // we couldn't open it\n }\n return true; // we didn't open it, but it was already opened.\n}\n</code></pre>\n<p>Returning as early as possible may make code like this easier to read, since the <code>if</code> branches end immediately, and we don't need the <code>else</code> clauses:</p>\n<pre><code>bool open()\n{\n if (m_opened)\n return true; // already open\n \n m_header.read(*m_stream.operator->());\n\n if (!m_header.valid())\n return false; // couldn't open it\n \n m_opened = true;\n load(0u, m_cacheSize);\n\n return true;\n}\n</code></pre>\n<hr />\n<pre><code>const size_t& cacheSize() const { return m_cacheSize; }\n//! Get start position of cache\nconst size_t& cachePos() const { return m_cachePos; }\n//! Has the file been opened\nconst bool& opened() const { return m_opened; }\n//! Get cache extension threshold: this is the fraction of the cache that is read before it is extended.\nconst double& cacheExtensionThreshold() const { return m_cacheExtensionThreshold; }\n</code></pre>\n<p>It is likely faster (and a little safer) to return these POD types by value, instead of by reference.</p>\n<hr />\n<pre><code>void setCacheExtensionThreshold(const double& cacheExtensionThreshold)\nvoid setCacheSize(const size_t& csize)\n</code></pre>\n<p>Similarly, these arguments should be passed by value.</p>\n<hr />\n<p>Unfortunately I don't have time to continue for now...</p>\n<p>Overall I think it would be neater if the caching of the data were entirely separate from the processing of the wave file format. Perhaps we could have some sort of <code>istream_caching_iterator{ stream, cache_size };</code> that reads from the stream into a buffer. Then the wave reader requests the data it needs to, when it needs it, without caring about the buffering itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T20:39:23.817",
"Id": "250484",
"ParentId": "250440",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T18:51:04.073",
"Id": "250440",
"Score": "5",
"Tags": [
"c++",
"c++11",
"library",
"audio"
],
"Title": "C++ WAVE file reader: library-like structure, safety, readability"
}
|
250440
|
<p>I apologize for the title, really didn't know what to call this program. In short, the program takes a file of values for the various atoms of amino acids, and then searches this file based on user input. I'm basically looking for any input on how to improve my script. I have a bad habit of using nested loops, splitting all the time, and poor naming. So any type of feedback on my code would be highly appreciated!</p>
<p>The file is a csv file that contains various information:</p>
<pre><code>comp_id,atom_id,count,min,max,avg,std
ALA,H,86795,-0.914,69.229,8.193,0.641,488
ALA,HA,58922,-2.52,17.870,4.244,0.443,1135
ALA,MB,56709,-14.040,5.48,1.352,0.280,1024
ALA,C,55999,0.037,187.2,177.728,3.776,40
ALA,CA,76797,17.007,354.698,53.166,2.773,88
ALA,CB,72862,-40.993,318.868,19.052,3.066,200
ALA,N,82913,0.049,766,123.353,6.027,93
ARG,H,57814,0.011,178,8.241,1.052,36
ARG,HA,40349,1.212,12.57,4.289,0.469,471
....
VAL,CG2,43052,-5.648,320.420,21.346,2.531,92
VAL,N,75697,0.2,529,121.146,7.361,82
</code></pre>
<p>There are various amino acids (e.g. ALA, ARG, VAL), each has various different types of atoms (N,HA,CA,etc.). What I care about however is purely the Carbon atoms, and their attached Hydrogen (e.g. CA and HA,CB and MB, etc.). Specifically, the avg and std values (e.g. 8.193 and 0.641). The user can input their own carbon and hydrogen values, to see what amino acid it matches up with. Think of it as coordinates, you put in the latitude and longitude values, and it gives you the location. Since the 2 go together, both the Carbon <em>and</em> Hydrogen must match to get a printout (again, like latitude and longitude). So practice example:</p>
<pre><code>#user inputs 52 and 4, they get a printout
ALA CA 53.166 2.773 ALA HA 4.244 0.443
</code></pre>
<p>Since 52 falls within 53.166+/-2.77 and 4 falls within 4.244+/-0.443, these coordinates designate ALA.<br />
I've also added an additional 'High error' printout. Sometimes you get a match because the error is so high, it has a massive range. For these values, the range probably doesn't mean too much (still valuable info, but wanted the user to know if they got a match due to a high std). I chose 25% of the average as the definition for high error.</p>
<p>Finally, thought I'd also mention this since you might notice in my script there is a specific conditional on 'VALN'. This was because the way I determine if you move on to another amino acid, is by checking the current looped value, by the previous. However, when you reach the end of the file, the current will be the same as the end value (and subsequently, that amino acids lists will not get checked/printed). This is my "hackish" way of resolving this issue.</p>
<p>This is what I came up with:</p>
<pre><code>
def search_fun(carbon,hydrogen):
"""
This will go through each amino acid, and check its carbon and hydrogen coordinates.
If they are within the user inputed range, it will store these in the lists.
Upon completing an amino acid, it will then go through all the matches, and print them out accordingly"""
residue_list=[]
carbon_list=[]
hydrogen_list=[]
with open('bmrb.csv') as file:
for lines in file:
if lines == '\n':
continue
split_lines=lines.split(',')
residue=split_lines[0]
if residue == 'comp_id':
continue
residue_list.append(residue)
atom=split_lines[1]
chemical_shift=float(split_lines[5])
std=float(split_lines[6])
lower_half=chemical_shift-std
upper_half=chemical_shift+std
if residue_list[0] != residue or (residue+atom) == 'VALN':
if len(carbon_list) >= 1 and len(hydrogen_list) >= 1:
for values in carbon_list:
split_carbon=values.split()
for values2 in hydrogen_list:
split_hydrogen=values2.split()
if split_hydrogen[1][1] == split_carbon[1][1]:
if float(split_carbon[3]) > (0.25*float(split_carbon[2])) or float(split_hydrogen[3]) > (0.25*float(split_hydrogen[2])):
print(f'{values} {values2} HIGH ERROR')
else:
print(values,values2)
carbon_list.clear()
hydrogen_list.clear()
else:
carbon_list.clear()
hydrogen_list.clear()
residue_list.clear()
residue_list.append(residue)
if carbon>lower_half and carbon<upper_half:
carbon_list.append(f'{residue} {atom} {chemical_shift} {std}')
if hydrogen>lower_half and hydrogen<upper_half:
hydrogen_list.append(f'{residue} {atom} {chemical_shift} {std}')
def main_loop():
while True:
question=input('input carbon and hydrogen values: ')
split_question=question.split()
search_fun(float(split_question[0]),float(split_question[1]))
print('\n\n\n')
main_loop()
</code></pre>
<p>This is a test run of the output you should get using the above code and below csv file:</p>
<pre><code>input carbon and hydrogen values: 42 3.2
ARG CD 43.201 2.938 ARG HD2 3.107 0.266
ARG CD 43.201 2.938 ARG HD3 3.091 0.285
ASP CB 40.895 2.563 ASP HB2 2.716 0.511
PHE CB 39.955 3.611 PHE HB2 2.992 0.381
PHE CB 39.955 3.611 PHE HB3 2.934 0.399
TYR CB 39.307 3.133 TYR HB2 2.898 0.466
TYR CB 39.307 3.133 TYR HB3 2.833 0.483
</code></pre>
<p>Here is the entire csv file:</p>
<pre><code>
comp_id,atom_id,count,min,max,avg,std
ALA,H,86795,-0.914,69.229,8.193,0.641,488
ALA,HA,58922,-2.52,17.870,4.244,0.443,1135
ALA,MB,56709,-14.040,5.48,1.352,0.280,1024
ALA,C,55999,0.037,187.2,177.728,3.776,40
ALA,CA,76797,17.007,354.698,53.166,2.773,88
ALA,CB,72862,-40.993,318.868,19.052,3.066,200
ALA,N,82913,0.049,766,123.353,6.027,93
ARG,H,57814,0.011,178,8.241,1.052,36
ARG,HA,40349,1.212,12.57,4.289,0.469,471
ARG,HB2,36605,-4.78,27.530,1.790,0.310,470
ARG,HB3,34641,-1.320,27.530,1.759,0.322,500
ARG,HD2,32127,-6.44,5.0,3.107,0.266,638
ARG,HD3,29287,-0.690,5.0,3.091,0.285,615
ARG,HE,10898,1.150,116.661,7.450,2.838,7
ARG,HG2,32714,-1.45,4.2,1.559,0.284,597
ARG,HG3,30376,-1.298,5.47,1.539,0.298,621
ARG,HH11,971,4.41,11.7,6.938,0.576,22
ARG,HH12,740,4.41,10.727,6.881,0.543,17
ARG,HH21,833,1.233,11.352,6.825,0.652,19
ARG,HH22,685,1.233,60.1410,6.905,2.136,1
ARG,C,35275,0.174,184.96,176.415,3.365,13
ARG,CA,49856,8.369,358.124,56.782,3.345,57
ARG,CB,46468,16.52,329.120,30.695,2.515,125
ARG,CD,27783,18.9350,342.642,43.201,2.938,46
ARG,CG,27535,12.17,328.290,27.260,3.041,42
ARG,CZ,743,43.199,184.497,160.136,7.440,8
ARG,N,53676,0.125,433.808,120.816,4.763,83
ARG,NE,6869,-23.150,149.1080,90.097,13.747,53
ARG,NH1,283,6.450,124.7890,78.516,13.368,6
ARG,NH2,248,66.2,128.470,78.360,13.933,7
ASN,H,47608,0.008,121.370,8.331,0.974,128
ASN,HA,33194,0.896,7.110,4.661,0.362,460
ASN,HB2,31112,-0.827,8.883,2.800,0.335,492
ASN,HB3,30047,-0.948,5.806,2.742,0.359,506
ASN,HD21,23425,0.783,111.320,7.337,0.850,48
ASN,HD22,23159,0.905,111.320,7.144,0.867,109
ASN,C,29727,0.114,185.3000,175.215,3.563,17
ASN,CA,41894,2.200,354.022,53.547,3.517,28
ASN,CB,39745,1.9620,342.798,38.727,3.598,45
ASN,CG,2689,0.000,185.503,176.229,8.760,11
ASN,N,44735,0.041,426.314,118.930,5.122,29
ASN,ND2,20306,21.038,1114.29,112.908,12.638,11
ASP,H,68763,-0.35,25.876,8.300,0.590,571
ASP,HA,46632,-3.75,8.66,4.585,0.327,680
ASP,HB2,43472,-5.2,37.4,2.716,0.511,75
ASP,HB3,41794,-1.46,37.2,2.667,0.518,100
ASP,HD2,18,1.160,12.30,5.991,3.334,0
ASP,C,43696,0.106,184.14,176.361,3.568,24
ASP,CA,60457,5.630,354.531,54.690,2.720,67
ASP,CB,57295,9.7,341.273,40.895,2.563,146
ASP,CG,963,2.637,188.215,177.196,18.089,13
ASP,N,66001,0.061,428.093,120.699,4.642,95
CYS,H,23821,3.723,12.660,8.380,0.695,148
CYS,HA,19401,-9.858,43.5,4.680,0.976,58
CYS,HB2,18672,-39.82,363.580,3.134,6.357,41
CYS,HB3,18201,-44.2,363.580,3.055,5.762,43
CYS,HG,254,-1.830,10.700,2.029,1.353,4
CYS,C,11404,1.000,187.591,174.775,3.469,10
CYS,CA,17149,30.6688,82.3,58.022,3.462,20
CYS,CB,16356,17.99,73.920,33.377,6.523,18
CYS,N,18895,-147,628,120.438,18.215,82
GLN,H,48881,0.000,66.542,8.216,0.653,231
GLN,HA,33387,0.403,7.43,4.264,0.432,551
GLN,HB2,30357,-1.514,10.461,2.043,0.276,415
GLN,HB3,28935,-1.4980,20.9,2.013,0.326,349
GLN,HE21,21428,-3.41,23.893,7.219,0.497,188
GLN,HE22,21310,1.025,113.695,7.036,0.879,29
GLN,HG2,28356,-1.76,33.5990,2.314,0.338,327
GLN,HG3,26350,-1.395,34.946,2.293,0.361,357
GLN,C,31356,0.069,1755.998,176.338,9.609,13
GLN,CA,43483,1.733,356.830,56.562,2.640,46
GLN,CB,40787,1.843,328.286,29.194,2.533,126
GLN,CD,2616,6.789,190.624,179.292,7.623,7
GLN,CG,25210,2.097,333.032,33.807,2.562,41
GLN,N,46869,0.000,418.059,119.962,4.176,126
GLN,NE2,19322,33.9,412.160,111.882,2.985,60
GLU,H,89195,0.008,122.9,8.330,0.743,322
GLU,HA,60909,0.433,8.02,4.242,0.413,1077
GLU,HB2,55127,-1.470,4.82,2.018,0.222,781
GLU,HB3,51907,-1.633,8.095,1.994,0.228,751
GLU,HE2,18,0.801,11.96,4.709,2.604,0
GLU,HG2,50906,-0.674,4.69,2.264,0.222,837
GLU,HG3,47453,-0.10,4.69,2.245,0.224,767
GLU,C,57652,0.074,184.71,176.828,4.280,40
GLU,CA,78638,1.056,360.826,57.327,3.270,75
GLU,CB,73549,9.08,330.834,30.019,3.150,117
GLU,CD,1013,0.000,198.609,181.090,14.839,8
GLU,CG,45672,6.16,337.230,36.143,2.948,64
GLU,N,85881,0.044,422.043,120.721,4.689,112
GLY,H,86072,-15.3,121.881,8.327,0.765,735
GLY,HA2,58056,-3.4,8.64,3.961,0.399,937
GLY,HA3,55297,-3.936,43.9930,3.888,0.439,773
GLY,C,54280,1.000,189.533,173.834,3.426,55
GLY,CA,76239,2.200,344.994,45.377,2.219,169
GLY,N,81099,0.2,791,109.680,7.053,192
HIS,H,24445,-0.3,13.34,8.256,0.733,261
HIS,HA,17566,0.676,11.38,4.617,0.565,230
HIS,HB2,16391,-2.168,45.897,3.159,1.118,129
HIS,HB3,15940,-6.2,38.5,3.100,1.087,138
HIS,HD1,1018,-15,86.5,9.987,8.570,23
HIS,HD2,11621,-25.85,67.8,7.148,3.262,90
HIS,HE1,9143,-26.6,134.811,7.831,2.535,63
HIS,HE2,388,-15,76.4,11.107,7.896,11
HIS,C,15093,1.000,184.204,175.133,4.716,15
HIS,CA,21851,11.40,355.084,56.521,3.407,62
HIS,CB,20513,13.496,329.046,30.324,3.186,56
HIS,CD2,7547,7.19,159.946,119.910,5.680,49
HIS,CE1,5913,8.198,166.282,137.244,5.712,55
HIS,CG,270,18.669,139.83,131.179,9.513,3
HIS,N,22875,0.2,427.146,119.658,5.239,41
HIS,ND1,816,31.026,261.013,193.109,32.573,2
HIS,NE2,754,17.0,257.572,180.840,20.342,20
ILE,H,59946,0.008,11.871,8.264,0.692,293
ILE,HA,41048,-9.0,173.538,4.167,1.009,7
ILE,HB,38633,-2.442,38.700,1.783,0.399,210
ILE,HG12,35114,-10.1,5.56,1.263,0.453,270
ILE,HG13,33779,-10.1,9.71,1.192,0.485,250
ILE,MD,38936,-4.15,13.891,0.671,0.332,621
ILE,MG,36922,-3.919,6.23,0.768,0.306,577
ILE,C,38288,0,187.551,175.800,4.524,29
ILE,CA,53038,20.877,362.184,61.623,3.359,62
ILE,CB,49504,-34.477,339.785,38.583,2.926,83
ILE,CD1,35029,2.7,314.600,13.505,3.480,110
ILE,CG1,31261,8.0,329.288,27.757,3.344,137
ILE,CG2,33140,0.79,317.615,17.608,3.243,97
ILE,N,57362,0.0000,531,121.425,6.042,89
LEU,H,99282,-0.3,13.220,8.219,0.651,501
LEU,HA,67703,0.000,119.411,4.303,0.644,70
LEU,HB2,62221,-1.522,8.02,1.607,0.360,803
LEU,HB3,59729,-1.79,8.39,1.523,0.376,865
LEU,HG,55123,-2.08,5.7,1.502,0.348,672
LEU,MD1,63101,-3.42,30.176,0.748,0.331,965
LEU,MD2,60780,-3.42,24.504,0.727,0.358,774
LEU,C,63540,0.071,189.78,176.991,3.682,29
LEU,CA,87816,1.056,158.320,55.653,2.236,189
LEU,CB,82155,7.439,93.180,42.248,2.020,527
LEU,CD1,54890,0.683,120.700,24.674,2.047,209
LEU,CD2,52489,0.280,116.300,24.119,2.125,161
LEU,CG,48288,0.000,75.280,26.805,1.494,354
LEU,N,94665,0.044,627,121.959,7.753,70
LYS,H,84117,0.002,64.423,8.175,0.668,498
LYS,HA,58613,-0.118,32.650,4.258,0.457,643
LYS,HB2,52752,-1.416,10.94,1.774,0.266,854
LYS,HB3,49716,-3.038,9.43,1.746,0.283,821
LYS,HD2,42396,-1.6800,119.620,1.607,0.643,29
LYS,HD3,38017,-2.02,29.047,1.595,0.272,557
LYS,HE2,41666,-0.493,42.02,2.911,0.289,457
LYS,HE3,36694,-0.046,7.344,2.903,0.223,782
LYS,HG2,47718,-1.654,6.7,1.363,0.272,978
LYS,HG3,44019,-1.83,5.575,1.348,0.283,923
LYS,C,51474,0.112,996.253,176.614,5.736,38
LYS,CA,71777,1.155,359.222,56.949,3.205,71
LYS,CB,67058,-26.686,332.988,32.791,2.923,94
LYS,CD,38624,0.834,329.284,28.997,2.640,75
LYS,CE,37258,-0.130,342.334,41.926,3.045,68
LYS,CG,40990,12.109,325.487,24.960,3.133,95
LYS,N,78570,0.041,427.245,121.038,4.691,124
LYS,NZ,303,1.950,177.2,51.816,33.019,2
LYS,QZ,1617,-10.9,10.506,7.339,1.046,44
MET,H,23446,-0.21,177,8.257,1.261,15
MET,HA,16662,-0.93,313.565,4.410,2.443,1
MET,HB2,14928,-27.312,33.750,2.024,0.583,84
MET,HB3,14085,-27.312,12.94,1.995,0.522,104
MET,HG2,13710,-33.86,32.7,2.376,1.463,44
MET,HG3,12981,-33.86,31.7,2.350,1.575,48
MET,ME,10583,-24.86,10.2000,1.773,1.563,79
MET,C,15432,2.200,183.25,176.200,3.324,5
MET,CA,21816,25.7283,85.327,56.149,2.289,59
MET,CB,20187,0.2,332.173,32.973,3.219,49
MET,CE,9592,0.000,317.645,17.254,4.252,53
MET,CG,11803,2.30,332.686,32.077,3.243,28
MET,N,22664,0.000,428.252,120.054,4.996,36
PHE,H,42717,-0.5,12.1759,8.337,0.731,262
PHE,HA,28990,1.33,59.70,4.618,0.727,23
PHE,HB2,27036,-0.463,7.979,2.992,0.381,371
PHE,HB3,26376,-0.212,12.72,2.934,0.399,389
PHE,HD1,22740,0.603,12.154,7.037,0.399,217
PHE,HD2,19220,0.603,12.154,7.038,0.412,194
PHE,HE1,19877,-2.838,14.080,7.062,0.453,167
PHE,HE2,16994,0,12.9,7.060,0.448,158
PHE,HZ,13928,-7.14,43.623,6.993,0.719,115
PHE,C,26768,0.088,184.929,175.449,3.069,9
PHE,CA,37271,4.917,363.618,58.107,3.822,36
PHE,CB,34997,2.161,341.700,39.955,3.611,44
PHE,CD1,13641,7.160,143.4500,131.172,5.998,70
PHE,CD2,9678,7.160,140.309,131.324,4.575,35
PHE,CE1,11887,0.000,149.609,130.316,5.835,61
PHE,CE2,8420,7.472,149.609,130.527,4.030,35
PHE,CG,421,7.229,152.844,137.247,11.620,4
PHE,CZ,8840,7.351,165.611,129.016,4.185,31
PHE,N,40480,0.067,422.843,120.393,5.461,51
PRO,H2,5,8.070,9.673,8.756,0.710,0
PRO,HA,33161,0.636,135.80,4.388,0.803,43
PRO,HB2,30818,-1.501,5.63,2.069,0.371,536
PRO,HB3,29932,-3.48,6.10,1.996,0.382,558
PRO,HD2,28519,-6.56,7.67,3.636,0.447,423
PRO,HD3,27539,-6.56,8.865,3.602,0.469,496
PRO,HG2,27730,-2.35,7.395,1.918,0.342,667
PRO,HG3,25811,-1.520,4.92,1.894,0.351,627
PRO,C,28640,0,183.517,176.630,4.386,30
PRO,CA,41044,0,363.087,63.330,3.613,80
PRO,CB,38296,0,333.586,31.887,3.162,71
PRO,CD,25032,1.155,350.648,50.343,3.214,61
PRO,CG,24932,2.436,327.402,27.277,3.727,44
PRO,N,2050,3.566,430,134.575,24.897,37
SER,H,72252,-15.3,116.95709,8.278,0.723,290
SER,HA,50558,1.277,58.739,4.477,0.475,421
SER,HB2,46319,0.61,9.182,3.867,0.278,725
SER,HB3,43053,0.61,41.7,3.843,0.343,503
SER,HG,924,0.13,11.36,5.422,1.193,23
SER,C,46531,0.000,197.1,174.589,3.254,32
SER,CA,65467,4.331,361.278,58.694,2.805,70
SER,CB,60788,-939.2800,365.087,63.723,4.984,170
SER,N,68552,0.000,416.964,116.292,4.253,189
THR,H,64336,0.02,21.7,8.233,0.640,534
THR,HA,44303,0.87,7.468,4.451,0.479,264
THR,HB,40659,0.087,71.587,4.168,0.655,78
THR,HG1,1629,-1.783,11.01,5.212,1.402,39
THR,MG,40565,-12.1,16.3,1.138,0.279,510
THR,C,40395,4.780,185.918,174.456,4.070,35
THR,CA,56552,0.971,92.659,62.210,2.759,104
THR,CB,52562,-939.2800,629.206,69.590,5.649,162
THR,CG2,34435,7.177,175.6,21.595,1.917,112
THR,N,61259,0.0,402,115.403,6.323,64
TRP,H,14089,3.421,17.315,8.269,0.781,92
TRP,HA,9794,2.043,11.414,4.678,0.534,77
TRP,HB2,9273,0.42,5.35,3.179,0.350,143
TRP,HB3,9017,-0.3776,7.972,3.116,0.372,137
TRP,HD1,8273,1.880,10.75,7.128,0.363,126
TRP,HE1,9199,-1.279,131.711,10.094,1.445,37
TRP,HE3,7185,1.85,12.233,7.299,0.525,128
TRP,HH2,7126,2.84,10.900,6.952,0.455,111
TRP,HZ2,7765,2.63,10.81,7.267,0.412,115
TRP,HZ3,6927,0.76,8.898,6.848,0.472,92
TRP,C,8460,2.500,184.30,175.973,6.049,12
TRP,CA,11894,2.966,362.099,57.713,4.800,12
TRP,CB,11102,1.6,328.795,30.089,4.784,23
TRP,CD1,5274,30.236,183.141,126.325,4.470,23
TRP,CD2,188,1.578,155.174,127.130,13.071,2
TRP,CE2,248,56.4176,177.710,137.535,9.569,6
TRP,CE3,4409,-10.872,174.807,120.173,5.545,29
TRP,CG,259,4.174,116.526,110.100,9.006,2
TRP,CH2,4655,-6.333,160.818,123.539,5.024,22
TRP,CZ2,5025,7.107,159.041,114.037,4.609,30
TRP,CZ3,4434,-8.702,161.540,121.151,4.660,22
TRP,N,12864,6.712,423.160,121.648,6.026,13
TRP,NE1,7540,0.53,435.960,129.269,6.295,31
TYR,H,36554,0.02,12.34,8.294,0.739,180
TYR,HA,25016,0.442,7.160,4.609,0.563,203
TYR,HB2,23316,-21.230,23.28,2.898,0.466,195
TYR,HB3,22790,-21.230,23.28,2.833,0.483,237
TYR,HD1,20167,0.190,10.5,6.920,0.373,237
TYR,HD2,17229,0.5522,10.499,6.916,0.377,211
TYR,HE1,19125,0.08,11.8,6.690,0.309,160
TYR,HE2,16443,0.43,11.7,6.690,0.320,147
TYR,HH,442,-0.788,31,9.103,2.096,5
TYR,C,22274,2.200,184.78,175.368,4.700,22
TYR,CA,31109,2.200,357.681,58.144,3.099,25
TYR,CB,28911,18.38,338.686,39.307,3.133,43
TYR,CD1,12301,19.589,141.572,132.361,5.290,65
TYR,CD2,8449,3.492,139.644,132.362,5.325,48
TYR,CE1,12085,40.435,182.764,117.730,4.101,109
TYR,CE2,8324,34.1221,154.10,117.772,3.349,68
TYR,CG,390,7.113,175.115,128.143,12.323,6
TYR,CZ,287,6.839,165.718,155.511,13.729,3
TYR,N,34074,0.2,818,120.749,11.899,35
VAL,H,78671,-0.41,120.980,8.271,0.790,168
VAL,HA,53950,-2.83,54.971,4.168,0.629,126
VAL,HB,50358,-27.480,31.75,1.979,0.450,389
VAL,MG1,50627,-27.2,24.20,0.819,0.333,562
VAL,MG2,49730,-27.2,56.56,0.801,0.431,245
VAL,C,50693,1,205.699,175.631,3.413,28
VAL,CA,69771,20.668,362.057,62.496,3.197,101
VAL,CB,64788,15.597025,331.747,32.716,2.289,140
VAL,CG1,44602,-7.4,321.185,21.547,2.434,90
VAL,CG2,43052,-5.648,320.420,21.346,2.531,92
VAL,N,75697,0.2,529,121.146,7.361,82
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T00:40:49.010",
"Id": "491390",
"Score": "0",
"body": "There are 7 column names, but 8 columns of data, is that intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T01:32:31.083",
"Id": "491391",
"Score": "0",
"body": "@AMC I have no idea what that last column is. I didn't make the csv file, I downloaded that online from a site. But it doesn't effect the my script either way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:27:05.927",
"Id": "492829",
"Score": "0",
"body": "consider accepting an answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T02:24:31.613",
"Id": "492859",
"Score": "0",
"body": "@AryanParekh sorry completely forgot"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:59:21.360",
"Id": "493049",
"Score": "0",
"body": "Use Pandas. It's made for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T00:11:47.597",
"Id": "493206",
"Score": "0",
"body": "@Reinderien isn't pandas a bit overkill for this? I'm also not too familiar with pandas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T00:17:56.763",
"Id": "493207",
"Score": "0",
"body": "No; it's definitely not overkill. It's free, open-source, popular, well-documented and (within reason) performs well. Perhaps more importantly, it will make your code shorter and more legible."
}
] |
[
{
"body": "<h1>Simplify code!</h1>\n<ul>\n<li><code>with open('bmrb.csv') as file:</code> followed by <code>for lines in file:</code> can be simplified into\n<code>for lines in open("bmrb.csv").readlines():</code></li>\n<li>with the change above you can completely remove <code>if (lines == '\\n')</code> clause</li>\n</ul>\n<h1>Use <code>Enum</code> for clarity</h1>\n<p><code>split_lines[0]</code>, <code>split_lines[1]</code>. 0 and 1 are called <a href=\"https://help.semmle.com/wiki/display/CCPPOBJ/Magic+numbers#:%7E:text=A%20magic%20number%20is%20a,using%20the%20named%20constants%20instead.\" rel=\"nofollow noreferrer\"><strong>magic numbers</strong></a>.</p>\n<blockquote>\n<p>A magic number is a numeric literal (for example, 8080, 2048) that is used in the middle of a block of code without explanation. It is considered good practice to avoid magic numbers by assigning the numbers to named constants and using the named constants instead.</p>\n</blockquote>\n<p>Instead what if you made an <code>Enum</code> called <code>Data</code> and named those constants?<br>\n<a href=\"https://www.tutorialspoint.com/enum-in-python#:%7E:text=Enum%20is%20a%20class%20in,enum%20has%20the%20following%20characteristics.\" rel=\"nofollow noreferrer\">Enums in Python</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\nclass Data(Enum):\n residue = 1\n atom = 2\n # the rest of the elements\n</code></pre>\n<p>Now when you want to refer to the 1st element, you can simply do <code>split_lines[Data.atom.value]</code> It is a little more typing, but it is also clearer as to what you mean from that line.</p>\n<p>This also means you can remove the creation of copies. Not to create a new variable <code>residue</code> but just <code>split_lines[Data.residue.value]</code></p>\n<h1>Format your code</h1>\n<p>if you write <code>x = y + 65</code> compared to <code>x+y=65</code> and <code>x = float(y)</code> compared to <code>x=float(y)</code>, your code becomes much more readable</p>\n<h1>More simplification</h1>\n<pre class=\"lang-py prettyprint-override\"><code>question=input('input carbon and hydrogen values: ')\nsplit_question=question.split()\nsearch_fun(float(split_question[0]),float(split_question[1]))\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-py prettyprint-override\"><code>carbon, hydrogen = map(float,input("Enter carbon and hydrogen values: ").split())\nsearch_fun(carbon, hydrogen)\n</code></pre>\n<h1>Split work into functions</h1>\n<p>you have this line <br></p>\n<pre class=\"lang-py prettyprint-override\"><code>if float(split_carbon[3]) > (0.25*float(split_carbon[2])) or float(split_hydrogen[3]) > (0.25*float(split_hydrogen[2])):\n print(f'{values} {values2} HIGH ERROR')\n</code></pre>\n<p>Give a meaningful name to a new function where it would take in the various <code>args</code> and return <code>True</code> or <code>False</code> based on the formula. This way you can get rid of a lot of clunk in the <code>search_fun()</code> function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if formula_1(Args...) or formula_2(Args...):\n print(f'{values} {values2} HIGH ERROR')\n</code></pre>\n<p>The same idea can apply to many other code segments, and make your code much more readable.</p>\n<h1>Using <code>csv.DictReader</code></h1>\n<p>As suggested by @Graipher, it will be much better to use <code>csv.DictReader</code> as it will do a lot of the splitting work for you</p>\n<pre class=\"lang-py prettyprint-override\"><code>from csv import DictReader\nwith open("csvfile.csv") as csvfile:\n reader = DictReader(csvfile, delimiter = ',')\n for line in reader:\n print(line['atom_id')\n</code></pre>\n<p>This will split the values into a dictionary, where the keys will be the words at the top of the file <code>comp_id,atom_id,count,min,max,avg,std</code>. This is much better as you won't need to split the lines manually, and there won't be any magic numbers as the keys to your dictionary will be pre-defined by you.<br>\n<a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\"><strong>csv file handling in Python</strong></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T09:47:58.590",
"Id": "491401",
"Score": "1",
"body": "Downvoter may i know your reason?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T01:15:59.283",
"Id": "491482",
"Score": "2",
"body": "Thank you for the feedback! A couple of questions. 1. Does the for lines segment remove any spaces? I.E. How does changing that line negate the use of if line == '\\n'. 2. If I want to split multiple values that aren't residue, doesn't that mean I will have multiple classes? Wouldn't it be cleaner to just split and use index values, rather than a bunch of classes defining various variable names? 3. So are you saying I should break my original function, into a bunch of smaller ones?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T02:00:29.510",
"Id": "491484",
"Score": "3",
"body": "@AryanParekh Recommending `open(\"bmrb.csv\").readlines()`, which does not ensure closing of the file and reads the whole file in memory, recommending an unnecessary enum, when a `csv.DictReader` would be so much easier and making the user input parsing more fragile instead of less by e.g. recommending to write a function to deal with it. Sorry, did not have the time to comment when I first saw your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:09:42.713",
"Id": "491486",
"Score": "0",
"body": "@Graipher wrong, when you loop through a file with a for loop in that manner, it MAKES SURE that the file is closed, I read about this thoroughly first before recommending, check [this](https://lerner.co.il/2015/01/18/dont-use-python-close-files-answer-depends/#:~:text=Within%20the%20block%20of%20code,the%20file%20is%20automatically%20closed.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:11:04.403",
"Id": "491487",
"Score": "0",
"body": "@samman no the class has nothing to do with the values don't worry, you are just using an enum to replace numeric constants like 1, 2, and 3 which don't mean anything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:15:42.930",
"Id": "491488",
"Score": "0",
"body": "@samman `.readlines()` will just split the lines of the files into a list which you iterate thourgh"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:34:59.930",
"Id": "491491",
"Score": "0",
"body": "@Graipher I have read about `csv.DictReader` and added it to my answer! Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:48:06.703",
"Id": "491492",
"Score": "0",
"body": "@samman 3. Yes try to split work into smaller functions, so that not the whole code is on one and it looks extremely clunky"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T06:34:06.380",
"Id": "491495",
"Score": "1",
"body": "@AryanParekh The one thing the article doesn't talk about, and which is actually the greater reason for `with` is the case when an exception occurs. Granted, here there is not a lot of space for that to happen, but when using `with`, the closing happens even in case of exceptions. In any case, if you do recommend something which quite clearly goes against the normal recommendations, and even made the efforts to research if it is okay under some specific circumstances, then at least add a note about this in your answer. It currently reads like you should never need that verbose `with` stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T06:36:00.303",
"Id": "491496",
"Score": "1",
"body": "Oh, and you missed to do either `from csv import DictReader` or `reader = csv.DictReader(csvfile, delimiter=',')` in your edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T14:36:54.730",
"Id": "491533",
"Score": "0",
"body": "@AryanParekh when I was commenting on using enum, my concern was over cleanliness. Index [1] will not always be residue, and in longer pieces of code, won't it be messy if you define your index values with classes? E.G. Say in your code you have 10 instances where you split your list, and want to index it. That is 10 different classes, defining variable names for those numbers. That seems a lot messier than just indexing them (plus, when you index them right above, you can see where it comes from, whereas in the class, you'd have to find what Class.variable name is defined as)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:01:45.103",
"Id": "491539",
"Score": "0",
"body": "@samman 10 classes?? Only 1 class, enums are **largely used** in other languages like C++ / C too. Good code is something that is easily readable, using an enum will be much better than saying `index[0]`. Also when you say `index[1]` won't always be residue, then you aren't supposed to use an enum in that case. I think you will understand it's importance as your projects become larger, and you start using more and more magic numbers, you will have to replace it with an `enum`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:03:03.230",
"Id": "491540",
"Score": "0",
"body": "@samman I was just recommending good practices . I highly suggest you to read this [when should you use enums?](https://stackoverflow.com/questions/4709175/what-are-enums-and-why-are-they-useful), note that although it's tagged java, the concept is the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T19:18:13.180",
"Id": "491664",
"Score": "0",
"body": "python has dataclasses, which i think are more suitable over enums here."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T03:27:00.873",
"Id": "250456",
"ParentId": "250455",
"Score": "3"
}
},
{
"body": "<p>Using <code>csv.DictReader()</code> in combination with <code>itertools.groupby()</code> would simplify processing the file. This presumes the rows in the file are grouped by comp_id.</p>\n<pre><code>from csv import DictReader\nfrom itertools import groupby\nfrom operator import itemgetter\n\nwith open('bmrb.csv') as file:\n # because we're using DictReader, each row is a dict keyed by column name\n reader = DictReader(file, restkey='extra')\n\n # group the rows by `comp_id` \n grouper = groupby(reader, key=itemgetter('comp_id'))\n\n # rows is an iterable over the rows that have the same comp_id\n for comp_id,rows in grouper:\n\n # this is where you would process the group of rows, I just print some data\n print(comp_id)\n for row in rows:\n atom_id = row['atom_id']\n avg = float(row['avg'])\n std = float(row['std'])\n print(f' {atom_id:4} {avg - std:6.2f} {avg + std:6.2f}')\n</code></pre>\n<p>It was too hard to figure out your code to process each row, so that is left as an exercise for someone else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T19:12:06.470",
"Id": "250560",
"ParentId": "250455",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250456",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T00:25:51.640",
"Id": "250455",
"Score": "5",
"Tags": [
"python"
],
"Title": "Atom searcher (basically a file search function)"
}
|
250455
|
<p>I'm quite new to Rust, and am working on a virtual machine image decompiler. I have some working code that uses <code>match</code> to check opcode numbers, but it doesn't feel very idiomatic, and am wondering what alternatives I should consider.</p>
<p>First up is the cleanest case:</p>
<pre class="lang-rust prettyprint-override"><code> // Stop, or next instruction?
let next = match opcode {
28 | 139 | 140 | 176 | 177 | 179 | 181 ..= 184 | 186 | 188 | 228 | 243 | 244 | 246 => None,
_ => Some(image.position() as u32),
};
</code></pre>
<p>I have only two paths here, and no guards. This seems like the kind of situation that <code>match</code> is ideal for. However, it is a lot of magic numbers.</p>
<p>This following match needs to guarded patterns because some of the opcodes change structure based on the image version. The same variable will be stored in each case however, so I used a <code>match</code> to produce a <code>bool</code>, and then took that to an <code>if</code> branch. Originally I just had a simple <code>match</code> statement and duplicated the <code>Some(image.get_u8())</code>. I'm still not sure that it wasn't better that way.</p>
<pre class="lang-rust prettyprint-override"><code> // Store variable
let store = if match opcode {
8 | 9 | 15 ..= 25 | 129 ..= 132 | 136 | 142 | 143 | 224 | 231 | 236 | 246 ..= 248 |
1000 ..= 1004 | 1009 | 1010 | 1012 | 1030 => true,
181 | 182 if version == 4 => true,
185 | 228 if version >= 5 => true,
_ => false,
} {
Some(image.get_u8())
} else {
None
};
</code></pre>
<p>Lastly we have a match with only one guarded pattern, but a much more complex calculation to follow, so I didn't want to just duplicating the code for each pattern.</p>
<pre class="lang-rust prettyprint-override"><code> // Branch offset
let branch = if match opcode {
1 ..= 7 | 10 | 128 ..= 130 | 140 | 189 | 191 | 247 | 255 => true,
181 | 182 if version == 3 => true,
_ => false,
} {
let first_branch_byte = image.get_u8();
let iftrue = first_branch_byte & 0x80 != 0;
let twobytes = first_branch_byte & 0x40 == 0;
let offset: i16 = if twobytes {
(((((first_branch_byte & 0x3F) as u16) << 8) | image.get_u8() as u16) << 2) as i16 >> 2
} else {
(first_branch_byte & 0x3F) as i16
};
Some(Branch {
iftrue,
offset,
})
} else {
None
};
</code></pre>
<p>Because of all the magic numbers, I have considered whether it would be better to try to make some macros to produce the patterns from data elsewhere, or if I should just test for data in a <code>HashMap</code> instead of using <code>match</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T03:50:44.227",
"Id": "250457",
"Score": "1",
"Tags": [
"rust",
"pattern-matching"
],
"Title": "Idiomatic Rust matches with pattern guards"
}
|
250457
|
<p>I recently started to take a look at the <a href="https://golang.org/" rel="nofollow noreferrer">Go programming language</a> and decided to write a small project without practical use.</p>
<p>The objectives were:</p>
<ul>
<li>Regularly poll the latest funding rates from <a href="https://ftx.com/api/funding_rates" rel="nofollow noreferrer">https://ftx.com/api/funding_rates</a> (I chose them, because each JSON object is rather small and because new updates are available by the hour)</li>
<li>Maintain a duplicate free database of all <code>dbRecords == jsonObjects</code> seen</li>
</ul>
<h1>Database setup</h1>
<h2>Dockerfile</h2>
<pre><code>FROM postgres:13
COPY *.sql /docker-entrypoint-initdb.d/
</code></pre>
<h2>Database init query</h2>
<pre><code>-- Create Database and mark it as active so that all
-- consecutive commands are applied to this table
CREATE DATABASE crypto_mining;
\connect crypto_mining;
CREATE TABLE funding_rates(
id SERIAL PRIMARY KEY,
exchange TEXT NOT NULL,
future TEXT NOT NULL,
time TIMESTAMP NOT NULL,
rate DOUBLE PRECISION DEFAULT 0.0
);
</code></pre>
<h1>REST Api Miner</h1>
<h2>Dockerfile</h2>
<pre><code>FROM golang
WORKDIR /src
RUN go get github.com/lib/pq
COPY . .
ENTRYPOINT [ "go", "run", "ftxminer.go" ]
</code></pre>
<h2>Polling the API</h2>
<pre><code>package main
import "fmt"
import "os"
import "time"
import "sort"
import "net/http"
import "io/ioutil"
import "encoding/json"
import "database/sql"
import _ "github.com/lib/pq"
type t_fundingRates struct {
Future string `json:"future`
Rate float64 `json:"rate"`
Time time.Time `json:"time"`
}
type t_fundingRates_apiResult struct {
Result []t_fundingRates `json:"result"`
Success bool `json:"success"`
}
// implement logic to sort t_fundingRates by time
type rateByTime []t_fundingRates
func (r rateByTime) Len() int {
return len(r)
}
func (r rateByTime) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
func (r rateByTime) Less(i, j int) bool {
return r[i].Time.Before(r[j].Time)
}
func getFundingRates(minedRates chan<- []t_fundingRates) {
ticker := time.NewTicker(30 * time.Second)
for {
<-ticker.C
// get response object with status code, result, etc
httpResponse, err := http.Get("https://ftx.com/api/funding_rates")
if nil != err {
fmt.Printf(err.Error())
continue
}
// extract application data
httpResponseText, err := ioutil.ReadAll(httpResponse.Body)
if nil != err {
fmt.Printf(err.Error())
continue
}
// parse application data
httpResponseJson := t_fundingRates_apiResult{}
if err := json.Unmarshal(httpResponseText, &httpResponseJson); err != nil {
fmt.Printf(err.Error())
continue
}
// if the api responds success
if httpResponseJson.Success {
// send data to consumer
minedRates <- httpResponseJson.Result
} else {
fmt.Printf("api did not send funding rates")
continue
}
}
}
func getIndex(rates []t_fundingRates, future string) int {
for i, rate := range rates {
if future == rate.Future {
return i
}
}
return -1
}
func storeFundingRates(minedRates <-chan []t_fundingRates) {
psqlInfo := os.Getenv("DATABASE_URL")
knownRates := make([]t_fundingRates, 0) // rates we have seen previously
updateCandidates := make([]t_fundingRates, 0) // rates we maybe need to compare to database and maybe update
updateRates := make([]t_fundingRates, 0) // rates we need to update in database
for {
// wait for funding rates to arrive
rates := <-minedRates
fmt.Println("Successfully retrieved", len(rates), "funding rates from ftx.com")
// evaluate which rates we need to update
updateRates = make([]t_fundingRates, 0) // clear updateRates and
updateCandidates = make([]t_fundingRates, 0) // updateCandidates first
for _, rate := range rates {
knownRatesIndex := getIndex(knownRates, rate.Future)
if -1 == knownRatesIndex {
// if we have not seen the future before, then add it to collection
updateCandidates = append(updateCandidates, rate) // mark as need to update in database
} else {
// if we have seen the future earlier, then compare dates and decide whether we
// need to update
knownRate := knownRates[knownRatesIndex]
if knownRate.Time.Before(rate.Time) {
knownRates[knownRatesIndex] = rate
updateRates = append(updateRates, rate)
}
}
}
// only pass this point if there is data to be inserted into the database
if 0 == len(updateRates) && 0 == len(updateCandidates) {
fmt.Println("No outdated or new futures found")
continue
} else {
fmt.Println("Found", len(updateRates)+len(updateCandidates), "outdated or potentially new futures")
}
// prepare the database connection
db, err := sql.Open("postgres", psqlInfo)
if nil != err {
fmt.Println(err.Error())
continue
}
defer db.Close()
// establish the connection and send a ping
err = db.Ping()
if nil != err {
fmt.Println(err.Error())
continue
}
fmt.Println("Successfully connected")
// check for update candidates and potentially mark for inserting
sort.Sort(rateByTime(updateCandidates))
for _, candidate := range updateCandidates {
candidateRecord := t_fundingRates{}
err := db.QueryRow(
"SELECT DISTINCT ON (future,time) future,time,rate FROM funding_rates WHERE exchange='ftx' AND future=$1 ORDER BY future,time DESC;",
candidate.Future).Scan(
&candidateRecord.Future,
&candidateRecord.Time,
&candidateRecord.Rate)
isCandidateRecordValid := true
// did we get the result? if not I am just going to assume that
if err != nil {
if err.Error() == "sql: no rows in result set" {
isCandidateRecordValid = false
knownRates = append(knownRates, candidate)
updateRates = append(updateRates, candidate)
} else {
fmt.Println(err.Error())
continue
}
}
// add the future to the list of known futures
if isCandidateRecordValid {
if candidateRecord.Time.Before(candidate.Time) {
updateRates = append(updateRates, candidate) // mark as definite update
knownRatesIndex := getIndex(knownRates, candidate.Future) // things get a bit messy here due to duplicates in source data
if -1 == knownRatesIndex {
knownRates = append(knownRates, candidate)
} else {
knownRate := knownRates[knownRatesIndex]
if knownRate.Time.Before(candidate.Time) {
knownRates[knownRatesIndex] = candidate
}
}
} else {
knownRates = append(knownRates, candidateRecord)
}
}
}
// insert guaranteed updates into database
for _, update := range updateRates {
_, err = db.Exec("INSERT INTO funding_rates (exchange , future , time , rate) VALUES ('ftx' , $1 , $2 , $3);", update.Future, update.Time, update.Rate)
if nil != err {
fmt.Println(err.Error())
continue
}
}
}
}
func main() {
fmt.Println("Starting FTX Miner")
chan_fundingRates := make(chan []t_fundingRates)
go storeFundingRates(chan_fundingRates)
go getFundingRates(chan_fundingRates)
fmt.Println("... Funding Rates [OK]")
sleepForever := make(chan string)
<-sleepForever
os.Exit(0)
}
</code></pre>
<h1>Putting it all together in docker-compose.yml</h1>
<pre><code>version: '2.0'
services:
database:
build:
context: ./database/
dockerfile: ./Dockerfile
environment:
POSTGRES_PASSWORD: test123
ports:
- 5432:5432
volumes:
- databasevol:/var/lib/postgresql/data
networks:
- net
ftxminer:
build:
context: ./ftx/
dockerfile: ./Dockerfile
depends_on:
- database
environment:
DATABASE_URL: host=database port=5432 user=postgres password=test123 dbname=crypto_mining sslmode=disable
networks:
- net
volumes:
databasevol:
driver: local
networks:
net:
driver: bridge
</code></pre>
<p>Points that I found clumsy during writing the go code or that I am particularly interested in improving:</p>
<ul>
<li>Is it the proper way to keep all go logic in one file?</li>
<li>Is it common that go code is permanently interrupted by small error checks (especially as in <code>storeFundingRates</code>)?</li>
<li>Is it common to distinguish error types by their error message (such as <code>if err.Error() == "sql: no rows in result set" {</code> in <code>storeFundingRates</code>?</li>
</ul>
|
[] |
[
{
"body": "<p>Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. Code should be useful and have real value.</p>\n<p>I found your code hard to read. Your code does not appear to be correct.</p>\n<hr />\n<p>In Go we write:</p>\n<pre><code>if err != nil {\n // error handling\n return // or continue, etc.\n}\n// normal code\n</code></pre>\n<p>You confuse everybody, for no obvious reason, by writing:</p>\n<pre><code>if nil != err {\n // error handling\n return // or continue, etc.\n}\n// normal code\n</code></pre>\n<p>Why?</p>\n<hr />\n<p>Your comments largely duplicate the code.</p>\n<hr />\n<p>In Go, read the package documentation.</p>\n<p>You write:</p>\n<pre><code>// implement logic to sort t_fundingRates by time\ntype rateByTime []t_fundingRates\n\nfunc (r rateByTime) Len() int {\n return len(r)\n}\n\nfunc (r rateByTime) Swap(i, j int) {\n r[i], r[j] = r[j], r[i]\n}\n\nfunc (r rateByTime) Less(i, j int) bool {\n return r[i].Time.Before(r[j].Time)\n}\n\nsort.Sort(rateByTime(updateCandidates))\n</code></pre>\n<p>It is more readable to write:</p>\n<pre><code>func ratesByTime(r []t_fundingRates) {\n sort.Slice(r, func(i, j int) bool {\n return r[i].Time.After(r[j].Time)\n })\n}\n\nratesByTime(updateCandidates)\n</code></pre>\n<p>Your code is more than a little ugly, so the <code>sort.Slice</code> function was added in Go 1.8. An <a href=\"https://golang.org/pkg/sort/#example_\" rel=\"nofollow noreferrer\">Example</a> in the <a href=\"https://golang.org/pkg/sort/\" rel=\"nofollow noreferrer\">sort package</a> documentation clearly illustrates the difference:</p>\n<p>Go Playground: <a href=\"https://play.golang.org/p/LZgZi-s8IX-\" rel=\"nofollow noreferrer\">https://play.golang.org/p/LZgZi-s8IX-</a></p>\n<p>Why did you choose the complex, hard-to-read version?</p>\n<hr />\n<p>In Go, read the package documentation.</p>\n<p>The <a href=\"https://golang.org/pkg/net/http/\" rel=\"nofollow noreferrer\">net/http package</a> documentation states:</p>\n<blockquote>\n<p>The client must close the response body when finished with it:</p>\n<pre><code>resp, err := http.Get("http://example.com/")\nif err != nil {\n // handle error\n}\ndefer resp.Body.Close()\nbody, err := ioutil.ReadAll(resp.Body)\n// ...\n</code></pre>\n</blockquote>\n<p>You do not <code>Close</code> <code>httpResponse.Body</code>. Why?</p>\n<hr />\n<p>In Go, read <a href=\"https://golang.org/ref/spec\" rel=\"nofollow noreferrer\">The Go Programming Language Specification</a>.</p>\n<p>In particular, <a href=\"https://golang.org/ref/spec#Defer_statements\" rel=\"nofollow noreferrer\">Defer statements</a></p>\n<blockquote>\n<p>A "defer" statement invokes a function whose execution is deferred to\nthe moment the surrounding function returns, either because the\nsurrounding function executed a return statement, reached the end of\nits function body, or because the corresponding goroutine is\npanicking.</p>\n<p>Each time a "defer" statement executes, the function value and\nparameters to the call are evaluated as usual and saved anew but the\nactual function is not invoked. Instead, deferred functions are\ninvoked immediately before the surrounding function returns, in the\nreverse order they were deferred.</p>\n</blockquote>\n<p>You write:</p>\n<pre><code>func storeFundingRates(minedRates <-chan []t_fundingRates) {\n\n for {\n\n db, err := sql.Open("postgres", psqlInfo)\n if nil != err {\n fmt.Println(err.Error())\n continue\n }\n defer db.Close()\n\n }\n\n}\n\ngo storeFundingRates(chan_fundingRates)\n</code></pre>\n<p>You appear to be in an infinite loop and so the function does not end. The deferred functioms accumulate but are never executed.</p>\n<hr />\n<p>Here's a first cut at cleaning up your <code>getFundingRates</code> (renamed to <code>mineFundingRates</code>) function.</p>\n<pre><code>func getFundingRates() ([]t_fundingRates, error) {\n resp, err := http.Get("https://ftx.com/api/funding_rates")\n if err != nil {\n return nil, err\n }\n defer resp.Body.Close()\n respBody, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n return nil, err\n }\n\n var respJson t_fundingRates_apiResult\n if err := json.Unmarshal(respBody, &respJson); err != nil {\n return nil, err\n }\n if !respJson.Success {\n err := fmt.Errorf("api did not send funding rates")\n return nil, err\n }\n\n return respJson.Result, nil\n}\n\nfunc mineFundingRates(minedRates chan<- []t_fundingRates) {\n ticker := time.NewTicker(30 * time.Second)\n for {\n <-ticker.C\n\n rates, err := getFundingRates()\n if err != nil {\n log.Printf(err.Error())\n continue\n }\n minedRates <- rates\n }\n}\n\ngo mineFundingRates(chan_fundingRates)\n</code></pre>\n<hr />\n<p>There is more, but I'm out of time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T05:50:27.777",
"Id": "491494",
"Score": "1",
"body": "The answer to most of your *Why*s is, that I just started learning the language and don't yet have an efficient way to find what I need in the docs. I appreciate that you went through > 200 lines of code which you find *hard to read* and would be interested in reading the rest of your review, should you find the time to write it. Particularly in how you would suggest to improve readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T07:42:54.523",
"Id": "491501",
"Score": "1",
"body": "What do you mean by *Your comments largely duplicate the code.*? How do you use comments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T06:49:54.157",
"Id": "493900",
"Score": "0",
"body": "@Benj I also think your comment may be a bit too much.The variable name and method names should express the meaning of usage. Short and cohesive method often does not need comments, the method name tells what they did.So when you want to use comment, you can first think about whether you can make the code more readable by refactoring.Eg. `storeFundingRates` is too long and too much comments."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:14:49.487",
"Id": "250486",
"ParentId": "250458",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250486",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T08:10:45.237",
"Id": "250458",
"Score": "4",
"Tags": [
"go",
"rest",
"postgresql",
"docker"
],
"Title": "Historical Funding Rate Miner for ftx.com"
}
|
250458
|
<p>The idea is to have a function which checks if all elements in a list are contained in another list. But not just the containedness has to be true, but also <strong>the times</strong> of containedness.</p>
<p>One could say the function has to be an extended version of <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/contains-all.html" rel="nofollow noreferrer">containsAll</a> , which checks only the containedness.</p>
<p>Here's my implementation of such a function:</p>
<pre><code>fun main(args: Array<String>) {
val toCheck = listOf(1, 2, 3, 4, 5, 6, 1, 1, 3)
val expected = listOf(1, 1, 1, 3, 3, 4)
val result = containsAllSameCount(toCheck, expected)
println("Result => $result")
val expected2 = listOf(1, 1, 3, 3, 4) // One 1 is missing!
val result2 = containsAllSameCount(toCheck, expected2)
println("Result 2 => $result2")
/*
Result => true
Result 2 => false
*/
}
fun containsAllSameCount(toCheck: List<Int>, expected: List<Int>): Boolean {
for (current in expected) {
var currentInExpected = expected.filter { it == current }
var currentInToCheck = toCheck.filter { it == current }
if (currentInExpected.size != currentInToCheck.size) {
return false
}
}
return true
}
</code></pre>
<p>It's clear to me, that the filter-methods are used multiple times, when the same element is contained multiple times. Therefore I suppose that my implementation isn't the most efficient way to solve the task.</p>
<p><strong>What do you think about my implementation?</strong></p>
<p><strong>What's a better way to solve the way?</strong></p>
|
[] |
[
{
"body": "<p>The best way would be to change data structure. Instead of using a <code>List<Int></code> you can use a <code>Map<Int, Int></code>. If you want to have a <code>List<Int></code> in the beginning, that's ok, you just need to convert it to a <code>Map<Int, Int></code> and compare the maps.</p>\n<p>Using the nice Kotlin methods in the stdlib, we can make the code into this:</p>\n<pre><code>fun <T> containsAllSameCount(toCheck: List<T>, expected: List<T>): Boolean {\n val toCheckCountMap = toCheck.groupBy { it }.mapValues { it.value.size }\n val expectedCountMap = expected.groupBy { it }.mapValues { it.value.size }\n return expectedCountMap.all { toCheckCountMap[it.key] == it.value }\n}\n</code></pre>\n<p>I have also added generics here because the same logic applies whether it's a <code>List<Int></code>, <code>List<String></code> and so on.</p>\n<p>Some other notes:</p>\n<ul>\n<li>Use JUnit for proper tests.</li>\n<li>The <code>main</code> method in Kotlin does not need to be declared with the <code>args</code>, simply <code>fun main() {</code> will do.</li>\n<li>Use <code>val</code> instead of <code>var</code> whenever possible.</li>\n<li>Instead of <code>.filter</code> and then checking the size, use <code>.count</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T10:49:49.040",
"Id": "250461",
"ParentId": "250459",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T09:03:49.057",
"Id": "250459",
"Score": "3",
"Tags": [
"algorithm",
"kotlin"
],
"Title": "Contains all elements and duplicates are taken into account"
}
|
250459
|
<p>I am trying to plot three dimensional (multiple plane) data onto figures with various perspective view. The input data is tab-separated values in multiple file, and each file represent each plane. The document I referred is <a href="http://www.gnuplot.info/docs_5.4/Gnuplot_5_4.pdf" rel="nofollow noreferrer">http://www.gnuplot.info/docs_5.4/Gnuplot_5_4.pdf</a> .</p>
<p>An example is illustrated as below.</p>
<p>Plane1.txt</p>
<pre><code>1 0 1
0 1 0
1 0 1
</code></pre>
<p>Plane2.txt</p>
<pre><code>0 1 0
1 0 1
0 1 0
</code></pre>
<p>Plane3.txt</p>
<pre><code>2 0 2
0 2 0
2 0 2
</code></pre>
<p>Is there any possible improvement of this code?</p>
<pre><code>do for [LoopNumber1=0:360] {
dir = 'View'.LoopNumber1
command1 = "mkdir " . dir
system command1
do for [LoopNumber2=0:360] {
set term jpeg size 1280,1024
set out dir.'/GNUPlotOutput'.LoopNumber2.'.jpeg'
set grid
set key off
#set logscale cb
set view LoopNumber1,LoopNumber2
splot for [i=1:3] 'Plane'.i.'.txt' matrix using 1:2:(i):3 with point pointtype 5 pointsize 0.75 pal
}
}
</code></pre>
<p>One of the plotting result is as below.</p>
<p><a href="https://i.stack.imgur.com/OvceV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OvceV.png" alt="PlottingResult" /></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T09:56:40.090",
"Id": "250460",
"Score": "2",
"Tags": [
"beginner",
"image",
"data-visualization"
],
"Title": "GNUPlot Code for Plotting Three Dimensional Data"
}
|
250460
|
<h1>Setting manager class for reading and managing Settings.ini file</h1>
<p>I have started a project creating <a href="https://github.com/Zoran-Jankov/Software-Installer" rel="nofollow noreferrer">Software Installer</a> application for auto download and auto install software, similar how <a href="https://ninite.com/" rel="nofollow noreferrer">Ninite</a> works. I have created <a href="https://github.com/Zoran-Jankov/Software-Installer/blob/main/src/main/java/com/zoran_jankov/software_installer/app/SettingsManager.java" rel="nofollow noreferrer"><code>SettingsManager.java</code></a> class for reading and managing <a href="https://github.com/Zoran-Jankov/Software-Installer/blob/main/src/main/resources/Settings.ini" rel="nofollow noreferrer">Settings.ini</a> file of the program so the rest of the program can use it. This is just a draft of the class an it is not complete, but it is functional. I would like your opinions on the overall design and implementation of this kind of class.</p>
<h2>The SettingsManager.java class</h2>
<pre><code>package com.zoran_jankov.software_installer.app;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.ini4j.Ini;
public class SettingsManager
{
private static SettingsManager instance;
private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";
private Map<Software, String> localRepositories = new HashMap<Software, String>();
private Map<Software, String> networkRepositories = new HashMap<Software, String>();
private Map<Software, String> onlineRepositories = new HashMap<Software, String>();
private Map<Software, String> arguments = new HashMap<Software, String>();
private SettingsManager()
{
loadSettings();
}
public static SettingsManager getInstance()
{
if(instance == null)
{
instance = new SettingsManager();
}
return instance;
}
public void loadSettings()
{
Ini settings = null;
try
{
settings = new Ini(new File(SETTINGS_FILE_PATH));
}
catch (IOException e)
{
e.printStackTrace();
}
localRepositories = getInstallerSettings(settings, "Local Repositories");
networkRepositories = getInstallerSettings(settings, "Network Repositories");
onlineRepositories = getInstallerSettings(settings, "Online Repositories");
arguments = getInstallerSettings(settings, "Arguments");
}
private Map<Software, String> getInstallerSettings(Ini setttings, String sectionName)
{
Map<Software, String> list = new HashMap<Software, String>();
for (Software installer : Software.values())
{
list.put(installer, setttings.get(sectionName, installer.name()));
}
return list;
}
public String getLocalRepository(Software software)
{
return localRepositories.get(software);
}
public String getNetworkRepository(Software software)
{
return networkRepositories.get(software);
}
public String getOnlineRepository(Software software)
{
return onlineRepositories.get(software);
}
public String getArguments(Software software)
{
return arguments.get(software);
}
}
</code></pre>
<h2>The Software.java enum</h2>
<p>package com.zoran_jankov.software_installer.app;</p>
<pre><code>public enum Software
{
AIMP,
CCleaner,
DWGSee,
Firefox,
FoxitReader,
ImgBurn,
Java,
LibreOffice,
Notepad,
Office365,
OpenOffice,
RocketChat,
Skype,
SpacePlanning,
Speccy,
Thunderbird,
UltraVNC,
VLC,
ZabbixAgent,
Zip;
}
</code></pre>
<h2>The <a href="https://github.com/Zoran-Jankov/Software-Installer/blob/main/src/main/resources/Settings.ini" rel="nofollow noreferrer">Settings.ini</a> file</h2>
<p>So you can better understand what is happening in the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T12:31:28.790",
"Id": "491419",
"Score": "3",
"body": "I suggest not reinventing the wheel. It sounds like you could rather use Java Properties classes/tools to handle configuration files. Check it out https://docs.oracle.com/javase/tutorial/essential/environment/properties.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T15:21:46.963",
"Id": "491431",
"Score": "1",
"body": "@user985366 he is parsing an `.ini` file, not really standard properties. And using the `init4j.Ini` library, not really reinventing the wheel IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T10:33:13.560",
"Id": "491508",
"Score": "0",
"body": "@user985366 Well I find the sections in ini4j.Ini very convenient, and as far as I can see java Properties class doesn't have that feature."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T13:23:59.417",
"Id": "491527",
"Score": "1",
"body": "@ZoranJankov Right. I was thinking more generally, that properties files could replace .ini files, but I see now that that's too far from your use case."
}
] |
[
{
"body": "<p>Defualt Java style is to have the opening braces on the same line, but that's down to preferences. Just be consistent in your code.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";\n</code></pre>\n<p>You want to pass that path, somehow, as it is not portable.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class SettingsManager\n{\n private static SettingsManager instance;\n\n public static SettingsManager getInstance()\n {\n if(instance == null)\n {\n instance = new SettingsManager();\n }\n return instance;\n }\n}\n</code></pre>\n<p>This is not thread-safe, in case you care about it. An obligatory number of threads could end up with their own, not-shared instances of the <code>SettingsManager</code>. There are three ways to prevent that:</p>\n<p>The first is to use a static initializer:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class SettingsManager\n{\n private static SettingsManager instance;\n\n static\n {\n instance = new SettingsManager();\n }\n}\n</code></pre>\n<p>Static initializers are guaranteed to be synchronized and will only be executed once the class is accessed.</p>\n<p>The second option is to synchronize the whole method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class SettingsManager\n{\n private static SettingsManager instance;\n\n public static synchronized SettingsManager getInstance()\n {\n if(instance == null)\n {\n instance = new SettingsManager();\n }\n return instance;\n }\n}\n</code></pre>\n<p>This guarantees a single instance for everyone, but it means that an expensive lock is acquired for each access. "Expensive" in this case means "compared to simply getting the value", in 99.99% of the cases you will <em><strong>not</strong></em> notice the performance difference to method #3.</p>\n<p>The third method is to check twice whether the value is available, once "cheap", and then synchronized:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class SettingsManager\n{\n private static SettingsManager instance;\n\n public static SettingsManager getInstance()\n {\n if(instance == null)\n {\n synchronized(SettingsManager.class)\n {\n if(instance == null)\n {\n instance = new SettingsManager();\n }\n }\n }\n return instance;\n }\n}\n</code></pre>\n<p>That skips the locking in most instances, except when required, namely if two threads try to access the instance for the first time.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final String SETTINGS_FILE_PATH = "D:/Programing/Java/Software Installer/src/main/resources/Settings.ini";\n</code></pre>\n<p>You want to pass that path, somehow, as it is not portable in the slightest in this way.</p>\n<p>Now, that leads to the problem that you only have one single, global instance, and if you pass the path you have to ask yourself the question what should be done when a second instance with a different path is requested. It might be better to have a single instance which you pass around in your application, or which you make globally accessible throughout your application, and not through the class level of this class.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> Ini settings = null;\n \n try\n {\n settings = new Ini(new File(SETTINGS_FILE_PATH));\n }\n catch (IOException e)\n {\n e.printStackTrace();\n }\n</code></pre>\n<p>You most likely want to re-throw that exception, or let it propagate freely by letting <code>loadSettings</code> throw <code>IOException</code>. Silently swallowing exceptions might lead to a really bad headache when debugging problems.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>Map<Software, String> list = new HashMap<Software, String>();\n</code></pre>\n<p>That's not a list, that's a map. Naming like that is confusing. Also, in Java 8+ you can omit the types in the constructor, as they are derived from the declaration:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Map<Software, String> list = new HashMap<>();\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public enum Software\n{\n AIMP,\n CCleaner,\n</code></pre>\n<p>Java convention is that enum members are considered constants, therefor should be UPPER_SNAKE_CASE.</p>\n<hr />\n<p>Now, what you don't want is that <code>Software</code> enum, that should be configuration that you read, too, because that allows easier maintenance and extension of the software. Overall, your ini format seems not suited for what you want, it looks more like you want to invert the format:</p>\n<pre><code>[AIMP]\nLocal Repository=...\nNetwork Repository=...\nOnline Repository=...\nArguments=...\n\n[CCleaner]\nLocal Repository=...\nNetwork Repository=...\nOnline Repository=...\nArguments=...\n</code></pre>\n<p>Because with that in place, you can kill off <code>Software</code> completely and make your application driven by configuration. You simply read the ini file and display the list of software that is configured instead of having it hard-coded.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T10:28:25.530",
"Id": "491507",
"Score": "0",
"body": "Thank you very much for your extensive a answer and advices. I will try implementing everything you mentioned in the answer except the Java Code Style Format, namely the to have the opening braces on the same. I don't like it because it makes code tightly packed and more harder to see code bloks, for me anyway. I follow C++ code style format for every language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T11:29:02.557",
"Id": "491514",
"Score": "1",
"body": "And as I said, that's fine as long as you're consistent (and if your working with somebody else, provide an automatic formatter)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:03:52.760",
"Id": "491519",
"Score": "0",
"body": "How can I get the names of all sections in .ini file from ini4j.ini class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:25:01.347",
"Id": "491521",
"Score": "1",
"body": "Skimming the documentation and source code, `keySet` most likely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:28:14.457",
"Id": "491572",
"Score": "0",
"body": "I just realized that I crated my `SettingsManager` class to be a wrapper class for `Ini` class. I don't know why I did that. Back to the design board..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:38:44.927",
"Id": "491646",
"Score": "1",
"body": "That's not necessarily a bad thing. Abstracting any dependencies can be a good idea to have control over the API within your application."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T19:16:22.370",
"Id": "250479",
"ParentId": "250462",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250479",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T11:27:22.423",
"Id": "250462",
"Score": "3",
"Tags": [
"java",
"file"
],
"Title": "Setting manager class for reading and managing Settings.ini file of my program"
}
|
250462
|
<pre class="lang-py prettyprint-override"><code>dc = {line.split('=')[0]: line.split('=')[1] for line in txt}
</code></pre>
<p>Below avoids duplication but is even longer:</p>
<pre class="lang-py prettyprint-override"><code>dc = {k: v for line in txt for k, v in
zip(*map(lambda x: [x], line.split('=')))}
</code></pre>
<p>Any better way? Just without any imports.</p>
<hr>
<p>Context: <code>with open('config.txt', 'r') as f: txt = f.read().split('\n')</code></p>
<pre class="lang-py prettyprint-override"><code>a=1
bc=sea
</code></pre>
<pre><code>>>> {'a': '1', 'bc': 'sea'} # desired output; values should be string
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T09:38:55.437",
"Id": "491504",
"Score": "1",
"body": "Just FYI, Python has a built-in [`ConfigParser`](https://docs.python.org/3/library/configparser.html#module-configparser) for parsing configration files in INI format, which requires a section header for each section."
}
] |
[
{
"body": "<pre class=\"lang-py prettyprint-override\"><code>{k: v for line in txt for k, v in [line.split('=')]}\n</code></pre>\n<p>Advantage over <code>superb rain</code>'s answer is ability to modify <code>k</code> and <code>v</code> if needed. Slight memory & speed advantage by avoiding allocation via a generator (credit @GZ0):</p>\n<pre class=\"lang-py prettyprint-override\"><code>{k: v for k, v in (line.split('=') for line in txt)}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T18:47:33.593",
"Id": "491456",
"Score": "1",
"body": "@Graipher That's the idea, `line` is split into a \"left' and \"right\", key and value, so a 'trick' around duplicating `line.split`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:51:40.610",
"Id": "491477",
"Score": "1",
"body": "You could also write `(line.split(\"=\"),)` to avoid allocating a list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T07:19:28.287",
"Id": "491499",
"Score": "2",
"body": "@MateenUlhaq That creates a tuple, which in this case is not much different from a list. One approach to avoid allocating a new collection is this: `{k: v for k, v in (line.split('=') for line in txt)}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T10:46:59.850",
"Id": "491509",
"Score": "0",
"body": "@GZ0 Nice improvement - can post as answer if you wish, or I'll edit it into mine with credit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T22:00:39.897",
"Id": "491573",
"Score": "0",
"body": "@OverLordGoldDragon You can edit it into yours."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T12:47:14.347",
"Id": "250465",
"ParentId": "250463",
"Score": "3"
}
},
{
"body": "<pre><code>dc = dict(line.split('=') for line in txt)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:11:00.650",
"Id": "491421",
"Score": "0",
"body": "I knew Python had to have better - excellent."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:04:30.437",
"Id": "250467",
"ParentId": "250463",
"Score": "6"
}
},
{
"body": "<p>This is one of the types of problems that the walrus operator <code>:=</code> can handle:</p>\n<pre><code>dc = {(s := line.split('='))[0]: s[1] for line in txt}\n</code></pre>\n<p>Of course, in this case there's a much cleaner solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:46:27.323",
"Id": "250490",
"ParentId": "250463",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250467",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T11:50:21.503",
"Id": "250463",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"iterator"
],
"Title": "Shorten dict comprehension with repeated operation"
}
|
250463
|
<p>I'm using this script to bulk update docs in my index.</p>
<p>I need to update a field of a doc in Elasticsearch and add the count of that doc in a list inside python code. The weight field contains the count of the doc in a dataset. The dataset needs to be updated from time to time.So the count of each document must be updated too. <code>hashed_ids</code> is a list of document ids that are in the new batch of data. the weight of matched id must be increased by the count of that id in <code>hashed_ids</code>.</p>
<p>For example let say a doc with <code>id=d1b145716ce1b04ea53d1ede9875e05a</code> and <code>weight=5</code> is already present in index. and also the string <code>d1b145716ce1b04ea53d1ede9875e05a</code> is repeated three times in the <code>hashed_ids</code> so the <code>update_with_query</code> query will match the doc in database. I need to add 3 to 5 and have 8 as final <code>weight</code>.</p>
<p>The code below works for it but it is too slow and from time to time I get time out error.</p>
<pre><code>hashed_ids = [hashlib.md5(doc.encode('utf-8')).hexdigest() for doc in shingles]
update_by_query_body =
{
"query":{
"terms": {
"id":["id1","id2"]
}
},
"script":{
"source":"long weightToAdd = params.hashed_ids.stream().filter(idFromList -> ctx._source.id.equals(idFromList)).count(); ctx._source.weight += weightToAdd;",
"params":{
"hashed_ids":["id1","id1","id1","id2"]
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:44:35.513",
"Id": "493292",
"Score": "0",
"body": "Where is the rest of your code? Please include it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T13:16:18.933",
"Id": "250468",
"Score": "4",
"Tags": [
"python",
"performance",
"elasticsearch"
],
"Title": "Elasticsearch update script using python bulk update"
}
|
250468
|
<p>I would like to make the below code more efficient by writing all text(CSV) to memory before writing to disk. The CSV file could have upwards of 10,000 or rows. With the current code, it opens and closes the file for R/W each time. There must be a better way. I am calling the WriteToCSV2 on each OnBarUpdate. The file on disk after it runs is approx. 10MB so there is no issue storing the entire contents of in memory before writing to disk.</p>
<p>This is part of a NinjaScript for Ninjatrader.</p>
<pre><code>private void WriteToCSV2()
{
if(CurrentBar <= BarsRequiredToPlot + LookBack) return;
StringBuilder header = new StringBuilder();
StringBuilder logEntry = new StringBuilder();
StringBuilder signalCode = new StringBuilder();
string fullPath = System.IO.Path.Combine(filePath,fileName);
header.Append("Index Key,");
header.Append("CurrentBar,");
header.Append("SignalCode,");
header.Append("Open,");
header.Append("High,");
header.Append("Low,");
header.Append("Close,");
header.Append("BarCloseTime");
//INPUT1
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input1_1_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input1_2_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input1_3_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input1_4_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input2_1_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input2_2_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input2_3_trendchar[i]);
if(i == LookBack) signalCode.Append("-");
}
for(int i = 1; i <= LookBack; i++)
{
signalCode.Append(input2_4_trendchar[i]);
}
logEntry.Append(indexKey);
logEntry.Append(",");
logEntry.Append(CurrentBar-1);
logEntry.Append(",");
logEntry.Append(signalCode.ToString());
logEntry.Append(",");
logEntry.Append(Open[1]);
logEntry.Append(",");
logEntry.Append(High[1]);
logEntry.Append(",");
logEntry.Append(Low[1]);
logEntry.Append(",");
logEntry.Append(Close[1]);
logEntry.Append(",");
logEntry.Append(Time[1]);
indexKey++;
try
{
if (File.Exists(fullPath) == false)
{
using (StreamWriter sw = new StreamWriter(fullPath, true))
{
sw.WriteLine(header); // If file doesnt exist, create it and add the Header
sw.WriteLine(logEntry); // Append a new line to the file
sw.Close(); // Close the file to allow future calls to access the file again.
}
}
else //File Does Exisit
{
if (IsFileLocked(fullPath) == false) //If file is not locked for editing
{
using (StreamWriter sw = new StreamWriter(fullPath, true))
{
sw.WriteLine(logEntry); // Append a new line to the file
sw.Close(); // Close the file to allow future calls to access the file again.
}
}
}
}
catch (Exception e)
{
// Outputs the error to the log
//Log(uniqueStrategy + ": ExecutionLog - cannot write and read at the same time.", NinjaTrader.Cbi.LogLevel.Error);
Print("ERROR WRITTING SignalLog");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T17:16:36.473",
"Id": "491437",
"Score": "0",
"body": "too many loops for a single operation! This might be a design issue. You must share all related code including the code where you handle the input to store them in arrays ! as it seems you're using an array for each column in the csv. Also, explain why you need to store it in memory ? what's your goal by storing it in memory rather than buffering it to disk ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T18:40:13.070",
"Id": "491452",
"Score": "0",
"body": "The loops are to generate the signal code and are necessary. The signal code is what is going to be eventually written to disk. Below is an example of a row \n \nZZZZZZZZZZ-ZZZZZZZZZZ-ZZZZZZZZZZ-BBAAAABBBB-ZBAAAAAAZZ-CCBCCXYZZZ-XXCXXYYZZZ-BBBBBBBBCC 1.1748 1.1748 1.17475 1.17475 10/5/2020 0:02'\n \nYes, each column refers to a data in an array. \n \nI run this code with historical data in an array and it takes an long time because of all in I/O operations R/W to disk. What I would like is for the data to be written into a memorystream and written only once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T20:25:59.303",
"Id": "491463",
"Score": "1",
"body": "This is why we need to see the related code to this part. As you can simply use models instead of multiple arrays, which would give you more managed structure to your data for more maintainability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T00:23:31.443",
"Id": "491481",
"Score": "2",
"body": "we need more code around this. Why can't you just keep the filestream open? Why do you need to close it? What is all the loops and, I assume, arrays in the loops? Hard to give better options when just a small subsection of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T14:56:49.463",
"Id": "491537",
"Score": "1",
"body": "Example of fast CSV builder [here](https://codereview.stackexchange.com/a/249247/226545). Btw, you may use some existing CSV tool e.g. CSVHelper."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:57:06.707",
"Id": "491545",
"Score": "0",
"body": "This is a ninjascript that runs within NinjaTrader. I do not have access to what goes on in the background. I can only access the data in the arrays as shown above. With each new bar/entry, a calc. is preformed and the WriteToCSV function is called. The WriteToCSV is called thousands of times after each calculation. The loops are necessary to compile the data, they are not the issue. The issue is the thousands of times it opens, reads,writes and closes the file on the harddisk. I would like to have it save all the entries into memory and just dump the entire csv file to disk once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:00:44.340",
"Id": "491546",
"Score": "0",
"body": "I do not have all the data to be written to the csv at any given time. Each entry is built dynamically in a sequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:01:51.337",
"Id": "491671",
"Score": "1",
"body": "Instead of strings with a length of one character, it is better to use char. In other words, replace double quotes with single ones. `Append(\",\")` => `Append(',')`"
}
] |
[
{
"body": "<p>My try to prettify the code. Some comments inside.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void WriteToCSV2()\n{\n if (CurrentBar <= BarsRequiredToPlot + LookBack) return;\n\n StringBuilder logEntry = new StringBuilder();\n\n string fullPath = Path.Combine(filePath, fileName);\n\n // don't need a Stringbuilder to build a constant string\n const string header = "Index Key,CurrentBar,SignalCode,Open,High,Low,Close,BarCloseTime";\n\n // StringBuilder has Fluent API, it means you may write like .Append.Append.Append...\n logEntry.Append(indexKey).Append(",");\n logEntry.Append(CurrentBar - 1).Append(",");\n\n var trendchars = new[] // let's make an array of it ...\n {\n input1_1_trendchar,\n input1_2_trendchar,\n input1_3_trendchar,\n input1_4_trendchar,\n input2_1_trendchar,\n input2_2_trendchar,\n input2_3_trendchar,\n input2_4_trendchar\n };\n\n foreach (var trendchar in trendchars) // ... and process it in a loop\n {\n for (int i = 1; i <= LookBack; i++)\n {\n logEntry.Append(trendchar[i]);\n }\n logEntry.Append("-");\n }\n logEntry.Remove(logEntry.Length - 1, 1); // cut the last redundant "-"\n \n logEntry.Append(",");\n logEntry.Append(Open[1]).Append(",");\n logEntry.Append(High[1]).Append(",");\n logEntry.Append(Low[1]).Append(",");\n logEntry.Append(Close[1]).Append(",");\n logEntry.Append(Time[1]);\n indexKey++;\n\n try\n {\n // "something == false" may be written as "!something"\n if (!File.Exists(fullPath))\n {\n File.WriteAllLines(fullPath, new[] { header, logEntry.ToString() });\n }\n else\n {\n // Warning! If the file is locked, here you may loose all the data to write\n if (!IsFileLocked(fullPath))\n {\n File.AppendAllLines(fullPath, new[] { logEntry.ToString() });\n }\n }\n }\n catch (Exception e)\n {\n // e.Message will tell what's exactly went wrong\n Print($"ERROR WRITTING SignalLog: {e.Message}");\n }\n}\n</code></pre>\n<p>Possibly I've processed not all the things to optimize but only visible part of code.</p>\n<hr />\n<p>Btw if you want write to disk once, you may try single <code>StringBuilder</code>, something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>StringBuilder sb = new StringBuilder();\nconst string header = ...\nif (!File.Exists(filename))\n{\n sb.AppendLine(header);\n}\n\nfor (...)\n{\n WriteToCSV2(sb);\n sb.AppendLine();\n}\n\nFile.AppendAllText(filename, sb.ToString());\n</code></pre>\n<p>And change signature of the method</p>\n<pre><code>private void WriteToCSV2(StringBuilder logEntry)\n{\n //...\n}\n</code></pre>\n<p><code>MemoryStream</code> would be a kind of redundancy here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:41:38.450",
"Id": "250552",
"ParentId": "250470",
"Score": "2"
}
},
{
"body": "<p>Thank you all for your input. I was able to dramatically make it more efficient by creating models and using CSVhelper. <a href=\"https://joshclose.github.io/CsvHelper/\" rel=\"nofollow noreferrer\">https://joshclose.github.io/CsvHelper/</a> to export all the historical records to disk, only once during transitioning to realtime. Much faster.</p>\n<pre><code>var trendchars = new[] // array of arrays\n{\n input1_1_trendchar,\n input1_2_trendchar,\n input1_3_trendchar,\n input1_4_trendchar,\n input2_1_trendchar,\n input2_2_trendchar,\n input2_3_trendchar,\n input2_4_trendchar\n};\n \nforeach (var trendchar in trendchars) // ... and process it in a loop\n{ \n for (int i = 1; i <= LookBack; i++)\n {\n signalCode.Append(trendchar[i]);\n }\n signalCode.Append("-");\n}\n \nsignalCode.Remove(signalCode.Length - 1, 1); // cut the last redundant "-"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:50:38.517",
"Id": "250581",
"ParentId": "250470",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "250552",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T15:42:27.437",
"Id": "250470",
"Score": "3",
"Tags": [
"c#",
"performance",
"beginner",
"file",
"io"
],
"Title": "NinjaTrader - Writting to MemoryStream then to Disk"
}
|
250470
|
<p>I am new to node.js, ajax, and asynchronous code. I’ve pieced together a working way to exchange json between browser and server and am wondering if someone with more experience considers the approach reasonable for my needs.</p>
<p>Requirement Context: This technique will be used for back-office update of data. Initially there will be one user on the same computer as the database. I’d rather not rule out allowing a few other users to remotely update the backend in the future, but if that happens, they would use simpler screens designed with the remote location in mind. Since this is back-office, I can insist on the latest Chrome browser.</p>
<p>My limitations: I’m a one-man shop developing/supporting a website in semi-retirement. I am part-time and my responsibilities extend beyond coding, so at best I can be a jack of some trades, but master of none.</p>
<p><strong>You can skip straight to “Requirement” below</strong>, or if you want more context, read on:</p>
<p>Why Not Use a Library to Do This?: I am open to being told that I should, but prefer to avoid libraries unless there is compelling reason to use them. I’m a 1-man shop who needs to figure out how to do a handful of things and then automate doing them again and again. It’s a very different situation than a large company doing a multitude of things. For example, the front-end of this application has half a million static web pages written by the back-end. There are only half a dozen page types and each loads with a single hit to the server. They are written with plain vanilla html, css, and javascript. The menus would look nicer if a library were used (or when I spend more time on them), but there is value in the simplicity. Libraries complicate version control, typically provide enormous capability I will never use, and drag along legacy support I don’t need. My personal experience is that relative to many others, I am better at going a little deeper on one product than I am at remembering how multiple products interface.</p>
<p>Tool Rationale: There are no plans for the site to generate revenue, so one of the reasons I chose MySQL and node.js is that there is no licensing costs for a hobby I hope to continue for twenty years. The tools seem up to my requirements and are popular enough that I can find ways of doing things on the internet. Also, as a part-time, 1-man shop, being able to use the same language on the server and browser is an enormous advantage.</p>
<p><strong>Requirement:</strong> With plain vanilla node.js, move large json files between browser and server to support backend data maintenance for a website. I have tested the current solution and it moves more data than I need to move more quickly than I need to move it. (I tested 100,000 objects requiring 8Meg json files both ways.) But I have no ajax experience and fear there might be problems I’m not foreseeing or easy ways to do this kind of ajax in a better way.</p>
<p>Issues I considered:</p>
<ul>
<li>CORS requires that the server that responds to an ajax request, must first have served the html file making the request.</li>
<li>Ajax POSTs are not idempotent</li>
<li>The browser will automatically call for a favicon</li>
</ul>
<p>On the server, the switch statement is going to get too long if I keep adding cases for each maintenance page. I’ll clean that up and welcome any general advice you’re willing to offer, but my question here is if the ajax technique is reasonable for my needs?</p>
<p>I’m including colorized-VSCode images of the code to make reading it easier, as well as actual code you can copy to a computer and run. The sample code can be tested as is by putting the .js and .html file in the same directory and naming them "test_ajax_post_json_sans_form”. You would test by executing "node filename" in the command console, and then loading http://localhost:8000/filename in your browser. I used Chrome.</p>
<p>html with client code image ORIGINAL (SEE snippet for update):
<a href="https://i.stack.imgur.com/evKoz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evKoz.png" alt="enter image description here" /></a></p>
<p>js image:
<a href="https://i.stack.imgur.com/mUpA2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mUpA2.png" alt="enter image description here" /></a></p>
<p>I included the code in snippets, but it requires node.js to run, so you'd have to copy it to a computer with node.js. (HTML UPDATED per suggestions 10/11):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
const host = 'localhost';
const http = require('http'); // VSCode shows 3 dots under "require" and says something about NodeRequire???
const fs = require('fs').promises;
const port = 8000;
const requestListener = function (req, res) {
switch (req.url) {
case "/test_ajax_post_json_sans_form.html": // serve an intial html file
fs.readFile(__dirname + '/test_ajax_post_json_sans_form.html')
.then(contents => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(contents);
})
.catch(err => {
res.writeHead(500);
res.end(err);
return;
});
break
case '/test_ajax_post_json_sans_form.html/ajaxTest1': // receive json, process, then return other json
let body = '';
req.on('data', (data) => {
body += data;
});
req.on('end', () => {
console.log(body); // to show all data has arrived
// here we will check or errors, create a complex return-object, stringify it, and send it back
const objToReturn = {data1: 'Test message from server', data2: 'could be a complex json object'};
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(objToReturn));
});
break
case '/favicon.ico':
// browser will call favicon automatically. This satisfies the request (though its failing
// won't keep the ajax from working).
fs.readFile(__dirname + '/favicon.ico')
.then(contents => {
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end(contents);
})
.catch(err => { // lacking favicon will not impact test
res.writeHead(200, {'Content-Type': 'image/x-icon'});
res.end();
});
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:'Resource not found'})); // in production, might load a not-found page here
}
}
const server = http.createServer(requestListener);
server.listen(port,host, () => { // binds the server object to a newtwork address
console.log(`Server is running on http://${host}:${port}. (^c to cancel)`);
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html><body>
<button type="button" id="submitButton">Send and then Receive JSON</button>
<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.
<br>Then the JSON response string from the server will replace what is below.
<br><br>
<div id='messageArea'>
Message to replace via ajax.
</div>
<script>
'use strict';
const submitButton = document.getElementById('submitButton');
const messageArea = document.getElementById('messageArea');
async function exchangeJSON() {
try {
submitButton.disabled = true;
// here can build a complex object to send
const objToSend = {message1: 'Test message from browser', message2: 'could be a complex JSON string'};
const response = await fetch('test_ajax_post_json_sans_form.html/ajaxTest1', {
method: 'POST',
body: JSON.stringify(objToSend)
});
if (response.ok) {
const jsonResponse = await response.json();
// here can parse, update screen, etc.
messageArea.textContent = JSON.stringify(jsonResponse);
}
//throw new Error('Test error in ExchangeJSON'); // uncomment for testing
} catch (error) {
messageArea.textContent = error;
} finally {
submitButton.disabled = false;
}
}
submitButton.addEventListener('click',exchangeJSON);
</script>
</body></html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong>Consider <code>fetch</code></strong> In modern browsers, which your code is guaranteed to be running in, <code>fetch</code> is usually a better choice than <code>XMLHttpRequest</code> - <code>fetch</code> is Promise-based (Promises are usually a bit nicer to work with than callbacks), its API is a bit cleaner to read and write, and it's a bit more concise.</p>\n<p><strong>Error handling</strong> The front-end has no error handling. If the request fails for whatever reason, there will be no indication of that to the user - after the button is pressed, it'll appear to be processing forever, without becoming un-disabled again. Consider</p>\n<ul>\n<li>Displaying the error message if there's an error, and</li>\n<li>Re-enabling the button if there's an error</li>\n</ul>\n<p><strong>Response</strong> If you want to show the response's JSON to the user:</p>\n<ul>\n<li>Don't set the response as <code>innerHTML</code> of an element. This can result in arbitrary code execution, unexpected additional HTML elements, and weird things related to HTML entities. Use <code>.textContent</code> instead.</li>\n<li>Since the response is JSON, maybe use a more code-like element, like a <code><pre></code>?</li>\n</ul>\n<p><strong>Callbacks</strong> When you add a listener, if you want a callback to run, if the callback doesn't take any arguments, you can pass the callback <em>directly</em> to <code>addEventListener</code> instead of wrapping it in another function.</p>\n<p><strong>Semicolons</strong> Some of your lines are missing semicolons. To be stylistically consistent, either use them or don't - and if you choose not to, hopefully you're an expert, else you may well run into problems with <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">automatic semicolon insertion</a>. Choose a style, then enforce it with <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">a linter</a>.</p>\n<p><strong>idSubmitButton?</strong> The selected button's variable name should probbaly be something like <code>submitButton</code> - the ID isn't relevant after it's been selected. Having <code>id</code> as a prefix in the id attribute is strange too, maybe just use <code>submitButton</code>.</p>\n<pre><code>\n<button type="button" id="submitButton">Send and then Receive JSON</button>\n<br>After clicking the button, the JSON string sent from the browser to the server will show in the console.\n<br>Then the JSON response string from the server will replace what is below.\n<br><br>\n<div class='error' style='color: red; display: none;'></div>\n<pre>Response gets inserted here</div>\n<script>\n 'use strict';\n const submitButton = document.getElementById('submitButton');\n function exchangeJSON() {\n submitButton.disabled = true; // assure post isn't sent again prior to a response\n const testObjToSend = { message1: 'Test message from browser', message2: 'could be a complex JSON string' };\n const errorDiv = document.querySelector('.error');\n errorDiv.style.display = 'none'; // Hide previous error\n // If you want to cause an error if the transaction is taking way longer than expected,\n // see https://stackoverflow.com/q/46946380\n fetch(\n 'ajaxTest1',\n {\n method: 'POST',\n body: JSON.stringify(testObjToSend),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n },\n )\n .then(res => res.text()) // if you wanted to expand error handling, could check if response is OK first\n .then((result) => {\n try {\n // If it's not JSON, this will throw\n JSON.parse(result);\n } catch(e) {\n // Send text to catch handler below\n throw new Error(result);\n }\n document.querySelector('pre').textContent = result;\n })\n .catch((error) => {\n errorDiv.style.display = 'block';\n errorDiv.textContent = JSON.stringify(error.message);\n })\n .finally(() => {\n submitButton.disabled = false; // post completed, so enable posting again\n });\n }\n submitButton.addEventListener('click', exchangeJSON);\n</script>\n</code></pre>\n<p>Onto the backend:</p>\n<p><strong>Serve static files with DRY code</strong> The request and response handler for both the HTML file and the favicon are currently hard-coded into the HTTP server. While that can <em>work</em>, it takes an annoying amount of boilerplate code and is kind of ugly. Consider if you had 4 or 5 static files to serve instead; your current method isn't scaleable.</p>\n<blockquote>\n<p>I prefer to avoid libraries unless there is compelling reason to use them</p>\n</blockquote>\n<p>This is a very compelling reason to use them. Although it's true they often come with many features one doesn't care about, it's worth it for the one or two or three nontrivial features that you would otherwise have to tediously implement yourself.</p>\n<p>Which one? I'd recommend Express, its use is very widespread, and it's well-documented on their site, on Stack Overflow, and on many other places around the internet.</p>\n<p><strong>Separate routes into different files</strong> Although I refactored all but one out below, for the general case when you have multiple non-static endpoints on a server that need to handle different logic, consider separating out the different routes into different files. For example, you could have one file that exports a function that handles <code>ajaxTest1</code> requests, and another file that exports a function that handles <code>login</code> requests (just as an example). As your application grows, this is much more maintainable than putting everything into a single file.</p>\n<pre><code>'use strict';\nconst port = 8000;\nconst express = require('express');\n// Recommended to use compression if you're transferring large files:\n// https://github.com/expressjs/compression\nconst compression = require('compression');\n\nconst app = express();\napp\n .use(compression())\n // Put static files into the "public" directory:\n .use(express.static(__dirname + '/public'))\n // Parse JSON request bodies:\n .use(express.json())\n .post('/ajaxTest1', (req, res) => {\n console.log(req.body);\n res.status(200).json({ data1: 'Test message from server', data2: 'could be a complex json object' });\n })\n .listen(port);\nconsole.log(`Server is running on http://localhost:${port}. (^c to cancel)`);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:33:26.723",
"Id": "491476",
"Score": "0",
"body": "Thank you CertainPerformance. This is enormously helpful! Some of this I understand immediately and other parts will take me a while to comprehend, but I wanted to express gratitude right away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:49:03.007",
"Id": "491551",
"Score": "0",
"body": "I updated the html snippet to reflect CertainPerformance suggestions to the best of my ability. It's much better. Had I presented this to begin with, would there have been other suggestions? I noticed accidentally that html ids can be accessed directly, so that it is possible (at least in Chrome) to write something like \"submitButton.disable = true\" rather than \"document.getElementById('submitButton').disable = true\". I found discussion years ago that suggested sticking with getElementById, but no recent discussion. Is it still best practice to use the verbose technique?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:45:48.353",
"Id": "491556",
"Score": "1",
"body": "IDs becoming global variables happens to be something that can be relied on, but it's poor practice. If it were me, since implicit global creation can be a source of bugs, I'd avoid IDs entirely and use classes (or some other method) to select the elements instead - that's why I did `const errorDiv = document.querySelector('.error');`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T19:19:00.040",
"Id": "500670",
"Score": "0",
"body": "browser support for fetch: https://caniuse.com/fetch 95.61% availability"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:19:36.683",
"Id": "250487",
"ParentId": "250472",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250487",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T16:23:39.897",
"Id": "250472",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"reinventing-the-wheel",
"json",
"ajax"
],
"Title": "AJAX with Vanilla Node.js/JavaScript – POST JSON without a form"
}
|
250472
|
<p>I decided to try my hand at a Hangman game to familiarize myself a bit with the language.</p>
<pre class="lang-rs prettyprint-override"><code>use std::io::{stdin, stdout, Write};
fn main() {
let stdin = stdin();
let mut stdout = stdout();
let to_guess = String::from("BENEDICT");
let mut letters: u128 = 0;
loop {
// Replace unguessed letters of to_guess by underscores
let current = to_guess.chars().map(|x| {
if x <= 127 as char && letters & (1 << x as u8) > 0 {
x
} else {
'_'
}
});
// Add spaces between letters
let current = current
.map(|x| x.to_string() + &' '.to_string())
.collect::<Vec<String>>()
.join(" ");
println!("Current word: {}", current.trim_end());
if !current.contains('_') {
println!("Congratulations!");
break;
}
print!("Enter new letter: ");
stdout.flush().unwrap();
let mut letter = String::new();
stdin.read_line(&mut letter).expect("Invalid letter");
if letter.trim().len() != 1 {
println!("Use only one ASCII letter");
continue;
}
let letter = letter.to_uppercase().chars().next().unwrap();
letters |= 1 << letter as u8
}
}
</code></pre>
<p>The <code>to_guess</code> word is hardcoded, and there is an unlimited number of guesses.</p>
<p>To store letters already guessed, I use an <code>u128</code> and flag the corresponding bit. It should be ok since all ASCII letters are represented by <code>u8</code> < 128.</p>
<p>Can you help me review the code, are there "Rust" things I missed?</p>
|
[] |
[
{
"body": "<p>Welcome to Rust. Here's some suggestions to get you started:</p>\n<h1>Creating idiomatic use declarations</h1>\n<p>It is not common in Rust to bring a function into scope directly via a use declaration. Instead, <code>io::stdin</code> and <code>io::stdout</code> are preferred. See the section <a href=\"https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#creating-idiomatic-use-paths\" rel=\"nofollow noreferrer\">Creating Idiomatic use Paths</a> in the book for more information.</p>\n<h1>Using structs to self-document code</h1>\n<p>You included this sentence in your explanation of the code:</p>\n<blockquote>\n<p>To store letters already guessed, I use an <code>u128</code> and flag the\ncorresponding bit. It should be ok since all ASCII letters are\nrepresented by <code>u8</code> < 128.</p>\n</blockquote>\n<p>It is preferable to include this information in the code itself. In this case, we can introduce a <code>struct</code>:</p>\n<pre><code>#[derive(Clone, Copy, Debug, Default)]\nstruct AsciiSet {\n flag: u128,\n}\n\nimpl AsciiSet {\n fn new() -> Self {\n Self { flag: 0 }\n }\n\n fn push(&mut self, letter: u8) {\n self.flag |= (1 << letter);\n }\n\n fn contains(&self, letter: u8) -> bool {\n (self.flag & (1 << letter)) != 0\n }\n}\n</code></pre>\n<p>and modify the code accordingly:</p>\n<pre><code>let mut letters = AsciiSet::new();\n\nloop {\n // ...\n if letters.contains(letter) { /* ... /* }\n\n // ...\n letters.push(letter);\n}\n</code></pre>\n<h1>Checking for ASCII</h1>\n<p><code>letter as u8</code> truncates the character if <code>!letter.is_ascii()</code>. Check for this case and prompt the user accordingly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T03:06:03.063",
"Id": "250777",
"ParentId": "250476",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T18:25:55.373",
"Id": "250476",
"Score": "2",
"Tags": [
"beginner",
"rust",
"hangman"
],
"Title": "New to Rust: Hangman game"
}
|
250476
|
<p>I'm making the very common example of Factory design pattern which creates a factory of cars and return an instance of a car. I found a example here <a href="https://refactoring.guru/design-patterns/factory-method/php/example" rel="nofollow noreferrer">https://refactoring.guru/design-patterns/factory-method/php/example</a> and decided to make my own factory. My question is why do I need a Creator for each car?</p>
<pre><code><?php
interface Car
{
public function drive();
}
</code></pre>
<pre><code><?php
require_once('Car.php');
class Audi implements Car
{
public function drive()
{
return "driving an Audi";
}
}
</code></pre>
<pre><code><?php
require_once('Car.php');
class Mercedes implements Car
{
public function drive()
{
return "driving an Mercedes";
}
}
</code></pre>
<pre><code><?php
abstract class CarFactory
{
abstract public function factoryMethod(): Car;
public function someOperation(): string
{
// Call the factory method to create a Product object.
$product = $this->factoryMethod();
// Now, use the product.
$result = "I want to drive something..... " .
$product->drive();
return $result;
}
}
</code></pre>
<pre><code><?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Audi.php');
class AudiCreator extends CarFactory
{
public function factoryMethod(): Car
{
return new Audi();
}
}
</code></pre>
<pre><code><?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Mercedes.php');
class MercedesCreator extends CarFactory
{
public function factoryMethod(): Car
{
return new Mercedes();
}
}
</code></pre>
<pre><code><?php
require_once('car/AudiCreator.php');
require_once('car/MercedesCreator.php');
function clientCode(CarFactory $carFactory)
{
// ...
echo "Client: "
. $carFactory->someOperation();
// ...
}
echo "The client . <br>";
clientCode(new AudiCreator());
echo "\r\n";
echo "<br>";
echo "<br>";
clientCode(new MercedesCreator());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T09:37:55.637",
"Id": "491503",
"Score": "1",
"body": "Find yourself a real world example of factory pattern. You've taken a misleading implementation written by Someone who probably did not understand the pattern himself and you renamed the classes. Cars, animals and alike are just crappy examples of something that lacks purpose, too far from reality, too far from problems we actually solve every day."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:29:14.030",
"Id": "491522",
"Score": "1",
"body": "Is this working code from a project you wrote, that is a requirement for the Code Review Site. Besides learning factory patterns what is the ultimate goal of what the code is supposed to do? That needs to be clearly stated in the question, generally as part of the title and in an English paragraph following the title. Please see the [guidelines for asking a good question](https://codereview.stackexchange.com/help/how-to-ask). As a side note, the model you chose is too simple which is why you are asking about different creators."
}
] |
[
{
"body": "<p>I think you're thinking of this backwards. The point isn't that you need to define special subclasses to use the factory method. Rather, when you need to define special subclasses containing their own complex functionality, then you use the factory method.</p>\n<p>From the <a href=\"https://www.google.com/books/edition/Design_Patterns/6oHuKQe3TjQC?hl=en&gbpv=0\" rel=\"nofollow noreferrer\">Gang of Four</a>:</p>\n<blockquote>\n<p>Use the Factory Method pattern when a class can't anticipate the class of objects it must create, [or it] wants its subclasses to specify the classes it creates [...].</p>\n</blockquote>\n<p>I think part of the problem is that your own example is a bit confusing. Interfaces are more for defining things different objects can <em>do</em>. You'll often hear people describe an interface as a sort of contract, because any object that implements an interface is required to implement every function of that interface. A <code>Car</code> would be more logically defined as a class because an Audi and a BMW are a <strong>type of</strong> car. On the other hand, it might make sense to define a <code>Drivable</code> interface, implemented by an abstract <code>Vehicle</code> class.</p>\n<pre><code>interface Drivable\n{\n public function drive();\n}\n</code></pre>\n<p>You could then define abstract base classes for each of the generic base object classes that implement this interface.</p>\n<pre><code>abstract class Vehicle implements Drivable\n{\n abstract public function drive();\n}\n</code></pre>\n<p>Once you do that, then you can implement functionality for each object.</p>\n<pre><code>abstract class Car extends Vehicle\n{\n abstract public function drive();\n}\n\nclass Audi extends Car\n{\n public function drive()\n {\n //...\n }\n}\n\nabstract class Aircraft extends Vehicle\n{\n abstract public function drive();\n}\n\nclass Airbus extends Aircraft\n{\n public function drive()\n {\n // ...\n }\n}\n</code></pre>\n<p>Keeping with the literal nature of your example, think about how different an aircraft factory and a car factory are. They're both factories that make vehicles, sure, (which is why their respective factories could -and probably would- be derived from the same base abstract <code>VehicleFactory</code> class) but the process of building an aircraft is so different from that of building a car that you <em>have</em> to define special factory subclasses for each of them.</p>\n<p>Getting more specific, let's focus on why and when you would use a factory. Suppose you're writing a game where a player can purchase a car. How do you know which car to instantiate until the user picks it?</p>\n<p>A simple script might do something like this.</p>\n<pre><code>$car = null;\n\nswitch ($choice) {\n case 'BMW': {\n $car = new BMW();\n } break;\n\n case 'Audi': {\n $car = new Audi();\n } break;\n\n ...\n}\n\n$car->drive();\n</code></pre>\n<p>This is all the factory pattern is. The difference is that an actual factory class gives you several benefits that this simple script doesn't.</p>\n<p>First of all, consider a <code>CarFactory</code> class that replicates the above script's functionality.</p>\n<pre><code>class CarFactory\n{\n public static function create($car) : Car\n {\n switch ($car)\n {\n case 'BMW': return new BMW();\n case 'Audi': return new Audi();\n // ...\n }\n }\n}\n\n$car = CarFactory::create($choice);\n$car->drive();\n</code></pre>\n<p>Right off the bat, you don't need <code>null</code> as the sentinel value for "the user hasn't picked a car yet." The car doesn't exist yet, so the car variable doesn't exist yet.</p>\n<p>Second, a script can't inherit or be derived from anything; it just is. In contrast, if you wanted your player to also be able to purchase an <code>Aircraft</code>, or any kind of transport derived from the <code>Vehicle</code> class, you can define a base <code>VehicleFactory</code> class from which you can implement your <code>CarFactory</code> and <code>AircraftFactory</code> classes.</p>\n<pre><code>interface Build\n{\n public static function build($choice);\n}\n\nabstract class VehicleFactory implements Build\n{\n abstract public static function build($choice) : Vehicle;\n}\n\nclass AircraftFactory extends VehicleFactory\n{\n public static function build($aircraft) : Aircraft\n {\n switch ($aircraft)\n {\n case 'Airbus': return new Airbus();\n case 'Boeing': return new Boeing();\n // ...\n }\n }\n}\n\nclass CarFactory extends VehicleFactory\n{\n public static function build($car) : Car\n {\n switch ($car)\n {\n case 'BMW': return new BMW();\n case 'Audi': return new Audi();\n // ...\n }\n }\n}\n\n$aircraft = AircraftFactory::build($choice);\n$aircraft->drive();\n\n$car = CarFactory::build($choice);\n$car->drive();\n</code></pre>\n<p>Hopefully this gives you an idea of why the factory pattern is useful. The upshot is that your base factory class defines the interface by which users will request an object be created, and the factory subclasses take care of the actual definition for how it happens. In addition, defining each factory's return type in terms of a base object (i.e..., the <code>CarFactory</code> returns a <code>Car</code>) allows us to choose the actual subclass of that object that actually gets created at runtime (users can pick a <code>BMW</code> or an <code>Audi</code>, both of which are <code>Cars</code>, all of which are <code>Vehicles</code>, all of which are <code>Drivable</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:18:13.353",
"Id": "491520",
"Score": "0",
"body": "Thank you for your explanation, now it's more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:34:07.957",
"Id": "491523",
"Score": "0",
"body": "Great answer to a poor question, you might want to flag questions that are too vague until you can vote to close."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T04:59:57.290",
"Id": "250495",
"ParentId": "250480",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250495",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T19:19:14.990",
"Id": "250480",
"Score": "0",
"Tags": [
"php",
"design-patterns"
],
"Title": "Learning factory design pattern"
}
|
250480
|
<p>a Littlewood polynomial is a polynomial where each coefficient is ether -1 or 1 and when the complex roots of them it produces a nice image. As a result I decided to make a program in c++ that plots a heatmap of the complex roots of randomly chosen Littlewood polynomials. Moreover at first I thought it would be as using GSL(gnu scientific library) as it already had a polynomial solver and libpng. However I after implementing a basic version of it using GSL I realized that GSL was to slow to use. Consequently that meant I had to find another polynomial library and after a little searching I found this <a href="https://www.codeproject.com/articles/674149/a-real-polynomial-class-with-root-finder" rel="noreferrer">https://www.codeproject.com/articles/674149/a-real-polynomial-class-with-root-finder</a>. Then after cleaning up that library and learning how to use libpng it was mostly smooth sailing. However my main concerns are that I could be still be ways of improving the performance of the code that I don't know of and that I could still improve the code quality in ways that I don't know of.</p>
<p><code>png.hh</code></p>
<pre><code>#ifndef PNG_HH
#define PNG_HH
#include <png.h>
namespace png
{
void write_image(char const *filename, std::uint8_t const *image_data, std::uint32_t image_width, std::uint32_t image_height)
{
/* create a zeroed out png_image struct */
png_image output_png;
std::memset(&output_png, 0, sizeof(output_png));
output_png.version = PNG_IMAGE_VERSION;
output_png.format = PNG_FORMAT_GRAY;
output_png.width = image_width;
output_png.height = image_height;
/* write the png file */
png_image_write_to_file(&output_png, filename, 0, image_data, image_height, nullptr);
/* cleanup */
png_image_free(&output_png);
}
}
#endif
</code></pre>
<p><code>PolynomialRootFinder.hh</code></p>
<pre><code>//=======================================================================
// Copyright (C) 2003-2013 William Hallahan
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//=======================================================================
//**********************************************************************
// File: PolynomialRootFinder.h
// Author: Bill Hallahan
// Date: January 30, 2003
//
// Abstract:
//
// This file contains the definition for class PolynomialRootFinder.
//
//**********************************************************************
#ifndef POLYNOMIALROOTFINDER_H
#define POLYNOMIALROOTFINDER_H
#include <array>
//======================================================================
// Class definition.
//======================================================================
template<std::int32_t degree>
struct PolynomialRootFinder
{
std::array<double, degree + 1> m_p_vector;
std::array<double, degree + 1> m_qp_vector;
std::array<double, degree + 1> m_k_vector;
std::array<double, degree + 1> m_qk_vector;
std::array<double, degree + 1> m_svk_vector;
std::int32_t m_n;
std::int32_t m_n_plus_one;
double m_real_s;
double m_imag_s;
double m_u;
double m_v;
double m_a;
double m_b;
double m_c;
double m_d;
double m_a1;
double m_a2;
double m_a3;
double m_a6;
double m_a7;
double m_e;
double m_f;
double m_g;
double m_h;
double m_real_sz;
double m_imag_sz;
double m_real_lz;
double m_imag_lz;
double m_are;
double m_mre;
enum class RootStatus_T
{
SUCCESS,
LEADING_COEFFICIENT_IS_ZERO,
SCALAR_VALUE_HAS_NO_ROOTS,
FAILED_TO_CONVERGE
};
PolynomialRootFinder::RootStatus_T FindRoots(double *coefficient_ptr,
double *real_zero_vector_ptr,
double *imaginary_zero_vector_ptr,
std::int32_t *number_of_roots_found_ptr = 0);
std::int32_t Fxshfr(std::int32_t l2var);
std::int32_t QuadraticIteration(double uu, double vv);
std::int32_t RealIteration(double &sss, std::int32_t &flag);
std::int32_t CalcSc();
void NextK(std::int32_t itype);
void Newest(std::int32_t itype, double &uu, double &vv);
void QuadraticSyntheticDivision(std::int32_t n_plus_one,
double u,
double v,
double *p_ptr,
double *q_ptr,
double &a,
double &b);
void SolveQuadraticEquation(double a,
double b,
double c,
double &sr,
double &si,
double &lr,
double &li);
};
#include <cmath>
#include <float.h>
namespace
{
//------------------------------------------------------------------
// The following machine constants are used in this method.
//
// f_BASE The base of the floating postd::int32_t number system used.
//
// f_ETA The maximum relative representation error which
// can be described as the smallest positive floating
// postd::int32_t number such that 1.0 + f_ETA is greater than 1.0.
//
// f_MAXIMUM_FLOAT The largest floating postd::int32_t number.
//
// f_MINIMUM_FLOAT The smallest positive floating postd::int32_t number.
//
//------------------------------------------------------------------
constexpr float f_BASE = 2.0;
constexpr float f_ETA = FLT_EPSILON;
constexpr float f_ETA_N = (10.0f) * f_ETA;
constexpr float f_ETA_N_SQUARED = (100.0f) * f_ETA;
constexpr float f_MAXIMUM_FLOAT = FLT_MAX;
constexpr float f_MINIMUM_FLOAT = FLT_MIN;
constexpr float f_XX_INITIAL_VALUE = (0.70710678f);
constexpr float f_COSR_INITIAL_VALUE = (-0.069756474f);
constexpr float f_SINR_INITIAL_VALUE = (0.99756405f);
};
//======================================================================
// Member Function: PolynomialRootFinder::FindRoots
//
// Abstract:
//
// This method determines the roots of a polynomial which
// has real coefficients. This code is based on FORTRAN
// code published in reference [1]. The method is based on
// an algorithm the three-stage algorithm described in
// Jenkins and Traub [2].
//
// 1. "Collected Algorithms from ACM, Volume III", Algorithms 493-545
// 1983. (The root finding algorithms is number 493)
//
// 2. Jenkins, M. A. and Traub, J. F., "A three-stage algorithm for
// real polynomials using quadratic iteration", SIAM Journal of
// Numerical Analysis, 7 (1970), 545-566
//
// 3. Jenkins, M. A. and Traub, J. F., "Principles for testing
// polynomial zerofinding programs", ACM TOMS 1,
// 1 (March 1975), 26-34
//
//
// Input:
//
// All vectors below must be at least a length equal to degree + 1.
//
// coefficicent_ptr A double precision vector that contains
// the polynomial coefficients in order
// of increasing power.
//
// degree The degree of the polynomial.
//
// real_zero_vector_ptr A double precision vector that will
// contain the real parts of the roots
// of the polynomial when this method
// returns.
//
// imaginary_zero_vector_ptr A double precision vector that will
// contain the real parts of the roots
// of the polynomial when this method
// returns.
//
// number_of_roots_found_ptr A postd::int32_ter to an std::int32_teger that will
// equal the number of roots found when
// this method returns. If the method
// returns SUCCESS then this value will
// always equal the degree of the
// polynomial.
//
// Return Value:
//
// The function returns an enum value of type
// 'PolynomialRootFinder::RootStatus_T'.
//
//======================================================================
template<std::int32_t degree>
typename PolynomialRootFinder<degree>::RootStatus_T PolynomialRootFinder<degree>::FindRoots(
double *coefficient_vector_ptr,
double *real_zero_vector_ptr,
double *imaginary_zero_vector_ptr,
std::int32_t *number_of_roots_found_ptr)
{
//--------------------------------------------------------------
// The algorithm fails if the polynomial is not at least
// degree on or the leading coefficient is zero.
//--------------------------------------------------------------
PolynomialRootFinder::RootStatus_T status;
//--------------------------------------------------------------
// Allocate temporary vectors used to find the roots.
//--------------------------------------------------------------
std::array<double, degree + 1> temp_vector;
std::array<double, degree + 1> pt_vector;
//--------------------------------------------------------------
// m_are and m_mre refer to the unit error in + and *
// respectively. they are assumed to be the same as
// f_ETA.
//--------------------------------------------------------------
m_are = f_ETA;
m_mre = f_ETA;
double lo = f_MINIMUM_FLOAT / f_ETA;
//--------------------------------------------------------------
// Initialization of constants for shift rotation.
//--------------------------------------------------------------
double xx = f_XX_INITIAL_VALUE;
double yy = -xx;
double cosr = f_COSR_INITIAL_VALUE;
double sinr = f_SINR_INITIAL_VALUE;
m_n = degree;
m_n_plus_one = m_n + 1;
//--------------------------------------------------------------
// Make a copy of the coefficients in reverse order.
//--------------------------------------------------------------
std::int32_t ii = 0;
for (ii = 0; ii < m_n_plus_one; ++ii) {
m_p_vector[m_n - ii] = coefficient_vector_ptr[ii];
}
//--------------------------------------------------------------
// Assume failure. The status is set to SUCCESS if all
// the roots are found.
//--------------------------------------------------------------
status = PolynomialRootFinder::RootStatus_T::FAILED_TO_CONVERGE;
//--------------------------------------------------------------
// If there are any zeros at the origin, remove them.
//--------------------------------------------------------------
std::int32_t jvar = 0;
while (m_p_vector[m_n] == 0.0) {
jvar = degree - m_n;
real_zero_vector_ptr[jvar] = 0.0;
imaginary_zero_vector_ptr[jvar] = 0.0;
m_n_plus_one = m_n_plus_one - 1;
m_n = m_n - 1;
}
//--------------------------------------------------------------
// Loop and find polynomial zeros. In the original algorithm
// this loop was an infinite loop. Testing revealed that the
// number of main loop iterations to solve a polynomial of a
// particular degree is usually about half the degree.
// We loop twice that to make sure the solution is found.
// (This should be revisited as it might preclude solving
// some large polynomials.)
//--------------------------------------------------------------
for (std::int32_t count = 0; count < degree; ++count) {
//----------------------------------------------------------
// Check for less than 2 zeros to finish the solution.
//----------------------------------------------------------
if (m_n <= 2) {
if (m_n > 0) {
//--------------------------------------------------
// Calculate the final zero or pair of zeros.
//--------------------------------------------------
if (m_n == 1) {
real_zero_vector_ptr[degree - 1] =
-m_p_vector[1] / m_p_vector[0];
imaginary_zero_vector_ptr[degree - 1] = 0.0;
} else {
SolveQuadraticEquation(
m_p_vector[0],
m_p_vector[1],
m_p_vector[2],
real_zero_vector_ptr[degree - 2],
imaginary_zero_vector_ptr[degree - 2],
real_zero_vector_ptr[degree - 1],
imaginary_zero_vector_ptr[degree - 1]);
}
}
m_n = 0;
status = PolynomialRootFinder::RootStatus_T::SUCCESS;
break;
} else {
//------------------------------------------------------
// Find largest and smallest moduli of coefficients.
//------------------------------------------------------
double max = 0.0;
double min = f_MAXIMUM_FLOAT;
double xvar;
for (ii = 0; ii < m_n_plus_one; ++ii) {
xvar = (double)(::fabs((double)(m_p_vector[ii])));
if (xvar > max) {
max = xvar;
}
if ((xvar != 0.0) && (xvar < min)) {
min = xvar;
}
}
//------------------------------------------------------
// Scale if there are large or very small coefficients.
// Computes a scale factor to multiply the coefficients
// of the polynomial. The scaling is done to avoid
// overflow and to avoid undetected underflow from
// std::int32_terfering with the convergence criterion.
// The factor is a power of the base.
//------------------------------------------------------
bool do_scaling_flag = false;
double sc = lo / min;
if (sc <= 1.0) {
do_scaling_flag = f_MAXIMUM_FLOAT / sc < max;
} else {
do_scaling_flag = max < 10.0;
if (!do_scaling_flag) {
if (sc == 0.0) {
sc = f_MINIMUM_FLOAT;
}
}
}
//------------------------------------------------------
// Conditionally scale the data.
//------------------------------------------------------
if (do_scaling_flag) {
std::int32_t lvar = (std::int32_t)(::log(sc) / ::log(f_BASE) + 0.5);
double factor = ::pow((double)(f_BASE * 1.0), double(lvar));
if (factor != 1.0) {
for (ii = 0; ii < m_n_plus_one; ++ii) {
m_p_vector[ii] = factor * m_p_vector[ii];
}
}
}
//------------------------------------------------------
// Compute lower bound on moduli of zeros.
//------------------------------------------------------
for (ii = 0; ii < m_n_plus_one; ++ii) {
pt_vector[ii] = (double)(::fabs((double)(m_p_vector[ii])));
}
pt_vector[m_n] = -pt_vector[m_n];
//------------------------------------------------------
// Compute upper estimate of bound.
//------------------------------------------------------
xvar = (double)
(::exp((::log(-pt_vector[m_n]) - ::log(pt_vector[0]))
/ (double)(m_n)));
//------------------------------------------------------
// If newton step at the origin is better, use it.
//------------------------------------------------------
double xm;
if (pt_vector[m_n - 1] != 0.0) {
xm = -pt_vector[m_n] / pt_vector[m_n - 1];
if (xm < xvar) {
xvar = xm;
}
}
//------------------------------------------------------
// Chop the std::int32_terval (0, xvar) until ff <= 0
//------------------------------------------------------
double ff;
for (;;) {
xm = (double)(xvar * 0.1);
ff = pt_vector[0];
for (ii = 1; ii < m_n_plus_one; ++ii) {
ff = ff * xm + pt_vector[ii];
}
if (ff <= 0.0) {
ff = 0.0;
break;
}
xvar = xm;
}
double dx = xvar;
//------------------------------------------------------
// Do newton iteration until xvar converges to two
// decimal places.
//------------------------------------------------------
for (;;) {
if ((double)(::fabs(dx / xvar)) <= 0.005) {
break;
}
ff = pt_vector[0];
double df = ff;
for (ii = 1; ii < m_n; ++ii) {
ff = ff * xvar + pt_vector[ii];
df = df * xvar + ff;
}
ff = ff * xvar + pt_vector[m_n];
dx = ff / df;
xvar = xvar - dx;
}
double bnd = xvar;
//------------------------------------------------------
// Compute the derivative as the std::int32_tial m_k_vector
// polynomial and do 5 steps with no shift.
//------------------------------------------------------
std::int32_t n_minus_one = m_n - 1;
for (ii = 1; ii < m_n; ++ii) {
m_k_vector[ii] =
(double)(m_n - ii) * m_p_vector[ii] / (double)(m_n);
}
m_k_vector[0] = m_p_vector[0];
double aa = m_p_vector[m_n];
double bb = m_p_vector[m_n - 1];
bool zerok_flag = m_k_vector[m_n - 1] == 0.0;
std::int32_t jj = 0;
for (jj = 1; jj <= 5; ++jj) {
double cc = m_k_vector[m_n - 1];
if (zerok_flag) {
//----------------------------------------------
// Use unscaled form of recurrence.
//----------------------------------------------
for (jvar = n_minus_one; jvar > 0; --jvar) {
m_k_vector[jvar] = m_k_vector[jvar - 1];
}
m_k_vector[0] = 0.0;
zerok_flag = m_k_vector[m_n - 1] == 0.0;
} else {
//----------------------------------------------
// Use scaled form of recurrence if value
// of m_k_vector at 0 is nonzero.
//----------------------------------------------
double tvar = -aa / cc;
for (jvar = n_minus_one; jvar > 0; --jvar) {
m_k_vector[jvar] =
tvar * m_k_vector[jvar - 1] + m_p_vector[jvar];
}
m_k_vector[0] = m_p_vector[0];
zerok_flag =
::fabs(m_k_vector[m_n - 1]) <= ::fabs(bb) * f_ETA_N;
}
}
//------------------------------------------------------
// Save m_k_vector for restarts with new shifts.
//------------------------------------------------------
for (ii = 0; ii < m_n; ++ii) {
temp_vector[ii] = m_k_vector[ii];
}
//------------------------------------------------------
// Loop to select the quadratic corresponding to
// each new shift.
//------------------------------------------------------
std::int32_t cnt = 0;
for (cnt = 1; cnt <= 20; ++cnt) {
//--------------------------------------------------
// Quadratic corresponds to a double shift to a
// non-real postd::int32_t and its complex conjugate. The
// postd::int32_t has modulus 'bnd' and amplitude rotated
// by 94 degrees from the previous shift.
//--------------------------------------------------
double xxx = cosr * xx - sinr * yy;
yy = sinr * xx + cosr * yy;
xx = xxx;
m_real_s = bnd * xx;
m_imag_s = bnd * yy;
m_u = -2.0 * m_real_s;
m_v = bnd;
//--------------------------------------------------
// Second stage calculation, fixed quadratic.
// Variable nz will contain the number of
// zeros found when function Fxshfr() returns.
//--------------------------------------------------
std::int32_t nz = Fxshfr(20 * cnt);
if (nz != 0) {
//----------------------------------------------
// The second stage jumps directly to one of
// the third stage iterations and returns here
// if successful. Deflate the polynomial,
// store the zero or zeros and return to the
// main algorithm.
//----------------------------------------------
jvar = degree - m_n;
real_zero_vector_ptr[jvar] = m_real_sz;
imaginary_zero_vector_ptr[jvar] = m_imag_sz;
m_n_plus_one = m_n_plus_one - nz;
m_n = m_n_plus_one - 1;
for (ii = 0; ii < m_n_plus_one; ++ii) {
m_p_vector[ii] = m_qp_vector[ii];
}
if (nz != 1) {
real_zero_vector_ptr[jvar + 1] = m_real_lz;
imaginary_zero_vector_ptr[jvar + 1] = m_imag_lz;
}
break;
//----------------------------------------------
// If the iteration is unsuccessful another
// quadratic is chosen after restoring
// m_k_vector.
//----------------------------------------------
}
for (ii = 0; ii < m_n; ++ii) {
m_k_vector[ii] = temp_vector[ii];
}
}
}
}
//--------------------------------------------------------------
// If no convergence with 20 shifts then adjust the degree
// for the number of roots found.
//--------------------------------------------------------------
if (number_of_roots_found_ptr != 0) {
*number_of_roots_found_ptr = degree - m_n;
}
return status;
}
//======================================================================
// Computes up to l2var fixed shift m_k_vector polynomials,
// testing for convergence in the linear or quadratic
// case. initiates one of the variable shift
// iterations and returns with the number of zeros
// found.
//
// l2var An std::int32_teger that is the limit of fixed shift steps.
//
// Return Value:
// nz An std::int32_teger that is the number of zeros found.
//======================================================================
template<std::int32_t degree>
std::int32_t PolynomialRootFinder<degree>::Fxshfr(std::int32_t l2var)
{
//------------------------------------------------------------------
// Evaluate polynomial by synthetic division.
//------------------------------------------------------------------
QuadraticSyntheticDivision(m_n_plus_one,
m_u,
m_v,
m_p_vector.data(),
m_qp_vector.data(),
m_a,
m_b);
std::int32_t itype = CalcSc();
std::int32_t nz = 0;
float betav = 0.25;
float betas = 0.25;
float oss = (float)(m_real_s);
float ovv = (float)(m_v);
float ots;
float otv;
double ui = 0.0;
double vi = 0.0;
double svar;
for (std::int32_t jvar = 1; jvar <= l2var; ++jvar) {
//--------------------------------------------------------------
// Calculate next m_k_vector polynomial and estimate m_v.
//--------------------------------------------------------------
NextK(itype);
itype = CalcSc();
Newest(itype, ui, vi);
float vv = (float)(vi);
//--------------------------------------------------------------
// Estimate svar
//--------------------------------------------------------------
float ss = 0.0;
if (m_k_vector[m_n - 1] != 0.0) {
ss = (float)(-m_p_vector[m_n] / m_k_vector[m_n - 1]);
}
float tv = 1.0;
float ts = 1.0;
if ((jvar != 1) && (itype != 3)) {
//----------------------------------------------------------
// Compute relative measures of convergence of
// svar and m_v sequences.
//----------------------------------------------------------
if (vv != 0.0) {
tv = (float)(::fabs((vv - ovv) / vv));
}
if (ss != 0.0) {
ts = (float)(::fabs((ss - oss) / ss));
}
//----------------------------------------------------------
// If decreasing, multiply two most recent convergence
// measures.
//----------------------------------------------------------
float tvv = 1.0;
if (tv < otv) {
tvv = tv * otv;
}
float tss = 1.0;
if (ts < ots) {
tss = ts * ots;
}
//----------------------------------------------------------
// Compare with convergence criteria.
//----------------------------------------------------------
bool vpass_flag = tvv < betav;
bool spass_flag = tss < betas;
if (spass_flag || vpass_flag) {
//------------------------------------------------------
// At least one sequence has passed the convergence
// test. Store variables before iterating.
//------------------------------------------------------
double svu = m_u;
double svv = m_v;
std::int32_t ii = 0;
for (ii = 0; ii < m_n; ++ii) {
m_svk_vector[ii] = m_k_vector[ii];
}
svar = ss;
//------------------------------------------------------
// Choose iteration according to the fastest
// converging sequence.
//------------------------------------------------------
bool vtry_flag = false;
bool stry_flag = false;
bool exit_outer_loop_flag = false;
bool start_with_real_iteration_flag =
(spass_flag && ((!vpass_flag) || (tss < tvv)));
do {
if (!start_with_real_iteration_flag) {
nz = QuadraticIteration(ui, vi);
if (nz > 0) {
exit_outer_loop_flag = true;
break;
}
//----------------------------------------------
// Quadratic iteration has failed. flag
// that it has been tried and decrease
// the convergence criterion.
//----------------------------------------------
vtry_flag = true;
betav = (float)(betav * 0.25);
}
//--------------------------------------------------
// Try linear iteration if it has not been
// tried and the svar sequence is converging.
//--------------------------------------------------
if (((!stry_flag) && spass_flag)
|| start_with_real_iteration_flag) {
if (!start_with_real_iteration_flag) {
for (ii = 0; ii < m_n; ++ii) {
m_k_vector[ii] = m_svk_vector[ii];
}
} else {
start_with_real_iteration_flag = false;
}
std::int32_t iflag = 0;
nz = RealIteration(svar, iflag);
if (nz > 0) {
exit_outer_loop_flag = true;
break;
}
//----------------------------------------------
// Linear iteration has failed. Flag that
// it has been tried and decrease the
// convergence criterion.
//----------------------------------------------
stry_flag = true;
betas = (float)(betas * 0.25);
if (iflag != 0) {
//------------------------------------------
// If linear iteration signals an almost
// double real zero attempt quadratic
// iteration.
//------------------------------------------
ui = -(svar + svar);
vi = svar * svar;
continue;
}
}
//--------------------------------------------------
// Restore variables
//--------------------------------------------------
m_u = svu;
m_v = svv;
for (ii = 0; ii < m_n; ++ii) {
m_k_vector[ii] = m_svk_vector[ii];
}
//----------------------------------------------
// Try quadratic iteration if it has not been
// tried and the m_v sequence is converging.
//----------------------------------------------
} while (vpass_flag && (!vtry_flag));
if (exit_outer_loop_flag) {
break;
}
//------------------------------------------------------
// Recompute m_qp_vector and scalar values to
// continue the second stage.
//------------------------------------------------------
QuadraticSyntheticDivision(m_n_plus_one,
m_u,
m_v,
m_p_vector.data(),
m_qp_vector.data(),
m_a,
m_b);
itype = CalcSc();
}
}
ovv = vv;
oss = ss;
otv = tv;
ots = ts;
}
return nz;
}
//======================================================================
// Variable-shift m_k_vector-polynomial iteration for
// a quadratic factor converges only if the zeros are
// equimodular or nearly so.
//
// uu Coefficients of starting quadratic
// vv Coefficients of starting quadratic
//
// Return value:
// nz The number of zeros found.
//======================================================================
template<std::int32_t degree>
std::int32_t PolynomialRootFinder<degree>::QuadraticIteration(double uu, double vv)
{
//------------------------------------------------------------------
// Main loop
//------------------------------------------------------------------
double ui = 0.0;
double vi = 0.0;
float omp = 0.0F;
float relstp = 0.0F;
std::int32_t itype = 0;
bool tried_flag = false;
std::int32_t jvar = 0;
std::int32_t nz = 0;
m_u = uu;
m_v = vv;
for(;;) {
SolveQuadraticEquation(1.0,
m_u,
m_v,
m_real_sz,
m_imag_sz,
m_real_lz,
m_imag_lz);
//--------------------------------------------------------------
// Return if roots of the quadratic are real and not close
// to multiple or nearly equal and of opposite sign.
//--------------------------------------------------------------
if (::fabs(::fabs(m_real_sz) - ::fabs(m_real_lz)) > 0.01 * ::fabs(m_real_lz)) {
break;
}
//--------------------------------------------------------------
// Evaluate polynomial by quadratic synthetic division.
//------------------------------------------------------------------
QuadraticSyntheticDivision(m_n_plus_one,
m_u,
m_v,
m_p_vector.data(),
m_qp_vector.data(),
m_a,
m_b);
float mp = (float)(::fabs(m_a - m_real_sz * m_b) + ::fabs(m_imag_sz * m_b));
//--------------------------------------------------------------
// Compute a rigorous bound on the rounding error in
// evaluting m_p_vector.
//--------------------------------------------------------------
float zm = (float)(::sqrt((float)(::fabs((float)(m_v)))));
float ee = (float)(2.0 * (float)(::fabs((float)(m_qp_vector[0]))));
float tvar = (float)(-m_real_sz * m_b);
std::int32_t ii = 0;
for (ii = 1; ii < m_n; ++ii) {
ee = ee * zm + (float)(::fabs((float)(m_qp_vector[ii])));
}
ee = ee * zm + (float)(::fabs((float)(m_a)+tvar));
ee = (float)((5.0 * m_mre + 4.0 * m_are) * ee
- (5.0 * m_mre + 2.0 * m_are) * ((float)(::fabs((float)(m_a)+tvar)) + (float)(::fabs((float)(m_b))) * zm)
+ 2.0 * m_are * (float)(::fabs(tvar)));
//--------------------------------------------------------------
// Iteration has converged sufficiently if the polynomial
// value is less than 20 times this bound.
//--------------------------------------------------------------
if (mp <= 20.0 * ee) {
nz = 2;
break;
}
jvar = jvar + 1;
//--------------------------------------------------------------
// Stop iteration after 20 steps.
//--------------------------------------------------------------
if (jvar > 20) {
break;
}
if ((jvar >= 2) && ((relstp <= 0.01)
&& (mp >= omp) && (!tried_flag))) {
//----------------------------------------------------------
// A cluster appears to be stalling the convergence.
// Five fixed shift steps are taken with a m_u, m_v
// close to the cluster.
//----------------------------------------------------------
if (relstp < f_ETA) {
relstp = f_ETA;
}
relstp = (float)(::sqrt(relstp));
m_u = m_u - m_u * relstp;
m_v = m_v + m_v * relstp;
QuadraticSyntheticDivision(m_n_plus_one,
m_u,
m_v,
m_p_vector.data(),
m_qp_vector.data(),
m_a,
m_b);
for (ii = 0; ii < 5; ++ii) {
itype = CalcSc();
NextK(itype);
}
tried_flag = true;
jvar = 0;
}
omp = mp;
//--------------------------------------------------------------
// Calculate next m_k_vector polynomial and
// new m_u and m_v.
//--------------------------------------------------------------
itype = CalcSc();
NextK(itype);
itype = CalcSc();
Newest(itype, ui, vi);
//--------------------------------------------------------------
// If vi is zero the iteration is not converging.
//--------------------------------------------------------------
if (vi == 0.0) {
break;
}
relstp = (float)(::fabs((vi - m_v) / vi));
m_u = ui;
m_v = vi;
}
return nz;
}
//======================================================================
// Variable-shift h polynomial iteration for a real zero.
//
// sss Starting iterate
// flag Flag to indicate a pair of zeros near real axis.
//
// Return Value:
// Number of zero found.
//======================================================================
template<std::int32_t degree>
std::int32_t PolynomialRootFinder<degree>::RealIteration(double &sss, std::int32_t &flag)
{
//------------------------------------------------------------------
// Main loop
//------------------------------------------------------------------
double tvar = 0.0;
float omp = 0.0F;
std::int32_t nz = 0;
flag = 0;
std::int32_t jvar = 0;
double svar = sss;
for(;;) {
double pv = m_p_vector[0];
//--------------------------------------------------------------
// Evaluate m_p_vector at svar
//--------------------------------------------------------------
m_qp_vector[0] = pv;
std::int32_t ii = 0;
for (ii = 1; ii < m_n_plus_one; ++ii) {
pv = pv * svar + m_p_vector[ii];
m_qp_vector[ii] = pv;
}
float mp = (float)(::fabs(pv));
//--------------------------------------------------------------
// Compute a rigorous bound on the error in evaluating p
//--------------------------------------------------------------
double ms = (double)(::fabs(svar));
double ee = (m_mre / (m_are + m_mre)) * (double)(::fabs((double)(m_qp_vector[0])));
for (ii = 1; ii < m_n_plus_one; ++ii) {
ee = ee * ms + (float)(::fabs((double)(m_qp_vector[ii])));
}
//--------------------------------------------------------------
// Iteration has converged sufficiently if the
// polynomial value is less than 20 times this bound.
//--------------------------------------------------------------
if (mp <= 20.0 * ((m_are + m_mre) * ee - m_mre * mp)) {
nz = 1;
m_real_sz = svar;
m_imag_sz = 0.0;
break;
}
jvar = jvar + 1;
//--------------------------------------------------------------
// Stop iteration after 10 steps.
//--------------------------------------------------------------
if (jvar > 10) {
break;
}
if ((jvar >= 2)
&& ((::fabs(tvar) <= 0.001 * ::fabs(svar - tvar))
&& (mp > omp))) {
//----------------------------------------------------------
// A cluster of zeros near the real axis has been
// encountered. Return with flag set to initiate
// a quadratic iteration.
//----------------------------------------------------------
flag = 1;
sss = svar;
break;
}
//--------------------------------------------------------------
// Return if the polynomial value has increased significantly.
//--------------------------------------------------------------
omp = mp;
//--------------------------------------------------------------
// Compute t, the next polynomial, and the new iterate.
//--------------------------------------------------------------
double kv = m_k_vector[0];
m_qk_vector[0] = kv;
for (ii = 1; ii < m_n; ++ii) {
kv = kv * svar + m_k_vector[ii];
m_qk_vector[ii] = kv;
}
if (::fabs(kv) <= ::fabs(m_k_vector[m_n - 1]) * f_ETA_N) {
m_k_vector[0] = 0.0;
for (ii = 1; ii < m_n; ++ii) {
m_k_vector[ii] = m_qk_vector[ii - 1];
}
} else {
//----------------------------------------------------------
// Use the scaled form of the recurrence if the
// value of m_k_vector at svar is non-zero.
//----------------------------------------------------------
tvar = -pv / kv;
m_k_vector[0] = m_qp_vector[0];
for (ii = 1; ii < m_n; ++ii) {
m_k_vector[ii] = tvar * m_qk_vector[ii - 1] + m_qp_vector[ii];
}
}
//--------------------------------------------------------------
// Use unscaled form.
//--------------------------------------------------------------
kv = m_k_vector[0];
for (ii = 1; ii < m_n; ++ii) {
kv = kv * svar + m_k_vector[ii];
}
tvar = 0.0;
if (::fabs(kv) > ::fabs(m_k_vector[m_n - 1]) * f_ETA_N) {
tvar = -pv / kv;
}
svar = svar + tvar;
}
return nz;
}
//======================================================================
// This routine calculates scalar quantities used to compute
// the next m_k_vector polynomial and new estimates of the
// quadratic coefficients.
//
// Return Value:
// type std::int32_teger variable set here indicating how the
// calculations are normalized to avoid overflow.
//======================================================================
template<std::int32_t degree>
std::int32_t PolynomialRootFinder<degree>::CalcSc()
{
//------------------------------------------------------------------
// Synthetic division of m_k_vector by the quadratic 1, m_u, m_v.
//------------------------------------------------------------------
QuadraticSyntheticDivision(m_n,
m_u,
m_v,
m_k_vector.data(),
m_qk_vector.data(),
m_c,
m_d);
std::int32_t itype = 0;
if ((::fabs(m_c) <= ::fabs(m_k_vector[m_n - 1]) * f_ETA_N_SQUARED)
&& (::fabs(m_d) <= ::fabs(m_k_vector[m_n - 2]) * f_ETA_N_SQUARED)) {
//--------------------------------------------------------------
// itype == 3 Indicates the quadratic is almost a
// factor of m_k_vector.
//--------------------------------------------------------------
itype = 3;
} else if (::fabs(m_d) >= ::fabs(m_c)) {
//--------------------------------------------------------------
// itype == 2 Indicates that all formulas are divided by m_d.
//--------------------------------------------------------------
itype = 2;
m_e = m_a / m_d;
m_f = m_c / m_d;
m_g = m_u * m_b;
m_h = m_v * m_b;
m_a3 = (m_a + m_g) * m_e + m_h * (m_b / m_d);
m_a1 = m_b * m_f - m_a;
m_a7 = (m_f + m_u) * m_a + m_h;
} else {
//--------------------------------------------------------------
// itype == 1 Indicates that all formulas are divided by m_c.
//--------------------------------------------------------------
itype = 1;
m_e = m_a / m_c;
m_f = m_d / m_c;
m_g = m_u * m_e;
m_h = m_v * m_b;
m_a3 = m_a * m_e + (m_h / m_c + m_g) * m_b;
m_a1 = m_b - m_a * (m_d / m_c);
m_a7 = m_a + m_g * m_d + m_h * m_f;
}
return itype;
}
//======================================================================
// Computes the next k polynomials using scalars computed in CalcSc.
//======================================================================
template<std::int32_t degree>
void PolynomialRootFinder<degree>::NextK(std::int32_t itype)
{
std::int32_t ii = 0;
if (itype == 3) {
//--------------------------------------------------------------
// Use unscaled form of the recurrence if type is 3.
//--------------------------------------------------------------
m_k_vector[0] = 0.0;
m_k_vector[1] = 0.0;
for (ii = 2; ii < m_n; ++ii) {
m_k_vector[ii] = m_qk_vector[ii - 2];
}
} else {
double temp = m_a;
if (itype == 1) {
temp = m_b;
}
if (::fabs(m_a1) <= ::fabs(temp) * f_ETA_N) {
//----------------------------------------------------------
// If m_a1 is nearly zero then use a special form of
// the recurrence.
//----------------------------------------------------------
m_k_vector[0] = 0.0;
m_k_vector[1] = -m_a7 * m_qp_vector[0];
for (ii = 2; ii < m_n; ++ii) {
m_k_vector[ii] = m_a3 * m_qk_vector[ii - 2] - m_a7 * m_qp_vector[ii - 1];
}
} else {
//----------------------------------------------------------
// Use scaled form of the recurrence.
//----------------------------------------------------------
m_a7 = m_a7 / m_a1;
m_a3 = m_a3 / m_a1;
m_k_vector[0] = m_qp_vector[0];
m_k_vector[1] = m_qp_vector[1] - m_a7 * m_qp_vector[0];
for (ii = 2; ii < m_n; ++ii) {
m_k_vector[ii] =
m_a3 * m_qk_vector[ii - 2] - m_a7 * m_qp_vector[ii - 1] + m_qp_vector[ii];
}
}
}
return;
}
//======================================================================
// Compute new estimates of the quadratic coefficients using the
// scalars computed in CalcSc.
//======================================================================
template<std::int32_t degree>
void PolynomialRootFinder<degree>::Newest(std::int32_t itype, double &uu, double &vv)
{
//------------------------------------------------------------------
// Use formulas appropriate to setting of itype.
//------------------------------------------------------------------
if (itype == 3) {
//--------------------------------------------------------------
// If itype == 3 the quadratic is zeroed.
//--------------------------------------------------------------
uu = 0.0;
vv = 0.0;
} else {
double a4;
double a5;
if (itype == 2) {
a4 = (m_a + m_g) * m_f + m_h;
a5 = (m_f + m_u) * m_c + m_v * m_d;
} else {
a4 = m_a + m_u * m_b + m_h * m_f;
a5 = m_c + (m_u + m_v * m_f) * m_d;
}
//--------------------------------------------------------------
// Evaluate new quadratic coefficients.
//--------------------------------------------------------------
double b1 = -m_k_vector[m_n - 1] / m_p_vector[m_n];
double b2 = -(m_k_vector[m_n - 2] + b1 * m_p_vector[m_n - 1]) / m_p_vector[m_n];
double c1 = m_v * b2 * m_a1;
double c2 = b1 * m_a7;
double c3 = b1 * b1 * m_a3;
double c4 = c1 - c2 - c3;
double temp = a5 + b1 * a4 - c4;
if (temp != 0.0) {
uu = m_u - (m_u * (c3 + c2) + m_v * (b1 * m_a1 + b2 * m_a7)) / temp;
vv = m_v * (1.0 + c4 / temp);
}
}
return;
}
//======================================================================
// Divides p by the quadratic 1, u, v placing the quotient in q
// and the remainder in a,b
//======================================================================
template<std::int32_t degree>
void PolynomialRootFinder<degree>::QuadraticSyntheticDivision(std::int32_t n_plus_one,
double u,
double v,
double *p_ptr,
double *q_ptr,
double &a,
double &b)
{
b = p_ptr[0];
q_ptr[0] = b;
a = p_ptr[1] - u * b;
q_ptr[1] = a;
for (std::int32_t ii = 2; ii < n_plus_one; ++ii) {
double c = p_ptr[ii] - u * a - v * b;
q_ptr[ii] = c;
b = a;
a = c;
}
return;
}
//======================================================================
// 2
// Calculate the zeros of the quadratic a x + b x + c.
// the quadratic formula, modified to avoid overflow, is used to find
// the larger zero if the zeros are real and both zeros are complex.
// the smaller real zero is found directly from the product of the
// zeros c / a.
//======================================================================
template<std::int32_t degree>
void PolynomialRootFinder<degree>::SolveQuadraticEquation(double a,
double b,
double c,
double &sr,
double &si,
double &lr,
double &li)
{
if (a == 0.0) {
if (b != 0.0) {
sr = -c / b;
} else {
sr = 0.0;
}
lr = 0.0;
si = 0.0;
li = 0.0;
} else if (c == 0.0) {
sr = 0.0;
lr = -b / a;
si = 0.0;
li = 0.0;
} else {
//--------------------------------------------------------------
// Compute discriminant avoiding overflow.
//--------------------------------------------------------------
double d;
double e;
double bvar = b / 2.0;
if (::fabs(bvar) < ::fabs(c)) {
if (c < 0.0) {
e = -a;
} else {
e = a;
}
e = bvar * (bvar / ::fabs(c)) - e;
d = ::sqrt(::fabs(e)) * ::sqrt(::fabs(c));
} else {
e = 1.0 - (a / bvar) * (c / bvar);
d = ::sqrt(::fabs(e)) * ::fabs(bvar);
}
if (e >= 0.0) {
//----------------------------------------------------------
// Real zeros
//----------------------------------------------------------
if (bvar >= 0.0) {
d = -d;
}
lr = (-bvar + d) / a;
sr = 0.0;
if (lr != 0.0) {
sr = (c / lr) / a;
}
si = 0.0;
li = 0.0;
} else {
//----------------------------------------------------------
// Complex conjugate zeros
//----------------------------------------------------------
sr = -bvar / a;
lr = sr;
si = ::fabs(d / a);
li = -si;
}
}
return;
}
#endif
</code></pre>
<p><code>main.cc</code></p>
<pre><code>/* standard headers */
#include <cstdint>
#include <array>
#include <vector>
#include <cmath>
#include <random>
#include <chrono>
#include <cstring>
#include <cstdio>
/* omp headers */
#include <omp.h>
/* png headers */
#include "png.hh"
/* note: I did not create the polynomial related files I got them from here
* and yes I know this has terrible code quailty but I could not find anything better
https://www.codeproject.com/articles/674149/a-real-polynomial-class-with-root-finder
*/
#include "PolynomialRootFinder.hh"
/* constants */
namespace
{
constexpr std::uint32_t width = 500;
constexpr std::uint32_t height = 500;
constexpr std::int32_t degree = 24;
constexpr std::int32_t coefficients = degree + 1;
constexpr std::uint64_t total_samples = 1000000;
std::uint64_t const individual_samples = total_samples / omp_get_max_threads();
using roots_t = std::array<double, coefficients * 2>;
using heatmap_t = std::uint32_t;
}
std::int32_t generate_roots(roots_t &output)
{
static thread_local std::mt19937_64 mt(std::random_device{}());
std::uniform_int_distribution<std::int32_t> dist(0, 1);
std::array<double, coefficients> cofs;
std::transform(cofs.begin(), cofs.end(), cofs.begin(), [&](auto) { return dist(mt) ? 1 : -1; });
PolynomialRootFinder<degree> poly = {};
std::int32_t roots_found;
if (poly.FindRoots(&cofs[0], &output[0], &output[coefficients], &roots_found) == PolynomialRootFinder<degree>::RootStatus_T::SUCCESS) {
return roots_found;
} else {
return 0;
}
}
void generate_heatmap(std::vector<heatmap_t> &heatmap, heatmap_t &max_value)
{
roots_t roots = {};
auto map_range = [](auto s, decltype(s) a1, decltype(s) a2, decltype(s) b1, decltype(s) b2) {
return b1 + (s - a1) * (b2 - b1) / (a2 - a1);
};
for (std::uint64_t i = 0; i < individual_samples; ++i) {
/* see if we found any roots */
if (std::int32_t roots_found = generate_roots(roots)) {
/* plot all the roots found to the heatmap */
while (--roots_found >= 0) {
double const real = roots[roots_found];
double const imag = roots[static_cast<std::size_t>(roots_found) + coefficients];
std::int32_t const col = static_cast<std::int32_t>(map_range(real, -1.6, 1.6, 0, width));
std::int32_t const row = static_cast<std::int32_t>(map_range(imag, -1.6, 1.6, 0, height));
/* only plot roots that are in bounds */
if (col < 0 || col >= width || row < 0 || row >= height) continue;
max_value = std::max(++heatmap[static_cast<std::size_t>(row) * width + col], max_value);
}
}
}
}
int main()
{
/* create a heatmap*/
std::vector<heatmap_t> heatmap(width * height);
/* start a timer */
std::chrono::time_point<std::chrono::high_resolution_clock> const t1 = std::chrono::high_resolution_clock::now();
/* generate heatmap */
heatmap_t max_value = 0;
#pragma omp parallel
generate_heatmap(heatmap, max_value);
/* write image */
std::vector<std::uint8_t> image;
image.resize(width * height);
for (std::int32_t i = 0; i < width * height; ++i) {
std::uint8_t color = static_cast<std::uint8_t>((std::log(heatmap[i]) / std::log(max_value)) * 255.0 + 0.55555);
image[i] = color;
}
png::write_image("output.png", image.data(), width, height);
/* print the time it took */
std::chrono::time_point<std::chrono::high_resolution_clock> const t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> const duration =
std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
double const time_took = duration.count();
std::printf("It took %f %s", time_took, std::array{ "seconds", "second" } [1.0 == time_took]);
/* wait for user input to close */
(void)std::getchar();
}
</code></pre>
<p>here is what the program produces:</p>
<p><a href="https://i.stack.imgur.com/N1Mrz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/N1Mrz.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T03:05:36.737",
"Id": "491485",
"Score": "7",
"body": "Since your file contains a copyright notice. I would just also point out that any code put on a stack exchange site is also released under a [creative commons license](https://stackoverflow.com/help/licensing) (its a condition of posting, see bottom of page for details). It does not affect this code much but just for future reference if you want to post code under a difference license."
}
] |
[
{
"body": "<h1>Variable names</h1>\n<p>There are a lot of variables with very short names. I know it is common in mathematical formulas to use single-letter names for variables, but you will at least find some accompanying text that explains what all the letters means. I would at least add some comments to the code at the place where you declare variabels like <code>double m_a</code>. This can be a short epxlaination, or perhaps a reference to a paper or book, including the number of the formula where it is first introduced. Alternatively, give the variables a longer, but more descriptive name.</p>\n<p>On the other hand, some variables are bit long, and can be shorted. For example, variables referring to arrays or vectors are commonly written using the plural form, and we don't have to repeat the type in the name. So for example, instead of <code>coefficient_vector_ptr</code>, write <code>coefficients</code>.</p>\n<h1>Use <code>std::complex</code> for complex variables</h1>\n<p>Instead of declaring two variables, one for the real and the other for the imaginary part, consider declaring a single <a href=\"https://en.cppreference.com/w/cpp/numeric/complex\" rel=\"noreferrer\"><code>std::complex</code></a> variable. You can still access the two components individually if needed, but it reduces the amount of variables, and there are also a lot of mathematical functions that can work directly on complex variables.</p>\n<h1>Use <code>const</code> pointers where appropriate</h1>\n<p>I see some use of <code>constexpr</code>, but almost no occurence of <code>const</code>. Whenever you are passing a pointer to something to a function, and you are not modifying the contents, make it a <code>const</code> pointer. This will catch errors if you accidentily do write to a <code>const</code> variable, and it might give the compiler some more opportunities to optimize the code. For example, <code>filename</code> and <code>image_data</code> in <code>write_image()</code>, and <code>coefficient_vector_ptr</code> in <code>FindRoots()</code> can be made <code>const</code> pointers.</p>\n<h1>Avoid casting unnecessarily</h1>\n<p>I see a lot of casts that seem unnecessary. For example:</p>\n<pre><code>xvar = (double)(::fabs((double)(m_p_vector[ii])));\n</code></pre>\n<p>Why the casts when <code>m_p_vector</code> is already an array of <code>double</code>s, and <code>xvar</code> is also a <code>double</code>? I would also avoid using the C library version of <code>fabs()</code>, and use <code>std::fabs()</code> instead:</p>\n<pre><code>xvar = std::fabs(m_p_vector[ii]);\n</code></pre>\n<p>Also note that C++, for better or for worse, will perform implicit casts and type promotions for you in some cases. They generally reduce the amount of casting necessary. Take for example:</p>\n<pre><code>std::int32_t lvar = (std::int32_t)(::log(sc) / ::log(f_BASE) + 0.5);\ndouble factor = ::pow((double)(f_BASE * 1.0), double(lvar));\n</code></pre>\n<p>This can be rewritten to:</p>\n<pre><code>std::int32_t lvar = std::log(sc) / std::log(f_BASE) + 0.5;\ndouble factor = std::pow(f_BASE * 1.0, lvar);\n</code></pre>\n<p>Note that it not only is shorter, it is even more efficient in this case: <code>std::pow()</code> has an overload for integer exponents, and can use a much faster algorithm to calculate the result in that case.</p>\n<h1>Avoid hoisting degenerate cases out of loops</h1>\n<p>I see this pattern repeated a lot of times:</p>\n<pre><code>double kv = m_k_vector[0];\nm_qk_vector[0] = kv;\n\nfor (ii = 1; ii < m_n; ++ii) {\n kv = kv * svar + m_k_vector[ii];\n m_qk_vector[ii] = kv;\n}\n</code></pre>\n<p>Here you treat <code>ii = 0</code> as a special case and have moved it out of the loop. But it can be rewritten to:</p>\n<pre><code>double kv = 0;\n\nfor (ii = 0; i < m_n; ++ii) {\n kv = kv * svar + m_k_vector[ii];\n m_qk_vector[ii] = kv;\n}\n</code></pre>\n<p>There is probably no difference in speed, but the latter is just simpler code, and it tells you that there is actually nothing special about the first element.</p>\n<h1>Use <code>auto</code> to avoid repeating (long) types</h1>\n<p>While I wouldn't use <code>auto</code> for most of the maths, it can be used effectively inside <code>main()</code> to avoid repeating yourself. For example:</p>\n<pre><code>auto const t1 = std::chrono::high_resolution_clock::now();\n...\n auto color = static_cast<std::uint8_t>((std::log(heatmap[i]) / std::log(max_value)) * 255.0 + 0.55555);\n...\nauto const t2 = std::chrono::high_resolution_clock::now();\nauto duration = t2 - t1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T21:14:08.003",
"Id": "250485",
"ParentId": "250481",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250485",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T19:34:10.247",
"Id": "250481",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Littlewood polynomial root heatmap"
}
|
250481
|
<p>Hey people on the internet!</p>
<p>I do not know where to share my new npm package so I am asking you do you know of a good place to share my package?</p>
<p>Also I would really appreciate if you take a look on it and give me your honest opinion on it <a href="https://www.npmjs.com/package/react-spear" rel="nofollow noreferrer">react-spear</a></p>
<p>In short the goal of this package is to make state management more appealing then redux/MobX.
It uses an object of store that contains Subjects that can subscribe to global value change and synchronize with local state.</p>
<p>I have made an effort to contribute to the developers community with this package and I hope it is a good one.</p>
<p>Please share with me your thoughts</p>
<p>If you have a counter like this:</p>
<p>src/Counter.(jsx/tsx)</p>
<pre><code>import React from 'react';
import { Down } from './Down';
import { Up } from './Up';
import { Display } from './Display';
export const Counter = () => {
return (
<div>
<Up />
<Down />
<Display />
</div>
);
};
</code></pre>
<p>That takes an Up and Down buttons compnent that needs to share their state.
You will have a <strong>store</strong> like this:</p>
<p>src/store.(js/ts)</p>
<pre><code>import { Subject } from 'react-spear';
export const Store = {
counter: new Subject(0),
// You can add Some other values here to the store,
// and even an entire Store object to be nested here, whatever you want.
};
</code></pre>
<p>The Down and Up components should look like this:</p>
<p>src/Up.(jsx/tsx)</p>
<pre><code>import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';
export const Up = () => {
const count = useSensable(Store.counter);
return <button onClick={() => Store.counter.broadcast(count + 1)}>Up {count}</button>;
};
</code></pre>
<p>src/Down.(jsx/tsx)</p>
<pre><code>import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';
export const Down = () => {
const count = useSensable(Store.counter);
return <button onClick={() => Store.counter.broadcast(count - 1)}>Down {count}</button>;
};
</code></pre>
<p>And the Display component will look loke this:</p>
<p>src/Display.(jsx/tsx)</p>
<pre><code>import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';
export const Display = () => {
const count = useSensable(Store.counter);
return (
<div>
<div>Count is {count}</div>
</div>
);
};
</code></pre>
<h2>Explanation</h2>
<ul>
<li><p>When creating the <strong>store</strong> you are creating a subscribable object that can listen to changes.</p>
</li>
<li><p>When using the <strong>broadcast</strong> method(<em>you can help me think other names if you don't like this one</em>),
you emit the next value of the state, actualy like setState but globally.</p>
</li>
<li><p>Then with the <strong>useSensable</strong> hook you are sensing the changes from the store(<em>listening to broadcast event of that specific subject</em>).
Inside it uses <strong><em>useState</em></strong> to manage the update of the incoming new value,
and <strong><em>useEffect</em></strong> to manage subscription to that value.</p>
</li>
<li><p>So everytime you broadcast a new value every component that consume that value via <strong>useSensable</strong>
are getting rerendered with the new value.</p>
</li>
</ul>
<p>Hope it make <strong>sense</strong> because it does to me.</p>
<h1>Update</h1>
<p>File structure:</p>
<pre><code>src
├── hooks
│ └── useSensable.ts
├── lib
│ ├── StorageHandler.ts
│ └── Subscribable.ts
└── subjects
├── LocalSubject.ts
├── StorageSubject.ts
├── SessionSubject.ts
└── Subject.ts
</code></pre>
<p>My code from the link above:</p>
<p>src/lib/Subscribable.ts</p>
<pre><code>export type SubscribableHandler<T> = (nextValue: T) => void;
export interface ISubscribable<T> {
subscribe: (handler: SubscribableHandler<T>) => () => void;
}
export class Subscribable<T> implements ISubscribable<T> {
private _norifiers: SubscribableHandler<T>[] = [];
protected broadcast(value: T) {
this._norifiers.forEach((notifier) => notifier(value));
}
public subscribe = (handler: SubscribableHandler<T>) => {
this._norifiers.push(handler);
return () => {
this._norifiers = this._norifiers.filter((_) => _ !== handler);
};
};
}
</code></pre>
<p>src/lib/StorageHandler.ts</p>
<pre><code>export class StorageHandler {
private storage: Storage;
constructor(storage: Storage) {
this.storage = storage;
}
public get<T>(key: string): T {
const item = this.storage.getItem(key);
return item ? JSON.parse(item) : null;
}
public set<T>(key: string, value: T): void {
this.storage.setItem(key, JSON.stringify(value));
}
public getOrCreate<T>(key: string, defaultValue: T): T {
let value: T = this.get<T>(key);
if (value === null) {
value = defaultValue;
this.set(key, value);
}
return value;
}
}
</code></pre>
<p>src/subjects/Subject.ts</p>
<pre><code>import { ISubscribable, Subscribable } from '../lib/Subscribable';
export interface ISubject<T> extends ISubscribable<T> {
value: T;
}
export class Subject<T> extends Subscribable<T> implements ISubject<T> {
public value: T;
constructor(initialValue?: T) {
super();
this.value = initialValue as T;
}
public broadcast(nextValue: T) {
this.value = nextValue;
super.broadcast(nextValue);
}
}
</code></pre>
<p>src/subjects/StorageSubject.ts</p>
<pre><code>
import { StorageHandler } from '../lib/StorageHandler';
import { Subject } from './Subject';
export class StorageSubject<T> extends Subject<T> {
private storageKey: string;
private storage: StorageHandler;
constructor(storage: StorageHandler, storageKey: string, initialValue?: T) {
super(storage.getOrCreate(storageKey, initialValue));
this.storageKey = storageKey;
this.storage = storage;
}
public broadcast = (nextValue: T) => {
this.storage.set(this.storageKey, nextValue);
super.broadcast(nextValue);
};
}
</code></pre>
<p>src/subjects/LocalSubject.ts</p>
<pre><code>import { StorageHandler } from '../lib/StorageHandler';
import { StorageSubject } from './StorageSubject';
const localStorageManager = new StorageHandler(localStorage);
export class LocalSubject<T> extends StorageSubject<T> {
constructor(storageKey: string, initialValue?: T) {
super(localStorageManager, storageKey, initialValue);
}
}
</code></pre>
<p>src/subjects/SessionSubject.ts</p>
<pre><code>import { StorageHandler } from '../lib/StorageHandler';
import { StorageSubject } from './StorageSubject';
const sessionStorageManager = new StorageHandler(sessionStorage);
export class SessionSubject<T> extends StorageSubject<T> {
constructor(storageKey: string, initialValue?: T) {
super(sessionStorageManager, storageKey, initialValue);
}
}
</code></pre>
<p>src/hooks/useSensable:</p>
<pre><code>import { ISubject } from '../subjects/Subject';
import { useEffect, useState } from 'react';
export const useSensable = <T>(subject: ISubject<T>) => {
const [value, setValue] = useState(subject.value);
useEffect(() => subject.subscribe(setValue), [subject]);
return value;
};
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-10T22:42:55.750",
"Id": "250489",
"Score": "6",
"Tags": [
"react.js",
"redux",
"state",
"mobx"
],
"Title": "React state management design pattern new approach thoughts"
}
|
250489
|
<p>I'm posting a solution for LeetCode's "Maximal Network Rank". If you'd like to review, please do so. Thank you!</p>
<h3><a href="https://leetcode.com/problems/maximal-network-rank/" rel="nofollow noreferrer">Problem</a></h3>
<p>There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.</p>
<p>The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.</p>
<p>The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.</p>
<p>Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.</p>
<pre><code>class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
indegrees = collections.defaultdict(list)
for i in range(n):
for a, b in roads:
if i == a:
indegrees[i].append(f'{i}-{b}')
indegrees[i].append(f'{b}-{i}')
if i == b:
indegrees[i].append(f'{i}-{a}')
indegrees[i].append(f'{a}-{i}')
max_net = 0
for i in range(n):
for j in range(n):
if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:
net = len(set(indegrees[i] + indegrees[j])) // 2
max_net = max(max_net, net)
return max_net
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid converting data structures to string unnecessarily</h1>\n<p>Just store tuples of values in <code>indegrees</code> instead of strings:</p>\n<pre><code>if i == a:\n indegrees[i].append((i, b))\n indegrees[i].append((b, i))\n</code></pre>\n<h1>Iterate over the keys in <code>indegrees</code> directly</h1>\n<p>In this piece of code:</p>\n<pre><code>for i in range(n):\n for j in range(n):\n if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:\n ...\n</code></pre>\n<p>What you are basically saying is: for every possible pair of integers, check if it's in <code>indegrees</code>, and if so, do something with it. That's very inefficient if there only few elements in <code>indegrees</code>. Why not just iterate over the keys of <code>indegrees</code> instead? You can do it with strings, but then you have to parse each key back into two values, if you store tuples instead it becomes really simple:</p>\n<pre><code>for i, j in indegrees:\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:14:46.510",
"Id": "250505",
"ParentId": "250494",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250505",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T04:05:23.107",
"Id": "250494",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "LeetCode 1615: Maximal Network Rank"
}
|
250494
|
<p>I got this question in an interview. Given a string of words, print it such as each line has at most <code>limit</code> characters, if a word does not fit on the line, print it on the next line and so on.</p>
<p>This is my implementation:</p>
<pre><code>public static void main(String[] args) {
String s = "Even aside from the rain and wind it hadn't been a happy practice session. Fred and George, who had been spying on the Slytherin team, had seen for themselves the speed of those new Nimbus Two Thousand and Ones. They reported that the Slytherin team was no more than seven greenish blurs, shooting through the air like missiles.";
wordWrapper(s, 11);
}
public static void wordWrapper(String s, int limit) {
// Time complexity: O(n) - n size of s
// Space complexity: O(n) - n number of words in s
int charCount = 0;
int i = 0;
String[] words = s.split(" ");
while (i < words.length) {
if (charCount + words[i].length() > limit) {
System.out.println();
charCount = 0;
}
charCount += words[i].length();
System.out.print(words[i] + " ");
i++;
}
}
</code></pre>
<p>I'm trying to reduce the space complexity, and just use pointers instead of <code>split()</code>, this is what I have so far, I'm thinking of keeping track of the last whitespace and going back to insert a line before that word when the limit is reached, if you run the code the new line is inserted correctly but half of the word would still print before the new line. Please let me know what I'm missing. I also would love to look at better approaches. Thank you!</p>
<pre><code>public static void wordWrapper1(String s, int limit) {
int i = 0;
int lastWhitespaceIdx = -1;
int lineCount = 0;
if (s.length() == 0) {
return;
}
while (i < s.length()) {
if (Character.isWhitespace(s.charAt(i))) {
lastWhitespaceIdx = i;
}
if (lineCount + 1 > limit) {
if (!Character.isWhitespace(s.charAt(i + 1))) {
i = lastWhitespaceIdx + 1;
System.out.println();
lineCount = 0;
continue;
} else {
System.out.println();
lineCount = 0;
}
}
lineCount += 1;
System.out.print(s.charAt(i));
i++;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T11:51:13.400",
"Id": "491516",
"Score": "2",
"body": "Hello, since the `wordWrapper1` doesn't work, we cannot review or make the correction for you; we can only review the first version (`wordWrapper`). I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:13:00.863",
"Id": "491550",
"Score": "0",
"body": "I like the first version better. It is much easier to understand. Unless you have measurements that say this code is a hot spot, I would stick with the first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:22:02.257",
"Id": "491569",
"Score": "0",
"body": "@brianbeuning got it, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:22:25.290",
"Id": "491570",
"Score": "0",
"body": "@Doi9t Ok, thank you for pointing that out"
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code> String s = "Even aside from the rain and wind it hadn't been a happy practice session. Fred and George, who had been spying on the Slytherin team, had seen for themselves the speed of those new Nimbus Two Thousand and Ones. They reported that the Slytherin team was no more than seven greenish blurs, shooting through the air like missiles.";\n</code></pre>\n<p><code>s</code> is not a good variable name. My rule is that you're only allowed to use single-character variable names when dealing with dimensions (yes, that also disallows <code>i</code>/<code>j</code>/<code>k</code> for loops, too).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static void wordWrapper(String s, int limit) {\n</code></pre>\n<p>The naming is off, this is not a "word wrapper" it's a function that does wrap a string by words, so more like <code>wrap</code> or <code>wrapText</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Time complexity: O(n) - n size of s\n // Space complexity: O(n) - n number of words in s\n</code></pre>\n<p>I'm not sure that is correct. I could be very well mistaken here because I rarely need to think about complexity limitations at all, but I think it is closer to "O(n + m)", with "n" being the number of characters (the split), and "m" being the number of words (your loop). Space should be "O(n*2)", with "n" being the number of characters in the string, as you need to keep each character twice in memory, once in the original, and once in the word string.</p>\n<p>However, most JVMs are implementing "substrings", which means that the array of codepoints is only held one in memory, and if you do a <code>substring</code>, you will receive a new <code>String</code> with the same array but different start/end index.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> int charCount = 0;\n int i = 0;\n String[] words = s.split(" ");\n while (i < words.length) {\n if (charCount + words[i].length() > limit) {\n System.out.println();\n charCount = 0;\n }\n charCount += words[i].length();\n System.out.print(words[i] + " ");\n i++;\n }\n</code></pre>\n<p>This code could be simplified to a for-each loop:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int currentLineLength = 0;\n\nfor (String word : text.split(" ")) {\n if ((currentLineLength + word.length()) > maxCharactersPerLine) {\n System.out.println();\n currentLineLength = 0;\n }\n \n System.out.print(word + " ");\n currentLineLength = currentLineLength + word.length();\n}\n</code></pre>\n<p>Note that your implementation, and this revised one, has three problems which should be dealt with at some point:</p>\n<ol>\n<li>The spaces are not taken into account for the maximum line length.</li>\n<li>It prints an extra space at the end of each line.</li>\n<li>How a word should be treated that is longer than the maximum line length.</li>\n</ol>\n<hr />\n<blockquote>\n<p>...and just use pointers instead of split(),...</p>\n</blockquote>\n<p>There is no such thing as "a pointer for strings" in Java. Though, you most likely mean, to iterate over the String and keep track of the index, but "pointer" is a heavily prejudiced word, and I would stay clear of it and instead use "index".</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>int lastWhitespaceIdx = -1;\n</code></pre>\n<p>Don't shorten names just because you can, it does make the code harder to read in the end of the day.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>int lineCount = 0;\n</code></pre>\n<p>The name of this variable is incorrect, it does not count lines, it counts characters on the current line, it should be named accordingly.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>while (i < s.length()) {\n</code></pre>\n<p>Not sure why you use a <code>while</code> when a <code>for</code> would be perfect for what you're doing here.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.out.print(s.charAt(i));\n</code></pre>\n<p>Printing single characters at a time can be quite wasteful, depends on whether the stream supports some sort of buffer or not.</p>\n<hr />\n<p>You could use <code>String.indexOf(String)</code> and <code>String.index(String, int)</code> to iterate over the string and simplify your logic. Then use <code>substring</code> to extract the part of the String between the spaces and print that, or print that part character by character.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:22:46.503",
"Id": "491571",
"Score": "0",
"body": "very helpful, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:21:23.387",
"Id": "250506",
"ParentId": "250496",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250506",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T05:29:25.930",
"Id": "250496",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "Limit characters by line without splitting word"
}
|
250496
|
<p>I tried solving Leetcode <a href="https://leetcode.com/problems/01-matrix/" rel="nofollow noreferrer">01 Matrix</a> problem.
It is running too slow when solved using DFS approach.</p>
<blockquote>
<p>Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.</p>
<p>The distance between two adjacent cells is 1.<br /></p>
</blockquote>
<p>Example 1</p>
<pre><code>Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
</code></pre>
<p>Note:</p>
<ul>
<li>The number of elements of the given matrix will not exceed 10,000.</li>
<li>There are at least one 0 in the given matrix.</li>
<li>The cells are adjacent in only four directions: up, down, left and right.</li>
</ul>
<pre><code>class Solution(object):
def updateMatrix(self, matrix):
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
op = [[-1 for _ in range(n)] for _ in range(m)]
directions = [(1,0), (-1,0), (0, 1), (0, -1)]
def dfs(i,j):
if matrix[i][j] == 0:
return 0
if op[i][j] != -1:
return op[i][j]
matrix[i][j] = -1
closest_zero = float('inf')
for direction in directions:
x,y = direction[0] + i , direction[1] + j
if 0 <= x < m and 0 <= y < n and matrix[x][y] != -1:
closest_zero = min(dfs(x,y), closest_zero)
closest_zero += 1
matrix[i][j] = 1
return closest_zero
for i in range(m):
for j in range(n):
if matrix[i][j] == 1 and op[i][j] == -1:
op[i][j] = dfs(i,j)
elif matrix[i][j] == 0:
op[i][j] = 0
return op
</code></pre>
<p>It is running too slowly and I don't understand what is the reason for that. Most optimised solution have solved this using BFS.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:08:35.090",
"Id": "491567",
"Score": "2",
"body": "Fundamentally your problem is that you recompute things too many times. Consider what your program does on the 1000 x 1000 matrix which is all 1s except the bottom right which is a 0. If you could remember results you have computed, your approach could be performant. The bfs approach isn't just bfs, it's a bfs starting from the 0s, where you update the ops matrix as you go with candidate distances, in this way you avoid recomputations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:45:22.307",
"Id": "492833",
"Score": "0",
"body": "There is no reason to do a DFS. Find all the zeros, and mark them with a distance of 0. The cells up/down/left/right from them are a distance of 1, unless it already has a lower distance. The cells adjacent to the \"1\"s are a distance of 2, and so on until all cells are marked. Taking a look at flood fill algorithms may be helpful."
}
] |
[
{
"body": "<p>The algorithm is slow since it creates paths in all 4 directions at\neach step. The algorithm is also using recursion, which is also slower\nthan a simple <code>for</code> loop.</p>\n<p>Consider a 5x5 matrix <code>A</code>:</p>\n<pre><code>[[1 1 1 1 0]\n [1 1 1 1 1]\n [1 1 1 1 1]\n [1 0 1 1 1]\n [1 1 1 1 1]]\n</code></pre>\n<p>to find the distance of the top-left cell, the algorithm first moves\ndown, then up, then right, and then left. It marks the cells it has\nalready visited by a -1 to avoid infinite loops. So the first five\nsteps will move down:</p>\n<pre><code>[[-1 1 1 1 0]\n [-1 1 1 1 1]\n [-1 1 1 1 1]\n [-1 0 1 1 1]\n [-1 1 1 1 1]]\n</code></pre>\n<p>now the algorithm cannot move further down since it has reached the\nmaximum row number, and it tries to move in the next direction which\nis upwards. Here, it encounters a -1 and gives up on that direction since\na -1 indicates that it has already visited that cell. Now it tries to\nmove to the right instead:</p>\n<pre><code>[[-1 1 1 1 0]\n [-1 1 1 1 1]\n [-1 1 1 1 1]\n [-1 0 1 1 1]\n [-1 -1 1 1 1]]\n</code></pre>\n<p>In cell <code>A(4,1)</code> (i.e. bottom row, second column) it does the same\nchecks and finds that it cannot move down, then it tries to move\nupwards and encounters a 0 in cell <code>A(3,1)</code>. At this point,\nwe are 6 levels deep into the recursion and the distance from\n<code>A(0,0)</code> to <code>A(3,1)</code> is hence found to be 6 for now. So ideally the algorithm should now reject any further paths that exceeds 6 levels of\nrecursion. Unfortunately this is not the case; first the algorithm steps\nback to recursion level 5 in cell <code>A(4,1)</code> and continues with cell\n<code>A(4,2)</code>:</p>\n<pre><code>[[-1 1 1 1 0]\n [-1 1 1 1 1]\n [-1 1 1 1 1]\n [-1 0 1 1 1]\n [-1 -1 -1 1 1]]\n</code></pre>\n<p>from this cell it moves upwards all the way up to cell <code>A(0,2)</code>:</p>\n<pre><code>[[-1 1 -1 1 0]\n [-1 1 -1 1 1]\n [-1 1 -1 1 1]\n [-1 0 -1 1 1]\n [-1 -1 -1 1 1]]\n</code></pre>\n<p>reaches a recursion level of 11. Here it can move either to the right or\nto the left. Since the algorithm always tries right before left, it\nmoves to cell <code>A(0,3)</code> and then continues downward to cell <code>A(4,3)</code> :</p>\n<pre><code>[[-1 1 -1 -1 0]\n [-1 1 -1 -1 1]\n [-1 1 -1 -1 1]\n [-1 0 -1 -1 1]\n [-1 -1 -1 -1 1]]\n</code></pre>\n<p>The recursion level is now 16. Then it moves to right to cell <code>A(4,4)</code> and\nthen upwards to cell <code>A(0,4)</code>.</p>\n<pre><code>[[-1 1 -1 -1 0]\n [-1 1 -1 -1 -1]\n [-1 1 -1 -1 -1]\n [-1 0 -1 -1 -1]\n [-1 -1 -1 -1 -1]]\n</code></pre>\n<p>The recursion level is now 21. A zero is\nfinally found in cell <code>A(0,4)</code> indicating a distance of 21 from cell\n<code>A(0,0)</code>. Still, the\nalgorithm continues to investigate useless paths (that is: paths\nwith recursion level more that 6 (remember that we have already found\na zero at distance 6) and moves back to cell <code>A(1,4)</code> at recursion\nlevel 20. Here it tries the remaining directions (left and right) but\nnone of those works, so level 20 is done. Then it enters back into\nlevel 19, 18, 17, 16, 15:</p>\n<pre><code>[[-1 1 -1 -1 0]\n [-1 1 -1 -1 1]\n [-1 1 -1 -1 1]\n [-1 0 -1 -1 1]\n [-1 -1 -1 1 1]]\n</code></pre>\n<p>notice that it replaces the -1 with 1 as it completes a level. So now\n<code>A(1,4)</code>, <code>A(2,4)</code>, <code>A(3,4)</code>, <code>A(4,4)</code>, and <code>A(4,3)</code> are all reset to value 1. At\nlevel 15, i.e. cell <code>A(3,3)</code>, it has already tried to move down, so now\nit tries to move up, but that does not work since cell <code>A(3,2)</code> has a\n-1. Then it tries to move to the right, to cell <code>A(3,4)</code>, which works\nsince <code>A(3,4)</code> is now 1 (and not -1). From cell <code>A(3,4)</code> it first tries to\nmove down and reaches cell <code>A(4,4)</code>. From that cell the only alternative\nis to move left and at recursion level 17 it reaches cell <code>A(4,3)</code>:</p>\n<pre><code>[[-1 1 -1 -1 0]\n [-1 1 -1 -1 1]\n [-1 1 -1 -1 1]\n [-1 0 -1 -1 -1]\n [-1 -1 -1 1 -1]]\n</code></pre>\n<p>In this cell it cannot get further, there is a -1 in all directions,\nand it gives up on level 17, (and moves back to level ...).</p>\n<p>The procedure should be clear by now. I will not continue further with\nthis example, the point was just to\nillustrate why the algorithm is so slow.</p>\n<p>In fact, in order to find the distance for <code>A(0,0)</code> in this 5x5\nmatrix example it executes a whopping 22254 (!) calls to the recursive <code>dfs()</code> method.\nThis simply to determine that the distance is 4 (which btw is found easily\nby moving horizontally to the zero in cell <code>A(0,4)</code>).</p>\n<p>I think it is a fair guess that the algorithm has an exponential complexity. And it should take forever to run cases with more than say 100 cells (i.e. a 10x10\nmatrix).</p>\n<p>Finally, here is an example of a much faster algorithm that should be\nable to find a solution for a 100x100 matrix in a fraction of a second:</p>\n<pre><code>import numpy as np\n\nclass Solution:\n """ Solution to leetCode problem 542. 01 Matrix\n Given a matrix consisting of 0 and 1, find the distance of the\n nearest 0 for each cell. The distance between two adjacent cells is 1.\n """\n def __init__(self, A):\n self.A = A\n\n def get_dist(self):\n """ Get the distance matrix for self.A as defined in the\n problem statement for problem 542. 01.\n """\n A = self.A\n (N, M) = A.shape\n B = np.zeros(A.shape, dtype=int)\n for i in range(N):\n for j in range(M):\n if A[i,j] == 1: # if A[i,j] == 0, B[i,j] is already set to 0\n dist = 1\n found = False\n while not found:\n for (x,y) in self.points(i, j, dist):\n if A[x,y] == 0:\n B[i,j] = dist\n found = True\n break\n if not found:\n dist = dist + 1\n if dist > M+N:\n raise Exception('Unexpected')\n return B\n\n def points(self, i, j, dist):\n """ Generate all valid points a distance 'dist' away from (i,j)\n The valid points will lie on the edge of a diamond centered on\n (i,j). Use a generator to avoid computing unecessary points.\n """\n (N, M) = self.A.shape\n for k in range(dist):\n if (i+k < N) and (j-dist+k >= 0):\n yield (i+k, j-dist+k)\n if (i+dist-k < N) and (j+k < M):\n yield (i+dist-k, j+k)\n if (i-k >= 0) and (j+dist-k < M):\n yield (i-k, j+dist-k)\n if (i-dist+k >= 0) and (j-k >= 0):\n yield (i-dist+k, j-k)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:50:01.070",
"Id": "250677",
"ParentId": "250498",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T06:03:20.160",
"Id": "250498",
"Score": "5",
"Tags": [
"python",
"time-limit-exceeded",
"complexity",
"breadth-first-search",
"depth-first-search"
],
"Title": "01 Matrix is too slow when solved using DFS"
}
|
250498
|
<p>This is my queue implementtion in C. Feel free to ask me any questions relating to my code. Any tips or suggestions are welcome, including tips on naming/spacing/common conventions.</p>
<p>Queue_node, Queue, create_queue, destroye_queue, queue_push, queue_pop are meant to work with any node struct which has a member <code>struct Queue_node *next</code> and functions to create the node and destroy the node.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
/* malloc(), EXIT_SUCCESS */
#include <stdio.h>
/* fprintf */
#include <stddef.h>
/* size_t */
struct Coordinate {
int x;
int y;
};
struct Queue_node {
struct Queue_node *next;
};
struct Queue {
struct Queue_node *front;
struct Queue_node *back;
size_t size;
};
struct Queue* create_queue(void) {
struct Queue *created_queue = malloc(sizeof(*created_queue));
if (created_queue == NULL) {
return NULL;
}
created_queue->back = NULL;
created_queue->front = NULL;
created_queue->size = 0;
return created_queue;
}
void destroy_queue(struct Queue *input_queue, void (*delete_node)(void*)) {
while (input_queue->front != NULL) {
struct Queue_node *deleted_node = input_queue->front;
input_queue->front = input_queue->front->next;
if (delete_node != NULL) {
delete_node(deleted_node);
}
}
free(input_queue);
}
void queue_push(struct Queue *input_queue, void *input_node) {
++input_queue->size;
if (input_queue->front == NULL) { // first insert
input_queue->front = (struct Queue_node*) input_node;
input_queue->back = (struct Queue_node*) input_node;
return;
}
input_queue->back->next = (struct Queue_node*) input_node;
input_queue->back = input_queue->back->next;
}
void* queue_pop(struct Queue* input_queue) {
if (input_queue->front == NULL) { // empty queue
return NULL;
}
--input_queue->size;
struct Queue_node *deleted_node = input_queue->front;
input_queue->front = input_queue->front->next;
return deleted_node;
}
/*
nodes that are queue_pop()'d must be free()'d by caller
*/
static struct Weighted_coord_node {
struct Queue_node *next;
// parent property
int weight;
struct Coordinate coord;
// child properties
};
static struct Weighted_coord_node* create_node(struct Coordinate coord, int weight) {
struct Weighted_coord_node *node = malloc(sizeof(*node));
if (node == NULL) {
return NULL;
}
node->next = NULL;
node->coord = coord;
node->weight = weight;
return node;
}
int main() {
struct Queue *my_queue = create_queue();
if (!my_queue) {
return EXIT_FAILURE;
}
struct Weighted_coord_node *my_node;
my_node = create_node((struct Coordinate){5,5}, 0);
if (!my_node) {
return EXIT_FAILURE;
}
queue_push(my_queue, my_node);
my_node = create_node((struct Coordinate){7,7}, 2);
if (!my_node) {
return EXIT_FAILURE;
}
queue_push(my_queue, my_node);
my_node = create_node((struct Coordinate){11,11}, 5);
if (!my_node) {
return EXIT_FAILURE;
}
queue_push(my_queue, my_node);
while (my_node = queue_pop(my_queue)) {
fprintf(stderr, "POP-> X: %i, Y:%i weight: %i\n", my_node->coord.x, my_node->coord.y, my_node->weight);
free(my_node);
}
destroy_queue(my_queue, free);
return EXIT_SUCCESS;
}
</code></pre>
<p>I rewrote the code following @vnp's suggestion. Here is the new version: <a href="https://codereview.stackexchange.com/questions/250537/my-queue-implementation-in-c-v-2">My queue implementation (in C) [V.2]</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:32:39.907",
"Id": "491593",
"Score": "1",
"body": "Welcome to Code Review! I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:48:07.607",
"Id": "491595",
"Score": "1",
"body": "@Sᴀᴍ Onᴇᴌᴀ, noted :)"
}
] |
[
{
"body": "<ul>\n<li><p><strong>DRY</strong>. <code>queue_push</code> assigns <code>queue_back</code> to the <code>input_node</code> no matter what. Consider</p>\n<pre><code> if (input_queue->front == NULL) {\n assert(input_queue->back == NULL);\n input_queue->front = input_node;\n } else {\n assert(input_queue->back != NULL);\n input_queue->back->next = input_node;\n }\n input_queue->back = input_node;\n</code></pre>\n<p>(<code>assert</code>s are there only to clarify the logic).</p>\n<p>Ditto for <code>queue_pop</code>.</p>\n</li>\n<li><p>Usually we don't want the client code to be aware of the containers, neither depend of them. If perchance you'd eventually decide to keep the weighted coordinates in a tree rather than a list, you'd need to redesign <code>struct Weighted_coord_node</code>, and the surrounding code. I strongly recommend to have <code>struct Queue_node</code> keeping the pointer to the actual data</p>\n<pre><code> struct Queue_node {\n struct Queue_node * next;\n void * client_data;\n };\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:16:42.977",
"Id": "491592",
"Score": "0",
"body": "Thanks a lot @vnp! I have modified my code according to your suggestions and added it into my post. Is it as you had suggested?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T20:07:04.050",
"Id": "250523",
"ParentId": "250499",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250523",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T08:17:51.260",
"Id": "250499",
"Score": "6",
"Tags": [
"c",
"queue"
],
"Title": "My queue implementation (in C)"
}
|
250499
|
<p><em><strong>Edit</strong>: added clarification for why I want this, and updated the code since I don't have any answers yet</em></p>
<p>I have a C++11 array-like class which (can be) a wrapper around a random-access iterator. Index-based access and <code>.begin()</code>/<code>.end()</code> can just pass through to the iterator, but there's a bit of complication when the object is <code>const</code>:</p>
<pre><code> template<class Size, typename DataIterator>
class Storage : public Size {
DataIterator iterator;
public:
Storage(const DataIterator &iterator, const Size &size) : Size(size), iterator(iterator) {}
auto operator[](index_t i)
-> decltype(iterator[i]) {
return iterator[i];
}
auto operator[](index_t i) const
-> MakeConst<decltype(iterator[i])> {
return iterator[i];
}
DataIterator begin() {return iterator;}
ConstWrapper<DataIterator> begin() const {return iterator;}
DataIterator end() {return iterator + this->size();}
ConstWrapper<DataIterator> end() const {return iterator + this->size();}
};
</code></pre>
<p>If we simply returned <code>DataIterator</code> from the <code>const</code> version of <code>.begin()</code> and <code>.end()</code>, then people holding a <code>Storage const &</code> would (incorrectly!) be able to modify the array through that iterator.</p>
<p>Containers like <code>std::vector</code> have two separate iterators (<code>::iterator</code> and <code>::const_iterator</code>), but our <code>Storage</code> class only has the read-write one, so we synthesise one using <code>ConstWrapper</code>:</p>
<pre><code> template <typename Iterator>
class ConstWrapper {
Iterator iterator;
using traits = std::iterator_traits<Iterator>;
public:
using difference_type = typename traits::difference_type;
using value_type = typename traits::value_type;
using pointer = ConstWrapper;
using reference = MakeConst<typename traits::reference>;
using iterator_category = typename traits::iterator_category;
ConstWrapper() {}
ConstWrapper(const Iterator &iterator) : iterator(iterator) {}
// The problematic cases:
auto operator[](index_t i) const
-> MakeConst<decltype(iterator[i])> {
return iterator[i];
}
auto operator*() const
-> MakeConst<decltype(*iterator)> {
return *iterator;
}
bool operator!= (const ConstWrapper& other) const {
return iterator != other.iterator;
}
/** All the other random-access iterator methods **/
};
// Specialisation to prevent infinite loops
template <typename Iterator>
class ConstWrapper<ConstWrapper<Iterator>> : ConstWrapper<Iterator> {
public:
using ConstWrapper<Iterator>::ConstWrapper;
};
</code></pre>
<p>The implementation forwards all the relevant methods, and has a specialisation for <code>ConstWrapper<ConstWrapper<...>></code> so that it can't wrap itself.</p>
<p>A key part is <code>MakeConst</code>, which turns types into the correct <code>const</code> variant (unlike simply adding <code>const</code>, which has no effect on references):</p>
<pre><code> // Converts (T & -> T const &), and (T -> const T)
using MakeConst = typename std::conditional<
std::is_reference<T>::value,
typename std::remove_reference<T>::type const &,
const T
>::type;
</code></pre>
<p>Does this make sense, and is it OK? Is there something else I could be doing which is more readable/efficient/etc.?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T09:59:48.307",
"Id": "491505",
"Score": "0",
"body": "[edit] your question to add your whole project here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T10:07:42.937",
"Id": "491506",
"Score": "0",
"body": "@Aryan Sorry, I don't understand what's missing. (I didn't think the implementation of the `Size` classes were relevant.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T11:05:48.977",
"Id": "491510",
"Score": "0",
"body": "Why make a wrapper around an iterator? It doesn't make any sense. Just use the iterator itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T11:10:02.053",
"Id": "491511",
"Score": "0",
"body": "It's hard to tell exactly what you want to do (and why). It would be nice to have an example of usage for const and non-const versions. If you have C++20, then perhaps you can just use `std::span` instead ( https://en.cppreference.com/w/cpp/container/span )."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T13:00:30.770",
"Id": "491525",
"Score": "0",
"body": "@ALX23z - if you iterate over a mutable container, the iterator returns mutable references when dereferenced (e.g. `int &`). If you iterate over a `const` container, you *should* get an iterator which produces const references (e.g. `const int &`) or actual values (`int`). `std::vector` does this, producing separate `iterator` and `const_iterator` types (https://en.cppreference.com/w/cpp/container/vector/begin)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T13:40:38.707",
"Id": "491529",
"Score": "1",
"body": "Ok, I see what you wanted. ConstWrapper will not work for fundamental reasons as it requires an iterator to instantiate it. A mutable non-const iterator. While if your class is a const it won't be able to supply a non-const iterator unless you use a const cast which you shouldn't do. Also the const and non-iterators might be very different types with very different behaviours - say if accessing the class requires to make a locking operation. For const version one could just do a shared_lock while mutable requires unique_lock You shouldn't just assume it is a trivial wrap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:03:11.140",
"Id": "491547",
"Score": "0",
"body": "@ALX23z Our Storage class gets instantiated with a mutable non-const iterator, so we already have that. A const Storage still contains the same (mutable non-const) iterator, so could just return that - but then the user would have an iterator which can modify the data. So we want a different iterator, and it seems it should be possible to construct one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:04:12.033",
"Id": "491548",
"Score": "0",
"body": "@ALX23z To illustrate: a `std::vector<bool>::const_iterator` returns `bool` values (not references) when accessed. A `std::vector<bool>::iterator` returns some other object (https://en.cppreference.com/w/cpp/container/vector_bool/reference) - but it's not copyable, and all the methods that would actually *change* the data are non-const. So, `const Storage<Size, std::vector<bool>::iterator` would produce `ConstWrapper<std::vector<bool>::iterator>` for iteration, which _could_ return a `const std::vector<bool>::reference` which (because it's const) still doesn't allow modification of the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T23:21:06.527",
"Id": "491576",
"Score": "0",
"body": "That was the other issue, that a Storage class is instantiated from iterator and contains one... it doesn't make sense. I'd expect Storage class to store and manage data. Instead it is a reference to a completely different container. Are you aware that iterators tend to get invalidated all the time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:36:51.633",
"Id": "491620",
"Score": "0",
"body": "@ALX23z Yeah - the larger project has Storage classes which manage their own data (and the iterator situation is also much simpler there). This is one specialisation of Storage, used as a temporary wrapper for other containers. I omitted that because it's `ConstWrapper` which I was mostly hoping to get feedback on."
}
] |
[
{
"body": "<p>I don't think your specialization is doing what you think it's doing. <a href=\"https://godbolt.org/z/Gfh7sv\" rel=\"nofollow noreferrer\">https://godbolt.org/z/Gfh7sv</a></p>\n<p>You don't want <code>ConstWrapper<ConstWrapper<Iterator>></code> to <em>inherit from</em> <code>ConstWrapper<Iterator></code>; that would mean that a <code>CW<CW<I>></code> "is-a-kind-of" <code>CW<I></code>, which isn't true. You don't want an inheritance relationship here. What you want is simply for specializations of <code>Storage</code> to <em>not wrap</em> <code>DataIterator</code>s that happen to be specializations of <code>ConstWrapper</code> already. The way you do that is with an extra layer of alias indirection:</p>\n<pre><code>template<class T> struct maybe_constwrap { using type = ConstWrapper<T>; };\ntemplate<class U> struct maybe_constwrap<ConstWrapper<U>> { using type = ConstWrapper<U>; };\n\ntemplate<class Size, typename DataIterator>\nclass Storage : public Size {\npublic:\n using iterator = DataIterator;\n using const_iterator = typename maybe_constwrap<DataIterator>::type;\n ~~~\n};\n</code></pre>\n<p>Now, if <code>DataIterator</code> is already a <code>ConstWrapper</code>, then both <code>iterator</code> and <code>const_iterator</code> will be literally the same type... which is what you want.</p>\n<hr />\n<p>Your <code>MakeConst</code> seems to be predicated on the dubious idea that <code>const _Bit_reference</code> is not going to be assignable-to. That's likely to change in C++23. See <a href=\"https://stackoverflow.com/questions/63412623/should-c20-stdrangessort-not-need-to-support-stdvectorbool\">https://stackoverflow.com/questions/63412623/should-c20-stdrangessort-not-need-to-support-stdvectorbool</a> for some context.</p>\n<hr />\n<p>You repeat some metaprogramming in the return types of <code>operator*</code> and <code>operator[]</code>. They should just return the type <code>reference</code> which you have already computed above.</p>\n<pre><code>reference operator*() const { return *it_; }\n</code></pre>\n<p>Incidentally, I'm changing your data member's name from <code>iterator</code> to <code>it_</code>, because I suspect it is a terrible idea, Concepts-wise, to have a container-ish class type with a member named <code>iterator</code> which member is (A) not public, and (B) not a type.</p>\n<hr />\n<p>Your <code>operator!=</code> should probably use the hidden friend idiom:</p>\n<pre><code>friend bool operator==(ConstWrapper a, ConstWrapper b) { return a.it_ == b.it_; }\nfriend bool operator!=(ConstWrapper a, ConstWrapper b) { return a.it_ != b.it_; }\n</code></pre>\n<p>In C++20 you could theoretically omit <code>operator!=</code> and provide <code>operator==</code> only. I don't know yet if that's a good idea.</p>\n<p>Passing <code>ConstWrapper</code> by value should be fine, because it holds only an iterator, and iterators are cheap to copy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T09:43:30.777",
"Id": "494316",
"Score": "0",
"body": "Thanks, this is really great"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T09:58:29.493",
"Id": "494317",
"Score": "0",
"body": "For the `MakeConst` point: now you point it out, yeah the constness of pointers/references is divorced from the constness of the values, so the fact that it worked for `std::vector<bool>::reference` in C++11 was itself not correct. So... am I going to need a whole shim-const-reference class, or does it mean `MakeConst` just isn't possible?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-25T06:30:50.157",
"Id": "251117",
"ParentId": "250502",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T09:26:25.683",
"Id": "250502",
"Score": "3",
"Tags": [
"c++",
"c++11",
"iterator",
"template-meta-programming"
],
"Title": "Const wrapper for iterator"
}
|
250502
|
<p>I am practicing to implement the KNN classification tool in C#. The basic point structure is constructed by the class <code>Point</code>, and there are two members in <code>Point</code> class: a list of double number and a string. A list of double number is used in order to represent location data in multi-dimensional space. A string is to represent the point label. For example, there are five points (on X-Y plane) here: A(0, 0), B(1, 0), C(0,1), D(10, 0) and E(10, 1). Moreover, point A, B and C are belong to class1, and point D and E are belong to class 2. They can be constructed as the following code.</p>
<pre><code>var pointA = new Point(new List<double>() {0, 0}, "class1");
var pointB = new Point(new List<double>() {1, 0}, "class1");
var pointC = new Point(new List<double>() {0, 1}, "class1");
var pointD = new Point(new List<double>() {10, 0}, "class2");
var pointE = new Point(new List<double>() {10, 1}, "class2");
</code></pre>
<p>The <code>Point</code> class implementation.</p>
<pre><code>public class Point
{
List<double> location;
string label;
public Point(List<double> newLocation, string newLabel)
{
this.location = newLocation;
this.label = newLabel;
}
public Point(List<double> newLocation, char newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, int newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, long newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, float newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, double newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, uint newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public Point(List<double> newLocation, ulong newLabel)
{
this.location = newLocation;
this.label = newLabel.ToString();
}
public List<double> GetPoint()
{
return this.location;
}
public string GetLabel()
{
return this.label;
}
public override string ToString()
{
System.Text.StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(this.label);
stringBuilder.Append(" (");
foreach (var eachNumber in this.location)
{
stringBuilder.Append(eachNumber.ToString());
stringBuilder.Append(", ");
}
stringBuilder.Remove(stringBuilder.Length - 2, 2);
stringBuilder.AppendLine(")");
return stringBuilder.ToString();
}
}
</code></pre>
<p>Then, the object counter which is used to store the number of existence of specific object is created as the following class <code>ObjectCounter</code>.</p>
<pre><code>public class ObjectCounter<T>
{
private T Object;
private ulong count;
public ObjectCounter(T newObject)
{
Object = newObject;
count = 1;
}
public void IncreaseCount()
{
count = count + 1;
}
public T GetObject()
{
return this.Object;
}
public ulong GetCount()
{
return count;
}
}
</code></pre>
<p>Next, the main structure of this <code>Unique</code> class is a list of ObjectCounter, and each object is unique.</p>
<pre><code>public class Unique
{
private List<ObjectCounter<string>> uniqueStrings;
public Unique()
{
uniqueStrings = new List<ObjectCounter<string>>();
}
public void AddData(string NewString)
{
if (IsDataExist(NewString) ==true)
{
IncreaseSpecificUniqueObject(NewString);
return;
}
else
{
uniqueStrings.Add(new ObjectCounter<string>(NewString));
return;
}
}
public ObjectCounter<string> GetMaxCountObject()
{
var SortedUniqueStrings = uniqueStrings.OrderByDescending(x => x.GetCount()).ToList();
return SortedUniqueStrings[0];
}
public List<ObjectCounter<string>> GetUniqueStrings()
{
return uniqueStrings;
}
private void IncreaseSpecificUniqueObject(string InputString)
{
Parallel.ForEach(uniqueStrings, (Item, state) =>
{
if (Item.GetObject().ToString().Equals(InputString))
{
Item.IncreaseCount();
state.Break();
}
});
return;
}
private bool IsDataExist(string NewData)
{
bool ReturnValue = false;
Parallel.ForEach(uniqueStrings, (Item, state) =>
{
if (Item.GetObject().ToString().Equals(NewData))
{
ReturnValue = true;
state.Break();
}
});
return ReturnValue;
}
public override string ToString()
{
System.Text.StringBuilder stringBuilder = new StringBuilder();
foreach (var item in uniqueStrings)
{
stringBuilder.AppendLine(item.GetObject().ToString() + "," + item.GetCount().ToString());
}
return stringBuilder.ToString();
}
}
</code></pre>
<p>The main KNN class is here. The distance calculation here is using Euclidean distance.</p>
<pre><code>public class KNNObject
{
private List<Point> listOfPoints;
public KNNObject()
{
this.listOfPoints = new List<Point>();
}
public void AddData(Point newPoint)
{
this.listOfPoints.Add(newPoint);
}
public void AddData(List<Point> newListOfPoints)
{
this.listOfPoints.AddRange(newListOfPoints);
}
public string Test(List<double> testPointData, int k)
{
List<Point> sortedListOfPoints = this.listOfPoints.OrderBy(x => Distance(x, new Point(testPointData, ""))).ToList();
List<Point> filtingByK = sortedListOfPoints.GetRange(0, ((sortedListOfPoints.Count > k) ? k : sortedListOfPoints.Count));
Unique LabelAnalysis = new Unique();
foreach (var item in filtingByK)
{
LabelAnalysis.AddData(item.GetLabel());
}
return LabelAnalysis.GetMaxCountObject().GetObject().ToString();
}
private double Distance(Point point1, Point point2)
{
double sum = 0.0;
if (point1.GetPoint().Count != point2.GetPoint().Count)
{
return double.NaN;
}
for (int Loopnum = 0; Loopnum < point1.GetPoint().Count; Loopnum++)
{
sum = Math.Pow((point1.GetPoint()[Loopnum] - point2.GetPoint()[Loopnum]), 2.0);
}
return Math.Pow(sum, 0.5);
}
}
</code></pre>
<p>The test of this <code>KNNObject</code> class.</p>
<pre><code>KNNObject kNNObject = new KNNObject();
kNNObject.AddData(new Point(new List<double>() { 1.234, 1.1 }, "class1"));
kNNObject.AddData(new Point(new List<double>() { 1.23, 1.11 }, "class1"));
kNNObject.AddData(new Point(new List<double>() { 1.0, 1.011 }, "class1"));
kNNObject.AddData(new Point(new List<double>() { 2.0, 1.023 }, "class1"));
kNNObject.AddData(new Point(new List<double>() { 111, 112 }, "class2"));
kNNObject.AddData(new Point(new List<double>() { 110.2, 112.7 }, "class2"));
kNNObject.AddData(new Point(new List<double>() { 109.5, 110.5 }, "class2"));
kNNObject.AddData(new Point(new List<double>() { 111.5, 112.3 }, "class2"));
Console.WriteLine(kNNObject.Test(new List<double>() { 1.0, 1.0 }, 2));
Console.WriteLine(kNNObject.Test(new List<double>() { 116, 110 }, 2));
</code></pre>
<p>The output would be as following.</p>
<pre><code>class1
class2
</code></pre>
<p>Is there any possible improvement of this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:31:05.310",
"Id": "491674",
"Score": "0",
"body": "Tip: As for me the last `AppendLine` in `ToString` should be `Append` as line shouldnt contain CRLF at the end, otherwise you'll get double CRLF output while using something like `WriteLine`. Unexpected behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T16:06:16.707",
"Id": "496103",
"Score": "0",
"body": "You can skip `Math.Pow` if you need distances for sorting only – it performs calculation which does not affect the result. You can sort by a distance squared as well."
}
] |
[
{
"body": "<p>I think there is plenty of room for improvement. Whenever I write code I try to focus on 3 things in this order:</p>\n<ol>\n<li>Does the code correctly perform its purpose?</li>\n<li>If another developer reads this code in 6 months, will they\nunderstand it?</li>\n<li>Does the code perform optimally?</li>\n</ol>\n<p>I think you fall short of (2). The thing that slaps me in the face is why is a List used as the inner data for the Point, especially since all other coding suggests it is a 2D point? If you intend to have this be a multi-dimensional point, I would consider renaming the class to be <code>MultiDimensionalPoint</code>. If you intend it to only be 2D, the name <code>Point</code> may be sufficient but the name <code>Point2D</code> would be more descriptive.</p>\n<p>For a 2D point, I would not expect to receive a List. Rather I would either be expecting to see an X and Y property, or perhaps have them named Longitude and Latitude.</p>\n<p>And you have way to many constructors for the class. Here is my attempt at it free-hand here in the CR editor:</p>\n<pre><code>public struct Point2D\n{\n public double X { get; }\n public double Y { get; }\n public double Label { get; }\n \n public Point2D(double x, double y, object label)\n {\n X = x;\n Y = y;\n Label = label?.ToString() ?? "";\n }\n\n public override string ToString() => $"{(string.IsNullOrWhitespace(label) ? label + " " : "")}({X}, {Y})";\n\n}\n</code></pre>\n<p>I would even suggest that the Distance formula would go inside the Point2D struct or the MultiDimensionalPoint class, if that's what you need. Again, the need and intent is not immediately discernible by someone reading your code.</p>\n<p>Let's review my version. I made it a struct instead of a class. The X, Y, and Label are read-only properties that are set in the constructor.</p>\n<p>Elsewhere, it is also more idiomatic to use <code>counter++</code> rather than <code>counter = counter + 1</code>.</p>\n<p>I've seen some of your other posts here and you have an affinity for <code>Parallel.ForEach</code>. Have you actually tested performance with this? Parallel has the potential to boost performance. But it equally has the potential to degrade performance. If you have a small enough collection, a straight-up <code>foreach</code> is better than parallel. And you have a huge collection, than the way you use <code>Parallel.ForEach</code> can also degrade performance since each iteration must spin up a task. Now spinning up a single task is only a tiny performance hit. But spinning up 1 million adds up to a big hit. Rather its better to chop up the collection into partitions, and then each partition can be run in parallel.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T14:38:47.783",
"Id": "491535",
"Score": "0",
"body": "Thank you for the comments. About the naming to the class `Point`, I want to keep the scalability on the dimension property but also simplify the name. If the point class is designed for 2D case, the definition you mentioned is a good idea. As your suggestion, using the name `MultiDimensionalPoint` is more clear for this case. Otherwise, the performance impact of using `Parallel.ForEach` syntax is seems a good issue to discuss. I wondering that how to determine using parallel or not in order to reach the optimal performance."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T13:42:41.307",
"Id": "250509",
"ParentId": "250504",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T10:36:12.227",
"Id": "250504",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"machine-learning",
"clustering"
],
"Title": "A Tiny Nearest Neighbor Classification Implementation in C#"
}
|
250504
|
<p>I have two entities in my database: <code>Employee</code> and <code>Shift</code>. I want to implement a C# repository pattern method, that given two <code>workshift</code> IDs, swaps the two <code>workshift</code>s for two employees.</p>
<p>Limitation: one employee cannot work multiple shifts at a time.</p>
<h3>Models</h3>
<pre class="lang-cs prettyprint-override"><code>public class Employee
{
public int ID { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
}
public class WorkShift
{
public int ID { get; set; }
public int EmployeeID { get; set; }
public DateTime ShiftStart { get; set; }
public DateTime ShiftEnd { get; set; }
}
</code></pre>
<h3>Repository</h3>
<pre class="lang-cs prettyprint-override"><code>public class WorkShiftRepository : RepositoryBase<WorkShift>, IWorkShiftRepository
{
private readonly ShiftContext _databaseContext;
public WorkShiftRepository(ShiftContext context) : base(context)
{
_databaseContext = context;
}
private async Task<bool> Overlaps(WorkShift shift, int employeeId)
{
return await _databaseContext.Shifts.Where(u => u.EmployeeID == employeeId).
Where((s => shift.ShiftStart < s.ShiftEnd && s.ShiftStart < shift.ShiftEnd)).AnyAsync();
}
public async Task<int> SwapShifts(int shiftIdA, int shiftIdB)
{
var result = 0;
// Load shifts into memory
var shiftA = await _databaseContext.Shifts.SingleAsync(s => s.ID == shiftIdA);
var shiftB = await _databaseContext.Shifts.SingleAsync(s => s.ID == shiftIdB);
int shiftAid = shiftA.EmployeeID;
// Swap Employee IDs
shiftA.EmployeeID = shiftB.EmployeeID;
shiftB.EmployeeID = shiftAid;
// Check if the swapped shifts has any overlaps on db
if (await Overlaps(shiftA, shiftA.EmployeeID) || await Overlaps(shiftB, shiftB.EmployeeID))
throw new Exception("ShiftsOverlap");
// update in memory
_databaseContext.Shifts.Update(shiftA);
_databaseContext.Shifts.Update(shiftB);
// Write changes to DB
result = await _databaseContext.SaveChangesAsync();
return result;
}
}
</code></pre>
<p>The code compiles and it meets the limitations. But I am looking for tips and tricks to make the code cleaner and/or more efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:10:05.217",
"Id": "491549",
"Score": "1",
"body": "not worth an answer, but `throw new Exception(\"ShiftsOverlap\");` I feel `return await Task.FromResult(-1);` would be better, because you don't need to throw an exception just because it's overlapped ! you just need to stop updating the swapping. Plus, you need to add validations such as null validations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:30:49.073",
"Id": "491602",
"Score": "0",
"body": "@JensJensen I think there is a problem with your code. The compare and swap methods are not treated as atomic. So it is possible that between checking overlap and actually performing the interchange one of employees modifies his/her shift and the overlap check become invalid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:32:36.623",
"Id": "491603",
"Score": "4",
"body": "`WorkShiftRepository` is not a repository, it's a service."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:22:27.140",
"Id": "491618",
"Score": "1",
"body": "`shiftAid` is badly named. It reads as \"aid\" not \"a-id\", plus it is the employee id, not the id of \"shift-a\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:26:33.080",
"Id": "491619",
"Score": "1",
"body": "You can one line swap with tuples: `(shiftA.EmployeeID, shiftB.EmployeeID) = (shiftB.EmployeeID, shiftA.EmployeeID);`. You could argue it's a terrible thing to do but I like it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:28:32.710",
"Id": "250507",
"Score": "4",
"Tags": [
"c#",
"linq",
"entity-framework"
],
"Title": "Repository pattern method implementation with entity framework and C#"
}
|
250507
|
<p>Consider a slice with some floating point numbers:</p>
<pre class="lang-golang prettyprint-override"><code>nums := []float64{0.17898, 0.25512, 1.98123, 1.35902, 0.97642}
</code></pre>
<p>Suppose I want to extract the numbers lying in between the range from <code>1</code> to <code>1.99</code> and ones lying in between the range from <code>0.0</code> to <code>0.99</code> (inclusive of both limits) from this slice and append it into two new separate slices each, then what would be the best possible way to do so?</p>
<p>I have the following code:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
)
func main() {
nums := []float64{0.17, 0.25, 2.19, 0.98, 1.35, 5.97, 1.21}
var oneSlice, zeroSlice []float64
for _, num := range nums {
if num <= 1.99 && num >= 1.0 {
oneSlice = append(oneSlice, num)
} else if num <= 0.99 && num >= 0.0 {
zeroSlice = append(zeroSlice, num)
}
}
fmt.Print("1.0-1.99 values:", oneSlice, "\n0.0-0.99 values:", zeroSlice)
}
</code></pre>
<pre class="lang-golang prettyprint-override"><code>1.0-1.99 values:[1.35 1.21]
0.0-0.99 values:[0.17 0.25 0.98]
</code></pre>
<p>Are there any better approaches than this? (such as avoiding the <code>if</code> & <code>else</code>, or a function that can be used, which I'm not aware of? - for e.g.: a function which can compare slice elements with a given value or range of values?)</p>
<p>I'm new to Go, so am just wondering if there could be a possibly better approach to this! Any help is appreciated :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:21:21.243",
"Id": "491541",
"Score": "1",
"body": "Welcome to Code Review where we review working code from your project and make suggestions on how to improve that code. Hypothetical code is considered off-topic and the question may be closed by the community. The question currently appears to be too hypothetical. If you reword the question so that it doesn't appear to be hypothetical and put real working code in the question this will become a good question. Take a look at our [guidelines for asking a good question](https://codereview.stackexchange.com/help/how-to-ask). You have a good start already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:40:29.707",
"Id": "491642",
"Score": "1",
"body": "@pacmaninbw I [was able to run the code online](https://onlinegdb.com/H1xAdugzDD) and see output that, while not declared explicitly in the post, matched the description. I am going to update the wording in the description here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:30:42.753",
"Id": "492719",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thanks for commenting that. In both ways, I thought the question was self-explanatory with the wording, so I didn't see a reason to edit it. (also, I obviously wouldn't throw in code that doesn't work!)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T12:45:39.517",
"Id": "250508",
"Score": "5",
"Tags": [
"beginner",
"go"
],
"Title": "Extracting numbers in specific ranges from a slice"
}
|
250508
|
<p>Following my previous question about a <a href="https://codereview.stackexchange.com/questions/245312/fifo-for-embedded-systems">FIFO for embedded systems</a> and the very detailed answer I got, I made some modifications to convert a simple FIFO to double-ended queue for Embedded Systems.
It is using a circular buffer.</p>
<p>How it works: When an element is added <strong>and</strong> the queue <strong>is not</strong> empty, the corresponding index is increased or decreased according to the side the element is added. When the queue is empty, and an element is added, neither index is changed so that the element can be accessed from either side.
The size of the queue is constant and it must be defined at compile time.
The data pointer must point to a static array that is also defined at compile time with the same size.</p>
<p>So here it is:</p>
<p><strong>queue.h</strong></p>
<pre><code>#ifndef QUEUE_H
#define QUEUE_H
#include <inttypes.h>
typedef uint16_t QueueDataType_t;
struct queue
{
QueueDataType_t * data;
QueueDataType_t front_idx;
QueueDataType_t back_idx;
const QueueDataType_t size;
QueueDataType_t elements;
};
#endif
</code></pre>
<p><strong>queue.c</strong></p>
<pre><code>/**
* \file queue.c
*
* \brief A double-ended queue (deque). Elements can be added or removed from
* either the front or the back side.
* \warning The current implementation is NOT interrupt safe. Make sure interrupts
* are disabled before access the QUEUE otherwise the program might yield
* unexpected results.
*/
#include "queue.h"
#include <stdbool.h>
/**
* Initializes - resets the queue.
*/
void queue_init(struct queue * queue)
{
memset(queue->data, 0, queue->size);
queue->back_idx = 0;
queue->front_idx = 0;
queue->elements = 0;
}
/**
* Checks if queue is full.
*
* \returns true if queue is full.
*/
bool queue_is_full(struct queue * queue)
{
return (queue->elements == queue->size);
}
/**
* Checks if queue is empty
*
* \returns true if queue is empty.
*/
bool queue_is_empty(struct queue * queue)
{
return (queue->elements == 0);
}
/**
* Adds one byte to the front of the queue.
*
* \returns false if the queue is full.
*/
bool queue_add_front(struct queue * queue,
QueueDataType_t data)
{
if (queue_is_full(queue))
{
return 0;
}
if (queue_is_empty(queue) == 0)
{
queue->front_idx = (queue->front_idx + 1) >= queue->size ? 0 : (queue->front_idx + 1);
}
queue->data[queue->front_idx] = data;
queue->elements++;
return 1;
}
/**
* Adds one byte to the back of the queue.
*
* \returns false if the queue is full.
*/
bool queue_add_back(struct queue * queue,
QueueDataType_t data)
{
if (queue_is_full(queue))
{
return 0;
}
if (queue_is_empty(queue) == 0)
{
queue->back_idx = (queue->back_idx == 0) ? (queue->size - 1) : (queue->back_idx - 1);
}
queue->data[queue->back_idx] = data;
queue->elements++;
return 1;
}
/**
* Reads one byte from the front of the queue.
*
* \returns false if the queue is empty.
*/
bool queue_get_front(struct queue * queue,
QueueDataType_t * data)
{
if (queue_is_empty(queue))
{
return 0;
}
*data = queue->data[queue->front_idx];
queue->front_idx = (queue->front_idx == 0) ? (queue->size - 1) : (queue->front_idx - 1);
queue->elements--;
return 1;
}
/**
* Reads one byte from the back of the queue.
*
* \returns false if the queue is empty.
*/
bool queue_get_back(struct queue * queue,
QueueDataType_t * data)
{
if (queue_is_empty(queue))
{
return 0;
}
*data = queue->data[queue->back_idx];
queue->back_idx = (queue->back_idx + 1) >= queue->size ? 0 : (queue->back_idx + 1);
queue->elements--;
return 1;
}
</code></pre>
<p>Initializing the queue</p>
<pre><code>#define MY_QUEUE_DATA_SIZE 50
static QueueDataType_t q_data[MY_QUEUE_DATA_SIZE];
static struct queue my_queue =
{
.data = q_data,
.size = MY_QUEUE_DATA_SIZE,
};
queue_init(&my_queue);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:11:20.737",
"Id": "491561",
"Score": "2",
"body": "I rolled back your edit. Editing the _answered_ question is not allowed in this exchange, because it invalidates the answer. Feel free to ask a follow-up question with all the changes you've made."
}
] |
[
{
"body": "<p>For consistency with your use of the <code><stdbool.h></code> header and the <code>bool</code> macro, your functions that return a <code>bool</code> should use <code>return true;</code> or <code>return false;</code> instead of returning 0 or 1. There will be no difference in the code but it is easier for a person reading the code to recognize what the return is (and this would also align better with your function documentation where you say that it "returns false").</p>\n<p>Also related to comments, the <code>add</code> and <code>get</code> functions say that they add or read "one byte" but, because <code>QueueDataType_t</code> is a 16 bit type, they add or read two bytes.</p>\n<p>If supported in your tool chain, <code>queue_is_full</code> and <code>queue_is_empty</code> could take their parameters as <code>const struct queue * queue</code> since they do not make any chances to the queue.</p>\n<p>There is a subtle bug when removing the last element from the queue. When a queue is initialized, and when the first element is added, the <code>front_idx</code> and <code>back_idx</code> values both refer to the same slot in the data array. However, when you remove this single element, you still change the idx variable, so the resulting empty queue has the front and back indexes referring to different slots. Then when you add a new element, the indexes are not changed so that this element isn't pointed to by both indexes. This can result in an incorrect value being returned when this elements are removed from the queue. The fix is to not change the idx value when removing the last element.</p>\n<p>You can create a function to adjust the indexes forward or backward to avoid having similar and duplicated code. This could then use the <code>%</code> operator (instead of a conditional branch) if appropriate on your embedded system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:09:16.313",
"Id": "491554",
"Score": "0",
"body": "You are right !! I changed the code adding a guard where I check \n`queue->front_idx == queue->back_idx`... I fixed the comments and the true/false values for the booleans!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:00:22.180",
"Id": "250516",
"ParentId": "250511",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "250516",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T14:12:49.860",
"Id": "250511",
"Score": "5",
"Tags": [
"c",
"queue",
"embedded"
],
"Title": "Double-ended queue for Embedded Systems"
}
|
250511
|
<p>I need the ability to generate random MAC addresses, so I wrote up a little function that does that:</p>
<pre><code>>>> random_mac()
'7C:93:B7:AF:BA:AE'
>>> random_mac()
'D8:D8:A0:D4:A5:3F'
>>> random_mac(unicast=False, universal=True)
'55:47:C6:EE:C6:2B'
>>> random_mac(unicast=True, universal=False)
'FE:A1:4B:98:76:B6'
</code></pre>
<p>I decided to allow the user to pick if it's unicast/multicast and universally/locally administered; even though I'll only need unicast/universal. This caused me headaches though because I'm still not great at dealing with bits. <a href="https://en.wikipedia.org/wiki/MAC_address#/media/File:MAC-48_Address.svg" rel="noreferrer">The LSB of the first octet indicates uni/multicast, and the second LSB of the octet indicates universal/local</a>, so these bits can't be random.</p>
<p>After playing around with a few failed ideas (generating all random bits, then "fixing" the two bits later), I finally decided to generate a random number between 0 and 63 inclusive, left shift it twice, than add the two bits on after. It works, but it's ugly and looks suboptimal.</p>
<p>It's not a lot of code, but I'd like a few things reviewed:</p>
<ul>
<li>Is there a better approach? It feels hacky generating it as two pieces then adding them together. I tried <a href="https://stackoverflow.com/a/47990/3000206">explicitly setting the bits</a>, but the code to decide between <code>|</code>, and <code>&</code> and <code>~</code> got messier than what I have now, so I went with this way.</li>
<li>The number constants are bugging me too. The numbers kind of sit on a border of self-explanatory and magic, so I decided to name them to be safe. <code>LAST_SIX_BITS_VALUE</code> feels off though.</li>
<li>Is treating a boolean value as a number during bitwise operation idiomatic? Is it clear as I have it now?</li>
<li>Attaching the first octet to the rest is suboptimal as well. Speed isn't a huge concern, but I'm curious if there's a cleaner way that I'm missing.</li>
</ul>
<hr />
<pre><code>from random import randint, randrange
N_MAC_OCTETS = 6
OCTET_VALUE = 256
LAST_SIX_BITS_VALUE = 63
def random_mac(unicast: bool = True, universal: bool = True) -> str:
least_two_bits = (not unicast) + ((not universal) << 1)
first_octet = least_two_bits + (randint(0, LAST_SIX_BITS_VALUE) << 2)
octets = [first_octet] + [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS - 1)]
return ":".join(f"{octet:02X}" for octet in octets)
</code></pre>
<hr />
<p>Examples of the bits for the first octet for different inputs:</p>
<pre><code>def display(mac):
print(mac, f"{int(mac.split(':')[0], 16):08b}")
# Unicast, Universal
>>> display(random_mac(True, True))
04:27:DE:9A:1B:D7 00000100 # Ends with 0,0
# Unicast, Local
>>> display(random_mac(True, False))
72:FB:49:43:D5:F2 01110010 # 1,0
# Multicast, Universal
>>> display(random_mac(False, True))
7D:BF:03:4E:E5:2A 01111101 # 0,1
# Multicast, Local
>>> display(random_mac(False, False))
2F:73:52:12:8C:50 00101111 # 1,1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T17:46:58.820",
"Id": "491552",
"Score": "6",
"body": "small suggestion, it might help to look at how the library `randmac` does it. [randmac Python 3](https://pypi.org/project/randmac/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:32:08.010",
"Id": "491555",
"Score": "3",
"body": "would it help that you deal with nibbles instead of octet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:47:53.740",
"Id": "491557",
"Score": "2",
"body": "@AryanParekh That's a good idea. For some reason I never even considered that there would be a library for this. I'll check it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:49:30.040",
"Id": "491558",
"Score": "1",
"body": "@hjpotter92 I don't really care too much about the implementation (except for readability) providing the end result is the same. It may ease it a bit though to deal with the \"special nibble\" on its own, then add it in to the rest of the octet. That would make some of the magic constants simpler numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:03:09.773",
"Id": "491559",
"Score": "2",
"body": "@Carcigenicate that's cool, I assume that you might have wanted to create your own method rather than using a library, if that's not the case, prefer using the library as the class from the library is really useful, with methods that allow you to use different formats,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:53:17.243",
"Id": "492972",
"Score": "0",
"body": "Note that some locally-administered addresses are well-known addresses. You should not gazump those. Basically, avoid 0?:??:??:??:??:?? to 6?:??:??:??:??:?? inclusive for LAs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:56:25.690",
"Id": "492973",
"Score": "0",
"body": "@vk5tu Stuff like that is why for my actual project, I ended up abandoning the two parameters. I'm glad I posted this question because I learned a lot, but only global/unicast make sense for my application, and multicast/local have their own nuances that make them inappropriate to randomize; at least not without a lot more considerations that I'm not wiling to deal with."
}
] |
[
{
"body": "<ul>\n<li><p>Negating an argument is somewhat counterintuitive. Consider passing them as <code>multicast</code> and <code>local</code> instead.</p>\n</li>\n<li><p>I would seriously consider defining</p>\n<pre><code> UNIVERSAL = 0x01\n MULTICAST = 0x02\n</code></pre>\n<p>and pass them as a single argument, is in</p>\n<pre><code> random_mac(UNIVERSAL | MULTICAST)\n</code></pre>\n</li>\n<li><p>Using both <code>randint</code> and <code>randrange</code> feels odd. I would stick with <code>randrange</code>.</p>\n</li>\n<li><p>First octet needs a special treatment anyway. That said, consider</p>\n<pre><code> def random_mac(special_bits = 0):\n octets = [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS)]\n octets[0] = fix_octet(octet[0], special_bits)\n return ":".join(f"{octet:02X}" for octet in octets)\n</code></pre>\n<p>with</p>\n<pre><code> def fix_octet(octet, special_bits):\n return (octet & ~0x03) | special_bits\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T02:42:52.200",
"Id": "491581",
"Score": "0",
"body": "@Carcigenicate: `fix_octet` just clears the low 2 bits, then ORs in what should be there. Looks very comprehensible to me, and exactly what I would have suggested if there wasn't already an answer doing that. (Generating all 6 octets the same way and modifying 1 is also what I was going to suggest). Getting the caller to pass ORed bitflags is great; it simplifies the implementation and makes the call-site more self-documenting. (And is a common idiom in C for system calls like `mmap(..., MAP_PRIVATE | MAP_ANONYMOUS | ...)`, or for ORing together permission bit flags, or lots of other things.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T03:12:41.000",
"Id": "491588",
"Score": "0",
"body": "@PeterCordes I may be misunderstanding something, but I was just saying that this currently seems to give an incorrect result. I think it's because the flags need to be `MULTICAST = 0x01; LOCAL = 0x02` instead of what they currently are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T03:14:54.910",
"Id": "491589",
"Score": "0",
"body": "@Carcigenicate: I was replying to your first comment. You second comment didn't point out what the problem was or give an example, and I didn't notice the bit-flags definitions were backwards. But yes, `0x1` is the LSB, `0x2` is the second bit, so that matches your question (and wikipedia)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T03:17:05.167",
"Id": "491590",
"Score": "0",
"body": "@PeterCordes OK, now this makes sense. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:02:23.910",
"Id": "491643",
"Score": "1",
"body": "After changing the flags to `MULTICAST = 0x01; LOCAL = 0x02`, this does indeed give the correct output. Thank you for the suggestions."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:04:34.333",
"Id": "250518",
"ParentId": "250514",
"Score": "15"
}
},
{
"body": "<p><code>random.randrange()</code> takes <em>start</em>, <em>stop</em>, and <em>step</em> arguments just like <code>range()</code>. To select the first octet, <em>start</em> is based on the unicast and universal flags, <em>end</em> is 256, and <em>step</em> is 4 (four possible combinations of unicast and universal).</p>\n<pre><code>N_MAC_OCTETS = 6\nOCTET_VALUE = 256\nLAST_SIX_BITS_VALUE = 63\n\ndef random_mac(unicast: bool = True, universal: bool = True) -> str:\n first_octet = randrange(3 ^ (universal*2 + unicast), OCTET_VALUE, 4)\n octets = [first_octet] + [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS - 1)]\n return ":".join(f"{octet:02X}" for octet in octets)\n</code></pre>\n<p>or better:</p>\n<pre><code>UNICAST = 0\nMULTICASE = 1\n\nUNIVERSAL = 0\nLOCAL = 2\n\ndef random_mac(flags: int = UNICAST | UNIVERSAL) -> str:\n first_octet = randrange(flags, OCTET_VALUE, 4)\n octets = [first_octet] + [randrange(OCTET_VALUE) for _ in range(N_MAC_OCTETS - 1)]\n return ":".join(f"{octet:02X}" for octet in octets)\n</code></pre>\n<p>Called like:</p>\n<pre><code>random_mac(LOCAL | MULTICAST)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T20:59:00.767",
"Id": "491565",
"Score": "1",
"body": "Using `universal = True` for unicast is the opposite of the bit value. That is, when `unicast` it true the bit value is false. Similarly for `universal`. This smells like a source of bugs. I'd suggest changing the parameters to `multicast` and `local` so they match the bit values or, as vnp suggested, define some constants that can be or-ed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:11:11.583",
"Id": "250520",
"ParentId": "250514",
"Score": "2"
}
},
{
"body": "<p>While still using @vnp's <code>fix_octet()</code> function, an alternate approach might be</p>\n<pre class=\"lang-py prettyprint-override\"><code>def random_mac(special_bits = 0):\n return ':'.join('%02x'%randint(0,255) if i != 0 else '%02x'%fix_octet(randint(0,255),special_bits) for i in range(6))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:35:30.393",
"Id": "250522",
"ParentId": "250514",
"Score": "2"
}
},
{
"body": "<h1>Some observations on the API</h1>\n<h2>Naming</h2>\n<p>The IEEE <em>strongly discourages</em> use of the name <em>MAC</em> or <em>MAC-48</em>. These names should only be used as an obsolete label for <em>EUI-48</em>.</p>\n<p>It is also imprecise, since not all MAC addresses are EUI-48 addresses. For example, FireWire MAC addresses are EUI-64.</p>\n<p>So, your function should probably be named <code>random_eui48</code> instead.</p>\n<h2>Keyword-only arguments</h2>\n<p>Having two boolean parameters can lead to confusion. I would make them <a href=\"https://www.python.org/dev/peps/pep-3102/\" rel=\"noreferrer\">keyword-only arguments</a> so that the caller is always forced to name them:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def random_eui48(*, unicast: bool = True, universal: bool = True) -> str:\n</code></pre>\n<h2>Defaults</h2>\n<p>I agree with the choice of making Unicast the default. It is probably what users will usually need more often. However, I <em>disagree</em> with making universally administered addresses the default. In fact, I find it highly dubious to randomly generate UAAs <em>at all</em>. At most, you should randomly generate addresses <em>within an OUI you own</em>.</p>\n<p>So, I would very much prefer to make LAAs the default.</p>\n<h2>Choice of parameters</h2>\n<p>I would choose the parameters such that they are "off-by-default" (<code>False</code>) and ca be "turned on" by the caller:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def random_eui48(*, multicast: bool = False, universal: bool = False) -> str:\n</code></pre>\n<h2>API extension: supply OUI</h2>\n<p>It really only makes sense to generate a UAA <em>within an OUI you own</em>. Therefore, your API should provide for passing in a OUI to generate an addresses for. Make sure you take care of both the MAC-S and MAC-L registries!</p>\n<h1>Implementation</h1>\n<p>An EUI-48 is a 48 bit number. I find it strange to treat it as a conglomerate of 5 8 bit and one 6 bit number.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T13:53:52.563",
"Id": "491628",
"Score": "2",
"body": "Thank you. Regarding \"EUI-48\", is \"MAC\" simply not used in industry, or should it only be avoided when you're referring to a physical address of a certain length? I've actually never heard of \"EUI-48\" before; beyond the mention on the Wiki page. And as for why I'm randomizing the OUI as well: I'm writing a malicious DHCP client and need random MACs so that I can continue requesting new addresses while keeping the previous addresses on lease."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T05:44:13.970",
"Id": "492696",
"Score": "3",
"body": "Oh, MAC is being used all over the place, it's just that the IEEE strongly advises against it. If you *really are* talking about MAC addresses, I think it makes sense to use the term \"MAC\", but be aware that, depending on the protocol, MAC addresses need not be 48 bit. And conversely, EUIs are used for addresses other than MAC addresses. E.g. the Clock ID in the Precision Type Protocol is an EUI, albeit an EUI-64."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:21:30.073",
"Id": "492805",
"Score": "0",
"body": "I'm not sure the IEEE disapproves of the use of \"MAC\" as a general term. Rather, my understanding is that the term \"MAC-48\" is deprecated in favour of \"EUI-48\". \"MAC address\" usually refers to how the identifier is used, where as \"[MAC/EUI]-48\" refers to the numbering scheme."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T06:12:03.337",
"Id": "250538",
"ParentId": "250514",
"Score": "11"
}
},
{
"body": "<pre><code>(not unicast) + ((not universal) << 1)\n</code></pre>\n<ul>\n<li>When manipulating bits or bitfields, use <code>|</code>, not <code>+</code>. Even though the result will be the same here, the semantic is different.</li>\n<li>You read left-to-right. So handle the bits left to right.</li>\n<li>I do agree with the fact that negations quickly mess with your head.</li>\n</ul>\n<p>I'd rather write:</p>\n<pre><code>(local << 1) | multicast\n</code></pre>\n<p>Going one step further, I'd replace:</p>\n<pre><code>least_two_bits = (not unicast) + ((not universal) << 1)\nfirst_octet = least_two_bits + (randint(0, LAST_SIX_BITS_VALUE) << 2)\n</code></pre>\n<p>With</p>\n<pre><code>first_octet = (randint(0, LAST_SIX_BITS_VALUE) << 2) | (local << 1) | multicast\n</code></pre>\n<p>You could define <code>LAST_SIX_BITS_VALUE</code> as <code>((1 << 6)-1)</code> to make it more explicit that its value comes from the need for 6 bits. One step further would be to define</p>\n<pre><code>FIRST_OCTET_RANDOM_BITS_NUMBER = 6\nFIRST_OCTET_RANDOM_BITS_MAX_VALUE = (1 << FIRST_OCTET_RANDOM_BITS_NUMBER) - 1\n</code></pre>\n<p>I agree that mixing <code>randint</code> (where the top value is inclusive) and <code>randrange</code> (where it isn't) is confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:49:08.957",
"Id": "250554",
"ParentId": "250514",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250518",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T16:58:09.130",
"Id": "250514",
"Score": "20",
"Tags": [
"python",
"python-3.x"
],
"Title": "Generating a random MAC address"
}
|
250514
|
<p>I'm starting to learn Rust. After reading through chapter 13 of <a href="https://doc.rust-lang.org/book/ch01-00-getting-started.html" rel="noreferrer">the Rust Book</a>, I've gone and implemented a handful of sorting algorithms for practice with the language.</p>
<p>Would love to learn some more experiences Rustacean's tips on ways to make this code more idiomatic. I have some particular difficulties with <code>mergesort</code> -- I am not sure how to making some unnecessary copies without changing the function signature from <code>Vec<u32></code> to <code>&[u32]</code>.</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
pub fn bubble_sort(vec: &mut Vec<u32>) -> &Vec<u32> {
if vec.len() == 0 {
return vec;
}
let mut swap_seen = true;
while swap_seen {
swap_seen = false;
for mut i in 0..(vec.len() - 1) {
while (i < (vec.len() - 1)) && (vec[i] > vec[i + 1]) {
let (a, b) = (vec[i], vec[i + 1]);
vec[i + 1] = a;
vec[i] = b;
swap_seen = true;
i += 1;
}
}
}
vec
}
pub fn selection_sort(vec: &mut Vec<u32>) -> &Vec<u32> {
if vec.len() == 0 {
return vec;
}
for i in 0..(vec.len()) {
let mut smallest_idx = i;
for j in (i + 1)..(vec.len()) {
if vec[j] < vec[smallest_idx] {
smallest_idx = j;
}
}
let (a, b) = (vec[i], vec[smallest_idx]);
vec[i] = b;
vec[smallest_idx] = a;
}
vec
}
pub fn counting_sort(vec: &mut Vec<u32>) -> Vec<u32> {
if vec.len() == 0 {
return vec![];
}
// The type matters. HashMap implements its methods using traits, and if you don't pick
// the right types the traits won't apply and the methods won't show up.
let mut counts: HashMap<&u32, u32> = HashMap::new();
for val in vec.iter() {
// Interesting usage note. This doesn't work:
//
// match counts.get(val) {
// Some(n_val) => counts.insert(val, n_val + 1),
// None => counts.insert(val, 1),
// };
//
// Why not?
// counts.get(val) is an immutable borrow of the counts hashmap.
// counts.insert(val) is a mutable borrow of the counts hashmap.
// This violates the constraint that only one mutable or any number of immutable
// borrows may be live at a time. However, it only throws a warning, not an error, for
// some reason. Ref:
// https://discord.com/channels/442252698964721669/448238009733742612/763950019681583152
//
// That brings us to this working code. The "entry API" is specifically designed to avoid
// this problem. In general, many APIs in Rust are designed around such concerns.
*counts.entry(val).or_default() += 1;
}
let mut sorted: Vec<u32> = vec![];
for digit in 0..=9u32 {
let digit_ref = &digit;
let digit_count = counts.get(digit_ref);
match digit_count {
Some(count) => {
for _ in 0..(*count as i32) {
sorted.push(digit);
}
},
None => (),
}
}
sorted
}
pub fn insertion_sort(vec: &mut Vec<u32>) -> &Vec<u32> {
// usize is Rust's "architecture-dependent integer size". It is u32 on 32-bit systems and
// u64 on 64-bit systems. usize is used in certain places in Rust lang where this low-level
// detail matters, e.g. if indexing into memory. It's used to represent array sizes I guess
// because array length maximum is the architecture's word size.
for i in 0..(vec.len()) {
for j in 0..i {
if vec[j] > vec[i] {
let (a, b) = (vec[i], vec[j]);
vec[j] = a;
vec[i] = b;
}
}
}
vec
}
pub fn quicksort(vec: Vec<u32>) -> Vec<u32> {
if vec.len() <= 1 {
return vec;
}
let pivot_idx = ((vec.len() as f32) / 2.0).floor() as usize;
let pivot_val = vec[pivot_idx];
let mut left: Vec<u32> = Vec::new();
let mut right: Vec<u32> = Vec::new();
for val in ([&vec[..pivot_idx], &vec[(pivot_idx + 1)..]].concat()).into_iter() {
if val < pivot_val {
left.push(val);
}
else {
right.push(val);
}
}
let mut result = quicksort(left);
result.push(pivot_val);
let mut right = quicksort(right);
result.append(&mut right);
result
}
pub fn mergesort(vec: Vec<u32>) -> Vec<u32> {
let join = |left: Vec<u32>, right: Vec<u32>| -> Vec<u32> {
let (mut j, mut k) = (0, 0);
let mut result: Vec<u32> = vec![];
while j < left.len() && k < right.len() {
if left[j] < right[k] {
result.push(left[j]);
j += 1;
}
else {
result.push(right[k]);
k += 1;
}
}
while j < left.len() {
result.push(left[j]);
j += 1;
}
while k < right.len() {
result.push(right[k]);
k += 1;
}
result
};
if vec.len() <= 1 {
return vec;
}
// Nit: eliminate this additional base case.
if vec.len() == 2 {
if vec[0] < vec[1] {
return vec;
} else {
return vec![vec[1], vec[0]];
}
}
// TODO: how do I eliminate this copy without changing the function signature from Vec<u32>
// to &[u32]?
let pivot = (((vec.len() as f32) / 2.0).floor()) as usize;
let mut left: Vec<u32> = Vec::new();
left.extend_from_slice(&vec[..pivot]);
let mut right: Vec<u32> = Vec::new();
right.extend_from_slice(&vec[pivot..]);
let left = mergesort(left);
let right = mergesort(right);
join(left, right)
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>This answer is only about mergesort</strong></p>\n<p>I don't see why you don't want mergesort to take <code>&[u32]</code> as an argument - it makes the function more generic! I read in the <a href=\"https://doc.rust-lang.org/book/ch04-03-slices.html#string-slices-as-parameters\" rel=\"nofollow noreferrer\">rust book</a> that rustaceans prefer to use <code>&str</code> instead of <code>&String</code> as an argument for that reason ;)</p>\n<p>I'm new to Rust as well - sorry! - and decided to try my hand at this.</p>\n<h2>Edge cases</h2>\n<p>My first comment is not rust-specific (all the others are) this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> if vec.len() <= 1 {\n return vec;\n }\n // Nit: eliminate this additional base case.\n if vec.len() == 2 {\n if vec[0] < vec[1] {\n return vec;\n } else {\n return vec![vec[1], vec[0]];\n }\n }\n</code></pre>\n<p>It can be rewritten like this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> if vec.len() == 2 && vec[0] > vec[1] {\n return vec![vec[1], vec[0]];\n }\n if vec.len() <= 2 {\n return vec;\n }\n</code></pre>\n<h2>pivot</h2>\n<pre class=\"lang-rust prettyprint-override\"><code> let pivot = (((vec.len() as f32) / 2.0).floor()) as usize;\n</code></pre>\n<p>When dividing a positive int by another positive int, the result is the same as in C / C++: you don't get what's after the floating point. You can just do:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let pivot = vec.len() / 2;\n</code></pre>\n<h2>Signature change</h2>\n<p>Let's study the signature of your function - and change it:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn mergesort(vec: Vec<u32>) -> Vec<u32>;\n</code></pre>\n<p>It takes a <code>Vec<u32></code> - not as a reference, so it moves the data into the function. The argument becomes unusable by the caller of the function. It then returns a <em>new</em> <code>Vec<u32></code>.</p>\n<p>For example, this code won't work, since <code>vec</code> was moved, it can't be used in the <code>println!</code>:</p>\n<pre><code>fn main() {\n let vec = vec![2,1,0,4,5];\n let sorted = mergesort(vec);\n\n println!("Original: {:?}, sorted: {?:}", vec, sorted);\n}\n</code></pre>\n<p>Given that, there is no downside to use <code>&mut [u32]</code> as the type, and reorder in place:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn mergesort(vec: &mut [u32]);\n</code></pre>\n<p>Now <code>mergesort</code> borrows a mutable slice.</p>\n<p>Now you probably have plenty of errors :)</p>\n<p>Let's look at the last part:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let mut left: Vec<u32> = Vec::new();\n left.extend_from_slice(&vec[..pivot]);\n let mut right: Vec<u32> = Vec::new();\n right.extend_from_slice(&vec[pivot..]);\n\n let left = mergesort(left);\n let right = mergesort(right);\n\n join(left, right)\n</code></pre>\n<p>Since <code>mergesort</code> takes a mutable reference, it can change to:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> mergesort(&mut vec[..pivot]);\n mergesort(&mut vec[pivot..]);\n\n join(???)\n</code></pre>\n<h2>join function</h2>\n<p>So now we must change the signature of <code>join</code>, to take two slices as parameters. Actually, I'd like to do this, and have join rewrite the slices in place:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> join (&mut vec[..pivot], &mut vec[pivot..]);\n</code></pre>\n<p>But it's not possible to borrow two mutable references at the same time!</p>\n<p>The next best thing, to me, is:</p>\n<ul>\n<li><code>join</code> borrows two immutable references and returns a <code>Vec</code></li>\n<li>Then assign the content of the <code>Vec</code> to the slice</li>\n</ul>\n<p>So here's the signature:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let join = |left: &[u32], right: &[u32]| -> Vec<u32> {\n // ...\n };\n\n let pivot = vec.len() / 2;\n\n mergesort(&mut vec[..pivot]);\n mergesort(&mut vec[pivot..]);\n\n let result = join(&vec[..pivot], &vec[pivot..]);\n vec.copy_from_slice(&result[..])\n</code></pre>\n<p>Now we just have to change join ;)</p>\n<p>First this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> while j < left.len() {\n result.push(left[j]);\n j += 1;\n }\n while k < right.len() {\n result.push(right[k]);\n k += 1;\n }\n</code></pre>\n<p>It can be changed to:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> result.extend_from_slice(&left[j..]);\n result.extend_from_slice(&right[k..]);\n</code></pre>\n<p>Now this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let (mut j, mut k) = (0, 0);\n let mut result: Vec<u32> = vec![];\n while j < left.len() && k < right.len() {\n if left[j] < right[k] {\n result.push(left[j]);\n j += 1;\n }\n else {\n result.push(right[k]);\n k += 1;\n }\n }\n</code></pre>\n<p>I don't think increasing indexes is in rust philosophy, I'd rather like to use iterators:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let mut left = left.iter();\n let mut right = right.iter();\n while let (Some(left), Some(right)) = (left.next(), right.next()) {\n // ...\n }\n</code></pre>\n<p>Unfortunately this is not possible, because we only want to advance one side at a time. Well, there is a <code>peekable</code> function for iterators, to check the next value without calling <code>next</code>, which gives this instead for <code>join</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let join = |left: &[u32], right: &[u32]| -> Vec<u32> {\n let mut result: Vec<u32> = vec![];\n\n let mut left = left.iter().peekable();\n let mut right = right.iter().peekable();\n\n while let (Some(left_val), Some(right_val)) = (left.peek(), right.peek()) {\n if left_val < right_val {\n result.push(**left_val);\n left.next(); // only advance left\n } else {\n result.push(**right_val);\n right.next(); // only advance right\n }\n }\n\n result.extend(left);\n result.extend(right);\n\n result\n };\n</code></pre>\n<p>I'm not sure if making an iterator peekable is all that great, however. But now you could even change the signature of <code>join</code> to take two mutable <code>Iter</code> as parameters!</p>\n<p>Here's another version with just slices:</p>\n<pre class=\"lang-rust prettyprint-override\"><code> let join = |mut left: &[u32], mut right: &[u32]| -> Vec<u32> {\n let mut result: Vec<u32> = vec![];\n \n while left.len() > 0 && right.len() > 0 {\n if left[0] < right[0] {\n result.push(left[0]);\n left = &left[1..];\n } else {\n result.push(right[0]);\n right = &right[1..];\n }\n }\n result.extend_from_slice(&left);\n result.extend_from_slice(&right);\n\n result\n };\n</code></pre>\n<p>Note that I made the arguments mutable, I could have done this instead:</p>\n<pre><code> let join = |left: &[u32], right: &[u32]| -> Vec<u32> {\n let mut left = left;\n let mut right = right;\n\n // ...\n };\n</code></pre>\n<h2>Final version</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn mergesort(vec: &mut [u32]) {\n if vec.len() == 2 && vec[0] > vec[1] {\n vec.swap(0, 1);\n }\n if vec.len() <= 2 {\n return;\n }\n\n let join = |mut left: &[u32], mut right: &[u32]| -> Vec<u32> {\n let mut result: Vec<u32> = vec![];\n\n while left.len() > 0 && right.len() > 0 {\n if left[0] < right[0] {\n result.push(left[0]);\n left = &left[1..];\n } else {\n result.push(right[0]);\n right = &right[1..];\n }\n }\n result.extend_from_slice(&left);\n result.extend_from_slice(&right);\n\n result\n };\n\n let pivot = vec.len() / 2;\n\n mergesort(&mut vec[..pivot]);\n mergesort(&mut vec[pivot..]);\n\n let result = join(&vec[..pivot], &vec[pivot..]);\n vec.copy_from_slice(&result[..])\n}\n</code></pre>\n<p>It's easy to get back the original signature as well, if you really want:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn mergesort (vec: Vec<u32>) -> Vec<u32> {\n mergesort_private(&mut vec[..]);\n vec\n}\n\n// Original mergesort function, renamed to mergesort_private\nfn mergesort_private(vec: &mut [u32]) {\n // ...\n}\n</code></pre>\n<h2>Bonus: bubble_sort</h2>\n<p>Without changing the signature of the function (<code>& mut[u32]</code> could be used), here it is transformed:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn bubble_sort(vec: &mut Vec<u32>) -> &Vec<u32> {\n loop {\n let mut swap_seen = false;\n\n for i in 0..(vec.len() - 1) {\n if vec[i] > vec[i + 1] {\n vec.swap(i, i + 1);\n swap_seen = true;\n }\n }\n\n if !swap_seen {\n break;\n }\n }\n vec\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:56:43.997",
"Id": "492951",
"Score": "1",
"body": "FYI: [`split_at_mut`](https://doc.rust-lang.org/std/primitive.str.html#method.split_at_mut) produces mutable references to two disjoint sections of a mutable slice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:53:46.257",
"Id": "493501",
"Score": "0",
"body": "Thank you for your answer! I learned a lot from reading this writeup. =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T23:04:56.853",
"Id": "250530",
"ParentId": "250515",
"Score": "4"
}
},
{
"body": "<p>On the whole, your Rust code looks good to me. You make appropriate use of the standard library and language features like closures. Nothing stands out as especially unidiomatic; even the formatting looks nice.</p>\n<p>That said, of course there are always things that could be improved.</p>\n<h2>General observations</h2>\n<ul>\n<li>If you're not using <code>rustfmt</code> yet, start now. Your formatting is basically identical to the <code>rustfmt</code> defaults, but an automated formatting tool has the advantage of finding the occasional mistake as well as making code look pretty.</li>\n<li>Except for <code>counting_sort</code> and <code>mergesort</code>, these algorithms are all in-place and work on slices, so they should accept <code>&mut [u32]</code> instead of <code>&mut Vec<u32></code>. This makes it possible to sort arrays and other array-like data structures as well as <code>Vec</code>tors.</li>\n<li>Returning <code>&Vec<u32></code> from the sort function allows it to be used like <code>foo(sort(&mut xs))</code> (<code>foo</code> will receive the sorted array). However, this can be misleading because the <code>sort</code> function actually mutates <code>xs</code>, which can be easily overlooked if it occurs in the middle of a more complicated expression. It's better for functions that mutate their arguments <em>not</em> to also return them, so the calling code is more obvious (<code>sort(&mut xs); foo(&xs)</code>). The standard library <code>sort</code> functions do not return anything.</li>\n<li>Use the slice <a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.swap\" rel=\"nofollow noreferrer\"><code>swap</code></a> method to swap two elements by index (not to be confused with the <code>std::mem::swap</code> function, which swaps the contents of any two <code>&mut</code> references).</li>\n<li>With the exception of <code>counting_sort</code>, all of these functions order the elements by comparing them, so they ought to work just as well with slices of any type that can be compared with <code>Ord</code>¹ -- not just <code>u32</code>. There's nothing wrong with writing a function that only sorts <code>u32</code>s, and in some cases that may even be desirable (for type inference, for example); however, it's nearly as easy to be generic as not, and even if you never expect to use the function with more than one type, coding to an interface (<code>T: Ord</code>) can help you avoid bugs that result from over-focusing on a particular implementation (<code>u32</code>).</li>\n<li>There is an <code>.is_empty()</code> function on slices you can use in place of <code>.len() == 0</code>.</li>\n<li>Note that <code>..</code> and <code>..=</code> have the lowest <a href=\"https://doc.rust-lang.org/reference/expressions.html#expression-precedence\" rel=\"nofollow noreferrer\">precedence</a> of any operator except the assignment operators. So you don't need to parenthesize, unless you find it helpful for readability.</li>\n<li>Don't write <code>for r in vec.iter()</code> or <code>for v in vec.into_iter()</code>. The <code>for</code> loop calls <code>into_iter()</code> implicitly. Use <code>for r in &vec</code> and <code>for v in vec</code> instead.</li>\n</ul>\n<h2>Bubble sort</h2>\n<p><a href=\"https://codereview.stackexchange.com/a/250530/172514\">coyotte508's answer</a> already suggested a fix for this, but the nested loop does some unnecessary comparisons because <code>i</code> does not increase monotonically. You probably expected that after the <code>while</code> loop was finished, the <code>for</code> loop would pick up where it left off with the current value of <code>i</code>, but <code>for</code> loops don't work like that in Rust.</p>\n<p><code>bubble_sort</code> also does extra work when the end of the array is already sorted. During a bubble sort, there's a section of the array that's already sorted, and each iteration of the outer loop grows that section by at least 1 (but sometimes more). You can exploit this fact by keeping track of the index of the last swap performed. At the end of each iteration of the outer loop, the index of the last value swapped is the beginning of the <em>sorted portion</em> of the array, which never needs to be sorted again - so you can use that index instead of <code>vec.len()</code> as a bound for the inner loop, and exit the outer loop when the length of the "unsorted" portion drops to 1 (since an array of length 1 is sorted already). As a bonus, if you initialize it with the length of the slice, you can avoid the initial check against <code>0</code>.</p>\n<p>Finally, it's a minor thing, but you can reduce the number of <code>+ 1</code>s and <code>- 1</code>s by iterating from <code>1</code> instead of <code>0</code>.</p>\n<p>With all these things in mind, here's how you might write <code>bubble_sort</code>:</p>\n<pre><code>pub fn bubble_sort<T: Ord>(vec: &mut [T]) {\n let mut unsorted_len = vec.len();\n while unsorted_len > 1 {\n let mut last_swap = 0;\n for i in 1..unsorted_len {\n if vec[i - 1] > vec[i] {\n vec.swap(i - 1, i);\n last_swap = i;\n }\n }\n unsorted_len = last_swap;\n }\n}\n</code></pre>\n<h2>Selection sort</h2>\n<p>This one is pretty textbook. IMO there's not much to improve beyond the general stuff I mentioned earlier, and that the <code>if vec.len() == 0</code> at the beginning is unnecessary because the <code>for</code> loop will immediately check it again.</p>\n<pre><code>pub fn selection_sort<T: Ord>(vec: &mut [T]) {\n for i in 0..vec.len() {\n let mut smallest_idx = i;\n for j in (i + 1)..vec.len() {\n if vec[j] < vec[smallest_idx] {\n smallest_idx = j;\n }\n }\n vec.swap(i, smallest_idx);\n }\n}\n</code></pre>\n<h2>Insertion sort</h2>\n<p>Again, pretty textbook. You can start the outer loop at <code>1</code> because there's never anything to do at <code>i = 0</code>.</p>\n<pre><code>pub fn insertion_sort<T: Ord>(vec: &mut [T]) {\n for i in 1..vec.len() {\n for j in 0..i {\n if vec[j] > vec[i] {\n vec.swap(j, i);\n }\n }\n }\n}\n</code></pre>\n<h2>Counting sort</h2>\n<p>This one can't be made generic, and it can't easily be made in-place. However, since it only has to work on integer keys with a limited range, there are some other ways it could be improved.</p>\n<p>First, since it isn't in-place, it doesn't need to mutate its input; we can make it accept <code>&[u32]</code>. (It's actually even more general than that: it can sort any sequence of integer values, even ones that are too large to fit in memory at once! But for the moment let's stick with <code>&[u32]</code>.)</p>\n<p>Next about the <code>HashMap</code>: this is an odd choice for a counting sort because choosing a <code>HashMap<&u32, u32></code> over a <code>Vec<u32></code> or even just a plain <code>[u32; 10]</code> (indexed by <code>*val</code>) suggests you're concerned about wasting space for a bunch of empty count-buckets. But usually you use a counting sort because you expect <code>n</code> (size of the input) to be much larger than <code>k</code> (number of buckets), which would only coincide with there being a lot of empty buckets if the data is concentrated into much fewer than <code>k</code> buckets. Probably 98% of the time you're writing a counting sort, you want either an array of buckets or a <code>Vec</code> of buckets. But let's suppose we're in the 2%. We can still replace the <code>HashMap</code> with a <code>BTreeMap</code>, which is more compact, likely faster,² and naturally keeps the keys in order. We'll also copy the key instead of taking a reference to it, since it's a small integer.</p>\n<p>Using <code>BTreeMap</code> also lets us sidestep one of the annoying problems of counting sorts: what happens if one of the inputs is out of range? You could solve this problem by <code>assert</code>ing the values are always in range, or by restricting the input type to one that only allows the values <code>0..=9</code>, but that's not always convenient. With <code>BTreeMap</code> the output is always correct. In the worst case scenario, with totally arbitrary inputs, the algorithm degrades to (a poorly-optimized) tree sort, which is still <code>O(n log n)</code>.</p>\n<p>Checking whether the input is empty at the beginning of the function probably does nothing useful. The function still does the same thing without it, so the best you can hope for is it saves you a handful of instructions (<code>BTreeMap::new</code> does not allocate), at the expense of adding an unavoidable branch at the beginning of every call. I wouldn't put it in unless profiling showed a non-negligible effect.</p>\n<p>To help myself not lose track of which <code>u32</code>s are data and which are counts, I'm going to add a type alias <code>Count</code>.</p>\n<p>Finally, this loop in the original offers a chance to use some iterator magic:</p>\n<pre><code> for _ in 0..(*count as i32) {\n sorted.push(digit);\n }\n</code></pre>\n<p>This is not just a tedious piece of boilerplate, but it may also be slow because <code>push</code> might have to reallocate the <code>Vec</code> several times. You could call <code>reserve_exact</code> beforehand, but instead let's replace the whole thing with <code>sorted.extend(std::iter::repeat(digit).take(count))</code>, which can be read almost like English: "extend <code>sorted</code> with repeated copies of <code>digit</code> up to <code>count</code> times".</p>\n<p>After making all those changes, here's what I came up with:</p>\n<pre><code>pub fn counting_sort(vec: &[u32]) -> Vec<u32> {\n type Count = u32;\n \n let mut counts: BTreeMap<_, Count> = BTreeMap::new();\n for val in vec {\n *counts.entry(*val).or_default() += 1;\n }\n\n let mut sorted: Vec<Count> = vec![];\n for (digit, count) in counts {\n sorted.extend(std::iter::repeat(digit).take(count as _));\n }\n sorted\n}\n</code></pre>\n<h2>Quicksort</h2>\n<p>Okay, I went a little overboard with critiquing counting sort, so I won't do a full rewrite of quicksort. Here's what I noticed.</p>\n<p><code>((vec.len() as f32) / 2.0).floor() as usize</code> is something you should never write. In the first place, truncating <code>vec.len()</code> to <code>f32</code> loses a lot of precision. This will not give the correct result for large slices. It doesn't really matter to the correctness of the algorithm in this case, but it's a thing to be aware of in general, and it can affect performance. Secondly, floating-point operations are usually significantly slower than comparable integer operations. For both these reasons you should always do integer math with integers. <code>usize</code> division always rounds towards zero, so the whole expression should just be <code>vec.len() / 2</code>.</p>\n<p>Also, <code>left</code> and <code>right</code> don't need explicit types; they can be inferred.</p>\n<h2>Mergesort</h2>\n<p>Largely already covered by coyotte508.</p>\n<h2>Further exercises for the reader</h2>\n<ul>\n<li><p>Implement <code>counting_sort</code> using an array instead of a <code>BTreeMap</code></p>\n</li>\n<li><p>Implement <code>counting_sort</code> with this signature:</p>\n<pre><code>fn counting_sort(impl IntoIterator<Item = u32>) -> impl Iterator<Item = u32>;\n</code></pre>\n</li>\n<li><p>Implement <code>quicksort</code> using an in-place algorithm.</p>\n</li>\n<li><p>Implement <code>heapsort</code>.</p>\n</li>\n</ul>\n<hr />\n<p>¹ Why <code>Ord</code> and not <code>PartialOrd</code>? Technically <code>PartialOrd</code> will also compile, but all textbook sorting algorithms assume that the items are comparable -- that is, each item is either greater than, less than, or equal to each other item. Values that are incomparable to other values, as <code>PartialOrd</code> allows, tend to wreak havoc in sorting algorithms.</p>\n<p>² The performance analysis is non-trivial. A B-tree is often faster than a hashtable when (1) comparing the keys is much cheaper than hashing them and (2) the keys are needed in order. Both are true here. However, caching also plays a large role and could sway the result, especially if you compare against a fast hasher such as FNV. If you look at only the asymptotic performance, <code>HashMap</code> wins (<code>O(n + k)</code> vs. <code>O((n + k)log(k))</code>), but I'm not convinced there's any value of <code>n</code> and <code>k</code> for which <code>HashMap</code> actually makes the most sense. Frankly, I also just wanted to write it with <code>BTreeMap</code> to make it more concise. If you were writing this code in a "real world" programming scenario, you'd want to profile it rather than just guessing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T16:55:18.213",
"Id": "493502",
"Score": "0",
"body": "Thank you for this extremely detailed response! I have gone and implemented most of these comments and learned a good amount in the process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:40:01.777",
"Id": "250604",
"ParentId": "250515",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T17:23:32.133",
"Id": "250515",
"Score": "6",
"Tags": [
"beginner",
"rust"
],
"Title": "Rust beginner implementing some sorts"
}
|
250515
|
<p>I am reading a book with different quizzes about coding interviews.</p>
<p>Please implement a function that increments a string based on the rules below:</p>
<ol>
<li>It should take the string of unknown length and increment the numberic ending of that string by 1.</li>
<li>If numberic ending is overflown it must be reset.</li>
<li>Don't use regular expressions</li>
</ol>
<p>Examples of correct functionality are the following:</p>
<pre><code>assertEquals("000003", increment("000002"));
assertEquals("000000", increment("999999"));
assertEquals("GL-322", increment("GL-321"));
assertEquals("GL-000", increment("GL-999"));
assertEquals("DRI000EDERS1RE", increment("DRI000EDERS0RE"));
assertEquals("DRI000EDERS0RE00000", increment("DRI000EDERS0RE99999"));
</code></pre>
<p>Here is my solution, I am sure it could be vastly more efficient / succinct:</p>
<pre><code>public class Increment {
static String padLeftZeros(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append('0');
}
sb.append(inputString);
return sb.toString();
}
static String increment(String referenceNumber) {
// Finding the last digit index in referenceNumber
int indexLastDigit = -1;
for (int i = 0; i < referenceNumber.length(); i++){
try {
Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));
indexLastDigit = i;
} catch (NumberFormatException nfe) {
}
}
// Finding the first digit index of the last digit group in referenceNumber
int indexFirstDigit = -1;
for (int i = indexLastDigit; i >= 0; i--){
try {
Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));
indexFirstDigit = i;
} catch (NumberFormatException nfe) {
break;
}
}
// Checking if numberToIncrement needs reset or not
String numberToIncrement = referenceNumber.substring(indexFirstDigit, indexLastDigit + 1);
boolean isReset = true;
for (int i = 0; i < numberToIncrement.length(); i++){
if (numberToIncrement.charAt(i) != '9') {
isReset = false;
}
}
// Incrementing or resetting number
StringBuilder incrementedNumberSB = new StringBuilder();
int incrementedNumberInt;
if (isReset) {
for (int i = 0; i < numberToIncrement.length(); i++){
incrementedNumberSB.append("0");
}
} else {
incrementedNumberInt = Integer.parseInt(numberToIncrement) + 1;
incrementedNumberSB.append(incrementedNumberInt);
}
// Creating result string according to referenceNumber structure
String incrementedNumberString = padLeftZeros(incrementedNumberSB.toString(), numberToIncrement.length());
String prefix = referenceNumber.substring(0, indexFirstDigit);
String suffix = referenceNumber.substring(indexLastDigit + 1, referenceNumber.length());
String result = "";
if (prefix.length() > 0) {
result += prefix;
}
result += incrementedNumberString;
if (suffix.length() > 0) {
result += suffix;
}
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T07:24:30.777",
"Id": "491599",
"Score": "0",
"body": "`assertEquals(\"DRI000EDERS1RE\", increment(\"DRI000EDERS0RE\"));` Why? How should the program determine the correct result here? I think we're missing an important part of the challenge here. Are all numbers in base 10 and thus all non 0-9 characters irrelevant when incrementing? `assertEquals(\"DRI000EDERS0RE00000\", increment(\"DRI000EDERS0RE99999\"));` The incremented value doesn't roll over to the `0` in `SORE`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:56:18.273",
"Id": "491622",
"Score": "0",
"body": "Just pointing out that this isn't a 'in Java' question, as the answer will be almost identical in any language with similar syntax"
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>static String padLeftZeros(String inputString, int length) {\n</code></pre>\n<p>Having no modifier specified means that it is <code>package-private</code>. Personally, I like to pretend that <code>package-private</code> does not exist, as it easily leads to "hidden" coupling between classes, and makes it harder for extending classes to actually utilize the classes. On top of that, you can circumvent the restrictions by simply being in the same package, another thing that smells.</p>\n<p>In this case, you most likely want <code>private</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>StringBuilder sb = new StringBuilder();\nint incrementedNumberInt;\n</code></pre>\n<p>Your variable names are good, with a few minor exceptions, like these. The first one should be something like <code>paddingZeros</code>, and the second one should not have that <code>Int</code> postfix.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>static String padLeftZeros(String inputString, int length) {\n</code></pre>\n<p>Consider whether a non-static utility would be better suited. But I guess in this exercise it doesn't really matter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (inputString.length() >= length) {\n return inputString;\n }\n StringBuilder sb = new StringBuilder();\n while (sb.length() < length - inputString.length()) {\n sb.append('0');\n }\n sb.append(inputString);\n\n return sb.toString();\n</code></pre>\n<p>Java 11 introduced <code>String.repeat(int)</code> which would simplify your code:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (inputString.length() >= length) {\n return inputString;\n }\n \n String paddingZeros = "0".repeat(length - inputString.length());\n \n return padding + inputString;\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Finding the last digit index in referenceNumber\n int indexLastDigit = -1;\n for (int i = 0; i < referenceNumber.length(); i++){\n try {\n Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));\n indexLastDigit = i;\n } catch (NumberFormatException nfe) {\n }\n }\n</code></pre>\n<p>A better option would be <code>Character.isDigit(int)</code>, and looping backwards through the string. You could extract that code into an extra function for better readability:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static int lastIndexOfDigit(String input) {\n for (int index = input.length - 1; index >= 0; index--) {\n if (Character.isDigit(input.codePointAt(index)) {\n return index;\n }\n }\n \n return -1;\n}\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Finding the first digit index of the last digit group in referenceNumber\n int indexFirstDigit = -1;\n for (int i = indexLastDigit; i >= 0; i--){\n try {\n Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));\n indexFirstDigit = i;\n } catch (NumberFormatException nfe) {\n break;\n }\n }\n</code></pre>\n<p>Same here, a loop with <code>Character.isDigit</code> would be better.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Checking if numberToIncrement needs reset or not\n String numberToIncrement = referenceNumber.substring(indexFirstDigit, indexLastDigit + 1);\n boolean isReset = true;\n for (int i = 0; i < numberToIncrement.length(); i++){\n if (numberToIncrement.charAt(i) != '9') {\n isReset = false;\n }\n }\n</code></pre>\n<p>This would also do well in its own function. Also, <code>isReset</code> is an odd name, it should either be <code>requiresReset</code>, <code>willReset</code>, <code>isMaximum</code> or <code>willOverflow</code>.</p>\n<p>Also also, I'm very sure there is an easier way to do this mathematically, but I can't think of that one right now.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> // Incrementing or resetting number\n StringBuilder incrementedNumberSB = new StringBuilder();\n int incrementedNumberInt;\n if (isReset) {\n for (int i = 0; i < numberToIncrement.length(); i++){\n incrementedNumberSB.append("0");\n }\n } else {\n incrementedNumberInt = Integer.parseInt(numberToIncrement) + 1;\n incrementedNumberSB.append(incrementedNumberInt);\n }\n</code></pre>\n<p>This assumes that the number will fit into an <code>int</code>. Maybe <code>BigInteger</code> would be safer thing to use here.</p>\n<p>And again, <code>String.repeat</code> would come in handy here.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>String suffix = referenceNumber.substring(indexLastDigit + 1, referenceNumber.length());\n</code></pre>\n<p>You can omit the second parameter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (prefix.length() > 0) {\n result += prefix;\n }\n result += incrementedNumberString;\n if (suffix.length() > 0) {\n result += suffix;\n }\n\n return result;\n</code></pre>\n<p>I'd really not care whether they have length or not, just concatenate the three strings. If you want to check that, I'd check it before creating a new substring from it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:17:11.830",
"Id": "250521",
"ParentId": "250517",
"Score": "5"
}
},
{
"body": "<p>Because this is an interview question, the most important part is the questions you ask. The questions show that you understand that requirements are seldom complete and know what kind of limitations affect the implementation of the algorithm. The ones that need to be asked here are:</p>\n<ol>\n<li>How long are the input strings of typical input?</li>\n<li>How long are the numeric values in the typical input?</li>\n<li>Is the algorithm supposed to work efficiently on all possible scenarios or are shortcuts allowed to make the code more maintainable?</li>\n<li>Bonus question: should the algorithm work with floating point numbers too?</li>\n</ol>\n<p>Judging by the examples in the tests I have made assumptions that the intended usage works on relatively short strings and that makes this problem much easier than it seems at first. The requirement "reset to 0 when overflow" is the key to simplifying the solution.</p>\n<ul>\n<li>Loop in reverse order starting from last digit in the string. This requires that the whole string is in memory and will not work for infinitely long input (see question 1). But seeing as you've also loaded the string to memory, it won't be any worse.</li>\n<li>Add one to the first digit you find.</li>\n<li>If it overflows to 10 you set <code>carry</code> to true and set the digit to 0.</li>\n<li>Repeat adding one to the next digit as long as <code>carry</code> is true or a character is found.</li>\n</ul>\n<p>Just like you would add one to a large number in first grade math. :)</p>\n<p>Edit: One simplification that may or may not be a smart thing to do in an interview is to start the algorithm by having <code>carry = true</code>. That way you implicitely add one to the first digit without needing special checks. But this needs to be commented clearly in the code regardless of it being production or interview code. It might be a good way of showing that you recognize structures that may not be immediately clear to the reader and know how to document them in code.</p>\n<p><strong>And most importantly, this was a trick question that tells nothing about you as a programmer.</strong> If someone asks you this in an interview, it is a sign that they don't really know how to interview programmers. I would not have been able to whip out this solution in a stressful environment of a job interview. And I've been working 25 years as a senior developer/architect... Scenarios like this never occur at work. We have enough time to evaluate ideas, discuss them with other people, rewrite if we figure a better solution. The stressed out crap we write in an interview never represents what we are capable of at actual work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:58:23.550",
"Id": "491623",
"Score": "2",
"body": "+10 for the summary comment. Any interviewer who looks at the \"what\" rather than the \"how\" that you produce is a fool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:02:23.000",
"Id": "491653",
"Score": "0",
"body": "I don't think that having a variable to store `carry` is even necessary. If `carry` is false, you just exit out of the loop. You could also implement this as recursion rather than looping: increment last character, if that results in an overflow, call the function on the string up to the last character. Recursion takes more memory since there's a function stack, but conceptually it has advantages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:44:58.003",
"Id": "491661",
"Score": "0",
"body": "@Acccumulation Unless you're in a language that converts recursion to a loop for you, recursion puts you at risk of stack overflows for long strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:51:58.917",
"Id": "491662",
"Score": "1",
"body": "I disagree with your last paragraph. It tells me enough about a person in an interview, that is, if it is not a whiteboard exercise. Given enough time, an IDE and a browser, and discussion before and afterwards, it tells me a lot about how a programmer approaches and solves problems. Combined with discussing the solution together, I think it is fine as an interview question if done right. Of course, it should not be the only thing during the interview."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:54:47.163",
"Id": "491663",
"Score": "0",
"body": "Also regarding your last paragraph, I don't see any need to insult anybody about such an out of context question \"they don't really know how to do an interview\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T22:31:23.757",
"Id": "491677",
"Score": "0",
"body": "I concur with @Bobby about your last paragraph. There's nothing \"trick\" about the question. The term \"trick question\" refers to questions that imply or outright say something false. This question is pretty easy if you understand the concept of incrementing: you start at the rightmost digit and add one, and if there's overflow you increment the next digit over. Even if the interviwee doesn't solve it completely, how far they get and how says something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T22:31:27.297",
"Id": "491678",
"Score": "0",
"body": "And of course interview questions are artificial. It's not practical to see how you work with their team. They're looking to see how you work through problems. Sure, \"I would look up the appropriate Python library\" is how I would answer much of the questions in \"the real world\", but that doesn't tell the interviewer how I would do in the role."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:46:15.337",
"Id": "492707",
"Score": "0",
"body": "@Acccumulation My point was, as I explained in the answer, that the way you behave in an interview has very little relation to how you perform in actual work because the interview scneario is such a stressful environment. That is why one should not give tasks that require any \"mental gymnastics.\" One should give a simple task and see how the applicants perform it on a computer, not whiteboard. How they format code, name variables, write comments. All the little things that we concentrate here on code review. The things that matter in production code. Not if they can figure out a trick."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:50:35.447",
"Id": "492708",
"Score": "0",
"body": "@Bobby Anyway, this is becoming a quite opinionated topic. We can continue it in chat if you like. But please familiarize yourself with the multitude of studies made on the subject before starting one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:07:59.530",
"Id": "492714",
"Score": "0",
"body": "@TorbenPutkonen Are you this demeaning and insulting on purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:54:39.967",
"Id": "492799",
"Score": "0",
"body": "@TorbenPutkonen 1. You should not ask about typical input, you should ask about maximal input. 2. You say \"One should give a simple task\". This is a simple task. Look at the other answer, a solution in 20 lines. The code in the question is much more complicated, it has more potential for errors and runs slower."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:09:15.860",
"Id": "250536",
"ParentId": "250517",
"Score": "8"
}
},
{
"body": "<h2>Extract some of the logic to methods.</h2>\n<p>As suggested by @bobby, the code in the <code>Increment#increment</code> method can be extracted in more than one method.</p>\n<p>I suggest that you extract the logic into multiples new methods; this will make the code shorter, easier to read and make the code more testable in any test framework (you will be able to test each new method with unit tests).</p>\n<ol>\n<li>To get the last index of the digit.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static int findIndexLastDigit(String referenceNumber) {\n int indexLastDigit = -1;\n for (int i = 0; i < referenceNumber.length(); i++) {\n try {\n Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));\n indexLastDigit = i;\n } catch (NumberFormatException nfe) {\n }\n }\n return indexLastDigit;\n}\n</code></pre>\n<ol start=\"2\">\n<li>To get the first index of the digit.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static int findIndexFirstDigit(String referenceNumber, int indexLastDigit) {\n int indexFirstDigit = -1;\n for (int i = indexLastDigit; i >= 0; i--) {\n try {\n Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));\n indexFirstDigit = i;\n } catch (NumberFormatException nfe) {\n break;\n }\n }\n return indexFirstDigit;\n}\n</code></pre>\n<ol start=\"3\">\n<li>To find the number to increase.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String findNumberToIncrement(String referenceNumber, int indexLastDigit, int indexFirstDigit) {\n return referenceNumber.substring(indexFirstDigit, indexLastDigit + 1);\n}\n</code></pre>\n<ol start=\"4\">\n<li>To check if we need to reset the number we increment.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static boolean needToResetNumberToIncrement(String numberToIncrement) {\n boolean isReset = true;\n for (int i = 0; i < numberToIncrement.length(); i++) {\n if (numberToIncrement.charAt(i) != '9') {\n isReset = false;\n }\n }\n return isReset;\n}\n</code></pre>\n<p>The loop can be optimized, since we know that the reset is not needed, we can break the loop early to prevent the iteration.</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < numberToIncrement.length(); i++) {\n if (numberToIncrement.charAt(i) != '9') {\n return false;\n }\n}\nreturn true;\n</code></pre>\n<ol start=\"5\">\n<li>To handle the reset of the number, if needed.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String handleNumberIncrementOrReset(String numberToIncrement) {\n boolean isReset = needToResetNumberToIncrement(numberToIncrement);\n\n // Incrementing or resetting number\n StringBuilder incrementedNumberSB = new StringBuilder();\n int incrementedNumberInt;\n if (isReset) {\n incrementedNumberSB.append("0".repeat(numberToIncrement.length())); // As suggested by @bobby, you can use the `java.lang.String.repeat`\n } else {\n incrementedNumberInt = Integer.parseInt(numberToIncrement) + 1;\n incrementedNumberSB.append(incrementedNumberInt);\n }\n return incrementedNumberSB.toString();\n}\n</code></pre>\n<ol start=\"6\">\n<li>A method that handles the replacement of the number, if needed.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String replaceNumber(String referenceNumber, int indexLastDigit, int indexFirstDigit, String numberToIncrement, String incrementedNumberSB) {\n String incrementedNumberString = padLeftZeros(incrementedNumberSB, numberToIncrement.length());\n String prefix = referenceNumber.substring(0, indexFirstDigit);\n String suffix = referenceNumber.substring(indexLastDigit + 1, referenceNumber.length());\n String result = "";\n\n if (prefix.length() > 0) {\n result += prefix;\n }\n result += incrementedNumberString;\n if (suffix.length() > 0) {\n result += suffix;\n }\n\n return result;\n}\n</code></pre>\n<p>This will make the <code>Increment#increment</code> shorter.</p>\n<pre class=\"lang-java prettyprint-override\"><code>static String increment(String referenceNumber) {\n // Finding the last digit index in referenceNumber\n int indexLastDigit = findIndexLastDigit(referenceNumber);\n\n // Finding the first digit index of the last digit group in referenceNumber\n int indexFirstDigit = findIndexFirstDigit(referenceNumber, indexLastDigit);\n\n // Checking if numberToIncrement needs reset or not\n String numberToIncrement = findNumberToIncrement(referenceNumber, indexLastDigit, indexFirstDigit);\n String incrementedNumberSB = handleNumberIncrementOrReset(numberToIncrement);\n\n // Creating result string according to referenceNumber structure\n return replaceNumber(referenceNumber, indexLastDigit, indexFirstDigit, numberToIncrement, incrementedNumberSB);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T13:29:39.317",
"Id": "250544",
"ParentId": "250517",
"Score": "3"
}
},
{
"body": "<p><strong>TL;DR</strong></p>\n<pre><code>private String increment(String input){\n char[] chars = input.toCharArray();\n\n boolean stopLoop = false;\n for(int i = chars.length - 1; i >= 0; i--){\n char character = chars[i];\n switch (character) {\n case '0', '1', '2', '3', '4', '5', '6', '7', '8' -> {\n chars[i] = (char) (character + 1);\n stopLoop = true;\n }\n case '9' -> chars[i] = '0';\n default -> {\n if(i + 1 < chars.length && chars[i + 1] == '0')\n stopLoop = true;\n }\n }\n\n if(stopLoop)\n break;\n }\n\n return new String(chars);\n}\n</code></pre>\n<p>The quizzes of the coding interviews have some goals:</p>\n<ul>\n<li>To check if the knowledge that the candidate claims is true.</li>\n<li>To filter candidates when you have too many applications.</li>\n<li>To know if you think beyond the obvious solution.</li>\n<li>To know how deep you know about a language, or a version of it.</li>\n<li>To check if you have some knowledge of data structures, algorithms\nand time / space complexity of algorigthms.</li>\n</ul>\n<p>Here the obvious solution is to work with Strings. Knowing that String in Java are immutable, you have to do all the stuff splitting and concatenating Strings. My proposal is to convert the String into a char array, work with it, and convert it back to an array.</p>\n<p>The cost in time of reading and writting into an array is constant, while making all the work with strings has a higher time cost. In an interview is not so important, but for a backend position it is.</p>\n<p>Is the char array the best thing ever? It is not, specially in this example. The good of it, is that you can use it like an integer of one byte space in memory. The bad, is because that behaviour, the editor wont tell you that you are writting 0 instead of '0'. 0 is the value of the NUL Ascii character. The Ascii value of '0' is 48. Well, this problem is designed to know if you write too error prone code.</p>\n<p>When you have the char array, you traverse it backwards. To traverse backwards is more error prone than to traverse forwards (IndexOutOfBoundExceptions). So, it is another way to check how many errors do you write without the help of your editor, or without compiling several times.</p>\n<p>Because you can use char as a value, it is perfect to use it into a switch statement. The first nine cases (from '0' to '8' character) share the same behaviour and code: Increment to next character and end the edition of the characters.</p>\n<p>The case of character '9' requires to replace this character with '0' and check the previous character in the array.</p>\n<p>The default case is the trickiest. It ignores the characters that aren't numbers if they appear before the characters that are numbers (remember, it is backwards traversing). When one number appears there are two options: the first option is one of the first nine cases, the other option is the case of a '9' converted into a '0'. So, if you find a non number character followed of a '0' the algorithm finishes.</p>\n<p>The last step is to convert the char array back into a String, what you can do easily calling one of the String constructors.</p>\n<p>You won't face this kind of problem in real life. You will use regular expresions. It is just to check you knowledge, in this case about Java. If you find a problem which solution is too complicate, try a less obvious one.</p>\n<p>I hope it helped you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T20:05:44.670",
"Id": "491667",
"Score": "1",
"body": "What will happen if you have 000091 ? Expected result is 000092."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:48:28.093",
"Id": "492741",
"Score": "0",
"body": "@Pitto: It seems to work too, thanks to `stopLoop`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:08:22.880",
"Id": "492801",
"Score": "0",
"body": "@Pitto: assertEquals(\"000092\", increment(\"000091\")) is the same case as assertEquals(\"000003\", increment(\"000002\")), it correspond to the first nine cases of the switch statement. In any case, just write all possible combinations you doubt about as assertions or test cases and check the code. It is a fast way to check the possible options."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T12:57:25.120",
"Id": "493562",
"Score": "0",
"body": "I don't have JDK 14 on my machine, can you please confirm that you pass all tests you can find in the question?\nThanks @NoMoreHelloWorld"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-29T05:21:00.100",
"Id": "494614",
"Score": "0",
"body": "@Pitto: I confirm that the code pass all the test. Anyway, if you have Java 8, you only have to change the sintaxis of the switch statement."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:25:09.953",
"Id": "250551",
"ParentId": "250517",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "250551",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T18:56:23.137",
"Id": "250517",
"Score": "7",
"Tags": [
"java",
"strings",
"interview-questions"
],
"Title": "How can I efficiently manipulate digits in a string without using RegEx in Java?"
}
|
250517
|
<p>router/article.js</p>
<pre><code>// =============================== GET / WITH PAGINATION ==============================
router.get('/?:page', async (req, res) => {
const { page } = req.params; // current Page
const { size } = req.params; // items per page
const limit = size || 5; // if size isn't specified, set size to 5
const offset = page ? (page - 1) * limit : 0; // skip previous items
const navBarIndexLimit = 4; // how many page indexes to show in navigation bar like < 1 2 3 4 >
const navBarIndexOffset = Math.floor(page / navBarIndexLimit); // offset previous indexes like < 5 6 7 8 >
const navBarIndexArray = []; // index for navigating pages in view
// fetch articles
const articles = await Article.findAndCountAll({
include: User,
raw: true,
nest: true,
limit,
offset,
});
const totalPage = Math.ceil(articles.count / limit);
// if at last page, show previous indexes
if (page >= totalPage) {
for (let i = 0; i < navBarIndexLimit; i += 1) {
const prevPage = page - i;
navBarIndexArray.push(page - i);
if (prevPage <= 0) {
break;
}
}
navBarIndexArray.sort();
}
// set index bar
else {
for (let i = 0; i < navBarIndexLimit; i += 1) {
const nextPage = i + navBarIndexOffset * navBarIndexLimit;
if (nextPage > totalPage) {
break;
}
navBarIndexArray.push(nextPage + 1);
}
}
articles.index = navBarIndexArray;
res.render('article/article_home.hbs', { articles });
});
</code></pre>
<p>article.home.hbs</p>
<pre><code><div class="ui pagination menu">
<a class="item">
<-
</a>
{{#each articles.index as |key|}}
<a class="item" href="/article/{{key}}">
{{key}}
</a>
{{/each}}
<a class="item">
->
</a>
</div>
</code></pre>
<p>I've managed to paginate my articles and while it is working, I have a strong feeling that I made the pagination navigation bar part extremely complicated and I'm sure there would be a better way.</p>
<p>Using Express, Sequelize and Handlebars</p>
|
[] |
[
{
"body": "<p><strong>Error handling</strong> You <code>await</code> inside an <code>async</code> function, but without a <code>try</code>/<code>catch</code> surrounding it. So, if <code>Article.findAndCountAll</code> rejects, you'll get an unhandled rejection (which is deprecated in Node) and no response will be sent.</p>\n<p><strong>Default destructuring and variable names</strong></p>\n<pre><code>const { page } = req.params; // current Page\nconst { size } = req.params; // items per page\nconst limit = size || 5; \n</code></pre>\n<p>simplifies to</p>\n<pre><code>const { page, size = 5 } = req.params;\n</code></pre>\n<p>and using the <code>size</code> variable. Though, if possible, change the param and variable name to <code>itemsPerPage</code>; it's much more representative of what the variable contains than <code>size</code>. <code>currentPage</code> would also be a bit more precise. Similarly, <code>totalPage</code>, since it contains a number, would sound better as <code>totalPages</code>.</p>\n<p><strong>Sorting bug</strong> You have:</p>\n<pre><code>navBarIndexArray.sort();\n</code></pre>\n<p>This will sort <em>lexiographically</em>, not numerically. For example, it could produce an output of</p>\n<pre><code>[1, 11, 2]\n</code></pre>\n<p>Compare numerically instead, eg <code>.sort((a, b) => a - b)</code>.</p>\n<p><strong>Pagination</strong> Or, even better, just insert the indicies in order to begin with.</p>\n<p>Your current results don't seem quite natural. When near the end, I'd expect the nav to be full of all nearby pages: eg, when on page 5 of 6, I'd expect <code>3 4 5 6</code>, not just <code>4 5 6</code>. Implementing this will require a bit of extra logic, though.</p>\n<p>Rather than two loops which do something very similar, identify the last page to display in the nav, then subtract by <code>navBarIndexLimit</code> to identify the first page to display in the nav, then iterate over it. See comments in snippet below:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const navBarIndexLimit = 4;\n// currentToLastPageOffset: Amount to add to current page to get last page\n// (eg: current page 4 results in last page 6, first page 3)\nconst currentToLastPageOffset = navBarIndexLimit - 2;\nconst makeNavbarIndexArr = (currentPage, totalPages) => {\n const lastPage = Math.min(\n totalPages,\n currentPage <= 1\n ? navBarIndexLimit - 1 // If on 0th or 1st page, set last page to 3\n : currentPage + currentToLastPageOffset\n );\n const firstPage = Math.max(lastPage - (navBarIndexLimit- 1), 0);\n // I prefer to create numeric arrays all at once with Array.from:\n return Array.from(\n { length: lastPage - firstPage + 1 },\n (_, i) => firstPage + i\n );\n // But you could also use a for loop and push if you find it easier to read\n};\nconsole.log(makeNavbarIndexArr(0, 9));\nconsole.log(makeNavbarIndexArr(1, 9));\nconsole.log(makeNavbarIndexArr(5, 9));\nconsole.log(makeNavbarIndexArr(8, 9));\nconsole.log(makeNavbarIndexArr(9, 9));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper {\n max-height: 100% !important;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Note that the above takes zero-indexed parameters and returns an array that's zero-indexed, though it's trivial to tweak it to be one-indexed instead if needed.</p>\n<p>It's a reasonable amount of code, but the logic that needs to be implemented is somewhat complicated, so there's no avoiding at least some of it. While it could be condensed somewhat (for example, by removing the <code>currentToLastPageOffset</code> variable), that would make it harder to understand.</p>\n<p>I highly recommend keeping the function in the snippet above - don't inline it into your <code>page</code> route, so as to clearly separate the calculation logic from the main route logic.</p>\n<pre><code>router.get('/?:page', (req, res) => {\n const { currentPage, itemsPerPage = 5 } = req.params;\n const offset = currentPage ? (currentPage - 1) * itemsPerPage : 0; // skip previous items\n Article.findAndCountAll({\n include: User,\n raw: true,\n nest: true,\n limit: itemsPerPage,\n offset,\n })\n .then((articles) => {\n const totalPages = Math.ceil(articles.count / itemsPerPage);\n articles.index = makeNavbarIndexArr(currentPage, totalPages);\n res.render('article/article_home.hbs', { articles });\n })\n .catch((error) => {\n // Handle errors, send error response\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:53:19.717",
"Id": "491675",
"Score": "0",
"body": "how about adding \n if (articles.index.includes(0)) {\n articles.index = articles.index.map((i) => i + 1);\n }\nto remove zero index?\nand thanks for your great insight!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T22:35:35.427",
"Id": "491680",
"Score": "0",
"body": "If you want it to be 1-indexed, you'd want to map the array unconditionally, no matter whether it includes 0 or not"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T21:04:31.183",
"Id": "250525",
"ParentId": "250519",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250525",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T19:07:48.513",
"Id": "250519",
"Score": "6",
"Tags": [
"javascript",
"node.js",
"express.js"
],
"Title": "Any better pagination logic?"
}
|
250519
|
<p>My project has thee models <code>Cart</code>, <code>Order</code> and <code>Product</code></p>
<p><code>Cart</code> and <code>Order</code> have the same fields for pivot model</p>
<pre><code> class Cart extends Model {
...
public function products() {
return $this->belongsToMany(Product::class)->withPivot([
'id',
'count',
'price',
'discount',
'tax',
'created_at',
'updated_at'
]);
}
}
class Order extends Model {
...
public function products() {
return $this->belongsToMany(Product::class)->withPivot([
'id',
'count',
'price',
'discount',
'tax',
'created_at',
'updated_at'
]);
}
}
</code></pre>
<p>How better create <code>Order</code> with pivot from <code>Cart</code> with pivot?</p>
<p>Now I have next code</p>
<pre><code> $cart = Cart::getCartFromSession();
$order = Order::create($request->all());
foreach ($cart->products as $product) {
$order->products()->attach($product, [
'count' => $product->pivot->count,
'price' => $product->pivot->price,
'discount' => $product->pivot->discount,
'tax' => $product->pivot->tax,
]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T01:11:04.060",
"Id": "502934",
"Score": "1",
"body": "Are `Cart` and `Pivot` related at all? e.g. would it make sense for one to be a sub-class of the other? or do they have completely separate implementations other than the `products` relation? Please add the rest of the models, since [65535 characters is allowed on CR posts](https://codereview.meta.stackexchange.com/a/7163/120114)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T20:27:44.513",
"Id": "250524",
"Score": "3",
"Tags": [
"beginner",
"php",
"laravel"
],
"Title": "Add pivot data from the same pivot model"
}
|
250524
|
<p>I want to recursively use a Vue component for each item in a multidimensional array, which is a list of topics. For example, Topic 1 can have subtopics 1.1, 1.1.1 and 1.1.2, but topic 2 might have no subtopics at all. (My working code is presented at the bottom)</p>
<p>My Array in Vue's app <code>data</code> is something like:</p>
<pre><code>[
['Topic 1', [
'Topic 1.1', [
['Topic 1.1.1', []],
['Topic 1.1.2', []]
]
],
['Topic 2', []],
['Topic 3', [
['Topic 3.1', []],
['Topic 3.2', []],
['Topic 3.3', []],
]
]
]
</code></pre>
<p>Supposing my component is just a <code>details</code> tag, this is my expected HTML output (borders were added just for clarity):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>details > details {
margin-left: 2em;
border: 1px solid black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><main id="root">
<details open><summary>Topic 1</summary>
<details open><summary>Topic 1.1</summary>
<details open><summary>Topic 1.1.1</summary>
</details>
<details open><summary>Topic 1.1.2</summary>
</details>
</details>
</details>
<details open><summary>Topic 2</summary>
</details>
<details open><summary>Topic 3</summary>
<details open><summary>Topic 3.1</summary>
</details>
<details open><summary>Topic 3.2</summary>
</details>
<details open><summary>Topic 3.3</summary>
</details>
</details>
etc.</code></pre>
</div>
</div>
</p>
<p>I can't anticipate all <code>v-for</code> loops I'll use, because I don't know the depth of each topic (i.e., I don't know how many subtopics there are, it depends on each topic and there can be dozens or none at all).</p>
<p>My solution was to use a <code>v-if</code> to check if there are subarrays inside the current array; if there are, a component is created for the subarrays too (and the component's template includes in the end this <code>div</code> with a <code>v-if</code>, so it works recursively).</p>
<p>This works, but looks clunky. <em>So my question is: what is the best way to run a while-loop with Vue (for the cases where I don't know how many for-loops I need to run)?</em> Or is my solution already the best way to approach this?</p>
<p>(I first thought of creating a <code>method</code>, and calling this method in the end to check if there are subarrays and then create components for them basically via JavaScript, but this seems worse than using <code>v-if</code> and adding a <code>v-for</code> for adding components to the subarray items)</p>
<hr />
<p>Here's my working 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>Vue.component('details-component', {
template: `<details><summary> {{ arritem[0] }} </summary><div v-if="arritem[1].length"> <div v-for="subitem in arritem[1]">
<details-component :arritem="subitem"></details-component> </div></details>`,
props: {
arritem: {
type: Array,
required: true
}
}
});
const app = new Vue({
el: "#root",
data: {
arr: [
['Topic 1', [
['Topic 1.1', [
['Topic 1.1.1', []],
['Topic 1.1.2', []]
]
]
]],
['Topic 2', []],
['Topic 3', [
['Topic 3.1', []],
['Topic 3.2', []],
['Topic 3.3', []],
]]
]
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>details details {
margin-left: 2em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<main id="root">
<div v-for="item in arr">
<details-component :arritem="item"></details-component>
</div>
</main></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>There is no <code>v-while</code>, no. You can however use <code>v-for</code> over a computed property (which you can compute using <code>while</code> if you so wish).</p>\n<p>Although I don't see a reason to use any while-loop. What you have is a data structure with topics and subtopics of any arbitrary length. Using a recursive component for this, which you have done here, is a good choice.</p>\n<p>About the only thing that I would change is to, instead of using <code>arritem[0]</code> and <code>arritem[1]</code>, using an object with properties <code>name</code> and <code>children</code>. This can possibly also help you determine if a component has any children or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T23:33:49.853",
"Id": "491577",
"Score": "1",
"body": "Thank you, that's great advice! And that's a good idea too in regard to the computed property, it's better than me simply using a method for cases like this, that I want to cache the result"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T23:06:45.637",
"Id": "250531",
"ParentId": "250527",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250531",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T22:35:47.437",
"Id": "250527",
"Score": "5",
"Tags": [
"beginner",
"vue.js"
],
"Title": "Best way to do unknown number of nested v-for loops, or how to do while loops in VueJs (is there a \"v-while\"?)"
}
|
250527
|
<p>Title should be self-explenatory. This is a simple URL parser I wrote in C. The function takes a URL from the user and produces a struct that contains the information that can be used to request the resource at the URL over http(s).</p>
<pre><code>enum url_protocol {
PROTOCOL_HTTP,
PROTOCOL_HTTPS
};
struct url {
/* Protocol to use */
enum url_protocol protocol;
/* Credentials */
char *username;
char *password;
/* Host and service */
char *host;
char *service;
/* Path to request */
char *path;
};
void
free_url(struct url *url);
int
parse_url(char *start, struct url *url)
{
char *end, *delim;
memset(url, 0, sizeof(*url));
/* Find the end of the scheme */
end = strchr(start, ':');
if (!end)
goto err;
/* Find protocol from scheme */
if (!strncmp(start, "http", end - start))
url->protocol = PROTOCOL_HTTP;
else if (!strncmp(start, "https", end - start))
url->protocol = PROTOCOL_HTTPS;
else
goto err;
/* URLs must begin with // */
if (*++end != '/' || *++end != '/')
goto err;
/* Parse credentials */
start = ++end;
end = strchr(start, '@');
if (end) {
delim = strchr(start, ':');
if (delim && delim < end) { /* Username and password */
if (!(delim - start))
goto err;
url->username = strndup(start, delim - start);
++delim;
if (!(end - delim))
goto err;
url->password = strndup(delim, end - delim);
} else { /* Only username */
if (!(end - start))
goto err;
url->username = strndup(start, end - start);
}
start = ++end;
}
/* Host till / or end of string */
end = strchrnul(start, '/');
/* Skip IPv6 literals before : search */
if (*start == '[' && (delim = strchr(start, ']')))
delim = strchr(delim, ':'); /* Found IPv6 literal */
else
delim = strchr(start, ':'); /* Normal search */
if (delim && delim < end) { /* Host and service */
if (!(delim - start))
goto err;
url->host = strndup(start, delim - start);
++delim;
if (!(end - delim))
goto err;
url->service = strndup(delim, end - delim);
} else { /* Only host */
if (!(end - start))
goto err;
url->host = strndup(start, end - start);;
}
/* Default path is a single / */
url->path = *end ? strdup(end) : strdup("/");
return 0;
err:
free_url(url);
return -1;
}
void
free_url(struct url *url)
{
/* Assume free ignores NULL */
free(url->username);
free(url->password);
free(url->host);
free(url->service);
free(url->path);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:15:57.453",
"Id": "491614",
"Score": "0",
"body": "does it meant to be [rfc 1738](https://tools.ietf.org/html/rfc1738) compatible?"
}
] |
[
{
"body": "<p>Just some minor things in your code. Is a bit strange that you have a function call free_url and you dont have one called init_url where you alloc and do the memset. My suggestion is that you have another function for that and you move your memset of the function</p>\n<pre><code>int\nparse_url(char *start, struct url *url)\n{\n char *end, *delim;\n\n memset(url, 0, sizeof(*url)); <- Move this to init_url\n</code></pre>\n<p>And your function</p>\n<pre><code> struct url *init_url()\n {\n struct url *u = (struct url*)malloc(sizeof(struct url));\n if (u != NULL)\n memset(u, 0, sizeof(struct url));\n return u\n } \n</code></pre>\n<p>My recommendation is that you should have a good suite of unit tests for parsing things for the user, so you will make your code more robust and with less errors.</p>\n<p>Hope it helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:43:45.240",
"Id": "491660",
"Score": "0",
"body": "There is no init_url on purpose, the struct how its used now is allocated on the callers stack instead of on the heap. The only job of the free_url is to free the strings."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T09:51:38.480",
"Id": "250541",
"ParentId": "250528",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T22:57:03.157",
"Id": "250528",
"Score": "4",
"Tags": [
"c",
"parsing",
"http",
"url",
"https"
],
"Title": "URL parser in C"
}
|
250528
|
<p>This is a riot analysis app. Collect data using the riot API and shows the user various data. Nothing too in depth.</p>
<p><strong>GUI file</strong> - This file is the GUI file for the program. I have the class that make the rest of the frames of the program. After clicking the button to search for a summoner, it will collect data from another class in game and return a list of 5 data's with each being a different type(kill, death, assists, vision, wins). I have two global variable that I don't want to use in DataCollected class, I can't seem to find a way not to use them.</p>
<pre><code>import tkinter as tk
from tkinter import font as tkfont
from getId import id_collected
from games import Game
from wins import is_player_good
class RiotApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, MenuPage, KillPage, DeathPage, CsPage, HonestPage):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
c = DataCollected()
self.controller = controller
self.label = tk.Label(self, text="Enter summoner name:", width = 20, font = ("bold", 20))
self.label.place(x=90,y=53)
self.entry = tk.Entry(self)
self.entry.place(x=190,y=130)
self.button = tk.Button(self, text="Search",width = 20, bg = 'brown', fg = 'white',
command=lambda: data_collected(self,controller))
self.button.place(x=180,y=200)
def data_collected(self,controller):
name = self.entry.get()
Key = '****************************************'
a = id_collected(name, Key)
if a != 'NO':
controller.show_frame("MenuPage")
c.collect_data(name, Key)
else:
controller.show_frame('StartPage')
class DataCollected():
def collect_data(self, name, Key):
num_games = 20
game = Game()
accId = id_collected(name, Key)
game_list = game.find_game_ids(accId, Key, num_games)
global stat_list
stat_list = game.game_data(game_list, Key, name, num_games)
global honest
honest = is_player_good(stat_list[5])
class MenuPage(tk.Frame,DataCollected):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Main Menu", font=controller.title_font)
label.place(x=180,y=50)
button = tk.Button(self, text="Kill Average",width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("KillPage")).place(x=180,y=100)
button = tk.Button(self, text="Death Average",width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("DeathPage")).place(x=180,y=150)
button = tk.Button(self, text="Cs Average",width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("CsPage")).place(x=180,y=200)
button = tk.Button(self, text="Honest Truth",width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("HonestPage")).place(x=180,y=250)
button = tk.Button(self, text="Back",width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("StartPage")).place(x=180,y=300)
class KillPage(tk.Frame, DataCollected):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = tk.Label(self, text = 'Kills Average', width=20,font=("bold", 20))
self.label.place(x=90, y=100)
self.label1 = tk.Label(self, text = ' ', width=20,font=("bold", 20))
self.label1.place(x=90, y=150)
self.label1.after(1000, self.refresh_label)
self.button = tk.Button(self, text = "Back", width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("MenuPage")).place(x=180,y=300)
def refresh_label(self):
self.label1.configure(text = stat_list[1])
self.label1.after(1000,self.refresh_label)
class DeathPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = tk.Label(self, text = 'Deaths Average', width=20,font=("bold", 20))
self.label.place(x=90, y=100)
self.label2 = tk.Label(self, text="", width=20,font=("bold", 20))
self.label2.place(x=90, y=150)
self.label2.after(1000, self.refresh_label)
self.button = tk.Button(self, text="Back", width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("MenuPage")).place(x=180,y=300)
def refresh_label(self):
self.label2.configure(text = stat_list[0])
self.label2.after(1000,self.refresh_label)
class CsPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = tk.Label(self, text = 'Cs Average', width=20,font=("bold", 20))
self.label.place(x=90, y=100)
self.label3 = tk.Label(self, text="", width=20,font=("bold", 20))
self.label3.place(x=90,y=150)
self.label3.after(1000, self.refresh_label)
self.button = tk.Button(self, text="Back", width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("MenuPage")).place(x=180,y=300)
def refresh_label(self):
self.label3.configure(text = stat_list[4])
self.label3.after(1000,self.refresh_label)
class HonestPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.label = tk.Label(self, text = 'Honest Truth', width=20,font=("bold", 20))
self.label.place(x=90, y=100)
self.label4 = tk.Label(self, text = " ", width=20,font=("bold", 20))
self.label4.place(x=90,y=150)
self.label4.after(1000, self.refresh_label())
self.button = tk.Button(self, text = "Back", width = 20, bg = 'brown', fg = 'white',
command=lambda: controller.show_frame("MenuPage")).place(x=180,y=300)
def refresh_label(self):
self.label4.configure(text = honest)
self.label4.after(1000,self.refresh_label)
if __name__ == "__main__":
stat_list = [1,1,1,1,1,1,1]
honest = ' '
root = RiotApp()
root.geometry("500x500")
root.mainloop()
</code></pre>
<p><strong>Game file</strong> - This file start by collecting game ids and using the game ids to collect the stats of said summoner in each of there 20 games. Then returns it to gui file.</p>
<pre><code>import requests
class Game:
def find_game_ids(self, accId, key, num_games):
i = 0
GAMEID = []
num_games = 20
url_match_list = ('https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/' + (accId) + '?queue=420&endIndex=20&api_key=' + (key))
response2 = requests.get(url_match_list)
# Adding 20 games into the list
while num_games > 0:
GAMEID.append('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(response2.json()['matches'][i]['gameId']) + '?api_key=' + (key))
i = i + 1
num_games = num_games - 1
return GAMEID
def game_data(self, game_list, key, sumName, num_games):
wins = []
deaths = []
deaths = []
kills = []
assists = []
visions = []
csTotal = []
# Finding the data of said summoner in each game id
for urls in game_list:
response = requests.get(urls)
resp_json = response.json()
Loop = 0
index = 0
while Loop <= 10:
if resp_json['participantIdentities'][index]['player']['summonerName'] != sumName:
Loop = Loop+1
index = index+1
elif resp_json['participantIdentities'][index]['player']['summonerName'] == sumName:
deaths.append(resp_json['participants'][index]['stats']['deaths'])
kills.append(resp_json['participants'][index]['stats']['kills'])
assists.append(resp_json['participants'][index]['stats']['assists'])
visions.append(resp_json['participants'][index]['stats']['visionScore'])
csTotal.append(resp_json['participants'][index]['stats']['totalMinionsKilled'])
wins.append(resp_json['participants'][index]['stats']['win'])
break
# Finding avg of each stat
deaths = sum(deaths)/num_games
kills = sum(kills)/num_games
assists = sum(assists)/num_games
visions = sum(visions)/num_games
csTotal = sum(csTotal)/num_games
wins = sum(wins)/num_games
stat_list = []
stat_list.append(deaths) #0
stat_list.append(kills) #1
stat_list.append(assists) #2
stat_list.append(visions) #3
stat_list.append(csTotal) #4
stat_list.append(wins) #5
return stat_list
</code></pre>
<p><strong>Get id file</strong> - This file collect the summoner id for the Game class in game file.</p>
<pre><code>import requests
def id_collected(sumName, key):
# COLLECTING DATA TO BE INSERTING FOR MATCHLIST DATABASE
url = ('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+(sumName)+'?api_key='+
(key))
response = requests.get(url)
if response.status_code == 200:
accId = (response.json()['accountId'])
return accId
else:
accId = 'NO'
return accId
</code></pre>
<p><strong>wins file</strong> - This file will use the <code>stat_list[5]</code> to determine whether the player has been good in past 20 games and will return a phrase.</p>
<pre><code>import random
def is_player_good(winlist):
if winlist < 0.33:
message = ['DIS MANE STINKS', 'run while you can', 'I repeat, YOU ARE NOT WINNING THIS', 'I predict a fat L', 'Have fun trying to carry this person', 'He is a walking trash can', 'He needs to find a new game', 'BAD LUCK!!!']
return (random.choice(message))
elif winlist > 0.33 and winlist <= 0.5:
message = ['Losing a bit', 'Not very good', 'He needs lots of help', 'Your back might hurt a little', 'Does not win much']
return (random.choice(message))
elif winlist > 0.5 and winlist <= 0.65:
message = ['He is ight', 'He can win a lil', 'You guys have a decent chance to win', 'Serviceable', 'Should be a dub']
return (random.choice(message))
elif winlist > 0.65:
message = ['DUB!', 'You getting carried', 'His back gonna hurt a bit', 'winner winner chicken dinner', 'Dude wins TOO MUCH', 'You aint even gotta try', 'GODLIKE']
return (random.choice(message))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T09:28:45.253",
"Id": "491613",
"Score": "3",
"body": "Please fix your title so that it states what your code does, also [edit] your question and explain the purpose of your code properly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T10:51:30.193",
"Id": "491621",
"Score": "4",
"body": "Where are those globals mentioned in the topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:35:14.200",
"Id": "491645",
"Score": "0",
"body": "they are in DataCollected class"
}
] |
[
{
"body": "<h2>Local variables</h2>\n<p>Since <code>F</code> is a local variable - even though it's technically a reference to a class, and classes are capitalized - <code>F</code> should be lower-case. Also, it deserves to have a name that isn't one letter. <code>Key</code> should also be lower-case.</p>\n<h2>Lambdas</h2>\n<p>This:</p>\n<pre><code>command=lambda: data_collected(self,controller))\n</code></pre>\n<p>does not deserve to be a lambda. Since you're also storing <code>controller</code> on <code>self</code>, it's better to simply make a method on the class for this, and pass a bound reference to that method for <code>command</code>.</p>\n<h2>Position-sensitive lists</h2>\n<pre><code>stat_list[5]\n</code></pre>\n<p>is a code smell. My guess is that this is a list of statistics, where each position in the list is a different kind of statistic. This should be converted to a class, or at the least, a named tuple.</p>\n<h2>In-place addition</h2>\n<pre><code>i = i + 1\n</code></pre>\n<p>should be</p>\n<pre><code>i += 1\n</code></pre>\n<h2>Range testing</h2>\n<pre><code>winlist > 0.33 and winlist <= 0.5\n</code></pre>\n<p>should be</p>\n<pre><code>0.33 < winlist <= 0.5\n</code></pre>\n<h2>Parens</h2>\n<p>This:</p>\n<pre><code>return (random.choice(message))\n</code></pre>\n<p>does not need outer parens and should remove them.</p>\n<h2>Typo?</h2>\n<p>In <code>He is ight</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T21:43:46.777",
"Id": "492843",
"Score": "0",
"body": "Thank you for the tips. You have any suggestions for the global variables in DataCollected class? I heard using global variables are not good. The problem is that frames are already made so I can't seem to collect the data and put it into the labels for the frames."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T02:56:36.047",
"Id": "492866",
"Score": "0",
"body": "If I have this right, `HonestPage.refresh_label` relies on being able to read `honest`, which you've made a global in `DataCollected.collect_data`. This seems like the former is the UI and the latter is the logic or data layer. The place where these fail to be connected is `StartPage.__init__`, where `DataCollected` is initialized but then no references are made to it. This needs to change or move so that there are references between the data collector and the user interface."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T19:00:07.367",
"Id": "250606",
"ParentId": "250533",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250606",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T01:57:47.137",
"Id": "250533",
"Score": "3",
"Tags": [
"python",
"api",
"tkinter"
],
"Title": "Riot Analysis Program"
}
|
250533
|
<p>I will start by saying I have gotten this to work, and the question is about how improve the script to make it better/faster.</p>
<p>I need to compare a series of files to each other. Let's say I have the below files:</p>
<pre><code>filename0 filename1 filename2
</code></pre>
<p>What I have done is:</p>
<pre><code>Z=0 # Beginning number
Y=2 # Final number
X=$Z # Initial file number
((W=Y+1)) # Number for ranges
while [[ $Z -lt $W ]]
do
while [[ $X -lt $W ]]
do
obabel filename$Z.xyz -oconfabreport -xf filename$X.xyz -xr 0.2 > Results.$Z.$X
((X=X+1))
done
((Z=Z+1))
((X=Z))
done
</code></pre>
<p>It compares files like this:</p>
<pre><code>filename0 filename0
filename0 filename1
filename0 filename2
filename1 filename1
filename1 filename2
filename2 filename2
</code></pre>
<p>I am using openbabel's <a href="https://open-babel.readthedocs.io/en/latest/3DStructureGen/multipleconformers.html#confab" rel="nofollow noreferrer">confabreport</a> tool to find RMSD of structures. Is there a better way of doing this in bash scripting? Such as skipping a self comparison or ones that have already been compared? Or just a faster way of achieving the same thing? Please let me know if I need to provide any additional information, or if this question would be better somewhere else.</p>
|
[] |
[
{
"body": "<p>Welcome to Code Review!</p>\n<h2>Shellcheck</h2>\n<p>Use the amazing <a href=\"https://www.shellcheck.net/\" rel=\"noreferrer\">shellcheck utility</a> to verify for common practices when writing bash/shell scripts. It reports missing shebang.</p>\n<h2>Loop using seq</h2>\n<p>Since you know the lower and upper bounds, and those are pure integers, use the <code>seq</code> command to iterate through them. You won't need to do custom increments and variable swaps.</p>\n<h2>Inner loop</h2>\n<p>Begin your inner loop with a value starting from current outer loop value + 1.</p>\n<h2>Variable</h2>\n<p>Using more descriptive variable names helps in understanding your code.</p>\n<h2>Parallelization</h2>\n<p>To achieve faster results, you can maybe use <code>parallel</code> to do the diff comparison for different files. If the set of files are small, you can also run the <code>obabel</code> tool in background, or disown the command from script entirely (depending on your requirements).</p>\n<hr />\n<pre><code>#!/bin/bash\n\nLOWER_BOUND=0\nUPPER_BOUND=2\n\nfor i in $(seq "$LOWER_BOUND" "$UPPER_BOUND")\ndo\n ((INNER_START=i+1))\n for j in $(seq "$INNER_START" "$UPPER_BOUND")\n do\n obabel "filename${i}.xyz" -oconfabreport -xf "filename${j}.xyz" -xr 0.2 > "Results.${i}.${j}"\n done\ndone\n</code></pre>\n<p>I'll leave parallelization to your own implementation. You can refer <a href=\"https://youtu.be/P40akGWJ_gY?list=PL284C9FF2488BC6D1\" rel=\"noreferrer\">this excellent demonstration</a> of parallel command.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T03:29:36.080",
"Id": "491591",
"Score": "0",
"body": "Thanks for the welcome! And thanks for the thorough response as well!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T03:23:12.710",
"Id": "250535",
"ParentId": "250534",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T02:36:37.250",
"Id": "250534",
"Score": "8",
"Tags": [
"bash"
],
"Title": "Compare all files to each other"
}
|
250534
|
<p>My previous implementation: <a href="https://codereview.stackexchange.com/questions/250499/my-queue-implementation-in-c">My queue implementation (in C)</a></p>
<p>I rewrote the queue following @vnp's suggestions. Here is the second version of it:
Any suggestions or tips are appreciated :)
(even tips about spacing/naming code)</p>
<p>(The client must malloc() the data needed to be inserted into the queue, and must provide dtor() while destroying the queue)</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
/* malloc(), EXIT_SUCCESS */
#include <stdio.h>
/* fprintf(), printf() */
#include <stddef.h>
/* size_t */
#include <assert.h>
/* assert() */
struct Queue_node {
struct Queue_node *next;
void *data;
};
struct Queue {
struct Queue_node *front;
struct Queue_node *back;
size_t size;
};
struct Queue* create_queue(void) {
struct Queue *created_queue = malloc(sizeof(*created_queue));
if (created_queue == NULL) { // if malloc() failed
return NULL;
}
created_queue->front = NULL;
created_queue->back = NULL;
created_queue->size = 0; // an empty queue
return created_queue;
}
struct Queue* destroy_queue(struct Queue *input_queue, void (*data_dtor)(void*)) { // (pointer arg) to force l-value
while (input_queue->front != NULL) {
struct Queue_node *deleted_node = input_queue->front;
input_queue->front = input_queue->front->next;
if (data_dtor != NULL) {
data_dtor(deleted_node->data);
}
free(deleted_node);
}
free(input_queue);
}
void queue_push(struct Queue *input_queue, void *input_data) {
struct Queue_node *input_node = malloc(sizeof(*input_node));
if (input_node == NULL) {
fprintf(stderr, "malloc() failed in queue_push()\n");
}
input_node->next = NULL;
input_node->data = input_data;
if (input_queue->front == NULL) { // first insert
assert(input_queue->back == NULL);
assert(input_queue->size == 0);
input_queue->front = input_node;
}
else {
assert(input_queue->back != NULL);
assert(input_queue->size > 0);
input_queue->back->next = input_node;
}
input_queue->back = input_node;
++input_queue->size;
}
void* queue_pop(struct Queue *input_queue) {
if (input_queue->front == NULL) {
assert(input_queue->back == NULL);
assert(input_queue->size == 0);
return NULL;
}
assert(input_queue->front != NULL);
assert(input_queue->back != NULL);
assert(input_queue->size > 0);
--input_queue->size;
struct Queue_node *deleted_node = input_queue->front;
input_queue->front = input_queue->front->next;
void *return_data = deleted_node->data;
free(deleted_node);
return return_data;
}
/*---- dtor written by client -----*/
void dtor(void *data) {
printf("DTOR: %i destroyed\n", *((int*)data));
free(data);
}
/*---------------------------------*/
int main() {
struct Queue *my_queue = create_queue();
if (my_queue == NULL) {
fprintf(stderr, "malloc() failed in create_queue()\n");
}
// ^ creates queue
for (int i = 0; i < 10; ++i) {
int *my_node = malloc(sizeof(int));
*my_node = i;
queue_push(my_queue, my_node);
}
// ^ appends 10 nodes
for (int i = 0; i < 8; ++i) {
int *my_data = queue_pop(my_queue);
printf("POP: %i popped\n", *my_data);
free(my_data);
}
// ^ pops and displays 8 nodes
destroy_queue(my_queue, dtor);
// ^ destroys the queue
return EXIT_SUCCESS;
}
</code></pre>
<p>It gives the output:</p>
<pre><code>POP: 0 popped
POP: 1 popped
POP: 2 popped
POP: 3 popped
POP: 4 popped
POP: 5 popped
POP: 6 popped
POP: 7 popped
DTOR: 8 destroyed
DTOR: 9 destroyed
</code></pre>
<p>Any suggestions or tips are appreciated :)</p>
<p>(even tips about spacing/naming code)</p>
<p>Edit:
There is a mistake in the code. Return type of destroy_queue must be void and not struct Queue.
Also in the queue_pop function, we need to set back to NULL when front is NULL. Otherwise trying to pop an empty queue causes assert.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:40:06.173",
"Id": "491641",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:35:55.890",
"Id": "491656",
"Score": "0",
"body": "The edit was necessary. It added a comment and fixed the return type of a function. It did not otherwise change the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:23:13.197",
"Id": "491657",
"Score": "2",
"body": "I know that you might not agree with it but I rolled back your last edit. In addition to the meta that Mast referenced, please see the section _What should I not do?_ on [The Help Center page: _What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information. Protip: you can post a new version of the code and likely earn more reputation that way..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:40:48.810",
"Id": "491659",
"Score": "0",
"body": "Ok. I added a sentence at the end instead of editing the code. My bad, thanks."
}
] |
[
{
"body": "<p>One thing that I would do different is create a queue_alloc_item so you can decide to use malloc or another memory manager in the future.</p>\n<p>You have:</p>\n<pre><code>int *my_node = malloc(sizeof(int));\n</code></pre>\n<p>for ints which always uses malloc. When there are clients using this already and you find a better way to replace the memory manager for small objects you can't change this anymore</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T07:23:34.450",
"Id": "491598",
"Score": "0",
"body": "Thanks a lot for replying! I did not understand what you said about queue_alloc_item, can you give a small example? Do you mean queue_alloc_item is a function which allocates *data (to be passed into the queue)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T09:01:22.213",
"Id": "491609",
"Score": "1",
"body": "edited changes in"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T11:19:04.883",
"Id": "491625",
"Score": "0",
"body": "Do you mean have something like this:\n`int *my_node = queue_alloc_item(value_of_node);\nqueue_push(my_queue, my_node);`\nwhere `queue_alloc_item()` is written by the person who wants to use the queue?\n\nIf so, thanks, noted. :) do you have any other tips? ^_^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:12:15.717",
"Id": "491644",
"Score": "2",
"body": "-1 The queue implementation leaves the memory management of data associated with nodes up to users of the queue while hiding the internal memory management for the queue. In this model, there is no added value to queue_alloc_item unless users of the queue would want to participate in the queue's memory manager."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T06:39:53.070",
"Id": "250539",
"ParentId": "250537",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T05:44:31.933",
"Id": "250537",
"Score": "7",
"Tags": [
"c",
"queue"
],
"Title": "My queue implementation (in C) [V.2]"
}
|
250537
|
<p>I wrote a small sitemap-checker.aspx, the goal of this code is to find the pages, that respond with the codes other than 200. I've only put the C# part here for the review:</p>
<pre><code> void Start_Click(object sender, EventArgs e)
{
CheckUrls(UrlTextBox.Text);
}
private void CheckUrls(string url)
{
try
{
var xmlDoc = LoadXml(url);
var urlNodes = xmlDoc.GetElementsByTagName("url");
var numberOfNodes = urlNodes.Count;
var index = 0;
Log("### Total nodes: " + numberOfNodes+ "<br>");
Log("Here is the list of URLs, with the status code other than 200: <br>");
foreach (XmlNode urlNode in urlNodes)
{
CheckUrlNode(urlNode, xmlDoc);
index++;
if(index % 10 == 0)
{
Log("<span style='color:red'>" + index + " nodes of " + numberOfNodes + " are finished, please wait...</span>");
}
};
Log("### Sitemap check finished. Please analyze the reported urls<br><br>");
}
catch (Exception e)
{
Log("Some problems were encountered while checking the sitemap<br>");
Log(e.Message + "<br>");
Log(e.StackTrace + "<br>");
}
}
private XmlDocument LoadXml(string url)
{
var m_strFilePath = url;
string xmlStr;
using (var wc = new WebClient())
{
xmlStr = wc.DownloadString(m_strFilePath);
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);
return xmlDoc;
}
private void CheckUrlNode(XmlNode xmlNode, XmlDocument xmlDoc)
{
var urlList = new List<string>() { xmlNode["loc"].InnerText };
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
var hrefLangUrls = xmlNode
.SelectNodes("xhtml:link", nsmgr)
.Cast<XmlNode>()
.Select(x => x.Attributes["href"].Value);
urlList.AddRange(hrefLangUrls);
foreach (var url in urlList)
{
string logMessage;
if (!CheckUrl(url, out logMessage))
{
Log(logMessage);
}
}
}
private bool CheckUrl(string url, out string logMessage)
{
logMessage = null;
try
{
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
request.Method = "HEAD"; //Get only the header information -- no need to download any content
using (var response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
if (statusCode == 200) //Good requests
{
return true;
}
else
{
logMessage = String.Format("<a href='{0}'>{0}</a>, status code: {1}", url, statusCode);
return false;
}
}
}
catch (WebException ex)
{
logMessage = String.Format("<a href='{0}'>{0}</a>, status: {1}", url, ex.Status);
}
catch (Exception ex)
{
logMessage = String.Format("Could not test url {0}, exeption message: {1}", url, ex.Message);
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I think you can achieve the same with less code by utilizing some libraries and language features.</p>\n<p><a href=\"https://www.sitemaps.org/protocol.html\" rel=\"nofollow noreferrer\">Google's Sitemap Protocol</a> is not supported by default in the .NET Framework / Core.<br />\nBut there are couple of packages which defines the corresponding C# classes, for example:</p>\n<ul>\n<li><a href=\"https://github.com/aseemgautam/google-sitemap\" rel=\"nofollow noreferrer\">Google-Sitemap</a></li>\n<li><a href=\"https://github.com/ernado-x/X.Web.Sitemap\" rel=\"nofollow noreferrer\">X.Web.Sitemap</a></li>\n</ul>\n<p>I have chosen the second one. So, the parsing logic would look like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static async Task<XDocument> LoadSitemap(string filePath = "./sitemap.xml")\n{\n var sitemap = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);\n return await XDocument.LoadAsync(sitemap, LoadOptions.None, CancellationToken.None);\n}\n\npublic static Sitemap ParseSitemap(XDocument document)\n{\n var serializer = new XmlSerializer(typeof(Sitemap));\n return (Sitemap) serializer.Deserialize(document.CreateReader());\n}\n</code></pre>\n<p>The <code>HEAD</code> retrieval could be done by the following helper method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly HttpClient client = new HttpClient();\n\nprivate static async Task<string> GetHead(string location, \n Func<HttpResponseMessage, string> successHandler, \n Func<Exception, string, string> failureHandler)\n{\n try\n {\n var timeoutPolicy = new CancellationTokenSource(5000);\n var request = new HttpRequestMessage(HttpMethod.Head, location);\n var response = await client.SendAsync(request, timeoutPolicy.Token);\n return successHandler(response);\n }\n catch (Exception ex)\n {\n return failureHandler(ex, location);\n }\n}\n</code></pre>\n<p>The success and failure handlers can be implemented like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string HandleResponse(HttpResponseMessage response)\n{\n var url = response.RequestMessage.RequestUri;\n return response.StatusCode == HttpStatusCode.OK \n ? $"{url} - OK" \n : $"{url} - Status code: {response.StatusCode}";\n}\n\nprivate static string HandleError(Exception exception, string url)\n{\n return exception switch\n { \n HttpRequestException hre => $"{url} - unreachable due to {hre.Message}",\n TaskCanceledException tce => $"{url} - timed out due to {tce.Message}",\n _ => $"{url} - failed due to {exception}"\n };\n}\n</code></pre>\n<p>Let's put all these pieces together:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static async Task Main(string[] args)\n{\n var siteMapXml = await LoadSitemap();\n var siteMap = ParseSitemap(siteMapXml);\n\n var siteChecks = siteMap\n .Select(url => GetHead(url.Location, HandleResponse, HandleError))\n .ToList();\n\n await Task.WhenAll(siteChecks);\n\n foreach (var siteCheck in siteChecks)\n {\n Console.WriteLine(await siteCheck); \n }\n\n Console.WriteLine("Finished");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:34:14.770",
"Id": "250588",
"ParentId": "250542",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T11:27:20.477",
"Id": "250542",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Small sitemap checker .aspx file"
}
|
250542
|
<p>So I wrote a rather primitive login logic in Node.js, which authenticates the user and handles JWT. Is it any good in terms of security, efficiency, building, async/sync, logging. <strong>SECURITY is my main concern.</strong>
On in a prettier format the question would be:</p>
<ul>
<li><strong>SECURITY</strong>: Is my website secure in any way, shape, or form? I'm wondering if I could implement any security measures other than the ones that are built in to the methods provided by <code>Node.js</code>. Also, I know the passwords are plainly obvious to guess, but they are like that to ensure logging in as different users works.</li>
<li><strong>EFFICIENCY</strong>: Is how I'm checking usernames and password efficient? Is there any better way to do this?</li>
<li><strong>BUILDING</strong>: Is how I loaded my website acceptable? Reading from a file and then ending the response?</li>
<li><strong>ASYNC/SYNC</strong>: I know I preform <code>async</code> and <code>sync</code> calls at the same time. Is there any problem to this?</li>
<li><strong>LOGGING</strong>: I log all connections to the server, and all login attempts. Is this a good practice, or am I overdoing what logging is supposed to accomplish?
(Source: <a href="https://codereview.stackexchange.com/questions/223228/login-server-with-node-js">Login Server with Node.js</a>)</li>
</ul>
<p>My code is:</p>
<pre><code>// main login logic
app.post('/api/login', apiLimiter, async function (req, res) {
// TODO: implement cookie check whether a still valid token is set and if so respond with cookie already set
// TODO: add roles into jwt and add roles checking into other code
// TODO: if wrong password send a response telling there's a wrong password/username
try {
const pw = req.body.password;
const submittedUser = req.body.email;
User.findOne({eMail: req.body.email}, async function (err, user) {
if (err) throw err;
console.log(user);
const match = await bcrypt.compare(pw, user.password);
console.log(match);
if (match === true && user.eMail == submittedUser) {
jwt2.sign({user}, 'secrettokenhere', { expiresIn: '15min'}, (err, token) =>{
res.cookie(
'access_token', 'Bearer '+ token, {
//domain: 'localhost',
path: '/',
expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins
httpOnly: true // in production also add secure: true
})
.json(
user
);
});
}
else {
res.status(200).send("Bad login");
}
});
} catch (err) {
res.status(500).send();
console.log(err);
}
});
</code></pre>
<p>P.S. there's gonna be a follow-up separate question with Frontend logic.</p>
|
[] |
[
{
"body": "<p><strong>Async login bug</strong> The <code>try</code>/<code>catch</code> around <code>User.findOne</code> does not accomplish anything because <code>findOne</code> is asynchronous. When <code>findOne</code> fails, it'll pass an error to the callback, but when the callback does <code>throw err</code>, nothing is there to catch the asynchronous error, so no response will be sent to the user. Another issue is that you aren't checking if <code>user</code> exists - <a href=\"https://stackoverflow.com/questions/10551313/mongodb-node-findone-how-to-handle-no-results\">if it doesn't</a>, an error will be thrown when you try to access its <code>password</code> property. (You also aren't checking for whether <code>.sign</code> results in an error or not)</p>\n<p>You could also consider using Promises instead of callbacks - <code>findOne</code> already returns a Promise, and Promises are often preferable because they're more easily chainable and their error handling can be cleaner.</p>\n<p><strong>Security</strong> looks reasonable, though:</p>\n<ul>\n<li>Make sure connections are only permitted over HTTPS. HTTP requests are interceptable.</li>\n<li>Even if the login bug above gets fixed, your current implementation is capable of informing anyone whether a given email is registered. For example, if I know your email address, I can try to login as you and examine the response to see whether the password was wrong or if no such email exists. This may not be desirable. If you wanted to fix it, have when the password doesn't match enter the same block as when the email isn't found, to make it indistinguishable to the user - you'd want to send a reply of <code>Bad login</code> in both cases.</li>\n<li>On a similar note, when authentication fails, the appropriate status code to send is <a href=\"https://httpstatuses.com/401\" rel=\"nofollow noreferrer\">401</a> (unauthorized), not 200.</li>\n</ul>\n<blockquote>\n<p>Is how I'm checking usernames and password efficient?</p>\n</blockquote>\n<p>Looks completely normal to me.</p>\n<blockquote>\n<p><strong>LOGGING:</strong> I log all connections to the server, and all login attempts. Is this a good practice</p>\n</blockquote>\n<p>If one is logging, login attempts are one of the most important things to log. But <code>console.log</code> is not the right way to do it, at least not alone - say that some user was concerned about their logins, how would you examine their recent login attempts? Control-F-ing through the application stdout isn't a very manageable way of doing it. I'm not sure what the industry standard for this is, but you could consider saving to a logging database.</p>\n<p><strong>Email login</strong> You do:</p>\n<pre><code>const pw = req.body.password;\nconst submittedUser = req.body.email;\n\nUser.findOne({eMail: req.body.email}, async function (err, user) {\n if (err) throw err;\n console.log(user);\n const match = await bcrypt.compare(pw, user.password);\n console.log(match);\n if (match === true && user.eMail == submittedUser) {\n</code></pre>\n<p>You put the request email into a variable named <code>submittedUser</code>, which doesn't sound all that intuitive to me - better to use a variable name that indicates that it contains an email string, not a user, like <code>email</code> - you could destructure both at once with:</p>\n<pre><code>const { password, email } = req.body;\n</code></pre>\n<p>Then, later, use those variables instead of going through <code>req.body</code> again.</p>\n<p>After the <code>.findOne</code>, there shouldn't be any need to do <code>user.eMail == submittedUser</code> - that check should be superflouous given the <code>findOne</code> call's constraint.</p>\n<p>The body contains <code>email</code>, but the database contains <code>eMail</code>. The capitalization is different, which is an odd inconsistency which could cause typos and bugs. I'd recommend using a <em>single</em> property name - probably <code>email</code>, since that capitalization is much more common.</p>\n<p>Rather than comparing the match against <code>=== true</code>, you can just check if the match is truthy - or, another option, to reduce unnecessary indentation would be to throw if the match <em>isn't</em> truthy, and handle errors in a <code>.catch</code>.</p>\n<p>Since <code>.sign</code> is callback-based, but you want to work with Promises, make it Promise-based with <code>util.promisify</code>.</p>\n<p><strong>Overall</strong> I'd hope to make the code look something like this:</p>\n<pre><code>const jwtSignPromisified = util.promisify(jwt2.sign).bind(jwt2);\napp.post('/api/login', apiLimiter, async function (req, res) {\n const failLogin = () => {\n logLoginAttempt(email, false); // or something - 2nd param indicates success\n // could also pass IP address\n res.status(401).send('Bad login');\n };\n const { password, email } = req.body;\n try {\n const user = await User.findOne({ email });\n if (!user) return failLogin();\n const match = await bcrypt.compare(password, user.password);\n if (!match) return failLogin();\n logLoginAttempt(email, true);\n const token = await jwtSignPromisified({ user }, 'secrettokenhere', { expiresIn: '15min' });\n res.cookie(\n 'access_token', 'Bearer ' + token, {\n //domain: 'localhost',\n path: '/',\n expires: new Date(Date.now() + 900000), // cookie will be removed after 15 mins\n httpOnly: true // in production also add secure: true\n })\n .json(user);\n } catch (error) {\n // This should not be entered under normal circumstances:\n logServerError(error);\n res.status(500).send('Unexpected server error');\n }\n});\n</code></pre>\n<p>where <code>logLoginAttempt</code> and <code>logServerError</code> save to logging databases that can be examined.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:11:35.950",
"Id": "493922",
"Score": "0",
"body": "There appears to be one small mistake: `jwtSignPromisified.sign` should be just `jwtSignPromisified`, otherwise an error gets thrown out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:53:40.813",
"Id": "493925",
"Score": "0",
"body": "also in findOne I had to do `eMail: email`, but that might be my mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T13:55:24.830",
"Id": "493926",
"Score": "0",
"body": "Can you change the `User` schema to have `email` be all lowercase? That's one of the things I was trying to recommend in the answer - it's better when all variables/properties referencing a particular thing use the same casing, it'll help reduce bugs due to typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:16:28.127",
"Id": "493928",
"Score": "0",
"body": "Changed the `User` schema to email and now it's giving out 401 again.. And yes I did change in the auth service of the frontend from eMail to email and in the backend from eMail to email... weird..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:21:02.013",
"Id": "493929",
"Score": "0",
"body": "If a user was previously registered with the `eMail` schema, maybe the same user can't login via `email` without restructuring the database? Try registering a new user and then logging in with them, if you haven't tried that already. Just an idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T14:43:24.610",
"Id": "493930",
"Score": "0",
"body": "You were right. I had to remove the index too and change some other code, hope it did not mess up everything else.."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:59:40.403",
"Id": "250558",
"ParentId": "250543",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250558",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T13:21:28.497",
"Id": "250543",
"Score": "8",
"Tags": [
"javascript",
"node.js",
"security",
"authentication",
"server"
],
"Title": "Node.js backend login logic"
}
|
250543
|
<p>I have a script that includes some independent tests that run together (not parallelly).
The tests include calls for some libraries that might raise exceptions (which indicate of a failure in the test).
Instead of wrapping each call with "try - except" mechanism I thought about wrapping the each test with "try - except" using decorator of this kind:</p>
<pre><code>def log_exceptions(func):
def inner(*args, **kwargs):
try:
return func(*args, *kwargs)
except Exception as e: # Can be more specific here, I know
logging.error("Python Exception raised from {} - {}".format(func.__name__, e))
ERROR_MSG.append("Python Exception raised from {} - {}".format(func.__name__, e))
return False
return inner
@log_exceptions
def test1():
some_funciton_call()
</code></pre>
<p>Where ERROR_MSG is a list of the errors that occurred during the tests.</p>
<p>Do you think managing the exceptions and errors this way is a good practice?
Can you suggest a different way of capturing exceptions?</p>
<p>Thanks! :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T14:40:23.307",
"Id": "491634",
"Score": "2",
"body": "Why do you need to catch and log the exceptions there in first place? afaik uncaught exceptions dont fail tests (at least not when using `pytest`), so if there's an exception affecting the functionality, then it should be reflected via failing `assert`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:45:55.480",
"Id": "491648",
"Score": "4",
"body": "What test framework are you using? There are several, and each one I've seen includes exception handling, including failing a test if an expected exception is not raised. Catching (and logging) an unexpected exception is the simplest case that all of those test frameworks already handle. Include your real code, and real test code, not pseudo code (`some_funciton_call()`) and hypothetically code (`# Can be more specific`), and you might get real help. Otherwise, this is vote-to-close/missing review context."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T14:03:46.840",
"Id": "250545",
"Score": "1",
"Tags": [
"python",
"error-handling",
"exception"
],
"Title": "How to catch exceptions in test code?(Python 3.8)"
}
|
250545
|
<p>How to make changes in my code so that it can take the least memory possible.?
This is a leetcode program , I have tested all the testcases and it has passed, I tried to reduce the memory usage, but by far now, I have not been able to understand.</p>
<p>I want to look into this so that I can understand the usage of memory spaces better. Any input would be helpful. Thank you very much. I will also post the link to the question, but since the logic is already clear to me, The only question is that is this a good solution or memory heavy?</p>
<pre><code> class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
int numberOfSeconds = duration;
if (timeSeries.length >0)
old_goalpost = timeSeries[0]+duration-1;
else
numberOfSeconds=0;
if (timeSeries.length >0)
for (i=1;i<timeSeries.length;i++)
{
new_goalpost = timeSeries[i]+duration-1;
diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));
numberOfSeconds = numberOfSeconds +diff;
old_goalpost = new_goalpost;
}
return numberOfSeconds;
}
}
</code></pre>
<p>the question is this
<a href="https://i.stack.imgur.com/4dGjX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4dGjX.png" alt="enter image description here" /></a></p>
<p>And it has passed all the test cases.</p>
<p><a href="https://i.stack.imgur.com/kZjnr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kZjnr.png" alt="enter image description here" /></a></p>
<p>If you want, this is the link to the question
<a href="https://leetcode.com/problems/teemo-attacking/submissions/" rel="nofollow noreferrer">https://leetcode.com/problems/teemo-attacking/</a></p>
<p>this code is 99.97% faster but memory heavy</p>
<pre><code>class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int i =0,old_goalpost=0,new_goalpost=0 ,diff=0;
int numberOfSeconds = duration;
if (timeSeries.length >0)
old_goalpost = timeSeries[0]+duration-1;
else
numberOfSeconds=0;
if (timeSeries.length >0)
for (i=1;i<timeSeries.length;i++)
{
new_goalpost = timeSeries[i]+duration-1;
diff = (new_goalpost - old_goalpost)>duration?duration:((new_goalpost - old_goalpost));
numberOfSeconds = numberOfSeconds +diff;
old_goalpost = new_goalpost;
}
return numberOfSeconds;
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/HsmRt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HsmRt.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:27:19.630",
"Id": "491640",
"Score": "0",
"body": "can I add just one sentence more about how to reduce memory in the question? @BCdotWEB ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T07:40:33.613",
"Id": "496852",
"Score": "0",
"body": "Let me know what you want to add please? @BCdotWEB"
}
] |
[
{
"body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<ul>\n<li><p>Just tested your code, it has a <code>1ms</code> runtime with <code>99.97%</code> faster than other solutions.</p>\n<p><a href=\"https://i.stack.imgur.com/orrzp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/orrzp.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Don't pay too much attention to these runtime/memory data provided by LeetCode especially when:</p>\n<ul>\n<li>it comes to memory; or</li>\n<li>test cases are too limited (such as Teemo) because their benchmarkings are not so accurate.</li>\n</ul>\n</li>\n<li><p>Maybe instead we'd format the code, just a bit making things based on Java's conventions:</p>\n</li>\n</ul>\n<pre><code>public class Solution {\n public static final int findPoisonedDuration(\n final int[] timeSeries,\n final int duration\n ) {\n\n int i = 0;\n int oldGoalpost = 0;\n int newGoalpost = 0;\n int diff = 0;\n int numberOfSeconds = duration;\n\n if (timeSeries.length > 0) {\n oldGoalpost = timeSeries[0] + duration - 1;\n\n } else {\n numberOfSeconds = 0;\n }\n\n if (timeSeries.length > 0)\n for (i = 1; i < timeSeries.length; i++) {\n newGoalpost = timeSeries[i] + duration - 1;\n\n diff = (newGoalpost - oldGoalpost) > duration ? duration : ((newGoalpost - oldGoalpost));\n\n\n numberOfSeconds = numberOfSeconds + diff;\n oldGoalpost = newGoalpost;\n\n }\n\n return numberOfSeconds;\n\n }\n}\n</code></pre>\n<hr />\n<ul>\n<li>Your solution has an order of N runtime with constant memory O(1).</li>\n<li>Algorithmically speaking, which is a key point on solving LeetCode questions, I don't think much can be done to make it any further efficient, I might be wrong though.</li>\n</ul>\n<pre><code>public class Solution {\n public static final int findPoisonedDuration(\n final int[] series,\n final int duration\n ) {\n if (series.length == 0 || duration == 0) {\n return 0;\n }\n\n int totalTime = duration;\n\n for (int i = 1; i < series.length; i++) {\n totalTime += Math.min(series[i] - series[i - 1], duration);\n }\n\n return totalTime;\n }\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:07:39.303",
"Id": "250549",
"ParentId": "250548",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:03:28.007",
"Id": "250548",
"Score": "5",
"Tags": [
"java"
],
"Title": "How do I lessen the memory usage of my solution to LeetCode 495: Teemo Attacking"
}
|
250548
|
<p>I have a simple task as part of a larger autocorrelation DSP system - to convert from signed 16-bit integer audio samples to floating-point. This part is quite self-contained:</p>
<pre><code>#include <cblas.h>
typedef int16_t sample_t;
void consume(const sample_t *samples, int N, int rate)
{
float *input = calloc(N, sizeof(float)),
*output = calloc(N, sizeof(float));
assert(input);
assert(output);
for (int i = 0; i < N; i++)
input[i] = (float)samples[i];
// BLAS processing of 'input'
for (int i = 0; i < N; i++)
{
output[i] = cblas_sdot( // Standard CBLAS call
N-i, // N
input, // X
1, // incX
input+i, // Y
1 // incY
);
}
}
</code></pre>
<p>Due to external constraints - the hardware only supports <code>S16_LE</code> samples - ALSA cannot do this conversion for me, nor can <code>cblas</code> accept integer types; so I'm stuck doing this myself. I've not found anything in <code>gsl</code> or <code>cblas</code> that runs vectorized type conversion.</p>
<p>I'm also not in love with having to loop over a level-1 dot product, but I've not been able to find a good way in BLAS to represent a single level-2 (matrix-vector) multiplication where the matrix is just a heavily-aliased single vector.</p>
<p>Is there a better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:48:20.220",
"Id": "492764",
"Score": "0",
"body": "What does the function `cblas_sdot()` do? Do floating point errors matter `input+i`? Note: the first question is about this question being on-topic for CR."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:51:15.520",
"Id": "492766",
"Score": "0",
"body": "`cblas_sdot` is a standard method of the CBLAS library. If you think it would improve clarity, I can include the header file statement and call this out in the description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:52:07.223",
"Id": "492767",
"Score": "1",
"body": "@pacmaninbw floating-point errors don't matter _all_ that much, though the addition you indicated is pointer addition, not floating-point addition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:52:56.107",
"Id": "492768",
"Score": "0",
"body": "Yes `include the header file statement and call this out in the description.` I don't see where rate is used in the function."
}
] |
[
{
"body": "<ol>\n<li>If this code goes into production then the asserts for the success of <code>calloc()</code> will be optimized out of the code if the code is optimized. Prefer if statements with calls to <code>fprintf(stderr,</code>.</li>\n<li>The parameter <code>rate</code> is never used, this can lead to maintenance errors in the future.</li>\n<li>For maintenance reasons the ability of someone else to understand the code I would suggest using <code>&input[i]</code> rather than <code>input+</code> in the function call.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:08:49.483",
"Id": "492770",
"Score": "0",
"body": "What's the mechanism by which `assert` gets dropped?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:10:33.273",
"Id": "492771",
"Score": "0",
"body": "Asserts are implemented as macros and are assumed to be debug tools. The macros go to blank code if the the debug flag isn't used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:12:05.103",
"Id": "492773",
"Score": "0",
"body": "For the gcc tool chain, what is the debug flag? Just DEBUG?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:12:47.103",
"Id": "492774",
"Score": "0",
"body": "See https://en.cppreference.com/w/cpp/error/assert"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:16:13.293",
"Id": "492775",
"Score": "0",
"body": "So it's not a debug flag; it's a non-debug flag - NDEBUG."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:21:37.050",
"Id": "492776",
"Score": "0",
"body": "Code compiled with -g will use the assert macro, code compiled without the -g flag shouldn't use the macro and code compiled with any -O will definitely not use the macro."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:04:35.667",
"Id": "250582",
"ParentId": "250550",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:21:28.340",
"Id": "250550",
"Score": "2",
"Tags": [
"c",
"numerical-methods"
],
"Title": "Vectorized type conversion for autocorrelation"
}
|
250550
|
<p>I'm working on a file interpreter and this is the code I have in my main() function right now:</p>
<pre><code>// main.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <crtdbg.h>
#include "FileReader.h"
#include "Interpreter.h"
int main()
{
{
std::unique_ptr<FileReader> fileReader = std::make_unique<FileReader>("https://www.swiftcoder.nl/cpp1/start.txt");
//fileReader->getData();
}
{
std::unique_ptr<Interpreter> interpreter = std::make_unique<Interpreter>();
//interpreter->decode();
}
_CrtDumpMemoryLeaks();
return 0;
}
</code></pre>
<p>Can this be considered 'good' or 'clean' code? What improvements or changes should I make?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:44:00.147",
"Id": "491647",
"Score": "0",
"body": "Does a vote on my post mean it's 'good' code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:50:01.067",
"Id": "491649",
"Score": "4",
"body": "No, a vote on your question just means someone thinks the question is a good question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:50:42.453",
"Id": "491650",
"Score": "0",
"body": "How does this work since you don't call fileReader->getData or interpreter->decode and you also don't tell the interpreter what to interpret?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:59:50.797",
"Id": "491651",
"Score": "0",
"body": "My question isn't really about functionality. I just wonder if this would be a 'clean' way of calling functions from other classes inside main(). And if this is undoubtedly free of memory leaks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:01:07.440",
"Id": "491652",
"Score": "1",
"body": "\"I want to call functions from other classes\" is the wrong way to think about classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:03:03.663",
"Id": "491654",
"Score": "0",
"body": "Could you elaborate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T17:14:16.240",
"Id": "491655",
"Score": "4",
"body": "I don't really think there's enough here to review. Without seeing `FileReader` and `Interpreter` we can only guess how they \"should\" be called."
}
] |
[
{
"body": "<p>As the comments have noted, this is such a tiny amount of code that it's somewhat difficult to comment on it.</p>\n<p>So, take the following with a grain of salt. It may be reading entirely too much intent into entirely too little code to really mean much.</p>\n<h3>Pointers</h3>\n<p>You're using <code>unique_ptr</code>s, which are generally preferred over raw pointers, <em>but</em> the code shows no indication that you have any real need or use for pointers of any kind, at all. Ultimately, you're just instantiating a couple of objects.</p>\n<p>I'd consider use of pointers in C++ a decision that requires at least a little justification. It's not necessarily terribly difficult to justify, but it should be avoided unless you honestly have <em>some</em> reason to do it.</p>\n<p>In this case, I see no hint of any such reason. So, lacking any reason to think it's a good idea, my immediate reaction is that it's probably not.</p>\n<p>If I were writing the code, my immediate take would be to just create <code>filereader</code> and <code>interpreter</code> as automatic variables.</p>\n<h3>Comments</h3>\n<p>You only have one comment.</p>\n<pre><code>// main.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n</code></pre>\n<p>Unfortunately, this doesn't seem to me to add anything useful to the code. Anybody who knows C or C++ even a little bit can see that this contains <code>main</code>, and knows what <code>main</code> means/is/does.</p>\n<h3>Return value from main</h3>\n<p>C++ automatically includes code to indicate a successful return from <code>main</code> if execution reaches the end of the function without executing another <code>return</code> first. As such, your <code>return 0;</code> is simply redundant.</p>\n<h3>Portability</h3>\n<p>I'd generally prefer to write most code to be as generic and portable as possible. As such, if I were doing this, I'd write at least a thin wrapper around <code>_CrtDumpMemoryLeaks</code>, and put that bit of code in a separate file, so it would be relatively easy to (for one example) have the build files link in one version for Windows, and another for Linux, so you can keep the bulk of the code portable, and keep that bit of non-portable code segregated from the rest (segregation may be bad in real life, but in programming, it's often useful).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T11:32:00.957",
"Id": "492748",
"Score": "0",
"body": "You might want to remove your answer, this question is in the Close Queue, and it should be closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:07:40.997",
"Id": "492759",
"Score": "0",
"body": "It should NOT be deleted. Any help is help and it makes no sense to delete this. Thanks a lot @Jerry Coffin for your clear answer! Helped me perfectly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:03:28.567",
"Id": "492825",
"Score": "0",
"body": "Can I ask you how you would write a thin wrapper around `_CrtDumpMemoryLeaks`? I'm not familiar with wrappers. @Jerry Coffin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T02:29:44.150",
"Id": "492861",
"Score": "0",
"body": "@TristanvO: I'd change `main` to include a call to something like `show_leaks()`, then have a Windows-specific file containing `void show_leaks() { _CrtDumpMemoryLeaks(); }` Then when/if you want to do similar on, say, Linux, add a new file specific to Linux that also implements `show_leaks()`, but using some Linux-specific code (e.g., `malloc_info`). Then you can (for example) have your build tool select the right file based on the target OS."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:07:16.333",
"Id": "250573",
"ParentId": "250553",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T15:45:34.353",
"Id": "250553",
"Score": "-1",
"Tags": [
"c++",
"object-oriented"
],
"Title": "C++ main architecture"
}
|
250553
|
<p>I would like to know if this is a good solution for a function that has to computer the power of integers given base and exponent.
The solution must include solution for negative numbers.
I'm trying to learn C++ trough a Deitel book and I'm doing several exercises.</p>
<pre><code>#include <iostream>
using namespace std;
double integerPower(int base, int exponent){
double result = 1;
if(exponent >=0){
for (int i = 0; i < exponent; i ++){
result *= base;
}
} else {
exponent *= -1;
for (int i = 0; i < exponent; i ++){
result /= base;
}
}
return result;
}
int main() {
int base, exponent;
double result;
cout << "Insert the base: " << endl;
cin >> base;
cout << "Insert the exponent: " << endl;
cin >> exponent;
result = integerPower(base, exponent);
cout <<"The result is: " << result << endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Use the standard library</h1>\n<p>If you are going to give the result as a <code>double</code>, then this function isn't really a pure integer power calculator. And in that case, just use <a href=\"https://en.cppreference.com/w/cpp/numeric/math/pow\" rel=\"nofollow noreferrer\"><code>std::pow()</code></a>. It has overloads for integer exponents that the compiler can optimize for.</p>\n<h1>A pure integer power function</h1>\n<p>If you just want to work purely on integers, then the typical algorithm to calculate a number raised to an arbitrary power efficiently is by recognizing that, for example, <span class=\"math-container\">\\$x^4 = ((x * x) * (x * x))\\$</span>, and so you can calculate <span class=\"math-container\">\\$y = x * x\\$</span>, and then <span class=\"math-container\">\\$x^4 = y * y\\$</span>. This only needs two multiplications instead of 3. So basically, you can divide and conquer the problem:</p>\n<pre><code>int integerPower(int base, int exponent) {\n if (exponent == 0)\n return 1;\n\n int result = integerPower(base, exponent / 2);\n int result *= result;\n\n if (exponent & 1)\n result *= base;\n\n return result;\n} \n</code></pre>\n<p>The above doesn't work for negative exponents, but then again that is not very useful if the result is just an integer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T20:24:16.270",
"Id": "491668",
"Score": "1",
"body": "_If the base and the exponent are both negative, then mathematically the result will be a complex number_ - not so. You confuse it with negative base and _fractional_ exponent. A negative exponent is just a division."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T20:27:59.340",
"Id": "491669",
"Score": "0",
"body": "@vnp Oops! I should've known that. Thanks for letting me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T05:12:09.113",
"Id": "492693",
"Score": "0",
"body": "@G.Sliepen If the power is negative, call the function again with the positive of the power, and the reciprocal of the base. For example, if the function is called with 10 as base and -5 as power. Call the function again with 5 as power, and 1/10 as the base (reciprocal). This way you can calculate it for negative exponents too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T05:12:35.477",
"Id": "492694",
"Score": "0",
"body": "x ^ -y = (1/x) ^ y"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T18:09:40.767",
"Id": "250559",
"ParentId": "250555",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:04:39.150",
"Id": "250555",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Integer Power C++ Function with base and exponent parameters"
}
|
250555
|
<p>so I've been working with R quite a while now, but due to very stressful deadlines in my last university module I had, I wrote code that I'm not very proud of. I would like to be more efficient in data wrangling, e.g. reading files, rearranging and cropping dfs. Here's a short excerpt of my code</p>
<pre><code> # Reading files
org_bm <- read.delim("DE_gebesee_metrx_org_physiology-daily.txt")
t_bm <- read.delim("DE_gebesee_metrx_t_physiology-daily.txt")
co2_bm <- read.delim("DE_gebesee_metrx_co2_physiology-daily.txt")
# Format Dates
org_bm$datetime <- as_datetime(org_bm$datetime) + years(98)
t_bm$datetime <- as_datetime(t_bm$datetime) + years(98)
co2_bm$datetime <- as_datetime(co2_bm$datetime) + years(98)
# Select cols
org_ghg <- select(org_ghg, c(datetime,
aN_n2o_emis.kgNha.1.,
aC_ch4_emis.kgCha.1.,
aC_co2_emis_hetero.kgCha.1.,
aC_co2_emis_auto.kgCha.1.))
t_ghg <- select(t_ghg, c(datetime,
aN_n2o_emis.kgNha.1.,
aC_ch4_emis.kgCha.1.,
aC_co2_emis_hetero.kgCha.1.,
aC_co2_emis_auto.kgCha.1.))
co2_ghg <- select(co2_ghg, c(datetime,
aN_n2o_emis.kgNha.1.,
aC_ch4_emis.kgCha.1.,
aC_co2_emis_hetero.kgCha.1.,
aC_co2_emis_auto.kgCha.1.))
</code></pre>
<p>As you can see I mastered c/p and "search and replace" XD
But seriously, I'm wondering how I could "automate" these tasks. Maybe loading everything into a list and than write helper functions to apply certain actions (i.e. date formatting, selecting cols) to every list entry ?</p>
<p>I've always struggled to find good practice tasks, b/c during class I usually don't have the time to read up on nicer ways to make things work. So if anybody has some suggestions on where to find exercises on data analysis tasks, I would very much appreciate that.</p>
<p>Looking forward to read your replies !
Leon</p>
|
[] |
[
{
"body": "<p>You can do more conversion as you read the data. The magic is done by the colClasses parameter to read.delim(). That parameter allows you to (1) convert the DateTime whilst reading and (2) drop unwanted columns.</p>\n<p>Now I don't know what your data looks like, but here's a rough outline of how to read a datetime (untested). Note that you can do the <code>+ years(98)</code> within the data-parsing class as well.</p>\n<pre><code>library(methods)\nsetClass("myDateTime")\nsetAs("character",\n "myDateTime",\n function(from) as.DateTime(from, format="%Y-%m-%d %H:%M:%S", tz=Sys.timezone())) + years(98)\n\nd = read.delim(..., colClasses = c(..., "myDateTime", ...))\n</code></pre>\n<p>For the columns you want to drop, code them as "NULL" (note the quotes).</p>\n<pre><code>d = read.delim(..., colClasses = c("numeric", "myDateTime", "NULL", ...))\n</code></pre>\n<p>This not only shortens your code, but by explicitly telling read.delim() the datatype of each column the read is 2x faster. And of course there aren't two copies of the data in memory after the parsing.</p>\n<p>You might also want to look at the <code>skip=</code> and <code>col.names=c()</code> parameters as they allow you to decide the names of the variables, rather than having those decided by the input file. If you decide to use <code>colCLasses=c()</code> you'll almost certainly want to skip the column headings rather than program a class which reads strings for row 1 and a different datatype for the remaining rows.</p>\n<p>BTW, if you have to do complex manipulation of input data, then the tidyverse's readr and dplyr libraries have useful improvement over the shipped R libraries. Regardless of your use or not of Tidyverse, its book is worth reading if you are an R programmer: <a href=\"https://r4ds.had.co.nz/\" rel=\"nofollow noreferrer\">https://r4ds.had.co.nz/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:08:04.663",
"Id": "250660",
"ParentId": "250556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T16:18:42.480",
"Id": "250556",
"Score": "2",
"Tags": [
"performance",
"r",
"automation"
],
"Title": "Unefficent data wrangling in R"
}
|
250556
|
<p>I have a simple task I want to do, I want to compare two arrays like this:</p>
<pre><code>array 1 of data: [0.0, 92.6, 87.8, 668.8, 0.0, 86.3, 0.0, 147.1]
array 2 of data: [16.7, 0.0, 0.0, 135.3, 0.0, 205.5, 0.0, 93.8]
</code></pre>
<p>I want to find the difference between each value by index, and if the difference is lower than 50%, keep the value of the second array in a third array.</p>
<pre><code>array 3 of data : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 93.8]
</code></pre>
<p>Now I believe using a for loop would be the best option, iterating through each array since both have the same length, the code below is part of my code, array1 and array2 are arrays like above.</p>
<pre><code>for scan in sensor:
#here is some code where we build the Array1 and Array 2 from serial data which is inside the loop.
if specialcount ==1: #build the first array
#get data from dict and build first array
datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }
if specialcount ==2: #build the second array.
#get data from dict and build second array
datadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }
if specialcount ==3: #after we build 2 arrays, specialcount goes to 3, and we now compare the arrays
indexsizeofArray1 = len(array1)
indexsizeofArray2 = len(array2)
if indexsizeofArray1 != indexsizeofArray2:
print ("array mismatch, try again")
break
elif indexsizeofArray1 == indexsizeofArray2:
print("array match, proccessing")
array3 = [0,0,0,0,0,0,0,0]
for X in range (indexsizeofArray2):
difference = array2[X]-array1[X]
fiftypercent = array1[X]-(array1[X]/2)
lowerrange = int(array1[X]-fiftypercent)
upperrange = int(array1[X]+fiftypercent)
if array2[X] in range (lowerrange,upperrange):
array3[X]=array2[X]
if X == indexsizeofArray2:
print("final array: ",array3)
specialcount +=1
</code></pre>
<p>Above is my code ,I do get the result I want of course, but I believe I could make it cleaner mostly because I am in the code transforming float to int as they work with the range function. I am sure there is a cleaner way of doing this , that specialcount==3 is my condition since I build the 2 arrays inside the forloop before as soon as the second array is built, then we, this is inside a loop where I am polling constantly a sensor, the sensor is special in the sense that if I stop polling it and go out of the loop, it will not work again unless I restart it , as such I must be inside this loop all the time.</p>
<p>I am sure I can improve the speed of it if slightly, mostly on the reinitialization of the datadict, since I initialized it before , however inside the loop I populate it with the data up until a certain point, in which I then create the first array of data, and clear it so I can rebuild it. The goal is to build two arrays of 2 different variables that must be related, once those 2 lists are built, I need to compare them, ensure that they are not that different and if they are not , pass it to another function , if its too different, the value for that index in the list is 0 .</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T19:25:05.250",
"Id": "491665",
"Score": "5",
"body": "\\$ 50 \\% \\$ of what? there are 2 values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T00:10:58.827",
"Id": "491684",
"Score": "0",
"body": "Can you provide a complete example, including input and output? Also, you're dealing with plain Python lists, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T01:55:26.437",
"Id": "492682",
"Score": "0",
"body": "`specialcount` is incremented every time through the loop. The `if` blocks only execute for values 1 to 3. After that, it's an infinite loop that doesn't do anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:31:13.473",
"Id": "492720",
"Score": "0",
"body": "50% of what, and how is this an appropriate threshold? \"-50%\" is 2:1, \"+50%\" 2:3. `code where we build the Array1` I don't see that. I see `datadict` set to a weird literal dict from 0…7 to empty lists - never to be used."
}
] |
[
{
"body": "<h1>Don't use the loop-switch antipattern</h1>\n<p>If you have three <em>different</em> things that have to be done in order, just write them in that order. Don't put a loop around them with <code>if</code>-statements inside to check what has to be done that iteration; loops are for doing the <em>same</em> task over and over. What you are doing has a name: it is the <a href=\"https://en.wikipedia.org/wiki/Loop-switch_sequence\" rel=\"noreferrer\">loop-switch antipattern</a>. Instead, just write:</p>\n<pre><code>#get data from dict and build first array\ndatadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }\n\n#get data from dict and build second array\ndatadict={ 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], }\n\n#we now compare the arrays\n...\n</code></pre>\n<p>I assume that's not the real code. If each of the three tasks is of course much longer than what you wrote, then it helps to put them in functions.</p>\n<h1>Split the problem up into smaller sections</h1>\n<p>It always helps to break up a problem into smaller sections, and for example you can then handle each sub-problem in a separate function. In this case, looping over the arrays can be split from deciding whether or not to keep a value. So:</p>\n<pre><code>keep_within_fifty_percent(a, b):\n fiftypercent = a // 2\n lower = a - fiftypercent\n upper = a + fiftypercent\n\n if b in range(lower, upper):\n return b;\n else:\n return 0\n\n...\n\n#we now compare the arrays\nif len(array1) != len(array2):\n # handle error here\n ...\n\narray3 = [keep_within_fifty_percent(a, b) for a, b in zip(array1, array2)]\nprint("final array: ", array3)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:20:38.500",
"Id": "491672",
"Score": "0",
"body": "Thanks for the comments, i have the if statement inside for a simple reason, since i am getting data constantly from the first loop where I poll a sensor, I fill there a dictionary, which then I use the \"if specialcount \" condition to fill two different arrays with different data. I think if I remove the loop switch, I ran into the issue of basically building two identical arrays with the same data instead of two arrays with different data!. \nWould splitting part of the code to its own function introduce any delay? I am polling data from a serial port sensor, any delay introduces data loss"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:24:45.813",
"Id": "491673",
"Score": "2",
"body": "If performance is a critical issue, Python is the wrong language to use. Consider using C or C++ in that case. That said, I don't think there is a significant overhead for putting code in their own functions, but if you really want to know, you should benchmark your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T23:49:53.323",
"Id": "491682",
"Score": "1",
"body": "lower is same as \\$ a / 2 \\$, you don't need integral value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T23:50:29.343",
"Id": "491683",
"Score": "2",
"body": "also, `lower <= b < upper` vs `range`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:07:59.247",
"Id": "492699",
"Score": "1",
"body": "@hjpotter92 You're right, the calculation can be simplified even more, like in Acccumulation's answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:37:55.443",
"Id": "492847",
"Score": "0",
"body": "I am not that versed in python but yes, I am looking on how to improve the code thanks for your suggestion. C++ would be ideal but unluckily the library compatible with the sensor in the platform I am using is on python, however the code above works perfectly fine. Improving or removing clutter or unnecesary operations is now my focus, thank you very much."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T20:44:23.040",
"Id": "250563",
"ParentId": "250561",
"Score": "5"
}
},
{
"body": "<p>You can just use comprehensions:</p>\n<pre><code>def get_third_value(value1, value2):\n if abs(value1 - value2) < value1/2:\n return value2\n return 0\n\nif len(array1) != len(array2):\n print ("array mismatch, try again")\n break\nprint("array match, proccessing")\narray3 = [get_third_value(array1[i], array2[i]) \n for i in range(len(array1))]\nprint("final array: ",array3)\n</code></pre>\n<p>If you convert your data to Pandas Series, you can just do</p>\n<p><code>(abs(array1-array2)<array1/2)*array2</code></p>\n<p>Some notes on your code:</p>\n<p><code>array1[X]-(array1[X]/2)</code> baffles me. Why not just write <code>array1[X]/2</code>?</p>\n<p>You don't need to create special variables to store the lengths of the data, you can just compare them directly.</p>\n<p><code>range</code> is for creating an iterable. If you want to find out whether a number is between two values, you should use inequalities.</p>\n<p>I would expect that <code>X == indexsizeofArray2</code> would always return <code>False</code>; <code>range</code> creates an iterable <em>up to</em> the argument. <code>range(n)</code> does not include <code>n</code>.</p>\n<p>This also means that <code>range(a-b,a+b)</code> starts at <code>a-b</code> but ends at <code>a+b-1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T08:04:04.597",
"Id": "492732",
"Score": "0",
"body": "Instead of using `for i in range(len(array1))` you can just do `[get_third_value(x, y) for x,y in zip(array1, array2)]`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T23:18:12.600",
"Id": "250565",
"ParentId": "250561",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T19:18:36.077",
"Id": "250561",
"Score": "3",
"Tags": [
"python"
],
"Title": "Comparing two arrays by index in python in a cleaner way"
}
|
250561
|
<p><a href="https://github.com/apocalyps0/dotcomgame" rel="nofollow noreferrer">Github repository</a></p>
<p>Origanally I wrote a program that let you play battleship against the computer.</p>
<p>Pretty easy:</p>
<ol>
<li>create a number of ships</li>
<li>generate random cells for all the ships</li>
<li>let the user try to guess</li>
</ol>
<p>I implemented a way to place as many ships as possible:</p>
<p>If I have a 3x3 board and I want to place 4 ships that are 2 cells long, there are only few placements that allow the maximum number of ships in the board.</p>
<p>Example correct placement:</p>
<pre><code>|1|1|O|
|2|2|4|
|3|3|4|
</code></pre>
<p>Example wrong placement:</p>
<pre><code>|0|1|1|
|2|2|0|
|0|3|3|
</code></pre>
<p>Code(full code on github):</p>
<pre><code>public void prepareGame(){
if (!(field_size*field_size/ship_length >= ship_numbers)){
System.out.println("Error: Game numbers are invalid");
System.exit(0);
}
for (int i = 0; i < ship_numbers; i++) {
Ships.add(new Ship();
}
ArrayList<String> toTest;
int leftToPlace = ship_numbers;
for (Ship ship : Ships){
System.out.println("generating cells for "+ship);
while(true){
toTest = generateCells();
if (!checkShips(toTest)){
if(backtrackShips(toTest, leftToPlace)){
ship.setShip(toTest);
System.out.println("success for "+ship+" "+toTest);
System.out.println();
leftToPlace--;
break;
}
}
}
}
}
</code></pre>
<hr />
<pre><code>private boolean backtrackShips(ArrayList<String> toBacktrack, int shipsToPlace){
boolean backtrack_result = false;
ArrayList<String> cells;
ArrayList<ArrayList<String>> givenCells = new ArrayList<>();
for (int i = 0; i < (ship_numbers - shipsToPlace); i++) {
givenCells.add(Ships.get(i).getCells());
}
//System.out.println("backtracking: "+toBacktrack);
//System.out.println("given cells before backtrack: "+ givenCells);
givenCells.add(toBacktrack);
shipsToPlace--;
for (int i = 0; i < shipsToPlace; i++) {
for (int j = 0; j < 1000; j++) {
cells = generateCells();
// check if cells lap over already chosen cells
for (ArrayList<String> list : givenCells) {
if (Collections.disjoint(list, cells)) {
backtrack_result = true;
} else if (!Collections.disjoint(list, cells)) {
backtrack_result = false;
break;
}
}
if(backtrack_result) {
givenCells.add(cells);
break;
}
}
}
if (shipsToPlace == 0) { //base-case
backtrack_result = true;
}
//System.out.println("given cells after backtrack: "+ givenCells);
return backtrack_result;
}
</code></pre>
<hr />
<pre><code>public boolean checkShips(ArrayList<String> cells){
boolean result = false;
for (Ship ship : Ships){
if (!Collections.disjoint(cells, ship.getCells())){
result = true;
}
}
return result;
}
</code></pre>
<hr />
<p>If you want to know the Ship Class:</p>
<pre><code>package src;
import java.util.ArrayList;
public class Ship {
ArrayList<String> cells = new ArrayList<>();
public void setShip(ArrayList<String> cells){
this.cells = cells;
}
public ArrayList<String> getCells(){
return this.cells;
}
public String checkYourself(String stringTip){
String result = "Miss";
if (this.cells.contains(stringTip)){
result = "Hit";
this.cells.remove(stringTip);
}
if (this.cells.isEmpty()) {
result = "submerged";
}
return result;
}
}
</code></pre>
<p>I have basically two questions.</p>
<p>Is this backtracking?</p>
<p>Where can I optimize the code?</p>
<p>Edit: changed naming of ships.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T22:15:46.083",
"Id": "491676",
"Score": "2",
"body": "Apologies if I'm missing something, but what the heck is a \"dotcom\" ?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:37:51.637",
"Id": "492722",
"Score": "2",
"body": "Welcome to CodeReview@SE. Please add *all* parts needed to give useful reviews (`DotCom`?) to the question body, see [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:31:58.193",
"Id": "492740",
"Score": "0",
"body": "In my case I named the ships \"dotcoms\" (\".com\") like internet adresses. Imagine you have \"google.com\" as a ship."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T10:51:03.887",
"Id": "492746",
"Score": "0",
"body": "@apocs yeah, but *why* did you name them `dotcom`s? Why do the ships represent URLs? For the sake of readability and given the context of this question, it doesn't seem like replacing all the `dotcom`s by `ship`s would hurt the integrity of your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T11:49:28.243",
"Id": "492751",
"Score": "0",
"body": "While it is okay to limit the scope of the review (we can only review the code posted in the question), it is necessary to include any functions called by the code in the question, and the function `checkDotcoms(toTest)` is currently missing. That will get the question closed by the community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T12:10:29.190",
"Id": "492753",
"Score": "0",
"body": "@JansthcirlU You are totally right. Sorry for the inconvenience."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T21:07:52.673",
"Id": "250564",
"Score": "3",
"Tags": [
"java",
"game",
"backtracking"
],
"Title": "Putting as many ships on a square board as possible"
}
|
250564
|
<p>I am having trouble with time and complexity analysis. I have done a fibonacci series in a recursive way. I think it is <em>O(n<sup>2</sup>)</em>. Can you find out the time analysis? If possible, could you elaborate it?</p>
<pre><code>#include<iostream>
using namespace std;
void fibonacci(int n,int n1,int n2)
{
if(n==0)
{
cout<<endl<<n1;
return;
}
else if(n==1)
{
cout<<endl<<n2;
return;
}
fibonacci(n-1,n2,n1+n2);
return;
}
int main()
{
int n;
cout<<"Enter the number:"<<endl;
cin>>n;
fibonacci(n,0,1);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T03:40:31.853",
"Id": "492684",
"Score": "2",
"body": "entered `100` got `-980107325`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T04:23:30.833",
"Id": "492686",
"Score": "0",
"body": "Yeah even i got it......guess there is something wrong in this approach...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T04:32:57.467",
"Id": "492688",
"Score": "2",
"body": "@aryanparekh there is a simple explanation. 100th fibonacci number is beyond the range of both 32 and 64bit integer and so it overflows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:40:01.580",
"Id": "492724",
"Score": "0",
"body": "@AryanParekh Fib(100) is beyond the range of 64 bit integers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:48:05.423",
"Id": "492763",
"Score": "1",
"body": "Welcome to Code Review. You are not supposed to change the code in your question after you have received answers, because doing so invalidates the answers. I have thus rolled back your edit. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) for more information."
}
] |
[
{
"body": "<h1>About <code>using namespace std</code></h1>\n<p>You should try to avoid this statement as it is considered <strong><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice</a></strong>. It is best to avoid it whenever you can. Here is a simple example why.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#inlcude <list>\n\nusing namespace std;\n\nclass list // uh-hoh, list is already defined, or is that std::list?\n{ \n ...\n};\n\n</code></pre>\n<p>Another problem is that if you have this in <em>any</em> of the header files in your project, you will be forced to use this in any file you have included the header.<br></p>\n<p><strong><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is using namespace std considered bad practice</a></strong></p>\n<h1>Template meta-programming</h1>\n<p>This moves the calculation from run-time to <a href=\"https://en.wikipedia.org/wiki/Compile_time_function_execution\" rel=\"nofollow noreferrer\">compile-time</a>. Your program will take a little longer to compile, but the complexity will be <code>O(1)</code>. It uses <a href=\"https://www.geeksforgeeks.org/templates-cpp/\" rel=\"nofollow noreferrer\">templates in C++</a> to force the compiler to calculate the value.</p>\n<p>This is another option to approach this problem and the fastest way since this moves calculation to <a href=\"https://en.wikipedia.org/wiki/Compile_time_function_execution\" rel=\"nofollow noreferrer\">compile time</a>.</p>\n<p>However, the drawback is that you cannot use values that aren't known at compile time. For example, you could find the value for <code>5</code> but not something the user will enter, or for example a random number generated.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include<iostream>\n\ntemplate <unsigned N>\nstruct Fibonacci\n{\n enum : uint64_t\n {\n value = Fibonacci<N-1>::value + Fibonacci<N-2>::value\n };\n};\n\ntemplate <>\nstruct Fibonacci<1>\n{\n enum\n {\n value = 1\n };\n};\n\ntemplate <>\nstruct Fibonacci<0>\n{\n enum\n {\n value = 0\n };\n};\n\nint main()\n{\n std::cout << Fibonacci<20>::value;\n}\n</code></pre>\n<p>This method will be the fastest but will only work if your numbers are constant.<br>\n<a href=\"https://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\"><strong>Template meta-programming in C++</strong></a></p>\n<h1>Replace recursion with iteration</h1>\n<p>Although recursion makes your code a little cleaner, <strong>recursion almost always runs slower</strong>, this is because for each call it needs allocation of a new stack frame <br>\nDue to the fact that space in the stack is <strong>finite</strong>, there is a limit to how many recursive calls you can make, before C++ gives you <code>0xC00000FD</code>. Which is <strong><a href=\"https://en.wikipedia.org/wiki/Stack_overflow\" rel=\"nofollow noreferrer\">stack overflow</a></strong><br>\nWith a few more lines of code, you can replace recursion with this scenario and make it much faster, without this problem.<br> This doesn't mean that you shouldn't use recursion, some algorithms <strong>need</strong> recursion, but if you <strong>can</strong> replace it with iteration, then it's worth.</p>\n<p>Here it is with iteration.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>uint64_t fibonacci(int n)\n{\n uint64_t n1 = 0,n2 = 1,n3 = 1;\n if (n == 1 || n == 0) return 0;\n else if(n == 2) return 1;\n\n for (int i = 2;i < n;++i)\n {\n n3 = n1 + n2;\n n1 = n2;\n n2 = n3;\n }\n return n3;\n}\n</code></pre>\n<h1><code>'\\n'</code> over <code>std::endl</code></h1>\n<p><code>'\\n'</code> and <code>std::endl</code> will both accomplish your task, but <code>std::endl</code> calls <code>std::flush</code> every time and flushes the stream, this is why it will be slower, than simply printing <code>'\\n'</code><br><br></p>\n<p><a href=\"https://codeforces.com/blog/entry/43780\" rel=\"nofollow noreferrer\">Comparison between std::endl and '\\n'</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T04:24:01.357",
"Id": "492687",
"Score": "3",
"body": "Very useful insights...Thanks a lot..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T05:56:11.037",
"Id": "492697",
"Score": "5",
"body": "There's nothing wrong with proper tail recursion, such forms are usually transformed into iterative ones by the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:28:36.817",
"Id": "492704",
"Score": "1",
"body": "@bipll I doubt that, even though it can be true, I don't want to be hanging on the likeliness of \"usually\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:44:14.150",
"Id": "492706",
"Score": "5",
"body": "Tail recursion is simple. Standard optimization. Recursion here is unlikely to be an issue as the depth of the recursion is `n`. The result of Fib() overflows integers relatively quickly: Fib(300) = `222232244629420445529739893461909967206666939096499764990979600` so for any reasonably n you are not going to overflow the stack of any normal computer. Even though the linear solution (you present) is a better solution its not faster for the reasons you state (which are just wrong) it is faster because the complexity is linear `O(n)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T07:38:05.640",
"Id": "492723",
"Score": "0",
"body": "@MartinYork I talked about the stack overflow point as it is possible. Not in this program, but a possibility of recursive functions. Isn't recursion almost always slower than iteration due to the fact that calling functions is more expensive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T08:53:46.757",
"Id": "492736",
"Score": "2",
"body": "@AryanParekh If a true function call is made, yes, but there are many cases where the compiler can avoid the need for that, for example by doing tail recursion, but also by inlining function calls. *In general*, you are right that if you can write it simply as a `for`-loop, you should do that, but in some specific cases a seemingly recursive call is more readable and just as performant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T11:47:43.030",
"Id": "492750",
"Score": "0",
"body": "I [called `fibonacci(1)`](https://repl.it/repls/HealthyWaterloggedTrigger#main.cpp) and it printed `Finbonacci number 1 is 140515937053168`. That's *two* errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:01:12.263",
"Id": "492769",
"Score": "0",
"body": "@HeapOverflow sorry about that, silly little error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:40:29.140",
"Id": "492782",
"Score": "0",
"body": "You only fixed one of the two. You're still printing \"Finbonacci\". Also, printing everything [on one line](https://repl.it/repls/NumbSquigglyGroupware#main.cpp) isn't nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:34:32.347",
"Id": "492794",
"Score": "0",
"body": "@HeapOverflow Yes what you're saying makes sense, I have just returned the correct value instead because one might not always want to print it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:48:19.047",
"Id": "492856",
"Score": "0",
"body": "You can see that fib() is TCO in this example (on godbolt)[https://godbolt.org/z/6Pd78b]. That makes it O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:44:16.003",
"Id": "492873",
"Score": "0",
"body": "@CarsonGraham link gives me \" Whoops, ID \"6Pd78b]\" could not be found \""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T17:47:21.910",
"Id": "492984",
"Score": "0",
"body": "@AryanParekh looks like I've forgotten my markdown syntax. Maybe [this link will work?](https://godbolt.org/z/6Pd78b)"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T04:04:53.140",
"Id": "250568",
"ParentId": "250566",
"Score": "14"
}
},
{
"body": "<p>The most obvious way to write fib:</p>\n<pre><code>int fib(int n)\n{\n if (n < 2) // 0 or 1\n {\n return 1;\n }\n return fib(n-1) + fib(n-2);\n}\n</code></pre>\n<p>You can see it explodes because for every call to fib() you get 2 subsequent calls which both get 2 calls with all get 2 calls etc.</p>\n<pre><code> Level Calls Calls This Level Total Calls\n Level n 1 1 1\n Level n-1 1 1 2 3\n Level n-2 1 1 1 1 4 7\n Level n-3 1 1 1 1 1 1 1 1 8 15\n</code></pre>\n<p>So the complexity of Fib is Fib!!!!!<br />\nMore exactly Complecity is <code>O(2Fib(n)-1)</code><br />\nbut removing constants <code>O(Fib(n))</code></p>\n<p>Lets write some code to validate this:</p>\n<pre><code>int fibComplexity(int n)\n{\n // has the same properties of fib.\n // but returns the number of calls rather than the value.\n if (n < 2)\n {\n return 1; // You called this function once.\n }\n return 1 // the call to this function.\n + fibComplexity(n-1) // Count of calls in this tree\n + fibComplexity(n-2) // Count of calls in this tree.\n}\n</code></pre>\n<p>If we runt this:</p>\n<pre><code>int main()\n{\n for(int loop = 2; loop < 15; ++loop)\n {\n std::cout << loop << " " << fib(loop) << " " << fibComplexity(loop) << "\\n";\n }\n}\n</code></pre>\n<p>Generates: ( added formatting)</p>\n<pre><code>n F O\n2 2 3 \n3 3 5\n4 5 9\n5 8 15\n6 13 25\n7 21 41\n8 34 67\n9 55 109\n10 89 177\n11 144 287\n12 233 465\n13 377 753\n14 610 1219 O = 2f-1\n</code></pre>\n<hr />\n<p>But every coding course you take will then ask you to make a linear based solution.</p>\n<p>What you present above is a recursive (but linear solution). Most people would have gone for a loop based linear solution (but there is no difference). The complexity is exactly the same.</p>\n<p>What you done is recursively call the function adding things up as you go. Each call makes exactly one additionally call but only to a depth of n. Then it returns.</p>\n<p>So you have complexity of <code>O(n)</code>.</p>\n<hr />\n<p>But you can take this one step further. The fib algorithm can easily be implemented as <code>O(1)</code>.</p>\n<p>This is because fib quickly outstrips the size of an integer (even long long). You can easily pre-calulcate all the valid values that can be stored in a variable and put them in an array. Then simply return the value by looking up the result:</p>\n<pre><code>int fib(int n) {\n static const int fibValue[] = { ... };\n if (n < 0 || n > std::size(fibValue)) {\n // This is 47 for 32 bit ints\n // 93 for 64 bit ints\n throw "Result out of range"\n }\n return fibValue[n];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:14:18.140",
"Id": "492809",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/115066/discussion-on-answer-by-martin-york-a-fibonacci-series)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:34:33.720",
"Id": "250571",
"ParentId": "250566",
"Score": "6"
}
},
{
"body": "<p>Just to be explicit: You are <span class=\"math-container\">\\$O(n)\\$</span> in time <strong>and</strong> <span class=\"math-container\">\\$O(n)\\$</span> in memory. I don't believe you can easily do better in integer arithmetic (when actually calculating it) in time, but memory could be <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n<p>As has been pointed out by <a href=\"https://codereview.stackexchange.com/users/50567/peter-cordes\">Peter Cordes</a>, there is a "<a href=\"https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression\" rel=\"nofollow noreferrer\">Closed form</a>" for the Fibonacci sequence, which means that if you have a constant time infinite precision floating point system, you can achieve <span class=\"math-container\">\\$O(1)\\$</span>. Computer floating point can achieve an approximation, but I think you will get more accurate results with integer math.</p>\n<p>As also pointed out by <a href=\"https://codereview.stackexchange.com/users/50567/peter-cordes\">Peter Cordes</a>, there is a "<a href=\"https://stackoverflow.com/a/32685824\">Lucas sequence method</a>" that can do <span class=\"math-container\">\\$O(\\log{n})\\$</span> given integer multiplication and a fair bit more complexity.</p>\n<p>If you use your function iteratively to print the Fibonacci sequence, your time result would be <span class=\"math-container\">\\$O(n^2)\\$</span>, and that can be done in <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:44:55.657",
"Id": "492874",
"Score": "1",
"body": "There is a closed-form for the nth Fibonacci number, so it's O(1) (assuming fixed precision; otherwise with extended precision something like O(log10 Fib(n)) if the cost of operations scales with the number of digits.) https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression. More practically for an exact integer result, in log2(n) iterations using uint64_t multiply and add with this [C implementation of the Lucas sequence method](https://stackoverflow.com/a/32685824). Of course if you want to print *every* Fib(n), it's of course best to just go iterative"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:18:01.347",
"Id": "250595",
"ParentId": "250566",
"Score": "3"
}
},
{
"body": "<p>I'm not sure any of the answers have yet really addressed the complexity. I'm going to do that by transforming your algorithm into one that is simpler without changing the time complexity. This both proves the time complexity and also gives you a version of the algorithm that might be easier to read and reason about.</p>\n<p>Let's start with your solution</p>\n<pre><code>void fibonacci(int n,int n1,int n2)\n{\n if(n==0)\n {\n cout<<endl<<n1;\n return;\n }\n else if(n==1)\n {\n cout<<endl<<n2;\n return;\n }\n fibonacci(n-1,n2,n1+n2);\n return;\n}\n</code></pre>\n<p>The <code>else if</code> part isn't really needed, so let's delete that and also get rid of the superfluous <code>return</code> commands. [See the comments for discussion of why this step isn't quite as innocent as it seems.]</p>\n<pre><code>void fibonacci(int n,int n1,int n2)\n{\n if(n==0) {\n cout<<endl<<n1; }\n else { \n fibonacci(n-1,n2,n1+n2); }\n}\n</code></pre>\n<p>Reverse the <code>if</code>. Also I'm going to put back one of those <code>return</code>s and take the printing out of the <code>else</code> part.</p>\n<pre><code>void fibonacci(int n,int n1,int n2)\n{\n if(n!=0) {\n fibonacci(n-1,n2,n1+n2);\n return ; }\n cout<<endl<<n1;\n}\n</code></pre>\n<p>Apply tail recursion optimization --- i.e., replace the recursive call and the following return with a reassignment of the parameters and a jump to the start of the subroutine. This step will change the space complexity,* but not the time complexity.</p>\n<pre><code>void fibonacci(int n,int n1,int n2)\n{\n start: \n if(n!=0) {\n int sum = n1+n2 ;\n n1 = n2 ;\n n2 = sum ;\n n = n-1 ;\n goto start ; }\n out<<endl<<n1;\n}\n</code></pre>\n<p>Use a loop instead of a <code>goto</code>.</p>\n<pre><code>void fibonacci(int n,int n1,int n2)\n{\n while(n!=0) {\n int sum = n1+n2 ;\n n1 = n2 ;\n n2 = sum ;\n n = n-1 ; }\n cout<<endl<<n1;\n}\n</code></pre>\n<p>You don't really need the parameters to be parameters. I'd probably document the subroutine, so it's clear what it does. And I'd document the while loop with an invariant, so it's more clear how it works.</p>\n<pre><code>void fibonacci(int n)\n// Precondition: n >= 0\n// Postcondition: the value of fib(n) has been printed to standard out\n// preceded by an end of line.\n{\n int n1 = 0 ;\n int n2 = 1 ;\n // Let n0 be the original value if n.\n // invariant n1 == fib( n0-n ) and n1 == fib(n0-n+1) \n while(n!=0) {\n int sum = n1+n2 ;\n n1 = n2 ;\n n2 = sum ;\n n = n-1 ; }\n cout<<endl<<n1;\n}\n</code></pre>\n<p>(And also change the place where it's called, course.)</p>\n<p>At this point, it's clear (I think) that the algorithm is O(n). None of the transformations change the time complexity, so the time complexity of the original is also O(n).</p>\n<p>(*) That is, it will change the space complexity from O(n) to O(1) unless your compiler does tail-recursion optimization. If it does, the space complexity was O(1) from the start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:46:16.673",
"Id": "492818",
"Score": "0",
"body": "Unlike the original algorithm, this algorithm does one extra addition that it doesn't need to. This was introduced when the `else if` part was eliminated. That isn't a problem in C or C++ where overflow is ignored, but it would be a problem in languages where overflow causes an exception. You can fix this by changing the invariant to `n1 == fib(n0-n-1) and n2==fib(n0-n-1)` and printing `n2` instead of `n1`. The initializations change to `n1=0` and `n2=1`, since fib(-1) is 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:39:34.217",
"Id": "492871",
"Score": "1",
"body": "Signed integer overflow is Undefined Behaviour in C and C++! If running under `gcc -fsanitize=undefined`, that change might well be required to output the largest Fib(n) that fits in an `int`. If the C+ abstract machine encounters UB at any point during execution of a program, all bets are off for everything *before* and after that in this run of the program. In practice when compiling for most hardware, signed overflow that isn't visible at compile time won't actually be harmful, but it's very incorrect to say it \"isn't a problem\" in C++ as a pure language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:53:07.847",
"Id": "492879",
"Score": "0",
"body": "But other than that, +1, good explanation of transforming between tail-recursion and looping. The OP's code is like a standard iterative implementation, just using tail-recursion to loop. (And the printing is in the base-case, which is super weird vs. returning it.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:04:25.317",
"Id": "492998",
"Score": "0",
"body": "@PeterCordes You are correct -- the best kind of correct. Thanks for pointing that out. I can't believe that I forgot that int overflow is undefined behaviour in C and C++!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:25:17.680",
"Id": "250598",
"ParentId": "250566",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250598",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T02:58:59.980",
"Id": "250566",
"Score": "5",
"Tags": [
"c++",
"beginner",
"fibonacci-sequence"
],
"Title": "A Fibonacci series"
}
|
250566
|
<p>I am trying to write a function that would do what a <code>cd ..</code> would do. Basically get the parent of the given path.
eg:</p>
<blockquote>
<pre><code>C:\ --> C:\
C:\Users\xxx --> C:\Users
test1\test2\test4 --> test1\test2\
/var/etc/jpt --> /var/etc
</code></pre>
</blockquote>
<p>I have tested this in windows and linux. Here are the list of comments I have.</p>
<p>I am declaring <code>forward_slash</code> and <code>backward_slash</code> so that it would work on both win and linux. One might ask, what if there are other path delimeter? For now, lets just stick to these two delimeters. If I do not find any of the two delimiters, I just return the path itself.</p>
<p>I loop over the <code>dir_path</code> trying to find the first and second delimiter.</p>
<ul>
<li><p>I have to do -1 here <code>int index = dir_path.size()-1;</code> to avoid out of bound error.</p>
</li>
<li><p>If there is no delimiter found from first delimiter position (using <code>find_last_of</code>) then I return sub string from 0 to first delimiter position + 1. I have to +1 here because the for loop already moved the index by -1.</p>
</li>
<li><p>If there is any thing in between the two consecutive delimiter, I just return the sub string from 0 to second delimiter position.</p>
</li>
<li><p>I have to do the <code>if (second_delimeter_pos == std::string::npos)</code> first.</p>
</li>
</ul>
<p>The below code also has test paths.</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> generatePaths() {
std::vector<std::string> paths;
paths.emplace_back("C:\\Users\\xxxx\\\\");
paths.emplace_back("C:\\");
paths.emplace_back("C:");
paths.emplace_back("C:\\\\");
paths.emplace_back("C://");
paths.emplace_back("C:/");
paths.emplace_back("test\\test1\\tmp2");
paths.emplace_back("C:\\Users\\xxxxx\\projects\\\\\\play_ground\\\\\\");
paths.emplace_back("C:/Users/xxxxxx/projects/////play_ground////");
return paths;
}
std::string getParentDir(const std::string& dir_path) {
std::string forward_slash = "/";
std::string backward_slash = "\\";
std::string delimiter;
if (dir_path.find(forward_slash) != std::string::npos) {
delimiter = forward_slash;
}
else if (dir_path.find(backward_slash) != std::string::npos) {
delimiter = backward_slash;
}
else {
return dir_path;
}
std::string parent_path;
for (int index = dir_path.size()-1; index > 0 ; --index) {
int first_delimeter_pos = index;
size_t second_delimeter_pos = (int)dir_path.find_last_of(delimiter, first_delimeter_pos);
int diff = first_delimeter_pos - second_delimeter_pos;
if (second_delimeter_pos == std::string::npos) {
parent_path = dir_path.substr(0, first_delimeter_pos+1);
break;
}
if (diff > 1) {
parent_path = dir_path.substr(0, second_delimeter_pos);
break;
}
index -= diff;
}
return parent_path;
}
int main() {
std::vector<std::string> test_paths = generatePaths();
for (int i = 0; i < test_paths.size(); ++i) {
std::string my_dir = test_paths[i];
std::string parent_dir = getParentDir(my_dir);
std::cout << "dir = " << my_dir << " :: parent dir = " << parent_dir << std::endl;
}
}
</code></pre>
<p>Any suggestion, improvements and pitfall on design and algorithm is highly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:10:04.647",
"Id": "492739",
"Score": "2",
"body": "Welcome to Code Review. I have rolled back your lates edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>If you can use c++17 you can use the stl filesystem, this header contains faculties for performing operations on paths and files and would make your code simpler, for example the delimiter can be handled with the <code>std::filesystem::path</code> class.</p>\n<p>According to the documentation of <code>std::filesystem::path</code> a path can be normalized by following this algorithm:</p>\n<ul>\n<li>If the path is empty, stop (normal form of an empty path is an empty path)</li>\n<li>Replace each directory-separator (which may consist of multiple slashes) with a single <code>path::preferred_separator</code>.</li>\n<li>Replace each slash character in the root-name with <code>path::preferred_separator</code>.</li>\n<li>Remove each dot and any immediately following directory-separator.</li>\n<li>Remove each non-dot-dot filename immediately followed by a directory-separator and a dot-dot, along with any immediately following directory-separator.</li>\n<li>If there is root-directory, remove all dot-dots and any directory-separators immediately following them.</li>\n<li>If the last filename is dot-dot, remove any trailing directory-separator.</li>\n<li>If the path is empty, add a dot (normal form of ./ is .)</li>\n</ul>\n<p><a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\">Look here for more info</a></p>\n<p><strong>Unnecessary cast size_t to int</strong><br />\nYou cast the result of <code>find_last_of</code> to int and assign it to a <code>size_t</code> this while the result of <code>find_last_of</code> is of type <code>size_t</code>.</p>\n<p><strong>Prefer using '\\n' instead of <code>std::endl</code></strong><br />\nIt won't make a lot of difference in this particular case but it is\ngood to make it an habbit, <code>std::endl</code> will flush the output buffer each time what can be a performance hit.\n<a href=\"https://codeforces.com/blog/entry/43780\" rel=\"nofollow noreferrer\">See this for more</a></p>\n<p><strong>Use range based for loop</strong><br />\nBecause you don't need the index for anything else but accessing the item in the vector you can replace:<br />\n<code>for (int i = 0; i < test_paths.size(); ++i)</code></p>\n<p>with: <code>for(auto path : test_paths)</code>\nwhere <code>path</code> will then be the item at n index of the vector.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T08:30:32.433",
"Id": "492735",
"Score": "1",
"body": "I updated the code after you suggestion, converted everything to size_t. I will also look into the `std::filesystem::path`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T21:58:10.427",
"Id": "492845",
"Score": "0",
"body": "the for loop goes from test_paths.size() to 0 not the other way round."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T06:36:18.817",
"Id": "492890",
"Score": "0",
"body": "The one I used as example, that's copied from your source code does not go from test_paths.size() to zero but the other way around. You say `int i = 0; i < test_paths.size(); ++i;` this will increment `i`, not decrement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T06:32:15.853",
"Id": "250570",
"ParentId": "250569",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250570",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T04:23:02.647",
"Id": "250569",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"strings"
],
"Title": "Get parent path"
}
|
250569
|
<p>This is a follow-up to this question <a href="https://codereview.stackexchange.com/questions/250543/node-js-backend-login-logic/">Node.js backend login logic</a>. I wrote the following login Angular frontend logic for my Node.js Backend (see the previous question above). Is it any good in terms of security, efficiency, building, async/sync, logging? <strong>SECURITY is my main concern.</strong>
On in a prettier format the question would be:</p>
<ul>
<li><strong>SECURITY</strong>: Is my website secure in any way, shape, or form? I'm wondering if I could implement any security measures other than the ones that are built in to the methods provided by <code>Angular</code>. Isn't the transmission of the password in plaintext a security issue? What about XSS and similar troubles? Can't my login just simply be circumvented? That would be a critical mistake.</li>
<li><strong>EFFICIENCY</strong>: Is how I'm checking usernames and password efficient? Is there any better way to do this?</li>
<li><strong>BUILDING</strong>: Is how I loaded my website acceptable?</li>
<li><strong>ASYNC/SYNC</strong>: I know I preform <code>async</code> and <code>sync</code> calls at the same time. Is there any problem to this?</li>
<li><strong>LOGGING</strong>: I log all connections to the server, and all login attempts. Is this a good practice, or am I overdoing what logging is supposed to accomplish?</li>
<li><strong>MISC</strong>: Are there any mistakes in the play between the backend and frontend? If I forgot some other important points about the code I would be glad if you mentioned them as well
(Source: <a href="https://codereview.stackexchange.com/questions/223228/login-server-with-node-js">Login Server with Node.js</a>)</li>
</ul>
<p><strong>My code</strong>:</p>
<p>authentication.service.ts:</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { User } from '../models/user.model';
import { Router } from '@angular/router';
import { GlobalDataService } from './global-data.service';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
constructor(private http: HttpClient,
private router: Router, public DataService: GlobalDataService) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
this.LoggedIn = true;
}
public LoggedIn = true;
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
getRedirectUrl() {
throw new Error('Method not implemented.');
}
isUserLoggedIn() {
throw new Error('Method not implemented.');
}
login(email: string, password: string) {
return this.http.post<any>(`${environment.apiUrl}/api/login`, { email, password }, {withCredentials: true})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
// https://dev.to/rdegges/please-stop-using-local-storage-1i04
localStorage.setItem('currentUserToken', JSON.stringify(user));
this.currentUserSubject.next(user);
}
// set firstname & email of loggedin user
this.DataService.loggedinfirstname = user['firstname'];
this.DataService.loggedinemail = user['eMail'];
this.redirtoDashboard();
this.Toolbar();
this.DataService.prefillSenderData();
return user;
}));
}
redirtoDashboard() {
this.router.navigate(['order']);
}
Toolbar() {
this.LoggedIn = !this.LoggedIn;
}
}
</code></pre>
<p>login.component.ts:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AuthenticationService } from '../services/authentication.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
returnUrl: string;
loginForm: FormGroup;
submitted = false;
error = '';
loading = false;
public errorMsg = 'Please login to continue.';
public redirected: boolean;
public utm_source: string;
constructor(private router: Router, private formBuilder: FormBuilder,
private authenticationService: AuthenticationService, private activatedRoute: ActivatedRoute) {
if (this.authenticationService.currentUserValue) {
this.router.navigate(['order']);
}
this.activatedRoute.queryParams.subscribe(params => {
const param = params['utm_source'];
if (param === 'order' || param === 'work-document' || param === 'profile') {
this.redirected = true;
this.utm_source = param;
} else {
this.redirected = false;
}
});
}
ngOnInit(): void {
this.loginForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit(loginsubmit) {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return console.log('LoginForm Invalid');
}
this.loading = true;
this.authenticationService.login(this.f.email.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
if (this.redirected) {
this.router.navigate([this.utm_source]);
} else {
this.router.navigate(['order']);
}
},
error => {
console.log('Login->authservice->err: ', error);
this.error = error;
this.loading = false;
});
}
}
</code></pre>
<p>login.component.html:</p>
<pre><code><div class="container">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div class="card card-signin my-5">
<div class="card-body">
<h5 class="card-title text-center">Login</h5>
<br>
<form [formGroup]="loginForm" class="form-signin" (ngSubmit)="onSubmit(this.loginForm.value)">
<div class="form-label-group">
<input #userName formControlName="email" type="text" id="inputUser" class="form-control" placeholder="E-Mail" required autofocus [ngClass]="{ 'is-invalid': submitted && f.email.errors }">
<div *ngIf="submitted && f['email'].errors" class="invalid-feedback">
<div *ngIf="f['email'].errors.required">E-Mail is required</div>
</div>
</div>
<br>
<div class="form-label-group">
<input #password type="password" formControlName="password" id="inputPassword" class="form-control" placeholder="Password" required [ngClass]="{ 'is-invalid': submitted && f.password.errors }">
<div *ngIf="submitted && f['password'].errors" class="invalid-feedback">
<div *ngIf="f['password'].errors.required">Password is required</div>
</div>
</div>
<br>
<div *ngIf="redirected">
<mat-error>
<p class="alert alert-danger">
{{errorMsg}}
</p>
</mat-error>
</div>
<button [disabled]="!loginForm.valid" class="btn btn-dark btn-block" id="loginSubmit" type="submit">Login</button>
<div class="forgot-password-link">
<a routerLink="/forgot-password">Forgot password</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T21:09:17.660",
"Id": "493620",
"Score": "0",
"body": "In the AuthenticationService class the property `LoggedIn` is declared with default value `true`, and also the constructor sets that property to `true`... it appears to then be set to the negated value of itself in the `Toolbar()` method, called from the callback to `map()` within the `login` method... should it ever explicitly be set to `false` or is the negation within the `Toolbar` currently the only way to assign a value of `false` (other than outside access)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T10:51:52.587",
"Id": "493675",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ the variable `LoggedIn` is used to hide not to be shown elements from the navbar/toolbar using [hidden]."
}
] |
[
{
"body": "<h2>Preface</h2>\n<p>I used AngularJS a few years ago but didn't get into Angular2+ so my knowledge of it is slim-to-none. I do however have a fair amount of familiar with Javascript and various frameworks.</p>\n<h1>Question responses</h1>\n<blockquote>\n<p><strong>Security</strong> <em>Isn't the transmission of the password in plaintext a security issue?</em></p>\n</blockquote>\n<p>I found posts about this question on multiple SE sites. For example, I found <a href=\"https://security.stackexchange.com/q/110415\"><em>Is it ok to send plain-text password over HTTPS? [duplicate]</em></a>. To quote <a href=\"https://security.stackexchange.com/a/110418\">the accepted answer by Buffalo5ix</a>:</p>\n<blockquote>\n<p><em>It is standard practice to send "plaintext" passwords over HTTPS. The passwords are ultimately not plaintext, since the client-server communication is encrypted as per TLS.</em></p>\n</blockquote>\n<p>That question is marked as a duplicate of two other posts, including this one:\n<a href=\"https://security.stackexchange.com/q/7057\"><em>I just send username and password over https. Is this ok?</em></a>. It has two answers and <a href=\"https://security.stackexchange.com/a/7059\">the second answer by Steve</a> offers an option:</p>\n<blockquote>\n<p><em>One additional thing you could do would be to use client certificates. The server can only guarantee to itself that there is no MitM by requiring a client cert. Otherwise, he has to trust the client to properly validate the absence of a MitM. This is more than a lot of services should be willing to trust.</em></p>\n</blockquote>\n<p>I haven't heard of anyone doing that but perhaps it is done and we just don't know about it.</p>\n<p>There is even <a href=\"https://stackoverflow.com/q/962187/1575353\">a Stack Overflow question about the question</a>, with <a href=\"https://stackoverflow.com/a/962194/1575353\">the accepted answer</a> very similar to the accepted answer of the first question (from Security SE) mentioned above.</p>\n<blockquote>\n<p><strong>EFFICIENCY</strong> Is how I'm checking usernames and password efficient? Is there any better way to do this?</p>\n</blockquote>\n<p>I am not aware of any better way to do this, but I do notice these lines in <code>AuthenticationService.login()</code> that should be able to use dot notation:</p>\n<blockquote>\n<pre><code> this.DataService.loggedinfirstname = user['firstname'];\n this.DataService.loggedinemail = user['eMail'];\n</code></pre>\n</blockquote>\n<h3>Method name</h3>\n<p>I asked about the updating of the property <code>LoggedIn</code> and noted that it was set in the constructor and then modified in the method <code>Toolbar</code>. A name like <code>Toolbar</code> seems like it might be associated with fetching a toolbar. The other methods in that class have a verb - e.g. <em>login</em>, <em>redirtoDashboard</em>. A more appropriate method name for that method might be <code>ToggleLoggedIn</code> or something along those lines.</p>\n<h3>Simplifying OR conditions</h3>\n<p>This line in <code>LoginComponent::constructor()</code>:</p>\n<blockquote>\n<pre><code> if (param === 'order' || param === 'work-document' || param === 'profile') {\n</code></pre>\n</blockquote>\n<p>could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>Array.prototype.includes()</code></a> which does a strict comparison<sup><a href=\"https://masteringjs.io/tutorials/fundamentals/includes\" rel=\"nofollow noreferrer\">1</a></sup> <sup><a href=\"https://stackoverflow.com/q/47864358/1575353\">2</a></sup>:</p>\n<pre><code> if ([ 'order', 'work-document', 'profile'].includes(param)) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:54:23.080",
"Id": "493797",
"Score": "0",
"body": "If noone else gives a deeper analysis I will hand you the bounty tomorrow so it doesn't go to waste.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T09:56:09.387",
"Id": "493798",
"Score": "0",
"body": "P.S: does `includes(param)` do the same thing as a `==` or a `===`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:57:25.513",
"Id": "495210",
"Score": "0",
"body": "Perhaps you saw my edit but I forgot to add a comment- yes the `includes` method would do a strict comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:00:10.720",
"Id": "495211",
"Score": "0",
"body": "I see, thanks for the comment and answer. I was unaware of this `includes`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T05:27:58.373",
"Id": "250943",
"ParentId": "250574",
"Score": "2"
}
},
{
"body": "<p>Sorry I didn't took a look at your backend code, so this is just half a review.</p>\n<p>For your questions:</p>\n<ul>\n<li><p>Security<br />\nAs Sam already analyzed, there is no obvious problem on the frontend part (as long as you run with HTTPS). I expect that the password is hashed (with a salt) in the backend, and only the hash is stored in the database, so that nobody can extract the real passwords from the database.</p>\n</li>\n<li><p>Efficiency<br />\nYep, Validators is the way to go in Angular. It would be technically a bit more performant to use HTML Validation, but those fractals of milliseconds are definitely not worth to lose the flexibility of Validators.</p>\n</li>\n<li><p>Building</p>\n</li>\n<li><p>Async / Sync<br />\nThe problem with calling an async method without handling the result is, that you will not realize if something did not worked as expected. Thats okay if you know that the code that you are using was developed and maintained by a godlike developer who is above errors. If the developer is a human, you should always expect that there may be a problem. And if you call a method and you know that any problem there is NOT a problem for your code, then make it explicit in you code, so that the following developers (e.g. you in 3 months) will know that too. :-)</p>\n</li>\n<li><p>Logging<br />\nThe question is, what you intend with the logging. If you would like to monitor everything to get knowledge about your users, your infrastructure, etc etc, than thats fine. Okay, i would then use one of the existing frameworks to do that for me and not reinvent the wheel.<br />\nIf you are just interested in the bad things, then i would only log those (like failing login attempts).<br />\nSo as always, there is no "YES" or "NO". It depends on your intention.<br />\nAs a clarification <code>console.log</code> is not "logging" for me, because its only visible to the user and for him only if he has the console open.</p>\n</li>\n<li><p>MISC<br />\nSee the following</p>\n</li>\n</ul>\n<h1>Refactoring</h1>\n<p>I would like to first refactor the code a bit for readability. In my experience it makes it easier to spot mistakes. You can ignore it and skip to the interesting part if you want.</p>\n<p>In general i really like to use always <code>private</code>and <code>public</code> and be as restrictive as possible. It shows the reader that i thought about the scope of a method/variable. And it reduces the chance of misuse. If i am not sure, then i start with <code>private</code>.<br />\nIf nothing is used, its public by default. And as a reader then i do not know if the developer choose that by intention or just forgot it.</p>\n<h2>AuthenticationService</h2>\n<p><code>LoggedIn</code> is set to true at definition time (<code>public LoggedIn = true</code>) and again in the constructor. I personally prefere the assignment of the initial value at definition time. Also this value is used as "true means not logged in". Thats irritating, therefore i would change the name to <code>isLogedIn</code> and initialize it with false.</p>\n<p><code>DataService</code> is public but seems not be used outside the class.</p>\n<p>I don't like constant strings in my code, so i extract them into constants. Like<br />\n<code>private loginUrl: string = `${environment.apiUrl}/api/login`;</code></p>\n<p>I like to use "speaking" RxJs Operators. The <code>map</code>Method in <code>login</code> does not change the stream, therefor i would use <code>tap</code>instead. That makes it obvious that there is only a side effect.`Also we then could skip the <code>return</code> line.</p>\n<p>I like speedreading code. Therefor, if i can extract some lines of code into a speaking method, i am doing that, because then i only have to read the methodname, not all the code behind it and can decide if i would like to dive deeper or just continue.<br />\nTherefor i would change the code in the <code>map</code>of the <code>login</code> method a bit.</p>\n<p>Also it seems that the "Toolbar" method is only used to change the <code>LogedIn</code>status once. So we could just set the value, without a toggle.<br />\nThere is also an issue here (see later in the issue chapter), therefor i will move the call of that functionality into the if statement.</p>\n<p>Normally the redirect is the last thing that should happen, therefor i move it to the end of the tap</p>\n<pre><code>export class AuthenticationService {\n public isLoggedIn = false;\n public currentUser: Observable<User>\n\n public get currentUserValue(): User {\n return this.currentUserSubject.value;\n } \n \n private currentUserSubject: BehaviorSubject<User> = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));\n private loginUrl: string = `${environment.apiUrl}/api/login`;\n\n constructor(private DataService: GlobalDataService,\n private http: HttpClient,\n private router: Router) {\n this.currentUser = this.currentUserSubject.asObservable();\n }\n \n private getRedirectUrl() {\n throw new Error('Method not implemented.');\n }\n \n private isUserLoggedIn() {\n throw new Error('Method not implemented.');\n }\n\n public login(email: string, password: string):Observable<User> {\n return this.http.post<User>(loginUrl, { email, password }, {withCredentials: true})\n .pipe(\n tap(user => {\n // login successful if there's a jwt token in the response\n if (this.isLoginSuccessful(user)) {\n this.setLogedInUser(user);\n this.isLoggedIn = true;\n }\n this.setDataServiceForUser(user); \n this.toggleLoginStatus();\n this.redirectToDashboard();\n })\n );\n }\n\n private isLoginSuccessful(user:User):boolean{\n return user && user.token;\n }\n\n private redirectToDashboard():void {\n this.router.navigate(['order']);\n }\n\n private setLogedInUser(user: User):void{\n // store user details and jwt token in local storage to keep user logged in between page refreshes\n // https://dev.to/rdegges/please-stop-using-local-storage-1i04\n localStorage.setItem('currentUserToken', JSON.stringify(user));\n this.currentUserSubject.next(user);\n }\n\n private setDataServiceForUser(user:User):void{\n // set firstname & email of loggedin user\n this.DataService.loggedinfirstname = user['firstname'];\n this.DataService.loggedinemail = user['eMail'];\n this.DataService.prefillSenderData();\n }\n}\n</code></pre>\n<h2>LoginComponent</h2>\n<p>In <code>onSubmit</code>you do not need a <code>first()</code>. Behind <code>this.authenticationService.login</code> is a http request. And those terminate automatically after the first result. Because of the same reason you do not need to unsubscribe those subscriptions.</p>\n<h1>Issues</h1>\n<h2>AuthenticationService</h2>\n<p>In the <code>login</code>method it seems that even in the case of a not successful login (no user or no token information), it still tries to send data into the <code>DataService</code> and does stuff. Here i would very clearly separate those things that should ALWAYS happen after a login attempt, and those that only may happen after a successful login.<br />\nSpecifically `currently it will change <code>LogedIn</code>even if the login was not successful.</p>\n<h2>LoginComponent</h2>\n<h1>Best Practices</h1>\n<p>Here some Best Practices (at least in my eyes :-) )</p>\n<p>In the code, the User Information is used for two things. For detailed information about the user and secondly as an implicit "the user is logged in". In the AuthentificationService this connection is valid. But to the outside, i would provide User-Information and additionally a "isLogedIn" information. In that way, a developer don't have to "know" that userinformation implies that a user is logged in.</p>\n<p>It's a good habit to unsubscribe, when you leave the component. Therefor I normally do something like this</p>\n<pre><code>private subscriptions: Subscription() = new Subscription();\n...\nthis.subscriptions.add(\n sourceA.subscribe(...)\n)\nthis.subscriptions.add(\n sourceB.subscribe(...)\n)\n\nngOnDestroy(){\n this.subscriptions.unsubcribe();\n}\n</code></pre>\n<p>That way, as soon as the component gets destroyed, those subscriptions all get automatically unsubscribed. Be aware, a component gets only destroyed if its completely removed from the DOM. If it's hidden, then it's still alive.</p>\n<p>I hope one or two things were helpful for you.</p>\n<p>warm regards</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T13:07:20.817",
"Id": "493815",
"Score": "0",
"body": "No need to apologize, because the backend code was already reviewed by other SE members :-) You seem to have to put together the most descriptive answer so you will get a bounty unless somehow someone magically manages to outperform your code analysis"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:38:42.657",
"Id": "497871",
"Score": "0",
"body": "loginUrl requires `this.loginUrl` AFAIK. Also, I tried commenting the localStorage logic out (since it's not the best practice) and I'm not sure whether I did the right thing. Also, if I add `public login(email: string, password: string):User` I get the error `Type 'Observable<any>' is missing the following properties from type 'User': _id, loginId, lastname, firstname, and 2 more.` I as well get the error `Type 'string' is not assignable to type 'boolean'.` at the function `private isLoginSuccessful(user:User):boolean{\n return user && user.token;\n }`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T10:13:05.697",
"Id": "497872",
"Score": "0",
"body": "also my linter complains about the string literals, even though you and Sam recommended me to use those..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T06:55:37.563",
"Id": "498010",
"Score": "0",
"body": "In my example the return type of the methods was set (''public login(....):User {...}''). Now it is checked if the value you return fits to the type. In the login it expects \"User\" but delivers an \"Observable<any>\" from the post. My Fault. Make the return type \"Observable<User>\" and the POST call \"return this.http.post<User>( ...)\"\nI changed the code accordingly"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T12:35:31.290",
"Id": "250956",
"ParentId": "250574",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250956",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:09:04.687",
"Id": "250574",
"Score": "4",
"Tags": [
"javascript",
"security",
"authentication",
"typescript",
"angular-2+"
],
"Title": "Angular Frontend login logic"
}
|
250574
|
<p>I just completed level 2 of The Python Challenge on pythonchallenge.com and I am in the process of learning python so please bear with me and any silly mistakes I may have made.</p>
<p>I am looking for some feedback about what I could have done better in my code. Two areas specifically:</p>
<ul>
<li>How could I have more easily identified the comment section of the HTML file? I used a beat-around-the-bush method that kind of found the end of the comment (or the beginning technically but it is counting from the end) and gave me some extra characters that I was able to recognize and anticipated (the extra "-->" and "-"). What condition would have better found this comment so I could put it in a new string to be counted?</li>
</ul>
<p>This is what I wrote:</p>
<pre><code>from collections import Counter
import requests
page = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')
pagetext = ""
pagetext = (page.text)
#find out what number we are going back to
i = 1
x = 4
testchar = ""
testcharstring = ""
while x == 4:
testcharstring = pagetext[-i:]
testchar = testcharstring[0]
if testchar == "-":
testcharstring = pagetext[-(i+1)]
testchar = testcharstring[0]
if testchar == "-":
testcharstring = pagetext[-(i+2)]
testchar = testcharstring[0]
if testchar == "!":
testcharstring = pagetext[-(i+3)]
testchar = testcharstring[0]
if testchar == "<":
x = 3
else:
i += 1
x = 4
else:
i += 1
x = 4
else:
i += 1
print(i)
newstring = pagetext[-i:]
charcount = Counter(newstring)
print(charcount)
</code></pre>
<p>And this is the source HTML:</p>
<pre><code><html>
<head>
<title>ocr</title>
<link rel="stylesheet" type="text/css" href="../style.css">
</head>
<body>
<center><img src="ocr.jpg">
<br><font color="#c03000">
recognize the characters. maybe they are in the book, <br>but MAYBE they
are in the page source.</center>
<br>
<br>
<br>
<font size="-1" color="gold">
General tips:
<li>Use the hints. They are helpful, most of the times.</li>
<li>Investigate the data given to you.</li>
<li>Avoid looking for spoilers.</li>
<br>
Forums: <a href="http://www.pythonchallenge.com/forums"/>Python Challenge Forums</a>,
read before you post.
<br>
IRC: irc.freenode.net #pythonchallenge
<br><br>
To see the solutions to the previous level, replace pc with pcc, i.e. go
to: http://www.pythonchallenge.com/pcc/def/ocr.html
</body>
</html>
<!--
find rare characters in the mess below:
-->
<!--
</code></pre>
<p>Followed by thousands of characters and the comment concludes with '-->'</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T12:12:20.960",
"Id": "492754",
"Score": "2",
"body": "use HTML parser (eg. BeautifulSoup), which allows you to find nodes that are comments: https://stackoverflow.com/a/33139458/217723"
}
] |
[
{
"body": "<p>I don’t have enough reputation to comment, so I must say this in an answer.\nIt looks clunky to use</p>\n<pre><code> while x == 4:\n</code></pre>\n<p>and then do</p>\n<pre><code> x = 3\n</code></pre>\n<p>whenever you want to break out of the loop.\nIt looks better to do</p>\n<pre><code> while True:\n</code></pre>\n<p>and when you want to break out of the loop do</p>\n<pre><code> break\n</code></pre>\n<p>Cheers!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:54:33.187",
"Id": "492786",
"Score": "2",
"body": "Welcome to CodeReview, you will fit right in ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:26:36.473",
"Id": "492790",
"Score": "0",
"body": "Thx man. I appreciate it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T13:36:48.477",
"Id": "250580",
"ParentId": "250575",
"Score": "2"
}
},
{
"body": "<h1>Redundant Code</h1>\n<pre><code>pagetext = ""\npagetext = (page.text)\n</code></pre>\n<p>The first line assigns an empty string to <code>pagetext</code>. The second line ignores the contents already in <code>pagetext</code> and assigns a different value to the variable.</p>\n<p>Why bother with the first statement? It simply makes the code longer, slower, and harder to understand.</p>\n<p>Why bother with the <code>(...)</code> around <code>page.text</code>? They also are not serving any purpose.</p>\n<h1>Variable Names</h1>\n<p>Variables like <code>i</code> are a double-edged sword. You're using it as a loop index, and then you're using it to reference a found location after the loop terminates. But <code>i</code> by itself doesn't have much meaning. <code>posn</code> might be clearer. <code>last_comment_posn</code> would be much clearer, though very verbose.</p>\n<p>PEP-8 recommends using underscores to separate words in variable names: ie, use <code>char_count</code> not <code>charcount</code> etc.</p>\n<h1>Searching for a string of characters</h1>\n<p>Python strings have built-in functions for searching for a substring in a larger string. For instance, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.find\" rel=\"nofollow noreferrer\"><code>str.find</code></a> could rapidly find the first occurrence of <code><!--</code> in the page text.</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = pagetext.find("<!--")\n</code></pre>\n<p>But you're not looking for the first one; you're looking for the last one. Python again has you covered, with the reverse find function: <a href=\"https://docs.python.org/3/library/stdtypes.html#str.rfind\" rel=\"nofollow noreferrer\"><code>str.rfind</code></a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = pagetext.rfind("<!--")\n</code></pre>\n<p>But this still finds the index of the last occurrence. You want the characters after the comment marker, so we need to skip forward 4 additional characters:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if i >= 0:\n newstring = pagetext[i+4:]\n</code></pre>\n<h1>Improved code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import requests\nfrom collections import Counter\n\npage = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')\npage.raise_for_status() # Crash if the request didn't succeed\npage_text = page.text\n\nposn = page_text.rfind("<!--")\nprint(posn)\n\nif posn >= 0:\n comment_text = page_text[posn+4:] # Fix! This is to end of string, not end of comment!\n char_count = Counter(comment_text)\n print(char_count)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:51:30.657",
"Id": "250620",
"ParentId": "250575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:32:33.280",
"Id": "250575",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"parsing"
],
"Title": "Counting Characters from an HTML File with Python"
}
|
250575
|
<p>Recently I implemented the algorithm, that can find all the patterns which may contain "?" as "any character". For example, if the text is "abracadabra" and the pattern is "a?a", then my algorithm finds patterns like "aca" and "ada". For that purpose, I was using the Aho-Corasick algorithm for "subtemplates" detection, and it worked out. Nevertheless, I wanted to use some c++17 techniques to make my code modern. But I am afraid that I could kind of misuse some of them. Could you give me some suggestions on my code?</p>
<p>P.S. I try to stick to Google codestyle</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <vector>
#include <memory>
class TemplateFinder {
private:
/* Trie node */
struct Node {
bool terminal_ = false;
size_t word_size_ = 0;
char parent_char_ = 0;
std::shared_ptr<Node> parent_;
std::shared_ptr<Node> suffix_;
std::shared_ptr<Node> shrink_suffix_;
std::vector<size_t> word_bias_; //Subtemplate bias. Subtemplates can be repeated -> several biases
std::unordered_map<char, std::shared_ptr<Node>> transitions_;
std::unordered_map<char, std::shared_ptr<Node>> delta_function_;
};
size_t subpattern_count_ = 0;
size_t pattern_size_;
std::shared_ptr<Node> root_;
char splitter_;
void AddSubTemplate(const std::string& subtemplate, size_t word_bias);
void ProcessShrunk(const std::shared_ptr<Node>& current_p, size_t char_pos, std::vector<size_t>& pattern_entries);
std::shared_ptr<Node> GetSuffix(const std::shared_ptr<Node>& current_p);
std::shared_ptr<Node> GoDelta(const std::shared_ptr<Node>& current_p, char c);
std::shared_ptr<Node> GetShrunkSuffix(const std::shared_ptr<Node>& current_p);
static void UpdateEntries(const std::shared_ptr<Node>& current_p, size_t char_position,
std::vector<size_t>& pattern_entries);
static auto Split(const std::string& text, char splitter)
-> std::pair<std::vector<std::string>, std::vector<size_t>>;
public:
explicit TemplateFinder(const std::string& pattern, char splitter);
template<typename OutputIterator>
void FindEntries(const std::string& text, OutputIterator& out);
};
/* Adding subtemplate to trie */
void TemplateFinder::AddSubTemplate(const std::string &subtemplate, size_t word_bias) {
auto p_current = root_;
for (char c : subtemplate) {
if (p_current->transitions_.find(c) == p_current->transitions_.end()) {
p_current->transitions_[c] = std::make_shared<Node>();
p_current->transitions_[c]->parent_ = p_current;
p_current->transitions_[c]->parent_char_ = c;
}
p_current = p_current->transitions_[c];
}
p_current->terminal_ = true;
p_current->word_bias_.push_back(word_bias);
p_current->word_size_ = subtemplate.size();
++subpattern_count_;
}
TemplateFinder::TemplateFinder(const std::string& pattern, char splitter) : pattern_size_(pattern.size()),
splitter_(splitter) {
root_ = std::make_shared<Node>();
auto [split_text, bias] = Split(pattern, splitter_);
for (size_t i = 0; i < split_text.size(); ++i) {
AddSubTemplate(split_text[i], bias[i]);
}
}
/* Splitting the template to subtemplates */
auto TemplateFinder::Split(const std::string &text, char splitter)
-> std::pair<std::vector<std::string>, std::vector<size_t>>
{
std::vector<std::string> split_text;
std::vector<size_t> bias; //Position of subtemplates in the template
std::string buffer;
size_t counter = 0;
for (char c : text) {
if (c == splitter && !buffer.empty()) {
bias.push_back(counter - buffer.size());
split_text.push_back(buffer);
buffer = "";
} else if (c != splitter) {
buffer += c;
}
++counter;
}
if (!buffer.empty()) {
bias.push_back(counter - buffer.size());
split_text.push_back(buffer);
}
return std::make_pair(split_text, bias);
}
/* Getting suffix link of the node */
auto TemplateFinder::GetSuffix(const std::shared_ptr<Node>& current_p)
-> std::shared_ptr<Node>
{
if (!current_p->suffix_) {
if (current_p == root_ || current_p->parent_ == root_) {
current_p->suffix_ = root_;
} else {
current_p->suffix_ = GoDelta(GetSuffix(current_p->parent_), current_p->parent_char_);
}
}
return current_p->suffix_;
}
/* Delta function of automata */
auto TemplateFinder::GoDelta(const std::shared_ptr<Node>& current_p, char c)
-> std::shared_ptr<Node>
{
if (current_p->delta_function_.find(c) == current_p->delta_function_.end()) {
if (current_p->transitions_.find(c) != current_p->transitions_.end()) {
current_p->delta_function_[c] = current_p->transitions_[c];
} else if (current_p == root_) {
current_p->delta_function_[c] = root_;
} else {
current_p->delta_function_[c] = GoDelta(GetSuffix(current_p), c);
}
}
return current_p->delta_function_[c];
}
/* Getting shrunk suffix link of the node */
auto TemplateFinder::GetShrunkSuffix(const std::shared_ptr<Node>& current_p)
-> std::shared_ptr<Node>
{
if (!current_p->shrink_suffix_) {
std::shared_ptr<Node> suffix_link = GetSuffix(current_p);
if (suffix_link->terminal_) {
current_p->shrink_suffix_ = suffix_link;
} else if (suffix_link == root_) {
current_p->shrink_suffix_ = root_;
} else {
current_p->shrink_suffix_ = GetShrunkSuffix(suffix_link);
}
}
return current_p->shrink_suffix_;
}
/* Main algorithm function - finding pattern in the text */
template<typename OutputIterator>
void TemplateFinder::FindEntries(const std::string &text, OutputIterator& out) {
std::shared_ptr<Node> current_p = root_;
std::vector<size_t> pattern_entries(text.size());
for (size_t char_pos = 0; char_pos < text.size(); ++char_pos) {
current_p = GoDelta(current_p, text[char_pos]);
ProcessShrunk(current_p, char_pos, pattern_entries);
if (current_p->terminal_) {
UpdateEntries(current_p, char_pos, pattern_entries);
}
}
for (size_t char_pos = 0; char_pos < pattern_entries.size(); ++char_pos) {
if (pattern_entries[char_pos] == subpattern_count_ && char_pos + pattern_size_ < text.size() + 1) {
*out = char_pos;
++out;
}
}
}
/* Shrunk suffix traversal */
auto TemplateFinder::ProcessShrunk(const std::shared_ptr<Node>& current_p, size_t char_pos,
std::vector<size_t> &pattern_entries) -> void
{
for (auto shrunk_p = GetShrunkSuffix(current_p); shrunk_p != root_; shrunk_p = GetShrunkSuffix(shrunk_p)) {
UpdateEntries(shrunk_p, char_pos, pattern_entries);
}
}
auto TemplateFinder::UpdateEntries(const std::shared_ptr<Node> &current_p, size_t char_pos,
std::vector<size_t> &pattern_entries) -> void
{
auto update_entries = [current_p, char_pos, &pattern_entries](size_t bias) {
auto pattern_pos = static_cast<int64_t>(char_pos - bias - current_p->word_size_ + 1);
if (pattern_pos >= 0 && pattern_pos < static_cast<int64_t>(pattern_entries.size())) {
++pattern_entries[static_cast<size_t>(pattern_pos)];
}
};
std::for_each(current_p->word_bias_.begin(), current_p->word_bias_.end(), update_entries);
}
int main() {
std::string text_template;
std::string text;
std::cin >> text_template >> text;
TemplateFinder finder(text_template, '?');
auto out_iter = std::ostream_iterator<size_t>(std::cout, " ");
finder.FindEntries(text, out_iter);
std::cout << std::endl;
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T08:25:42.147",
"Id": "493465",
"Score": "0",
"body": "Please don't vandalize your post by removing most of the code after receiving answers."
}
] |
[
{
"body": "<h1>Trailing return types</h1>\n<p>Your use of trailing return types looks very inconsistent. Looking at the Google C++ Style Guide, it seems that they recommend using them if leading return types are "impractical or much less readable". That is of course a matter of taste then, but I would recommend being as consistent as possible: first, use the same type of leading/trailing return type in the declaration of a function as in the definition of the function. Second, if the return type is so unwieldly you have to use the trailing style, perhaps it is better to create a type alias for it. For example:</p>\n<pre><code>using SubTemplateList = std::pair<std::vector<std::string>, std::vector<size_t>>;\n\nstatic SubTemplateList Split(const std::string& text, char splitter);\n</code></pre>\n<h1>Pair of vectors vs. vector of pairs</h1>\n<p><code>TemplateFinder::Split()</code> returns a pair of vectors, but the entries in each vector always match up. So it makes more sense to return a vector of pairs:</p>\n<pre><code>using SubTemplateList = std::vector<std::pair<std::string, size_t>>;\n...\nSubTemplateList TemplateFinder::Split(const std::string &text, char splitter)\n{\n SubTemplateList result;\n ...\n result.push_back({buffer, counter - buffer.size()});\n ...\n return result;\n}\n</code></pre>\n<p>This will simplify some users of this vector as well.</p>\n<h1>Avoid unnecessary temporary storage</h1>\n<p><code>Split()</code> is only called once in the constructor, and the results are used to call <code>AddSubtemplate()</code>. This will waste memory by first creating the temporary vector. You could solve this in several ways. First, you could merge <code>Split()</code> into the constructor, since apart from allocating the root node, that's basically the only thing the constructor does. If you want to keep <code>Split()</code> a separate function, then have it take a callback parameter that is called for each subtemplate it finds, kind of like how <code>FindEntries()</code> takes an output iterator as an argument.</p>\n<h1>Smart pointers</h1>\n<p>I see you only use <code>std::shared_ptr</code> in your code. However, this is doing reference counting, which has an impact on performance. You should only use it if you are really need it. You should use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> instead of you only need an owning pointer, and you can use bare pointers for non-owning pointers to object you know will not be deleted before the last use of that non-owning pointer.</p>\n<p>For example, a <code>Node</code> has child pointers that it owns, so it should use <code>std::unique_ptr</code> for those, but the parent of a <code>Node</code> will always outlive its children, so you can use a bare pointer for <code>parent_</code>:</p>\n<pre><code>struct Node {\n ...\n Node *parent_;\n Node *suffix_;\n Node *shrink_suffix_;\n\n std::unordered_map<char, std::unique_ptr<Node>> transitions_;\n std::unordered_map<char, Node *> delta_function_;\n};\n</code></pre>\n<p>The member variable <code>root_</code> doesn't even have to be a pointer at all, it could just be a <code>Node</code> value. But for consistency with the other allocated nodes, you could use a <code>std::unique_ptr</code> here. Note that you can use member value initialization:</p>\n<pre><code>std::unique_ptr<Node> root_ = std::make_unique<Node>();\n</code></pre>\n<p>Note that once you use <code>std::unique_ptr</code>, you shouldn't write code like this anymore:</p>\n<pre><code>auto p_current = root_;\n</code></pre>\n<p>This will actually steal the memory from <code>root_</code>. Since you just want to get the pointer, write:</p>\n<pre><code>auto p_current = root_.get();\n</code></pre>\n<p>Virtually all uses of <code>std::shared_ptr</code> in your code can be replaced with bare pointers, except for the owning pointers <code>root_</code> and <code>Node::transitions_</code>.</p>\n<h1>Consider adding member functions to <code>struct Node</code></h1>\n<p>There are operations you do on <code>Node</code>s that could be made member functions of <code>struct Node</code>. For example:</p>\n<pre><code>struct Node\n{\n ...\n Node(Node *parent, char parent_char): parent_(parent), parent_char_(parent_char) {}\n\n Node *GetTransition(char c) {\n if (transitions_.find(c) == transitions_.end()) {\n transitions_[c] = std::make_unique<Node>(this, c);\n }\n\n return transitions_[c].get();\n }\n};\n</code></pre>\n<p>And then use it like this:</p>\n<pre><code>void TemplateFinder::AddSubTemplate(const std::string &subtemplate, size_t word_bias) {\n ...\n for (char c : subtemplate) {\n p_current = p_current->GetTransition(c);\n }\n ...\n}\n</code></pre>\n<h1>Be careful when casting integers between signed and unsigned</h1>\n<p>I see this code:</p>\n<pre><code>auto pattern_pos = static_cast<int64_t>(char_pos - bias - current_p->word_size_ + 1);\nif (pattern_pos >= 0 && pattern_pos < static_cast<int64_t>(pattern_entries.size())) {\n ...\n}\n</code></pre>\n<p>This will work correctly on 64-bit architectures, but what about 32-bit ones where <code>size_t</code> is actually a <code>uint32_t</code>? You could use <code>ssize_t</code> or <code>ptrdiff_t</code> here, but perhaps better is to just avoid the need to cast altogether:</p>\n<pre><code>if (char_pos > bias + current_p->word_size) {\n size_t pattern_pos = char_pos - bias - current_p->word_size_ + 1;\n if (pattern_pos < pattern_entries.size()) {\n ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:37:45.517",
"Id": "492912",
"Score": "0",
"body": "Wow, really great suggestions, thanks so much for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T21:03:08.717",
"Id": "250615",
"ParentId": "250576",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250615",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T09:34:17.207",
"Id": "250576",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"c++17"
],
"Title": "Aho-Corasick C++17 implementation"
}
|
250576
|
<p>I've been playing with COM lately and while getting to understand the mechanism of how class methods/properties are called an idea came to mind: what if we can have a global instance of a class that exposes a Factory for creating new instances of that class but the Initializer method is Private. Is that possible? The answer is YES. We can make use of the <code>Me</code> special variable to find and replace the instance pointer so that we can redirect calls to the desired instance.</p>
<p>Consider <code>Class1</code> which has the <code>VB_PredeclaredId</code> set to True:</p>
<pre><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Class1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'@PredeclaredId
Option Explicit
#If Mac Then
#If VBA7 Then
Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr
#Else
Private Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long
#End If
#Else 'Windows
'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
#If VBA7 Then
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
#Else
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
#End If
#End If
#If Win64 Then
Private Const PTR_SIZE As Long = 8
#Else
Private Const PTR_SIZE As Long = 4
#End If
Private m_name As String
Private m_id As Long
Public Function Factory(ByVal newName As String, ByVal newID As Long) As Class1
Dim newClass1 As Class1
Set newClass1 = New Class1
'
#If VBA7 Then
Dim mePtr As LongPtr
Dim swapAddr As LongPtr
#Else
Dim mePtr As Long
Dim swapAddr As Long
#End If
'
'Find the address where the swap must happen
'Note we cannot save ObjPtr(Me) to a variable because
' we could get the position of that variable instead
swapAddr = VarPtr(Me)
Do
swapAddr = swapAddr + PTR_SIZE
CopyMemory mePtr, ByVal swapAddr, PTR_SIZE
Loop Until mePtr = ObjPtr(Me)
'Debug.Print swapAddr - VarPtr(Me) '56 on x64 and 168 on x32
'
CopyMemory ByVal swapAddr, ObjPtr(newClass1), PTR_SIZE
Init newName, newID
CopyMemory ByVal swapAddr, mePtr, PTR_SIZE
'
Set Factory = newClass1
End Function
Private Sub Init(ByVal newName As String, ByVal newID As Long)
m_name = newName
m_id = newID
End Sub
Public Property Get Name() As String
Name = m_name
End Property
Public Property Get ID() As Long
ID = m_id
End Property
</code></pre>
<p>Now we could create and use new instances like this:</p>
<pre><code>Sub TestFactory()
With Class1.Factory("Test", 4)
Debug.Print .Name
Debug.Print .ID
End With
End Sub
</code></pre>
<p>even if the <code>Init</code> method is <code>Private</code>.</p>
<p>I don't really understand why the offset is 56 bytes on x64 and 168 bytes on x32 (at least on my computers). Would be nice if somebody could figure this out so that the loop used in finding the swap address is not needed anymore.</p>
<hr />
<p><strong>EDIT 1</strong></p>
<p>Apparently on x64 it is sufficient to get the swap address like this:</p>
<pre><code> #If Win64 Then
swapAddr = VarPtr(Factory) + PTR_SIZE
mePtr = ObjPtr(Me)
#End If
</code></pre>
<p>so no loop would be needed.</p>
<p><strong>Edit 2</strong></p>
<p>I've decided to create a new follow-up question with a new improved code, instead of answering this question because the code here is slower and less safer. Go to: <a href="https://codereview.stackexchange.com/questions/253233/private-vba-class-initializer-called-from-factory-2">Private VBA Class Initializer called from Factory #2</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T12:43:35.653",
"Id": "492757",
"Score": "0",
"body": "That's pretty nifty, it basically eliminates the need for a separate get-only interface (and lets you have the class' default interface the way you want/need it, which is awesome)... on the other hand I feel like that little chunk of logic needs to be encapsulated into its own class, so it can be easily reused in any class that needs it (should be possible, by passing the necessary pointers). Good job!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:29:33.577",
"Id": "492777",
"Score": "0",
"body": "@MathieuGuindon Thanks Matt! I need to figure out a simpler process for x32 and then I will post a solution in a separate module. I suspect it has to do with the calling convention difference between x32 and x64."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:31:41.110",
"Id": "492793",
"Score": "0",
"body": "Very very interesting. I would really like to see this as a Compare method where you can compare private variables of two instances of a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:19:17.223",
"Id": "492810",
"Score": "0",
"body": "Ha, moving the functionality elsewhere is tricky, because now you need a data structure (dictionary?) to pass the initializer values around... and it doesn't get any simpler from there (passing the values is easy... retrieving them by name... gets very clunky and stringly-typed, very fast. Ugh!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:34:53.470",
"Id": "492911",
"Score": "0",
"body": "@TinMan This is a nice idea. This way there is no need to replicate the factory method signature inside the Init method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T14:26:19.387",
"Id": "499426",
"Score": "0",
"body": "@MathieuGuindon I would be grateful if you could review the follow-up question: [Private VBA Class Initializer called from Factory #2](https://codereview.stackexchange.com/questions/253233/private-vba-class-initializer-called-from-factory-2)"
}
] |
[
{
"body": "<p>This is not so much an review but a variation of the OP's technique. As Mathieu Guindon mentioned in the comments the "logic needs to be encapsulated". My Caster class does just that. The Person class is just for testing.</p>\n<h2>Caster:Class</h2>\n<pre><code>Attribute VB_Name = "Caster"\nOption Explicit\n\n#If Mac Then\n #If VBA7 Then\n Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr\n #Else\n Private Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long\n #End If\n#Else 'Windows\n 'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx\n #If VBA7 Then\n Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)\n #Else\n Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)\n #End If\n#End If\n\n#If Win64 Then\n Private Const PTR_SIZE As Long = 8\n#Else\n Private Const PTR_SIZE As Long = 4\n#End If\n\n#If VBA7 Then\n Private SourcePointer As LongPtr\n Private DestinationPointer As LongPtr\n#Else\n Private SourcePointer As Long\n Private DestinationPointer As Long\n#End If\n\nPublic Sub SaveAs(ByRef Source As Object, ByRef Destination As Object)\n DestinationPointer = VarPtr(Source)\n Do\n DestinationPointer = DestinationPointer + PTR_SIZE\n CopyMemory SourcePointer, ByVal DestinationPointer, PTR_SIZE\n Loop Until SourcePointer = ObjPtr(Source)\n\n CopyMemory ByVal DestinationPointer, ObjPtr(Destination), PTR_SIZE\nEnd Sub\n\nPublic Sub Restore()\n CopyMemory ByVal DestinationPointer, SourcePointer, PTR_SIZE\nEnd Sub\n</code></pre>\n<h2>Person:Class</h2>\n<p>Note: The Init method is just to demonstrate the OP's original concept. It could be replaced with <code> m = t</code>.</p>\n<pre><code>Attribute VB_Name = "Person"\nAttribute VB_PredeclaredId = True\n\nOption Explicit\n\nPrivate Type Members\n DOB As Date\n Name As String\n Sex As String\nEnd Type\n\nPrivate this As Members\n\nPublic Function Factory(pDOB As Date, pName As String, pSex As String) As Person\n DOB = pDOB\n Name = pName\n Sex = pSex\n Set Factory = Clone\nEnd Function\n\nPublic Function Clone() As Person\n Dim Object As Person\n Set Object = New Person\n\n Dim Caster As New Caster\n \n Dim t As Members\n t = this\n Caster.SaveAs Me, Object\n Init t\n Caster.Restore\n Set Clone = Object\nEnd Function\n\nPrivate Sub Init(t As Members)\n this = t\nEnd Sub\n\nPublic Property Get DOB() As Date\n\n DOB = this.DOB\n\nEnd Property\n\nPublic Property Let DOB(ByVal Value As Date)\n\n this.DOB = Value\n\nEnd Property\n\nPublic Property Get Name() As String\n\n Name = this.Name\n\nEnd Property\n\nPublic Property Let Name(ByVal Value As String)\n\n this.Name = Value\n\nEnd Property\n\nPublic Property Get Sex() As String\n\n Sex = this.Sex\n\nEnd Property\n\nPublic Property Let Sex(ByVal Value As String)\n\n this.Sex = Value\n\nEnd Property\n</code></pre>\n<h2>Test</h2>\n<pre><code>Sub TestClone()\n Dim Tom As New Person\n With Tom\n .DOB = #7/26/1970#\n .Name = "Tom"\n .Sex = "M"\n End With\n \n Debug.Print "TestClone"\n With Tom.Clone\n Tom.Name = "Thomas"\n Debug.Print "DOB: ", .DOB\n Debug.Print "Name: ", .Name\n Debug.Print "Sex: ", .Sex\n End With\n Debug.Print\nEnd Sub\n\nSub TestFactory()\n Dim Tom As Person\n Set Tom = Person.Factory(#7/26/1970#, "Tom", "M")\n Person.Name = "Thomas"\n Debug.Print "TestFactory"\n With Tom\n Debug.Print "DOB: ", .DOB\n Debug.Print "Name: ", .Name\n Debug.Print "Sex: ", .Sex\n End With\nEnd Sub\n</code></pre>\n<p><img src=\"https://i.stack.imgur.com/Wrbzm.png\" alt=\"Immediate Window Results\" /></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:03:05.173",
"Id": "492915",
"Score": "0",
"body": "I've used the ```UnsignedAddition``` function (see [here](https://github.com/cristianbuse/VBA-StringBuffer/blob/master/Code%20Modules/StringBuffer.cls)) before, when doing pointer arithmetic. Would that be an overkill here? Is it really possible that the pointers will be at the very boundary of sign change? I ask because we merely add 4 or 8 bytes on each iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:10:49.910",
"Id": "492919",
"Score": "0",
"body": "@CristianBuse I don't understand the need for the offset. I'm guessing that there is some sort of header that doesn't get copied over?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:13:18.480",
"Id": "492921",
"Score": "1",
"body": "@CristianBuse You use of compiler directives is outstanding. Your pattern with an explanation of when to convert WinAPI Declarations Long to LongPtr belongs on ByteComb."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:17:29.967",
"Id": "492922",
"Score": "1",
"body": "On x64 the calling convention forces the first 4 parameters into registers and only from the 5th forward will go on stack, meaning that immediately after the VarPtr(Method) (the address of the return value) there is the ```this``` pointer passed to the class method in order to identify the instance. On x32 they are pushed on the stack thus making it more difficult to find. Note that ```Me``` acts like a variable but when testing it looks like a Property Get because if you save the VarPtr(Me) and then peek at that address there is nothing, just 0. In short, Me is not the hidden This"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:28:24.077",
"Id": "492923",
"Score": "0",
"body": "Thanks. I've never used ByteComb. Is that your website? Feel free to add any of my code / explanations in there if you consider it's useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:43:23.323",
"Id": "492959",
"Score": "0",
"body": "@CristianBuse MySite...lol, I wish I was that good. [ByteComb](https://bytecomb.com/vba-reference/) takes a deep look into VBA. You should check out there section on VBA Internals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T11:28:12.263",
"Id": "493680",
"Score": "0",
"body": "What prompted you to switch from `mePtr` `swapAddr` to `SourcePointer` `DestinatinPointer` - although they correspond well to the arguments of CopyMemory, I feel they are a bit more generic - don't really explain the purposes of the variables?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:34:23.450",
"Id": "493686",
"Score": "0",
"body": "@Greedo I believe in using generic variable names . My initial code was much more complex. It had the `Caster` class swap with the Default Instance and then with the New Instance.`Swap` was a little hard to follow. I don't like `addr` because it's value is assigned using`VarPtr()` and `ObjPtr()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T12:37:43.090",
"Id": "493687",
"Score": "0",
"body": "@Greedo in retrospect having a separate function with a `swapPtr` to return the pointer variable have been better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T20:41:59.603",
"Id": "499330",
"Score": "0",
"body": "@Greedo and TinMan - I would be grateful if you could review the follow-up question: [Private VBA Class Initializer called from Factory #2](https://codereview.stackexchange.com/questions/253233/private-vba-class-initializer-called-from-factory-2)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:01:01.513",
"Id": "250644",
"ParentId": "250578",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T11:33:33.507",
"Id": "250578",
"Score": "8",
"Tags": [
"vba",
"classes",
"factory-method"
],
"Title": "Private VBA Class Initializer called from Factory"
}
|
250578
|
<p>I have written a tool that is used to rebalance weights in a weighted round robin in AWS. I am quite happy with it whereas I would welcome feedback from any Bash programmers.</p>
<pre class="lang-bash prettyprint-override"><code>#!/usr/bin/env bash
declare -g -A set_identifiers
usage() {
echo "\
Usage: $0 list zones # list hosted zones
Usage: $0 -z HOSTEDZONE list names # list record set names in
# hosted zone with weights and sets
Usage: $0 -z HOSTEDZONE -r RECORDSET -S SETID -a ACTION
Available actions:
X # Configure weight on this set to exactly X
X% # Distribute X% of traffic to this set
[+-]X% # Adjust traffic by +/- X%"
exit 1
}
indent() {
sed 's/^/ /'
}
get_opts() {
[ -z "$*" ] && usage
while getopts ":z:r:S:a:" opt ; do
case "$opt" in
z) hosted_zone_id="$OPTARG" ;;
r) resource_record_set="$OPTARG" ;;
S) set_identifier_a="$OPTARG" ;;
a) action="$OPTARG" ;;
\?) echo "ERROR: Invalid option -$OPTARG"
usage ;;
esac
done
shift $((OPTIND-1))
[ -n "$1" ] && command="$1 $2"
}
validate_opts() {
local f com commands vars var message
vars=(
hosted_zone_id
resource_record_set
set_identifier_a
action
)
commands=(
'list zones'
'list names'
)
if [ -n "$command" ] ; then
f=0 ; for com in "${commands[@]}" ; do
[ "$command" == "$com" ] && ((f++))
done
if ((f==0)) ; then
echo "Unknown command $command"
usage
fi
fi
if [ "$command" == "list names" ] ; then
if [ -z "$hosted_zone_id" ] ; then
echo "You must set hosted zone ID. Try list zones"
usage
fi
fi
[ -n "$command" ] && return
for var in "${vars[@]}" ; do
if eval '[ -z "$'"$var"'" ]' ; then
echo "$var is not set"
usage
fi
done
message="action must be either a number between \
0 and 100, a percentage like 83%, or an increment like \
+5% or -7%"
if [[ $action =~ ^[0-9]+$ ]] ; then
if ((action > 100)) ; then
echo "$message"
usage
fi
elif [[ $action =~ ^[0-9]+%$ ]] ; then
:
elif [[ $action =~ ^[+-][0-9]+%$ ]] ; then
:
else
echo "$message"
usage
fi
}
list_hosted_zones() {
aws route53 list-hosted-zones | jq .
}
list_sets_and_weights() {
aws route53 list-resource-record-sets \
--hosted-zone-id "$hosted_zone_id" \
--query \
'ResourceRecordSets[?Weight!=`null`]' | jq .
}
get_set_identifiers() {
local set_id weight
while IFS=$'\t' read -r set_id weight ; do
set_identifiers["$set_id"]="$weight"
if [ "$set_identifier_a" != "$set_id" ] ; then
set_identifier_b="$set_id"
fi
done \
<<< \
"$(
aws route53 list-resource-record-sets \
--output 'text' \
--hosted-zone-id "$hosted_zone_id" \
--query \
'ResourceRecordSets[?Name==`'"$resource_record_set"'`].[SetIdentifier, Weight]'
)"
}
update_weight() {
local set_id="$1"
local weight="$2"
printf "Updating %s to weight %s\n" "$set_id" "$weight"
aws route53 list-resource-record-sets \
--hosted-zone-id "$hosted_zone_id" \
--query \
'ResourceRecordSets[?Name==`'"$resource_record_set"'` && SetIdentifier==`'"$set_id"'`]' | \
\
jq \
--arg script "$0" \
--arg weight "$weight" \
'
{
"Comment": "Update by \($script)",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": (.[0] | .Weight = ($weight | tonumber))
}
]
}
' > change-resource-record-sets.json
printf "Applying change record set:\n"
jq . change-resource-record-sets.json | indent
printf "Running aws route53 change-resource-record-sets:\n"
aws route53 change-resource-record-sets \
--hosted-zone-id "$hosted_zone_id" \
--change-batch 'file://change-resource-record-sets.json'
}
set_absolute() {
printf "Setting %s to absolute weight %s\n" "$set_identifier_a" "$action"
update_weight "$set_identifier_a" "$action"
}
set_percent() {
printf "Setting %s to %s\n" "$set_identifier_a" "$action"
local a b s
a="${action//%/}"
((b = 100 - a))
update_weight "$set_identifier_a" "$a"
update_weight "$set_identifier_b" "$b"
}
convert_to_percent() {
printf "Recomputing weights on a 0 to 100 scale\n"
local t ap bp s a b
a="${set_identifiers["$set_identifier_a"]}"
b="${set_identifiers["$set_identifier_b"]}"
((t = a + b))
((ap = a * 100/t))
((bp = b * 100/t))
set_identifiers["$set_identifier_a"]="$ap"
set_identifiers["$set_identifier_b"]="$bp"
printf " Got %s for %s\n" "$ap" "$set_identifier_a"
printf " Got %s for %s\n" "$bp" "$set_identifier_b"
}
adjust_by_percent() {
printf "Adjusting %s by %s\n" "$set_identifier_a" "$action"
local op po s n
convert_to_percent
op="${action//%/}" # e.g. +5
po="$(sed 'y/+-/-+/' <<< "$op")" # => -5
for s in "${!set_identifiers[@]}" ; do
n="${set_identifiers["$s"]}"
if [ "$s" == "$set_identifier_a" ] ; then
eval "((n = n $op))"
else
eval "((n = n $po))"
fi
((n > 100)) && n=100
((n < 0)) && n=0
update_weight "$s" "$n"
done
}
cleanup() {
rm -f change-resource-record-sets.json
}
main() {
get_opts "$@"
validate_opts
case "$command" in
"list zones")
list_hosted_zones
exit 0
;;
"list names")
list_sets_and_weights
exit 0
;;
esac
if [[ $action =~ ^[0-9]+$ ]] ; then
set_absolute ; cleanup ; exit 0
fi
get_set_identifiers
if [[ $action =~ ^[0-9]+%$ ]] ; then
set_percent
elif [[ $action =~ ^[+-][0-9]+%$ ]] ; then
adjust_by_percent
fi
cleanup
}
if [ "$0" == "${BASH_SOURCE[0]}" ] ; then
main "$@"
fi
# vim: set ft=sh:
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:11:33.780",
"Id": "250583",
"Score": "3",
"Tags": [
"bash",
"amazon-web-services"
],
"Title": "Bash script for rebalancing weighted round robin"
}
|
250583
|
<p>If i have a object like following</p>
<pre><code>result = [
{
phones : ["ABC", "DEF"],
name: "Simon"
},
{
phones : ["ABC", "XZY"],
name: "John"
}
]
</code></pre>
<p>Expected output</p>
<p>Map of key, value</p>
<pre><code>{ABC, ["Simon", "John"]}
{DEF, ["Simon"]}
{XYZ, ["John"]}
</code></pre>
<p>My try</p>
<pre><code>map: Map = new Map();
for ( r of result ) {
for( phone of r.phones) {
if(map.get(phone)){
map.set(phone, map.get(phone).concat(r.name))
} else {
map.set(phone, r.name);
}
}
}
</code></pre>
<p>Is there a ES6 way to perform the above double iteration in a minimised way ?</p>
|
[] |
[
{
"body": "<p><strong>Overall</strong> Your code is quite reasonable, after fixing something that looks to be a typo. The transformation that needs to be applied to the data structure isn't entirely trivial, so the logic that needs to be implemented requires a handful of lines of code.</p>\n<p><strong>Typo?</strong> But your code also has a typo/bug: the <code>map.set(phone, r.name);</code> will set the value in the map to be a <em>string</em>, not an array. You probably meant to do <code>map.set(phone, [r.name]);</code> (maybe a miscopy?) There's also <code>map: Map = new Map();</code>, which isn't valid syntax in JS, remove the <code>: Map</code> part.</p>\n<p><strong>Conditional operator</strong> If you wanted to shorten your existing code, see how you're using <code>.map.set(phone, someExpression)</code> depending on a condition - this is a sign that you can use the conditional operator instead of the <code>if</code>/<code>else</code>.</p>\n<pre><code>map.set(phone, (map.get(phone) ?? []).concat(r.name));\n</code></pre>\n<p>But while that makes the code <em>shorter</em>, is it easier to read? I'm not entirely convinced. Maybe you'll like it, or maybe you won't.</p>\n<p>There are a few other things that can improve the code quality:</p>\n<p><strong>Declare your variables</strong> Doing <code>for (r of result)</code> will implicitly create a global <code>r</code> variable and put it on the global object. If you're running in strict mode, this will throw an error too. Always declare variables before using them, preferably with <code>const</code>.</p>\n<p><strong>Destructure?</strong> With <code>for (r of result)</code> or <code>for (const r of result)</code>, you create a variable named <code>r</code>, which isn't so intuitive - what's an <code>r</code>? Maybe destructure the <code>name</code> and <code>phones</code> properties immediately.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const result = [\n {\n phones : [\"ABC\", \"DEF\"],\n name: \"Simon\"\n },\n {\n phones : [\"ABC\", \"XZY\"],\n name: \"John\"\n }\n]\nconst map = new Map();\nfor (const { phones, name } of result) {\n for (const phone of phones) {\n map.set(phone, (map.get(phone) ?? []).concat(name));\n }\n}\nconsole.log([...map]);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:04:18.780",
"Id": "250587",
"ParentId": "250584",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T14:44:55.363",
"Id": "250584",
"Score": "2",
"Tags": [
"javascript",
"node.js"
],
"Title": "Array to map based on object property containing array items"
}
|
250584
|
<p>I'm writing a python game-bot where a user needs to send in an input within a certain amount of time.</p>
<p>My current implementation of this is to spawn a new thread that sleeps for that amount of time, then checks if an input has been sent. A nonce is added as the time could run out after another thread starts which would cause the <code>if chatid in user_threads</code> part to evaluate to true. Should I use this method or is there a better solution to having a timed input (in the sense less likely to fail due to like race conditions).</p>
<p>I've also tried using <code>multiprocessing.Process</code> but sharing variables to the other process seems to be a lot more cumbersome.</p>
<pre><code>from threading import Thread
from time import time, sleep
from random import randint
user_threads = {}
def timeout(t,r):
while time()-t<5:
sleep(5-time()+t)
if chatid in user_threads:
if user_threads[chatid][3] != r:
return
del user_threads[chatid]
print("Too slow")
def recvans(ans,inp):
if ans==inp:
print("yes")
else:
print("no")
def starttimer(chatid):
r = randint(0,1<<128)
user_threads[chatid] = [None,None,None,r]
user_threads[chatid][2] = ["a"]
P = Thread(target = timeout, args = (time(),r))
user_threads[chatid][0] = P
user_threads[chatid][1] = recvans
P.start()
while True: # simulating user input from different users (here chatid=1)
inp = input()
chatid = 1
if chatid in user_threads:
t, func, args, _ = user_threads[chatid]
if t == None:
print("Please wait")
continue
del user_threads[chatid]
args += [inp]
func(*args)
continue
if inp == "Start":
starttimer(chatid)
continue
if inp == "Quit":
break
print("Unknown msg")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:29:46.833",
"Id": "492792",
"Score": "3",
"body": "Usually is is done via [select.select](https://docs.python.org/2/library/select.html#module-select)"
}
] |
[
{
"body": "<p>What @vnp said. Fundamentally,</p>\n<ul>\n<li><code>input</code> uses <code>stdin</code>;</li>\n<li><code>stdin</code> can be interpreted as a file handle so long as you're not in Windows;</li>\n<li><code>select</code> can wait for data availability on such handles.</li>\n</ul>\n<p>There's a lot of internet help on this topic, including <a href=\"https://stackoverflow.com/a/3471853/313768\">https://stackoverflow.com/a/3471853/313768</a> ; to quote the solution there:</p>\n<blockquote>\n<pre><code>import sys \nfrom select import select\n\ntimeout = 10 \nprint "Enter something:", \nrlist, _, _ = select([sys.stdin], [], [], timeout) \nif rlist:\n s = sys.stdin.readline()\n print s \nelse:\n print "No input. Moving on..."\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:08:46.227",
"Id": "492945",
"Score": "0",
"body": "ahh ic this looks way cleaner\nfor my case since I'm using this in context of a game which receives http(s) requests is there a similar way to do this?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:41:52.430",
"Id": "250600",
"ParentId": "250585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:01:00.870",
"Id": "250585",
"Score": "2",
"Tags": [
"python",
"multithreading"
],
"Title": "Python timed input"
}
|
250585
|
<p>(See the next follow-up <a href="https://codereview.stackexchange.com/questions/262793/a-simple-c-winapi-program-for-terminating-processes-via-process-image-names-fo">here</a>.)</p>
<p>This is the 4th version of the program killer tool:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <shlwapi.h>
#include <TlHelp32.h>
#pragma comment(lib, "Shlwapi.lib")
static const char* get_last_err_msg() {
DWORD errorMessageId = GetLastError();
if (errorMessageId == 0) {
return "";
}
LPSTR messageBuffer = NULL;
size_t size =
FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorMessageId,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)& messageBuffer,
0,
NULL);
char* errmsg = _strdup(messageBuffer);
LocalFree(messageBuffer);
return errmsg;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
char* bname = _strdup(argv[0]);
PathStripPath(bname);
fprintf(stderr, "%s PROCESS_NAME\n", bname);
free(bname);
return EXIT_FAILURE;
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (snapshot == INVALID_HANDLE_VALUE) {
fprintf(
stderr,
"Error: could not get the process snapshot. "
"Cause: %s\n", get_last_err_msg());
return EXIT_FAILURE;
}
size_t totalProcesses = 0;
size_t totalProcessesMatched = 0;
size_t totalProcessesTerminated = 0;
if (Process32First(snapshot, &entry)) {
do {
totalProcesses++;
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\". "
"Cause: %s",
entry.th32ProcessID,
entry.szExeFile,
get_last_err_msg());
} else {
if (TerminateProcess(hProcess, 0)) {
totalProcessesTerminated++;
printf("Terminated process ID %d\n",
entry.th32ParentProcessID);
} else {
fprintf(
stderr,
"Warning: could not terminate the process with ID %d. "
"Cause: %s",
entry.th32ProcessID,
get_last_err_msg());
}
if (!CloseHandle(hProcess)) {
fprintf(
stderr,
"Warning: could not close the handle to the process ID %d. "
"Cause: %s",
entry.th32ProcessID,
get_last_err_msg());
}
}
}
} while (Process32Next(snapshot, &entry));
}
BOOL snapshotHandleClosed = CloseHandle(snapshot);
if (!snapshotHandleClosed) {
fprintf(stderr,
"Warning: could not close the process snapshot. Cause: %s",
get_last_err_msg());
}
printf("Info: total processes: %zu, "
"total matching processes: %zu, total terminated: %zu.\n",
totalProcesses,
totalProcessesMatched,
totalProcessesTerminated);
return EXIT_SUCCESS;
}
</code></pre>
<p><em><strong>Critique request</strong></em></p>
<p>Is there anything else I could do here?</p>
|
[] |
[
{
"body": "<h2>Memory ownership</h2>\n<p>This:</p>\n<pre><code>char* errmsg = _strdup(messageBuffer);\nLocalFree(messageBuffer);\nreturn errmsg;\n</code></pre>\n<p>is problematic. The documentation for <code>_strdup</code> says that</p>\n<blockquote>\n<p>The <code>_strdup</code> function calls <code>malloc</code> to allocate storage space for a copy of <code>strSource</code> and then copies <code>strSource</code> to the allocated space.</p>\n</blockquote>\n<p>So you're allocating, reallocating, doing one free, and leaving the second buffer dangling. The typical solutions for this are</p>\n<ul>\n<li>Make the caller contract such that the caller is responsible for calling <code>LocalFree</code>, and don't call <code>strdup</code> at all. If you do this, the <code>""</code> case must use your own <code>malloc</code> and <code>strcpy</code>.</li>\n<li>Have <code>get_last_err_msg()</code> accept a buffer and size instead, and simply have <code>FormatMessage</code> fill that buffer</li>\n<li>Accept a callback function pointer that is called with the message, after which <code>get_last_err_msg()</code> does the free - this one is needlessly complicated for this application</li>\n</ul>\n<p>I recommend the second.</p>\n<h2>Logic inversion</h2>\n<p>Change this:</p>\n<pre><code> if (strcmp(entry.szExeFile, argv[1]) == 0) {\n</code></pre>\n<p>to</p>\n<pre><code> if (strcmp(entry.szExeFile, argv[1]) != 0)\n continue;\n</code></pre>\n<p>so that the rest of the loop can be de-indented.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T06:20:29.240",
"Id": "492888",
"Score": "1",
"body": "I don't agree about adding `continue`, the need to do that always originates from cluttered, needlessly complex loops. In this case the solution is to split the big function into several. The OpenProcess + handling the results from it looks like a good candidate for a separate function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:18:05.380",
"Id": "250596",
"ParentId": "250586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250596",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:02:22.020",
"Id": "250586",
"Score": "2",
"Tags": [
"c",
"windows"
],
"Title": "A simple C WinAPI program for terminating processes via process image names - follow-up 3"
}
|
250586
|
<p>I worked on a script that takes as input a multi-sequence <code>.fasta</code> file and outputs the number of each aminoacid/sequence in a <code>.tsv</code> format.</p>
<p>This is how a <code>.fasta</code> file looks:</p>
<pre><code>>sp|P21515|ACPH_ECOLI Acyl carrier protein phosphodiesterase OS=Escherichia coli (strain K12) OX=83333 GN=acpH PE=1 SV=2
MNFLAHLHLAHLAESSLSGNLLADFVRGNPEESFPPDVVAGIHMHRRIDVLTDNLPEVREAREWFRSETRRVAPITLDVMWDHFLSRHWSQLSPDFPLQEFVCYAREQVMTILPDSPPRFINLNNYLWSEQWLVRYRDMDFIQNVLNGMASRRPRLDALRDSWYDLDAHYDALETRFWQFYPRMMAQASRKAL
</code></pre>
<p>I know there are libraries which do the same thing, however, I had to write this script as a homework, without the help of <code>BioPython</code> or other similar libraries.</p>
<p>My question is: how can I make this code more efficient?</p>
<pre><code>import sys
import os
def readFasta( path ):
seq = { }
aCount = { }
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWYZX*-"
for fileName in path:
with open( fileName ) as file:
fastaLine = file.readlines( )
# sequence storage
for line in fastaLine:
if line[ 0 ] == ">" :
headerTitle = line.split( "|" )[ 1 ]
seq[ headerTitle ] = ""
else:
seq[ headerTitle ] += line.strip( )
# aminoacid count
for id in seq:
aCount[ id ] = { }
for sequence in seq[ id ]:
if sequence not in alphabet:
print( "Check your sequence! Character: " + str(sequence) + " from sequence: " + id )
for letter in alphabet:
aCount[ id ][ letter ] = 0
# count aminoacid occurence/sequence
for name in seq:
for char in seq[ name ]:
if char in aCount[ name ]:
aCount[ name ][ char ] += 1
# write to .csv file
outFile = open( "output.csv" , "w" )
outFile.write( "Name" + '\t' )
header = ""
for letter in alphabet:
header += letter + '\t'
outFile.write( header + "Total" )
outFile.write( '\n' )
for name in aCount:
entry = ""
counter = 0
for letter in aCount[ name ]:
entry += str(aCount[ name ][ letter ]).strip( ) + '\t'
counter += aCount[ name ][ letter ]
outFile.write( name + '\t' + entry + '\t' + str( counter ) )
outFile.write( '\n' )
# files to list
entries = os.listdir( path )
# filter for .fasta/.fa files
new_list = [ ]
for entry in entries:
if ".fasta" in entry:
new_list.append( entry )
elif ".fa" in entry:
new_list.append( entry )
# execute func
readFasta( new_list )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:59:19.193",
"Id": "492800",
"Score": "0",
"body": "Your indentation is wrong. Since indentation is vital in Python, please fix it before we can review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:15:13.017",
"Id": "492802",
"Score": "0",
"body": "@Mast fixed it, so sorry, I haven't noticed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:16:52.110",
"Id": "492804",
"Score": "0",
"body": "Much better, thank you. 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-10-14T05:40:22.550",
"Id": "492887",
"Score": "0",
"body": "I don't know if Python has a more efficient way to histogram the characters in a string; I hope so because looping manually is very slow in the CPython interpreter. (Other Python implementations might be less bad.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:22:47.357",
"Id": "492908",
"Score": "1",
"body": "@PeterCordes Well, there's [`numpy.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html), I imagine `pandas`/`counter`/`seaborn` (either by themselves or in any combination) would work too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:27:12.277",
"Id": "492909",
"Score": "0",
"body": "@Mast: Graipher also [suggested](https://codereview.stackexchange.com/questions/250589/fasta-to-tsv-conversion-script?noredirect=1#comment492895_250635) `collections.Counter`. The answer suggesting `str.count` 28 times (alphabet length) could probably be several times faster (especially for sequences larger than L2 cache size, often 256kiB on modern x86) with an efficient one-pass histogram of bytes, see my comments on that answer for how it solves the alphabet-checking problem as well. (Genetic-sequence files can have very long lines so it's worth considering numpy for this)"
}
] |
[
{
"body": "<h2>Path?</h2>\n<p>Surely <code>path</code> is not a single path, since you loop through it. So at the least, this is poorly-named and should be <code>paths</code>. The variable you iterate through it, <code>fileName</code>, should be <code>file_name</code>; similarly for your other function and variable names.</p>\n<h2>Line iteration</h2>\n<p>Rather than calling <code>readlines()</code>, simply iterate over <code>file</code> itself, which will have the same effect.</p>\n<h2>Alphabet</h2>\n<p>Why is it out of order - <code>WYZX</code>?</p>\n<h2>Redundant <code>if</code></h2>\n<pre><code>if ".fasta" in entry:\n new_list.append( entry )\nelif ".fa" in entry:\n new_list.append( entry )\n</code></pre>\n<p>can collapse the <code>if</code> to</p>\n<pre><code>if '.fa' in entry:\n new_list.append(entry)\n</code></pre>\n<p>If you look at the substring pattern, the second includes the first. Also, don't add spaces on the inside of your parens.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T23:05:41.790",
"Id": "492849",
"Score": "1",
"body": "Thank you for your suggestions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:56:34.253",
"Id": "250593",
"ParentId": "250589",
"Score": "7"
}
},
{
"body": "<p>Welcome to Code Review!</p>\n<p>I'll add to the other answer from Reinderien.</p>\n<h2>PEP-8</h2>\n<p>In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.</p>\n<p>Functions and variables should be named in a <code>lower_snake_case</code>, classes as <code>UpperCamelCase</code>, and constants as <code>UPPER_SNAKE_CASE</code>.</p>\n<p>No unnecessary whitespaces are needed around the arguments when defining or calling a function. This applies for referring array/list elements as well.</p>\n<h2>Functions</h2>\n<p>Split your code into individual smaller functions, doing singular tasks. A few examples would be, reading/parsing the fasta files, validating sequence of gene, counting occurrences (try <code>collections.Counter</code> package to do this).</p>\n<h2>CSV/TSV</h2>\n<p>Python comes with inbuilt package <code>csv</code> which can also be used to write tsv files. You do not need to modify/write each line yourself.</p>\n<h2>Glob searching for files</h2>\n<p>Python 3+ has another inbuilt package <code>pathlib</code>, which supports getting all files using a glob pattern. You would again, not need to manually (metaphorically) aggregate all the files with <code>.fa</code> or <code>.fasta</code> extensions.</p>\n<h2><code>if __name__</code> block</h2>\n<p>For scripts, it is a good practice to put your executable feature inside the <code>if __name__ == "__main__"</code> clause.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:57:13.630",
"Id": "492848",
"Score": "0",
"body": "Thank you for all your suggestions! Regarding the built-in csv package, I know of it, but our teacher wanted us to do it without. That's also the case with the whitespace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T23:35:53.670",
"Id": "492850",
"Score": "3",
"body": "@sachikox not using csv is ok, but whitespaces around functions are frowned upon in python, __officially__. You can link your teacher to the PEP: https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:55:59.517",
"Id": "250605",
"ParentId": "250589",
"Score": "8"
}
},
{
"body": "<p>In addition to the points raised in the other answers:</p>\n<h2>Extraneous import</h2>\n<p>The first line is <code>import sys</code>, but I don't see <code>sys</code> used anywhere; this can go.</p>\n<h2>Explicit naming</h2>\n<p>It's generally better to use explicit names. Thus, rather than just <code>seq</code> (which might be short for <code>sequence</code> or <code>sequences</code>, for example) spell it out. In this case, it looks like you should use <code>sequences</code>. Similarly, <code>aCounts</code> doesn't tell me what you're counting, other than the fact that there's an <code>a</code> involved; just call it <code>amino_acid_counts</code>.</p>\n<h2>Consistent naming</h2>\n<p>When you're talking about the same object in two different places in the code, you should prefer to use consistent names. For example, you use <code>headerTitle</code> for the <code>seq</code> key when reading the file in, but <code>id</code> for the same keys in the next block, and <code>name</code> in the block after that. Again, I would go with a more explicit name like <code>sequence_id</code>.</p>\n<h2>Shadowing built-in objects</h2>\n<p>Speaking of <code>id</code>, that's actually a <a href=\"https://docs.python.org/3/library/functions.html#id\" rel=\"nofollow noreferrer\">built-in function</a>. It's generally a bad idea to rename something that's built in to the language. This is called <a href=\"https://en.wikipedia.org/wiki/Variable_shadowing\" rel=\"nofollow noreferrer\">"shadowing"</a>, and it's possible to break code by doing it — and generally considered bad form.</p>\n<h2>Keeping the file open longer than it's needed</h2>\n<p>Once you've run <code>fastaLine = file.readlines( )</code>, you're done with the file, and you can close it — meaning that you're done with the <code>with open</code> block, and you can un-indent the blocks after it. Of course, as <code>Reinderien</code> pointed out, it's probably better to just process each line as you iterate over them. (This is especially important with huge files, where you might want to just load a single line at a time into memory, rather than loading the entire file into memory.) So you'll want that <code>with open</code> block to look more like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> # sequence storage\n with open(path, "r") as file:\n for line in file:\n if line[0] == ">" :\n sequence_id = line.split("|")[1]\n sequences[sequence_id] = ""\n else:\n sequences[sequence_id] += line.strip()\n\n # amino acid count\n</code></pre>\n<p>Note that I've un-indented the amino acid count comment (and everything following it).</p>\n<h2>Probably excessive looping</h2>\n<p>I'm guessing that you just want to warn the user about all unrecognized characters in a given line, rather than every single occurrence of every such character. In that case, it's better to make a <code>set</code> of all the characters in the sequence, and check if any are not in <code>alphabet</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>sequence_characters = set(seq[id])\nif not sequence_characters.issubset(alphabet):\n print(\n "Check your sequence! Extra characters: '" + str(sequence_characters - alphabet)\n + "' from sequence: " + str(sequence_id)\n )\n</code></pre>\n<h2>Definitely excessive looping</h2>\n<p>When doing <code>for sequence in seq[ id ]</code>, you're looping over every character in the sequence. While I doubt that this is what you want for the previous lines, this definitely is not what you want when doing <code>for letter in alphabet</code>; that loop should be un-indented, so that it's just done once for each <code>id</code>.</p>\n<h2>Use the built-in <code>str.count</code> method to do your counting</h2>\n<p>Python already knows how to count how many times a character appears in a string: that's <a href=\"https://docs.python.org/3/library/stdtypes.html#str.count\" rel=\"nofollow noreferrer\">the <code>str.count</code> method</a>. So rather than looping over every character in the string and adding 1 to the appropriate character, just loop over the alphabet. You can cut out that loop where you initialize the counts to 0, and just figure out the counts. Putting this together with the previous items (including renaming some variables), you'll have something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> # amino acid count\n for sequence_id, sequence in sequences.items():\n amino_acid_counts[sequence_id] = { }\n sequence_characters = set(sequence)\n if not sequence_characters.issubset(alphabet):\n print(\n "Check your sequence! Extra characters: '" + str(sequence_characters - alphabet)\n + "' from sequence: " + str(sequence_id)\n )\n for letter in alphabet:\n amino_acid_counts[sequence_id][letter] = sequence.count(letter)\n</code></pre>\n<p>And that whole loop under <code># count aminoacid occurence/sequence</code> can be removed. This will be much faster.</p>\n<h2>Use <code>with open</code> block for writing file, too</h2>\n<p>You correctly used a <code>with open</code> block for reading the files; use it when you write the CSV file, too:</p>\n<pre class=\"lang-py prettyprint-override\"><code> with open("output.csv", "w") as outFile:\n</code></pre>\n<p>(and indent whatever follows and uses <code>outFile</code>).</p>\n<h2>No need to add explicit strings</h2>\n<p>When you write <code>"Name" + '\\t'</code>, you could just as well write <code>"Name\\t"</code>. Similarly, when you write</p>\n<pre class=\"lang-py prettyprint-override\"><code> outFile.write( header + "Total" )\n outFile.write( '\\n' )\n</code></pre>\n<p>you could just as well write</p>\n<pre class=\"lang-py prettyprint-override\"><code> outFile.write(header + "Total\\n")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T05:27:48.593",
"Id": "492885",
"Score": "0",
"body": "`str.count()` has to loop over the *whole* string, and you're doing that 26 times. That costs 26x the memory traffic if it's a long sequence that doesn't fit in CPU cache. It's probably still faster than looping manually (assuming CPython where interpreter overhead is killer), but even better would be if Python has an efficient function to *histogram*, like into a dictionary of key => count. (Then you could check the set of keys against the alphabet instead of doing that separately.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T05:31:58.513",
"Id": "492886",
"Score": "0",
"body": "Also, probably it would make more sense to do the alphabet check by looking for a match against the regex `[^-*A-Z]`. If it matches, there was a character not in that set. Perhaps faster than forcing it to figure out exactly which characters were present/absent, IDK. (If it were just one contiguous range, it could be checked very efficiently if the regex engine had the right optimizations...) But hopefully that goes away with a histogram where we end up with the set of keys as part of the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T08:33:01.137",
"Id": "492895",
"Score": "2",
"body": "@PeterCordes `collections.Counter` is exactly what you hoped for in your first comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T08:38:01.067",
"Id": "492896",
"Score": "0",
"body": "@Graipher: Thanks. Someone that knows something about Python should post that as an answer, then; if it has an efficient internal implementation it should be much faster than anything proposed in any existing answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:14:50.830",
"Id": "492947",
"Score": "1",
"body": "But if they're asked to \"do without\" `csv`, I'm thinking the teacher wants them to do things at a more basic level than just calling `Counter`. It seems the students are at a level where they could use more learning about writing their own algorithms before learning about libraries. And I'd bet regexes are a bit advanced for them too — whereas using a basic built-in type like `set` is probably something the teacher would approve."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T04:37:49.047",
"Id": "250635",
"ParentId": "250589",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250635",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:47:05.127",
"Id": "250589",
"Score": "11",
"Tags": [
"python",
"parsing",
"reinventing-the-wheel",
"bioinformatics"
],
"Title": "FASTA-to-tsv conversion script"
}
|
250589
|
<p>Here I am making a calculator for a robotics assignment. I need the program to be able to take two inputs and convert to float. It also needs to display previous calculations when exiting and also stop when trying to divide by 0. It works I just want to make sure its clean and im not using any bad practices.</p>
<pre><code>operators = ["+", "-", "*", "/"]
answers = []
def run_calculator():
def instructions():
try: chosen_operator = int(input("Choose an Operator:\n1) Addition\n2) Subtraction\n3) Multiplication\n4) Division\n\n5) Exit\nInput (1/2/3/4/5):"))
except:
print('Invalid Input: Choose A Valid Operation')
return
if chosen_operator > 4 or chosen_operator < 1:
if chosen_operator == 5: return
print('Invalid Input: Choose a Valid Operation')
return
operator = operators[chosen_operator - 1]
try: firstnum = float(input('First Number:'))
except:
print('Invalid Input: Not a valid number')
return
try: secondnum = float(input('Second Number:'))
except:
print('Invalid Input: Not a valid number')
return
return operator, firstnum, secondnum
while (True):
try: operator, firstnum, secondnum = instructions()
except: break
if operator == "/" and secondnum == 0.0:
print("Cannot divide by 0")
break
calc_function = float.__add__ if operator == "+" else float.__sub__ if operator == "-" else float.__mul__ if operator == "*" else float.__truediv__
answers.append(f"{firstnum} {operator} {secondnum} = {calc_function(firstnum, secondnum)}")
restart = input((f"{firstnum} {operator} {secondnum} = {calc_function(firstnum, secondnum)}\nWould you like to do another calculation? (Y/N)"))
if restart.lower() == 'y':
continue
else:
print("Results:")
for x in range(len(answers)):
print(f"{answers[x]}")
break
run_calculator()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:15:39.930",
"Id": "492803",
"Score": "3",
"body": "linked: [Calculator that can add/subtract/multiply/divide two inputs](https://codereview.stackexchange.com/questions/250003/simple-calculator-to-add-subtract-multiply-divide-2-inputs)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T07:09:21.040",
"Id": "493347",
"Score": "0",
"body": "consider accepting an answer :)"
}
] |
[
{
"body": "<h2>Immutable sequences</h2>\n<p><code>operators</code> should be a tuple (i.e. <code>('+', ...)</code>), since you don't change it.</p>\n<h2>Nested functions</h2>\n<p><code>instructions</code> should be moved to the global level - you shouldn't need a closure, and should be passing information between <code>instructions</code> and <code>run_calculator</code> with parameters and return values, not closure variables.</p>\n<h2>Index-based selection</h2>\n<p>It's a little awkward to ask that the user select an operator based on numerical index. Make <code>operators</code> a dictionary instead, and have the user input the operator character. Of course, this is only possible if the parameters of your homework assignment permit.</p>\n<h2>Never <code>except: </code></h2>\n<p>Seriously. <code>except ValueError:</code> instead. Otherwise, you'll catch exceptions you don't want to, including user-break Ctrl+C.</p>\n<h2>Parens</h2>\n<p>Python doesn't need parens here:</p>\n<pre><code>while (True):\n</code></pre>\n<p>so delete them.</p>\n<h2>Logic inversion</h2>\n<pre><code> if restart.lower() == 'y':\n continue\n else:\n print("Results:")\n for x in range(len(answers)):\n print(f"{answers[x]}")\n break\n</code></pre>\n<p>is more easily expressed as</p>\n<pre><code> if restart.lower() != 'y':\n print("Results:")\n for x in range(len(answers)):\n print(f"{answers[x]}")\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:37:46.067",
"Id": "492814",
"Score": "0",
"body": "From the last suggestion.What is the use of using index range for the loop when you can do `in answers`? Also, what is the point of using f-strings when you have only one value? Lastly, It might be better to do `[print x for x in answers]` for the last suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:43:27.043",
"Id": "492816",
"Score": "0",
"body": "@AryanParekh Those comments belong in your own answer, since they're about the original code and not my suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:44:52.347",
"Id": "492817",
"Score": "0",
"body": "@AryanParekh Also I discourage discarded comprehension-loops like `[print x for x in answers]`. You're throwing the list away, so why make it at all? Just use a regular loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:48:53.307",
"Id": "492819",
"Score": "0",
"body": "Those were in your **improved** version, I was suggesting you correct a bad implementation in **your** version, I was trying to improve your answer more, I could've ignored it/downvoted but now I will just let it be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:36:56.753",
"Id": "492855",
"Score": "0",
"body": "Yeah I dont like using a numerical value to choose the operator but its what my assignment required."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:09:27.127",
"Id": "250594",
"ParentId": "250590",
"Score": "1"
}
},
{
"body": "<h2>Positives</h2>\n<ul>\n<li>Your code adopts better practices than <a href=\"https://codereview.stackexchange.com/questions/250003/simple-calculator-to-add-subtract-multiply-divide-2-inputs\">before</a>.</li>\n<li>You have used meaningfully names for variables and functions</li>\n</ul>\n<h2>Negatives</h2>\n<ul>\n<li>Code looks a little clunky as one whole chunk of code that does everything</li>\n<li>Can improve readability by using <code>eval</code>.</li>\n<li>Program terminates on invalid input, rather than asking vaild input</li>\n</ul>\n<p>Let's see how we can do <code>Negatives = []</code></p>\n<hr />\n<h1>Split work into multiple functions</h1>\n<p>In your program <strong>all operations are done by a single function</strong>. That is <br></p>\n<ol>\n<li>Input<br></li>\n<li>Processing<br></li>\n<li>Output<br></li>\n<li>Starting over again</li>\n</ol>\n<p>Instead what if you split the work into functions with meaningful names, your <code>loop()</code> function could look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>def calculator_loop():\n while True:\n clear_screen()\n show_instructions()\n args = calculator_input()\n result = process_input(args)\n print_result(result)\n if input("Do you want to calculate again(y/n) ?\\n").lower() == 'n':\n break\n \n</code></pre>\n<h1>Show instructions</h1>\n<p>We can move printing the instructions into a separate function, making it easy to show the instruction whenever we might want to.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def show_instructions():\n print( # I/O instructions for calculator ) \n</code></pre>\n<h1>Taking input</h1>\n<p>With our current <code>loop()</code> function in mind, out <code>calculator_function()</code> keeping the same logic should look like, note that this comes after showing the instructions (<code>show_instructions</code>)</p>\n<pre class=\"lang-py prettyprint-override\"><code>def calculator_input():\n operators = ['+','-','*','/']\n try:\n chosen_operator = int(input("Enter operator: "))\n except:\n print('Invalid Input: Choose A Valid Operation')\n return\n if chosen_operator > 4 or chosen_operator < 1:\n if chosen_operator == 5: return\n print('Invalid Input: Choose a Valid Operation')\n return\n operator = operators[chosen_operator - 1]\n try:\n firstnum = float(input('First Number:'))\n except:\n print('Invalid Input: Not a valid number')\n return\n try: \n secondnum = float(input('Second Number:'))\n except:\n print('Invalid Input: Not a valid number')\n return\n return operator, firstnum, secondnum\n</code></pre>\n<ul>\n<li><p>Notice these error messages<br> <code>'Invalid Input: Choose a Valid Operation' 'Invalid Input: Not a valid number'</code><br> Instead of\ncopy-pasting these messages everywhere, a better idea would be to use\n<code>operator_err_message</code> and <code>number_err_message</code> and print them.</p>\n</li>\n<li><p>As I mentioned before, the program shouldn't terminate if the user entered invalidly, instead it should ask the user for valid input. Does <em>command prompt</em> in Windows close if you made a mistake? Or does it show you <code> Unknown x command</code>?</p>\n</li>\n<li><p>You can handle list index error using <code>IndexError</code>. Ultimately it is shorter and clear compared to <code>if chosen_operator > 4 or...</code>.</p>\n</li>\n</ul>\n<p>With these improvements</p>\n<pre class=\"lang-py prettyprint-override\"><code>def calculator_input():\n operators = ['+','-','*','/']\n operator_err_message = 'Invalid Input: Choose A Valid Operation'\n number_err_message = 'Invalid Input: Not a valid number'\n\n try:\n chosen_operator = int(input("Enter operator: "))\n except Exception:\n print(operator_err_message)\n calculator_input()\n\n if operator == 5:\n return \n\n try:\n operator = operators[chosen_operator - 1]\n except IndexError:\n print(operator_err_message)\n calculator_input()\n try:\n firstnum = float(input('First Number:'))\n except Exception:\n print(number_err_message)\n calculator_input()\n try:\n secondnum = float(input('Second Number:'))\n except Exception:\n print(number_err_message)\n calculator_input()\n \n return operator, firstnum, secondnum\n</code></pre>\n<p>Edit: As suggested by @Reinderien, <code>except: </code> fill catch if <code>Cntrl-C</code> is pressed, hence it is better to use <code>except Exception:</code></p>\n<h1>Processing input</h1>\n<p>Again, if you split the work into a new function without any changes, it would look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>def process_input(num1,num2,operator):\n calc_function = float.__add__ if operator == "+" else float.__sub__ if operator == "-" else float.__mul__ if operator == "*" else float.__truediv__\n return calc_function(num1,num2)\n</code></pre>\n<p>With <a href=\"https://www.programiz.com/python-programming/methods/built-in/eval\" rel=\"nofollow noreferrer\"><code>eval</code></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>def process_input(num1,num2,operator):\n return eval(f"{num1}{operator}{num2}")\n</code></pre>\n<h1>Printing result</h1>\n<p>Your current method is just fine, and I believe that it doesn't need improvements, you can decide to move it into a function or not.</p>\n<hr />\n<h1>Final</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def show_instructions():\n instructions = \n"""\nOperators:\n 1) Addition\n 2) Subtraction\n 3) Multiplication\n 4) Division\n 5) Exit\n"""\n print(instructions)\n\ndef calculator_input():\n operators = ['+','-','*','/']\n operator_err_message = 'Invalid Input: Choose A Valid Operation'\n number_err_message = 'Invalid Input: Not a valid number'\n\n try:\n chosen_operator = int(input("Enter operator: "))\n except Exception:\n print(operator_err_message)\n calculator_input()\n if operator == 5:\n return\n try:\n operator = operators[chosen_operator - 1]\n except IndexError:\n print(operator_err_message)\n calculator_input()\n try:\n firstnum = float(input('First Number:'))\n except Exception:\n print(number_err_message)\n calculator_input()\n try:\n secondnum = float(input('Second Number:'))\n except Exception:\n print(number_err_message)\n calculator_input()\n\n return operator, firstnum, secondnum\n\ndef process_input(num1,num2,operator):\n return eval(f"{num1}{operator}{num2}")\n\ndef clear_screen():\n print(chr(27) + "[2J")\n\ndef calc_loop():\n while True:\n clear_screen()\n show_instructions()\n operator,num1,num2 = calculator_input()\n result = process_input(num1,num2,operator)\n print(f"{num1} {operator} {num2} = {result}\\n")\n if input("Would you like to play again?(y/n): ").lower() == 'n':\n break\n\n\ncalc_loop()\n</code></pre>\n<p>The results are stored in <code>answers</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:54:26.597",
"Id": "492820",
"Score": "0",
"body": "Having repeated newline-escape continuations in a literal is a poor idea for a handful of reasons, not the least being: that literal is going to inherit all of the indentation from its enclosing code block. You're best to use a triple-quote literal, or perhaps one string per line joined by implicit concatenation, instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:56:35.637",
"Id": "492821",
"Score": "0",
"body": "`except operator == 5:` makes no sense and I'm frankly surprised that it's accepted as valid syntax. It certainly doesn't do what you likely want, which is to enter the `except` block when the condition is true. That's what `if` is for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:56:45.327",
"Id": "492822",
"Score": "1",
"body": "@Reinderien Triple quoted literal sounds good, thank you for suggesting! I will add it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:00:33.643",
"Id": "492824",
"Score": "1",
"body": "Also: don't `except:`. I encourage you to try cancelling the program with Ctrl+C during a `try`-protected input, to see how this affects you. The solution is to `except Exception:`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:05:44.837",
"Id": "492826",
"Score": "2",
"body": "@Reinderien I have fixed all errors and added `Exception`, thank you for the correction"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:32:35.627",
"Id": "250599",
"ParentId": "250590",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T15:47:33.957",
"Id": "250590",
"Score": "4",
"Tags": [
"python"
],
"Title": "Calculator that can add/subtract/divide/multiply two inputs"
}
|
250590
|
<p>I would love to get some feedback on this Sleeping barber implementation in C.</p>
<p>the entire project can be found here: <a href="https://github.com/T0iS/sleeping-barber" rel="nofollow noreferrer">https://github.com/T0iS/sleeping-barber</a></p>
<pre><code> How to run.
1. make
2. start the server on a selected port ( ./server XXXX)
3. start the client on localhost and connect to the previously specified port (./holic_cl localhost XXXX)
</code></pre>
<p>I would love to hear some advice on the code quality in general, what to do, what not to do and/or how could I improve the code stability and quality or readability as well.</p>
<p>Editing the question and specifying the code parts, did not know about that rule, thanks for letting me know.</p>
<p>The most important parts are these.</p>
<p>The readline function that reads a line from a FD</p>
<pre><code>int readline(fdStruct& fd, char* buf){
int ret, mv;
char temp[256];
bzero(temp, sizeof(temp));
char* t = NULL;
while(1){
bzero(temp, sizeof(temp));
bzero(buf,sizeof(buf));
ret = read(fd.fd, &temp, 256 - sizeof(strlen(fd.BUF)));
if (ret > 0 ){
temp[ret] = '\0';
}
strcat(fd.BUF, temp);
t = strchr(fd.BUF,'\n');
if (t != NULL){
mv = t-fd.BUF+1;
strncpy(buf,fd.BUF, mv);
strcpy(fd.BUF,fd.BUF+mv);
return strlen(buf);
}
if (ret <= 0) {
if (strlen(fd.BUF) == 0){
return ret;
}
strcpy(buf, fd.BUF);
strcpy(fd.BUF,fd.BUF+strlen(buf));
return strlen(buf);
}
}
}
</code></pre>
<p>The other one the actual barber code (and also the customer one, not including that one since it would be too long)</p>
<pre><code>void* holic(void* arg){
if(global_data->child_count>0){
close(comPipe[1]);
}
log_msg(LOG_INFO, "Getting to work..");
msg m;
char l[256];
int val_check = -1;
int cut_time = 0;
global_data->customer_count = 0;
while(1){
sem_getvalue(sem_customers, &val_check);
if (val_check==0){
log_msg(LOG_INFO,"Sleeping..");
}
sem_wait(sem_customers);
log_msg(LOG_INFO, "Woke up, start cutting..");
global_data->customer_count -= 1;
sem_post(sem_barber);
bzero(l,sizeof(l));
bzero(m.text, sizeof(m.text));
log_msg(LOG_INFO, "barber before read %d", fd_pipe.fd);
int tmp = read(comPipe[0], l, sizeof(l));
l[tmp] = '\0';
//wait_for_message(fd_pipe,l,&m,'A', AI_Zakazka);
sscanf(l, "Cut me for %d seconds", &cut_time);
global_data->chairs[global_data->last_chair] = 0;
log_msg(LOG_INFO, "Cutting hair, customer on chair %d, duration %d sec.",global_data->last_chair, cut_time);
sleep(cut_time);
sem_post(sem_cutting);
bzero(l,sizeof(l));
bzero(m.text, sizeof(m.text));
wait_for_message(fd_pipe,l,&m,'A', AI_Nashledanou);
log_msg(LOG_INFO, "Goodbye.");
}
if (global_data->child_count>0){
close(comPipe[0]);
}
}
</code></pre>
<p>Thanks for every input!</p>
|
[] |
[
{
"body": "<p><strong><code>readline</code></strong></p>\n<ul>\n<li><p><code>buf</code> is a pointer. <code>sizeof(buf)</code> is either 8 or 4, depending on the architecture. <code>bzero(buf,sizeof(buf));</code> only clears 8 (or 4) bytes of the buffer.</p>\n</li>\n<li><p>Similarly, <code>sizeof(strlen(fd.BUF))</code> is equal to <code>sizeof(int)</code>, and <code>256 - sizeof(strlen(fd.BUF)</code> always evaluates to 252, regardless of the <code>fd.BUF</code> contents. Doesn't look right, and may lead to a buffer overrun.</p>\n</li>\n<li><p>Looking for <code>'\\n'</code> in <code>fd.BUF</code> may degrade the performance. Looking for it in <code>temp</code> would be faster (because <code>temp</code> is smaller).</p>\n</li>\n<li><p>I don't see why do you need <code>temp</code> at all. It only introduces an extra copy. You may read directly to <code>fd.BUF</code>.</p>\n</li>\n<li><p><code>strcpy(fd.BUF,fd.BUF+mv)</code> is very dangerous, and technically introduces an undefined behaviour: <code>strcpy</code> is declared as</p>\n<pre><code> cher * stpcpy(char * dst, const char * src);\n</code></pre>\n<p>The <code>const</code> states a contract, that the source string is not modified. You invocation violates the contract.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:09:47.603",
"Id": "493010",
"Score": "0",
"body": "Thanks for the feedback! Very valuable points.\n\nCould you please suggest how could I possibly do the last point differently?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T18:33:52.307",
"Id": "250603",
"ParentId": "250601",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T17:42:42.650",
"Id": "250601",
"Score": "2",
"Tags": [
"c",
"ipc"
],
"Title": "IPC The sleeping barber problem in C feedback"
}
|
250601
|
<p>I'm using Spring boot - 2.3.3.RELEASE and gradle.</p>
<p>Note- I'm using Factory and Strategy pattern. This project is going to be used as a Library for other projects to import and use the methods exposed by Service layer.</p>
<p>Here is the folder structure: <a href="https://imgur.com/a/jYr7wyP" rel="nofollow noreferrer">https://imgur.com/a/jYr7wyP</a></p>
<p><strong>I would appreciate if the community can review this code and give suggestions to make it better.</strong></p>
<p>Demo.class</p>
<pre><code>@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@SpringBootApplication
public class Demo {
public static void main(String[] args) {
SpringApplication.run(Demo.class, args);
}
}
</code></pre>
<p>Init.java</p>
<pre><code>@Component
public class InitClass implements ApplicationRunner {
@Autowired
PhoneService phoneService;
@Override
public void run(ApplicationArguments args) throws Exception {
String title="Title";
String message="message";
List<String> phoneNumbers = new ArrayList<>();
phoneNumbers.add("333-222-1111");
phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
}
}
</code></pre>
<p>PhoneService.java</p>
<pre><code>@Service
public class PhoneService {
@Autowired
PhoneServiceImpl notificationServiceImpl;
public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
notificationServiceImpl.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
}
}
</code></pre>
<p>PhoneServiceImpl.java</p>
<pre><code>@Slf4j
@Component
public class PhoneServiceImpl {
@Value("${notificationService.url}")
String url;
public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
PhoneContext phoneContext = new PhoneContext(new SendPhoneByPhoneNumbers(url));
phoneContext.notify(title, message, phoneNumbers);
}
}
</code></pre>
<p>PhoneContext.java</p>
<pre><code>public class PhoneContext {
private PhoneStrategy phoneStrategy;
public PhoneContext(PhoneStrategy phoneStrategy){
this.phoneStrategy = phoneStrategy;
}
public void notify(String title, String message, List<String> employees){
phoneStrategy.sendNotification(title, message, employees);
}
}
</code></pre>
<p>PhoneStrategy.java</p>
<pre><code>public interface PhoneStrategy {
public void sendNotification(String title, String message, List<String> listOfEmployeeIdGroupNamePhoneNumbers);
}
</code></pre>
<p>SendPhoneByPhoneNumbers.java</p>
<pre><code>@Slf4j
public class SendPhoneByPhoneNumbers implements PhoneStrategy {
RestTemplate restTemplate;
String notificationServiceURL;
BuildHttpRequest buildHttpRequest;
public SendPhoneByPhoneNumbers(String notificationServiceURL) {
this.notificationServiceURL = notificationServiceURL;
this.restTemplate = new RestTemplate();
this.buildHttpRequest = new BuildHttpRequest();
}
@Async
public void sendNotification(String title, String message, List<String> listOfEmployeeIdGroupNamePhoneNumbers) {
SmsMessage smsMessage= new SmsMessage(title, message, listOfEmployeeIdGroupNamePhoneNumbers, Collections.emptyList(), Collections.emptyList());
try {
HttpHeaders headers = new HttpHeaders();
headers.set("idToken", buildHttpRequest.getNewToken());
HttpEntity<SmsMessage> newRequest = new HttpEntity<>(smsMessage, headers);
restTemplate.postForObject(notificationServiceURL + "/sms/custom", newRequest, String.class);
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>PhoneService class</h2>\n<p>In my opinion, the <code>PhoneService</code> should be converted to an interface exposing the methods.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface PhoneService {\n void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers);\n}\n</code></pre>\n<p>Then, the <code>PhoneServiceImpl</code> class can implement the interface <code>PhoneService</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>@Slf4j\n@Service\npublic class PhoneServiceImpl implements PhoneService {\n\n @Value("${notificationService.url}")\n String url;\n\n @Override\n public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {\n PhoneContext phoneContext = new PhoneContext(new SendPhoneByPhoneNumbers(url));\n phoneContext.notify(title, message, phoneNumbers);\n }\n}\n</code></pre>\n<p>Those’s changes will allow you to use inheritance and make the code easier to refactor if, you want to add any new phone services (new implementations). The old implementation was, in my opinion, a bit confusing and did not add any advantages that I can see.</p>\n<h2>Prefer <code>Constructor-based Dependency Injection</code> / <code>Setter-based Dependency Injection</code> over <code>Field Injection</code></h2>\n<p>In my opinion, the <a href=\"https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-constructor-injection\" rel=\"nofollow noreferrer\"><code>Constructor Dependency Injection</code></a> should be preferred over the <code>Field Injection</code> since it makes the testing easier and more natural (you can pass the mocks directly into the constructor) without using hardcore ways to inject the dependencies.</p>\n<p>Also, even in Spring documentation, the <code>Field Injection</code> <a href=\"https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-collaborators\" rel=\"nofollow noreferrer\">is not even mentioned as a way to inject</a> and lots of people don’t recommend it.</p>\n<h2>Never expose the variables directly in classes</h2>\n<p>In my opinion, it's a bad habit to have public variables in classes, since you don’t control your own data. Try to <code>hide</code> them by adding the <code>private</code> / <code>protected</code> keyword before them and use <code>getters</code> / <code>setters</code> to change the state. This will give you more control over the class own data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T00:42:45.427",
"Id": "250624",
"ParentId": "250607",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250624",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T19:16:37.917",
"Id": "250607",
"Score": "4",
"Tags": [
"java",
"spring"
],
"Title": "SpringBoot application to send notification via phone numbers on SMS"
}
|
250607
|
<p>I have a list of names and ID's, with many multiplication (it's a payroll list). I'd like to see those ID's and names where the name changed somewhen.</p>
<p>Input:</p>
<p>id1 name</p>
<hr />
<p>1 Josephine Baker<br />
2 Norma Jeane Morteson<br />
2 Marilyn Monroe<br />
33 Sandra Bullock<br />
15 Issur Danielovitch<br />
1 Freda Josephine McDonald<br />
15 Kirk Douglas<br />
28 Meg Ryan<br />
28 Margaret Hyra<br />
36 Vin Diesel<br />
36 Mark Sinclair<br />
8 Sean Connery<br />
11 Mel Gibson<br />
16 Julia Roberts</p>
<p>Desired output:</p>
<p>ID Name</p>
<hr />
<p>1 Freda Josephine McDonald<br />
1 Josephine Baker<br />
2 Marilyn Monroe<br />
2 Norma Jeane Morteson<br />
15 Issur Danielovitch<br />
15 Kirk Douglas<br />
28 Margaret Hyra<br />
28 Meg Ryan<br />
36 Mark Sinclair<br />
36 Vin Diesel</p>
<p>I'm running this query. It works well, it is fast enough, I just have a feeling that this could be a lot more professional.</p>
<pre><code>SELECT first(ST.id1) as ID , first(ST.nam) as Name
FROM Stars AS ST
INNER JOIN
(select id1, first(nam), count(id1) from
(select [ST1.id1]&[ST1.nam], first(ST1.id1) as id1, first(ST1.nam) as nam,
count(*) from Stars ST1
group by [ST1.id1]&[ST1.nam])
group by id1
having count(id1)>1) AS SJ
ON SJ.id1=ST.id1
GROUP BY ST.id1, ST.nam
ORDER BY ST.id1;
</code></pre>
<p>The logic behind is to select unique id&name pairs, then select those id's that come up more than once, then (self)join the table and select the unique names to those id's.</p>
<p>Any advise is welcome!</p>
|
[] |
[
{
"body": "<p>You'll have to take this with a huge grain of salt, because the following advice is for generic, standards-abiding SQL - which Access is not.</p>\n<p>In regular SQL, this is as simple as:</p>\n<pre><code>select dupes.id1, ST1.nam\nfrom (\n select id1\n from ST1\n group by id1\n having count(*) > 1\n) dupes\njoin ST1 on ST1.id1 = dupes.ST1\norder by dupes.id1;\n</code></pre>\n<p>Another way to do it without a join at all is a partition (window) function that adds a count column within each group. Unfortunately, <a href=\"https://support.microsoft.com/en-us/office/partition-function-1a846a33-60c7-4371-8e77-c94278274dc5\" rel=\"nofollow noreferrer\">the Access idea of a partition</a> diverges significantly from <a href=\"https://www.postgresql.org/docs/current/tutorial-window.html\" rel=\"nofollow noreferrer\">the rest of reality</a>, so this probably isn't possible for you. Regardless, for what it's worth, it would look like</p>\n<pre><code>select id1, nam\nfrom (\n select id1, nam,\n count(*) over (partition by id1) as n\n from ST1\n)\nwhere n > 1\norder by id1;\n</code></pre>\n<p>If at all possible, consider moving away from Access. It introduces more problems than it solves.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:02:44.813",
"Id": "492867",
"Score": "1",
"body": "Thank you, it works! And it is really as simple as I felt it should have been... and change to `inner join`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:13:13.903",
"Id": "250610",
"ParentId": "250608",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T19:18:05.393",
"Id": "250608",
"Score": "2",
"Tags": [
"sql",
"ms-access"
],
"Title": "MS Access query complexity on finding duplicates"
}
|
250608
|
<p>I'm posting a solution for LeetCode's "Design Circular Deque". If you'd like to review, please do so. Thank you!</p>
<h3><a href="https://leetcode.com/problems/design-circular-deque/" rel="noreferrer">Problem</a></h3>
<p>Design your implementation of the circular double-ended queue (deque).</p>
<p>Your implementation should support following operations:</p>
<ul>
<li><code>MyCircularDeque(k)</code>: Constructor, set the size of the deque to be k.</li>
<li><code>insertFront()</code>: Adds an item at the front of Deque. Return true if the operation is successful.</li>
<li><code>insertLast()</code>: Adds an item at the rear of Deque. Return true if the operation is successful.</li>
<li><code>deleteFront()</code>: Deletes an item from the front of Deque. Return true if the operation is successful.</li>
<li><code>deleteLast()</code>: Deletes an item from the rear of Deque. Return true if the operation is successful.</li>
<li><code>getFront()</code>: Gets the front item from the Deque. If the deque is empty, return -1.</li>
<li><code>getRear()</code>: Gets the last item from Deque. If the deque is empty, return -1.</li>
<li><code>isEmpty()</code>: Checks whether Deque is empty or not.</li>
<li><code>isFull()</code>: Checks whether Deque is full or not.</li>
</ul>
<h3>Example:</h3>
<pre><code>MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3
circularDeque.insertLast(1); // return true
circularDeque.insertLast(2); // return true
circularDeque.insertFront(3); // return true
circularDeque.insertFront(4); // return false, the queue is full
circularDeque.getRear(); // return 2
circularDeque.isFull(); // return true
circularDeque.deleteLast(); // return true
circularDeque.insertFront(4); // return true
circularDeque.getFront(); // return 4
</code></pre>
<h3>Note:</h3>
<ul>
<li>All values will be in the range of [0, 1000].</li>
<li>The number of operations will be in the range of [1, 1000].</li>
<li>Please do not use the built-in Deque library.</li>
</ul>
<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(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
struct MyCircularDeque {
MyCircularDeque(int k): stream(k, 0), counts(0), k(k), head(k - 1), tail(0) {}
const bool insertFront(
const int value
) {
if (isFull()) {
return false;
}
stream[head] = value;
--head;
head += k;
head %= k;
++counts;
return true;
}
const bool insertLast(const int value) {
if (isFull()) {
return false;
}
stream[tail] = value;
++tail;
tail %= k;
++counts;
return true;
}
const bool deleteFront() {
if (isEmpty()) {
return false;
}
++head;
head %= k;
--counts;
return true;
}
const bool deleteLast() {
if (isEmpty()) {
return false;
}
--tail;
tail += k;
tail %= k;
--counts;
return true;
}
const int getFront() {
return isEmpty() ? -1 : stream[(head + 1) % k];
}
const int getRear() {
return isEmpty() ? -1 : stream[(tail - 1 + k) % k];
}
const bool isEmpty() {
return !counts;
}
const bool isFull() {
return counts == k;
}
private:
using ValueType = std::uint_fast16_t;
std::vector<ValueType> stream;
ValueType counts;
ValueType k;
ValueType head;
ValueType tail;
};
</code></pre>
|
[] |
[
{
"body": "<p>You can call <code>stream.reserve(k)</code> in the constructor to improve the efficiency of the vector because you know that you will only have <code>k</code> elements, so <code>.reserve()</code> will pre-allocate the memory.</p>\n<p><a href=\"https://stackoverflow.com/questions/994288/size-t-vs-int-in-c-and-or-c\">Prefer using <code>std::size_t</code> over <code>int</code></a><br>\n<code>int k</code> would be <code>std::size_t k</code></p>\n<p>You haven't declared a <a href=\"https://en.cppreference.com/w/cpp/language/copy_constructor\" rel=\"nofollow noreferrer\">copy constructor</a> nor a <a href=\"https://en.cppreference.com/w/cpp/language/copy_assignment\" rel=\"nofollow noreferrer\">copy assignment operator</a>. This can cause issues if you wanted to assign one <code>Deque</code> to another.</p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/inline\" rel=\"nofollow noreferrer\">Inlining </a> some member functions of your <code>struct</code> like <code>isEmpty()</code>, <code>getRear()</code>, <code>getFront()</code> <strong>can</strong> improve the performance of your container, but it will be a trade for space.</p>\n<p><strong>If you are doing this for the sole purpose of completing the challenge, you can ignore the next part</strong></p>\n<h2>Templates</h2>\n<p>Right now, your <code>deque</code> is bound to use <code>std::uint_fast16_t</code>. But what if I wanted to make a <code>deque</code> of names? Or a <code>deque</code> of different decimal values? I can't just create 15 classes for each of the data types.</p>\n<p>Hence, I will use <a href=\"https://en.cppreference.com/w/cpp/language/templates\" rel=\"nofollow noreferrer\">templates</a> in C++ so I can create a <a href=\"https://en.cppreference.com/w/c/language/generic\" rel=\"nofollow noreferrer\">generic</a> <code>deque</code>.</p>\n<p>The syntax is simple</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template < typename T >\nstruct deque\n{\n public:\n // public member functions\n private:\n std::vector< T > stream;\n};\n</code></pre>\n<p>Now when you want to create a new deque, you can do <code>deque<any_data_type> my_deque</code>.</p>\n<p>Wherever you would use <code>ValueType</code>, you replace it with <code>T</code>.</p>\n<p>What C++ does is that it takes <code>any_data_type</code> and replaces <code>T</code> with that data type during <strong>compile-time</strong>. Implementing this in your program will teach you a lot about how templates work in C++ which will be helpful in your future projects.</p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/function_template\" rel=\"nofollow noreferrer\">Templates in C++</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T02:50:07.763",
"Id": "492863",
"Score": "1",
"body": "@Emma not really, I haven't been into competitive programming a lot, although i do like to solve some problems from time to time. Thanks for the feedback :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:49:04.090",
"Id": "250612",
"ParentId": "250609",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>Using the same type for the deque contents <em>and</em> the sizes/indices (<code>k, count, head, tail</code>) feels wrong. At least, <code>k</code> and <code>count</code> should be <code>std::vector::size_type</code>.</p>\n</li>\n<li><p>Since you are backing up the deque with <code>std::vector</code>, making <code>head</code> and <code>tail</code> the <code>std::vector::iterator</code> looks more idiomatic.</p>\n</li>\n<li><p><code>k</code> is not the most descriptive name. Consider <code>capacity</code>.</p>\n</li>\n<li><p>I am not sure that <code>std::vector</code> is the best container to back up the fixed size deque. After all, the point of <code>std::vector</code> is to have a dynamic size. <code>std::array</code>, or even a plain old C-style array, looks more natural.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:12:08.830",
"Id": "492846",
"Score": "1",
"body": "@Emma I wish there was one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:52:56.533",
"Id": "250613",
"ParentId": "250609",
"Score": "4"
}
},
{
"body": "<p>I think this is a theme for your code: <code>const</code>, where you've put it, has no benefit; and it's missing from other places that it should be there. Every single function in <code>MyCircularDeque</code> should drop the <code>const</code> out front, because those return values are scalar so marking them <code>const</code> has literally no effect. <code>insertLast(const int value)</code> has slightly more effect but is really not important.</p>\n<p>The most important place to put <code>const</code> is to modify the const-ness of <code>this</code> for your <code>get</code> and <code>is</code> methods. They need to have <code>const</code> added <em>after</em> the parentheses. This registers a promise that the methods do not modify any members.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T02:53:13.907",
"Id": "492864",
"Score": "1",
"body": "declaring a parameter const *does* have an effect. It makes sure that you will never modify the value. All in all, it is a good practice to declare variables that you will not modify `const` or `constexpr` if the value can be calculated at compile-time. [Use of const in function parameters](https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters#:~:text=Up%20vote%205-,const%20is%20pointless%20when%20the%20argument%20is%20passed%20by%20value,to%20modify%20the%20passed%20value.&text=If%20the%20function%20was%20not,result%20in%20a%20compiler%20warning.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:53:22.760",
"Id": "250614",
"ParentId": "250609",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T19:57:38.750",
"Id": "250609",
"Score": "4",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 641: Design Circular Deque"
}
|
250609
|
<p>I'm making a simple 2D framework / engine for the first time based on two books and before the project gets too big I would like to know if I'm ordering things the right way. Maybe there are better ways of doing this. I tried to apply patterns so I could decouple as much as possible and keep things abstract.</p>
<p>For example this is the <code>Game</code> class:</p>
<pre><code>#include "Game.h"
void Game::Create(int width, int height, const char * title, int window_flag, int renderer_flag){
display.CreateWindow(800,600,"Game", SDL_WINDOW_SHOWN, SDL_RENDERER_ACCELERATED);
}
void Game::Start(){
Uint32 first_frame_ticks; float delta_time = 0;
SDL_Renderer * renderer = display.GetRenderer();
while(input_handler.GetLastEvent() != SDL_QUIT){
first_frame_ticks = SDL_GetTicks();
bool state_manager_empty = state_manager.isEmpty();
//update
input_handler.Update();
if(!state_manager_empty) state_manager.GetGameState()->onUpdate(delta_time);
//render
SDL_RenderClear(renderer);
if(!state_manager_empty) state_manager.GetGameState()->onRender();
SDL_RenderPresent(renderer);
delta_time = (SDL_GetTicks() - first_frame_ticks) / 1000.0f;
}
display.Clear();
}
void Game::AddState(GameState* state){
state->Set(display.GetRenderer(), &input_handler);
state_manager.Add(state);
}
</code></pre>
<p>Or the Drawer class (wich I have some doubts about, the DrawEntity method is static)</p>
<pre><code>#include "Drawer.h"
void Drawer::DrawEntity(Entity& entity, TextureManager* texture_manager, SDL_Renderer * renderer){
texture_manager->Draw(entity.GetSprite(), entity.GetPosition(), renderer);
}
</code></pre>
<p>It acts like a mediator between TexureManager(wich draws texures) and Entity wich has all the information like position, scale, etc.</p>
<p>Finally the example input class</p>
<pre><code>#include "InputHandler.h"
#include <cstdio>
InputHandler::InputHandler(){
keyboard_state = SDL_GetKeyboardState(NULL);
printf("Event handler initialized\n");
}
void InputHandler::Update(){
SDL_Event ev;
while(SDL_PollEvent(&ev)){
if(ev.type == SDL_KEYUP || ev.type == SDL_KEYDOWN){
keyboard_state = SDL_GetKeyboardState(NULL);
}else last_event = ev.type;
}
}
bool InputHandler::isKeyPressed(SDL_Scancode key){
if(keyboard_state[key]) return true;
else return false;
}
Uint32 InputHandler::GetLastEvent(){
return last_event;
}
</code></pre>
<p>I'm going to upload a dependency diagram as well as the GitHub repo:
<a href="https://i.stack.imgur.com/1JIeT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1JIeT.png" alt="enter image description here" /></a></p>
<h1>Github Repo with all the Code</h1>
<p><a href="https://github.com/grazianobolla/monke-engine" rel="nofollow noreferrer">https://github.com/grazianobolla/monke-engine</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T21:00:41.333",
"Id": "492835",
"Score": "4",
"body": "Long code isn't frowned upon on code review, you **should** post your full project here"
}
] |
[
{
"body": "<h1>Update:</h1>\n<p>Well, if someone wants to know, I've done some changes for good,\none of the main problems I had was that I couldn't really "connect" the GameStates to the main Engine itself without passing a pointer to the engine (wich is messy) or individual pointers to the <code>InputHandler</code>, <code>Display</code>, etc.</p>\n<p>The thing was that for example the InputHandler handled the Window events and the keyboard input, so for a GameState to have access to it, I would have to create a pointer to Game::InputHandler, so I did a few things:</p>\n<p>First I created a <code>KeyboardHandle</code> class wich is totally independent from the Engine itself and its only function its to get keyboard input, that way I can make every game state to have an independent <code>KeyboardHandle</code>, also every game state has a pointer to the engine <code>Display</code> class, that means that from the game state you can get access to information like windows size or the <code>SDL_Renderer</code> without having much trouble, you add states from the <code>Engine</code> so the <code>Display</code> pointer is set at that moment.</p>\n<p>The <code>GameState</code> class is the base for all games, now it looks like this:</p>\n<pre><code>#pragma once\n#include "KeyboardHandle.h"\n#include "TextureManager.h"\n#include "Display.h"\n\nclass GameState{\nprotected:\n KeyboardHandle keyboard;\n TextureManager texture_manager;\n Display * screen_display;\npublic:\n GameState(Display * display){ this->screen_display = display; }\n virtual void onStart() = 0;\n virtual void handleInput() = 0;\n virtual void onUpdate(float) = 0;\n virtual void onRender() = 0;\n};\n</code></pre>\n<p>As you can see is almost all independent from the <code>Engine</code>, it just shares the display so we can render the graphics.</p>\n<p>Here is an example state (drawing an image on the center of the screen):</p>\n<pre><code>#include "GameState.h"\n#include "Entity.h"\n\nclass DefaultState : public GameState{\n Entity splash_logo;\npublic:\n DefaultState(Display * display) : GameState(display){ }\n\n void onStart(){\n texture_manager.Load("textures/splash_logo.png", "splash_logo", screen_display->GetRenderer());\n splash_logo = Entity("splash_logo", Vector2i(0, 0), Vector2i(336, 336), 1.0f);\n\n float center_x = (screen_display->GetWindowWidth() / 2) - splash_logo.GetCollisionBox().w / 2;\n float center_y = (screen_display->GetWindowHeight() / 2) - splash_logo.GetCollisionBox().h / 2;\n splash_logo.SetPosition({center_x, center_y});\n }\n\n void handleInput(){\n\n }\n\n void onUpdate(float delta_time){\n\n }\n\n void onRender(){\n texture_manager.Draw(splash_logo.GetSprite(), splash_logo.GetPosition(), screen_display->GetRenderer());\n }\n};\n</code></pre>\n<p>And just for fun here is the dependency diagram:\n<a href=\"https://i.stack.imgur.com/tJOYJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tJOYJ.png\" alt=\"Dependency Diagram\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:01:32.673",
"Id": "250680",
"ParentId": "250611",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "250680",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T20:48:34.573",
"Id": "250611",
"Score": "3",
"Tags": [
"c++",
"sdl"
],
"Title": "2D Game Framework in C++ and SDL"
}
|
250611
|
<p>I am an undergraduate CS student trying to implement <a href="https://github.com/pazamelin/sutf" rel="nofollow noreferrer">simple unit test framework</a> on C++ as a pet project.</p>
<p>The framework has an assertion macro like <code>ASSERT_EQ(var1, var2)</code>, which checks whether two variables are equal or not. If the assertion fails, I want to print a failure message to std::cerr and provide as much information as possible about failed comparison. Therefore, values <code>var1</code> and <code>var2</code> are to be printed. But what if there is no corresponding operator << for the variables' type(s)? In this case I have to provide output operators for the types, so the framework is able to print the values in a "default" way. However, a default output operator should not be called for some type T if the type already has output operator.</p>
<p>With a relative success, I employed SFINAE for it in the following way.</p>
<p>file "sfinae_print.hpp":</p>
<pre><code>#include <type_traits> // for enable_if
#include <iostream>
#include <utility>
//////////////////////////////////////
// META TYPE CHECK: OPERATOR << //
//////////////////////////////////////
// checks whether T has declared output iterator or not
template<typename T>
class has_output_operator
{
private:
// decltype(...) statically evaluates the type of passed expression
// fail leads to substitution failure in the context
template<typename U, typename = decltype(std::cout << std::declval<U>())>
static constexpr bool
check(nullptr_t) noexcept
{
return true;
}
// less specialized function - check(nullptr_t) is
// more preferable (but may cause substitution failure)
template<typename ...>
static constexpr bool check(...) noexcept
{
return false;
}
public:
static constexpr bool value{check<T>(nullptr)};
};
///////////////////////////////////////
// META TYPE CHECK: IS ITERATABLE //
///////////////////////////////////////
// checks whether T is iteratable (supports begin() and end()) or not
template<typename T>
class is_iteratable
{
private:
template<typename U>
static constexpr decltype(std::begin(std::declval<U>()),
std::end(std::declval<U>()),
bool())
check(nullptr_t) noexcept
{
return true;
}
template<typename ...>
static constexpr bool check(...) noexcept
{
return false;
}
public:
static constexpr bool value{check<T>(nullptr)};
};
template<typename T>
void print_meta_info(std::ostream& os = std::cout)
{
os << "is iteratable: " << is_iteratable<T>::value << std::endl;
os << "has output operator: " << has_output_operator<T>::value << std::endl;
os << std::endl;
}
/////////////////////////
// ITERATABLE TYPE //
/////////////////////////
// "default" output operators:
// operator << for iteratable type with no other output operators
template <typename T>
typename std::enable_if<is_iteratable<T>::value &&
!has_output_operator<T>::value,
std::ostream&>::type
operator << (std::ostream& os, const T& obj)
{
bool flag{false};
os << "{";
for(const auto& unit : obj)
{
if(flag)
{
os << ", ";
}
flag = true;
os << unit;
}
os << "}";
return os;
}
//////////////
// PAIR //
//////////////
// same for a pair:
template <typename LHS, typename RHS>
typename std::enable_if<!has_output_operator<std::pair<LHS, RHS>>::value, std::ostream&>::type
operator << (std::ostream& os, const std::pair<LHS, RHS>& obj)
{
return os << "{" << obj.first << "," << obj.second << "}";
}
/////////////////////////////
// NON-ITERATABLE TYPE //
/////////////////////////////
// same for non-iteratable type:
template <typename T>
typename std::enable_if<!is_iteratable<T>::value &&
!has_output_operator<T>::value,
std::ostream&>::type
operator << (std::ostream& os, const T& value)
{
// cannot be printed
// some failure is bound to occur
return os << value;
// print POD with reflection?
}
</code></pre>
<p>Usage example:</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include "sfinae_print.hpp"
std::ostream& operator << (std::ostream& os, const std::set<int> obj)
{
return os << "explicitly defined operator << for set<int>";
}
int main()
{
// printing values using "default" output operators:
const std::vector<std::string> v_str{"sfinae", "is", "dope"};
std::cout << v_str << std::endl;
const std::vector<int> v_int{1, 2, 3};
std::cout << v_int << std::endl;
const std::map<int, int> map_int_int{{1, 2}, {3, 4}};
std::cout << map_int_int << std::endl;
// std::set<int> has defined operator <<, thus there is no need in default operator <<
const std::set<int> set_int{1, 9, 1, 7};
std::cout << set_int << std::endl;
return 0;
}
</code></pre>
<p>CMakeLists.txt:</p>
<pre><code>cmake_minimum_required(VERSION 3.17)
# set the project name and version
project(SFINAE VERSION 0.1)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# set a variable for .cpp source files
set(SOURCES
main.cpp
)
# set a variable .h headers
set(HEADERS
sfinae_print.hpp
)
# add the executable
add_executable(SFINAE ${SOURCES} ${HEADERS})
# enable all warnings during compile process
# append flag to previously defined flag
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
</code></pre>
<p>Is it a tolerable solution? Could you please give me any suggestions on how to improve it?</p>
|
[] |
[
{
"body": "<p>I like the idea generally—it’s not bad at all—but the one thing that really raises my hackles about it is that you’re using <code>operator<<(ostream&, T)</code>, the standard stream inserter interface, as your basis testing output function.</p>\n<p>The reason it bothers me is three-fold. First, what you’re doing by doing this is <em>changing the public interface of the type under test</em> (assuming the type doesn’t already have a stream inserter function defined, of course—if it does, then no harm no foul). Now, this is somewhat unavoidable if you actually want to print the value of the type for useful test output… but… <code>operator<<(ostream&, T)</code> is a <em>very</em> generic interface component. It’s the <em>standard</em> stream interface. It’s one thing to add a very esoteric, your-test-framework-only function to the interface… that’s not ideal, but, as I said, it’s unavoidable. But adding an interface component as universal as <code>operator<<(ostream&, T)</code>… that seems a bit reckless.</p>\n<p>Second, I may have very good reasons for not wanting <code>operator<<(ostream&, T)</code> to be defined for some <code>T</code>. In fact, I may even have done <code>operator<<(ostream&, T) = delete</code>. What happens then?</p>\n<p>And third, even if I already have a stream inserter defined for my type… I may actually want <em>different</em> output for testing than the “normal” output. For example, I may want to print hidden flags or data in the type that normally wouldn’t want exposed in normal use.</p>\n<p>Another issue is that by adding stream inserter functions for things like <code>std::pair</code> and literally any iterable type, you have <em>radically</em> changed the environment. Again, this is unavoidable—any test framework, by axiomatic necessity, must exist in the test environment when it wouldn’t exist in normal operation. But again, it’s one thing for your test framework to add stuff that by-and-large won’t interact with anything else unless specifically made to (for example, by putting it in its own namespace that won’t conflict with other namespaces)… it’s quite another to add stuff that will likely—or in this case, almost certainly—get entangled with the the operations of the system-under-test.</p>\n<p>For example, my type may be designed to check for a stream inserter for <code>pair<X, Y></code>, which the user could provide if they want custom behaviour, and if one doesn’t exist, do a default output format instead. Since your test framework adds a stream inserter for <em>all</em> <code>pair<X, Y></code> (that don’t already have one), that means my type will never have to use its default output format. That means my type behaves differently depending on whether it’s being tested or not… which is absolutely <em>not</em> what you want.</p>\n<p>Yet another issue—one that you may already have run into—is the problem of where to put all your fallback stream inserter machinery. There are two arguments to standard stream inserters: one is in the <code>std</code> namespace (namely <code>std::ostream</code>), and the other is in an arbitrary namespace (namely, the namespace of <code>T</code>). You can’t put your fallback inserters in your test framework namespace (which you should absolutely have), because then they won’t be found for arbitrary types. You would either have to put it in the <code>std</code> namespace (no, don’t do that), or the namespace of <em>every <code>T</code> you might possibly use</em> (which is impossible), or—as you’ve done—in the “working” namespace (which in your case is the global namespace). Bad solutions all around.</p>\n<p>Okay, so enough doom and gloom: I’ve explained the problem, now what’s the solution?</p>\n<p>The solution is simply to <em>not</em> use the standard stream inserter interface as your test framework’s go-to output interface. Instead, use something that’s very loudly specific <em>only</em> to your test framework.</p>\n<p>You have basically two options.</p>\n<p>Option 1 is to use a custom function that can be found by ADL. <a href=\"https://www.boost.org/doc/libs/release/libs/test/doc/html/boost_test/test_output/test_tools_support_for_logging/testing_tool_output_disable.html\" rel=\"nofollow noreferrer\">This is what Boost.Test does</a>. All you need to do is define a function in your type’s namespace with the following signature:</p>\n<pre><code>auto boost_test_print_type(std::ostream&, T const&) -> std::ostream&;\n</code></pre>\n<p>For any variable <code>t</code>, Boost.Test basically does:</p>\n<ol>\n<li>Try an ADL call to <code>boost_test_print_type(cout, t)</code>.</li>\n<li>If that fails, try <code>cout << t</code>.</li>\n<li>If that fails, error.</li>\n</ol>\n<p>(There’s actually much more to it, including supporting the <code>BOOST_TEST_DONT_PRINT_LOG_VALUE</code> macro. But this is the gist of it.)</p>\n<p>So if you don’t want to or can’t provide a stream inserter for your type… <em>OR</em> you want different output for testing versus “normal” output for your type, you can just add a function <code>your_test_framework_printer_function(ostream&, T)</code> in <code>T</code>’s namespace (so ADL can find it). And of course you can have <code>your_test_framework_printer_function(ostream&, pair<X, Y>)</code> or <code>your_test_framework_printer_function(ostream&, AnyIterableType)</code> as defaults within your framework if you want.</p>\n<p>The key thing is that long, loud name is highly unlikely to conflict with anything else.</p>\n<p>Option 2 is to create a custom stream type. It doesn’t need to be complex—it could just be a simple wrapper around <code>std::ostream</code>. Then for each type you want special test output for, you’d define a function like:</p>\n<pre><code>namespace my_ns {\n\nstruct my_type {};\n\n// You probably wouldn't put this in the header file, you'd probably define\n// it only in the actual unit test file. But, whatever:\nauto operator<<(test_framework::ostream& o, my_type const& v)\n{\n // Do whatever you want here.\n o << "[my_type]";\n\n return o;\n}\n\n} // namespace my_ns\n</code></pre>\n<p>Your test framework, using a <code>test_framework::ostream</code> internally (which could just be a thin wrapper around a <code>std::ostream</code>), would then do:</p>\n<ol>\n<li>Try <code>o << t</code> (with <code>o</code> being a <code>test_framework::ostream</code>).</li>\n<li>If that fails, try <code>o.wrapped_stream << t</code> (where the wrapped stream is a <code>std::ostream</code>).</li>\n<li>If that fails, error.</li>\n</ol>\n<p>And again, you can provide defaults for <code>std::pair</code>, iterables, and whatever you like.</p>\n<p>The key thing here is that that special stream type, <code>test_framework::ostream</code>, is specific to the test framework, and thus won’t interact/interfere with the environment or type-under-test.</p>\n<p>In summary, what you’ve done so far is correct… but instead of working around the standard interface incantation <code>operator<<(std::ostream&, T)</code>, you should use a <em>custom</em> interface incantation that won’t interact or get entangled with the environment or the type-under-test. There are several ways to do that (I just mentioned 2), and you can still use <code>operator<<(std::ostream&, T)</code> as a default.</p>\n<p>Okay, now onto the code itself:</p>\n<pre><code>// checks whether T has declared output iterator or not\ntemplate<typename T>\nclass has_output_operator\n{\nprivate:\n\n // decltype(...) statically evaluates the type of passed expression\n // fail leads to substitution failure in the context\n template<typename U, typename = decltype(std::cout << std::declval<U>())>\n static constexpr bool\n check(nullptr_t) noexcept\n {\n return true;\n }\n\n // less specialized function - check(nullptr_t) is\n // more preferable (but may cause substitution failure)\n template<typename ...>\n static constexpr bool check(...) noexcept\n {\n return false;\n }\n\npublic:\n static constexpr bool value{check<T>(nullptr)};\n};\n</code></pre>\n<p>This isn’t “wrong”… but this really isn’t the way to do type traits in C++17 and beyond. Hell, it isn’t even the way to do type traits in C++11 anymore (because you can backport <code>void_t</code> pretty trivially).</p>\n<p>The tool you need is <code>std::void_t</code>. Trust me, it’s magical. This is what the type trait above looks like using <code>void_t</code>:</p>\n<pre><code>template <typename T, typename = void>\nstruct has_output_operator : std::false_type {};\n\ntemplate <typename T>\nstruct has_output_operator<T, std::void_t<decltype(std::cout << std::declval<T>())>> : std::true_type {};\n</code></pre>\n<p>That’s it. Basically 4 lines of code, 3 of which are <em>ENTIRELY</em> boilerplate, and the 4th is <em>mostly</em> boilerplate. And once you know the magic, you know exactly where to look for the meat of the type trait (which is just the stuff within <code>void_t</code>’s angle brackets). No need for comments explaining function overload precedence or any of that stuff.</p>\n<p>By the by, rather than:</p>\n<pre><code>std::cout << std::declval<T>()\n</code></pre>\n<p>as the test, I’d suggest:</p>\n<pre><code>std::declval<std::ostream&>() << std::declval<T>()\n</code></pre>\n<p>because it’s <em>technically</em> possible to have different behaviour when doing output to <code>cout</code> rather than a generic <code>ostream</code>. (I mean, any type that does this is evil, but….) As a bonus, now you can just include <code><iosfwd></code> rather than the much heavier <code><iostream></code>. (Well, except you need it for <code>cout</code> later.)</p>\n<p>As for the <code>is_iterable</code> type trait, the same <code>void_t</code> trick applies. In fact, <a href=\"https://en.cppreference.com/w/cpp/types/void_t\" rel=\"nofollow noreferrer\">the cppreference example for <code>void_t</code> has <code>is_iterable</code></a>.</p>\n<pre><code>// same for non-iteratable type:\ntemplate <typename T>\ntypename std::enable_if<!is_iteratable<T>::value &&\n !has_output_operator<T>::value,\n std::ostream&>::type\noperator << (std::ostream& os, const T& value)\n{\n // cannot be printed\n // some failure is bound to occur\n return os << value;\n // print POD with reflection?\n}\n</code></pre>\n<p>I may be misunderstanding what’s going on here, but if I’m reading this correctly, you want this function to be available for a <code>T</code> when <code>os << value</code> <em>fails</em> to compile? (And it’s not a type that supports iteration, which you provide a separate overload for.) But… if that’s the case, then you already know the body won’t compile.</p>\n<p>Except… it <em>will</em> compile… because you just wrote that missing inserter function. Thanks to the above function, <code>os << value</code> will now compile… and call <code>os << value</code>… which calls <code>os << value</code>… which calls <code>os << value</code>….</p>\n<p>See for yourself. In your <code>main.cpp</code>, add two lines: <code>struct foo {};</code> just before <code>main()</code>, and then <code>std::cout << foo{};</code> anywhere in <code>main()</code>. Compile, run, watch the fireworks. (To get a better visual sense of what’s going on, you could add a line in that function above that prints something like<code>"hi!\\n"</code> or maybe a counter before <code>os << value</code>.)</p>\n<p>So… what was supposed to happen here? I mean, you could fix the recursion by not trying to stream out <code>value</code>. But… then what? The comment indicates you might want to use reflection to print the type’s value? I guess lacking reflection, you could at least <a href=\"https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c\">print the type’s name using something like <code>abi::__cxa_demangle</code> or maybe picking apart <code>__PRETTY_FUNCTION__</code></a>.</p>\n<h1>Summary</h1>\n<p>I’d strongly recommend against working with the standard stream inserter interface. When you do, you’re screwing around with the environment and the widely-used public interface of the type-under-test, which could break a lot of stuff, and even if it doesn’t, it will probably make things behave differently during testing versus regular operation (which is a <em>HUGE</em> no-no). Instead, make a custom output interface—either a function or a custom stream—for your test framework; one that is clearly distinct and won’t get mixed up with the usual environment of the system-under-test.</p>\n<p>Use <code>std::void_t</code> to make your type traits. It’s a thousand times easier, and much easier to read, understand, and maintain.</p>\n<p>Beware that infinite recursion bug in your fallback inserter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:27:36.407",
"Id": "250737",
"ParentId": "250619",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T22:17:51.453",
"Id": "250619",
"Score": "5",
"Tags": [
"c++",
"template-meta-programming",
"sfinae"
],
"Title": "Using SFINAE to provide \"default\" output operators"
}
|
250619
|
<p>This is a problem from Codesignal.</p>
<p>The guaranteed constraints are <code>1 <= a.length <= 10^5</code>, and <code>1 <= a[i] <= a.length</code>.</p>
<p>You have to return the first duplicate encoutered in <code>a</code>, or <code>-1</code> if no duplicate is found.</p>
<pre><code>def firstDuplicate(a):
b = [0] * 100001
for num in a:
if b[num] == 1:
return num
else:
b[num] = 1
return -1
</code></pre>
<p>Is there a better way to do this? Perhaps faster or using less memory? The unused <code>0</code> index in the <code>b</code> array also doesn't feel very clean.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T23:40:00.480",
"Id": "492851",
"Score": "5",
"body": "you can use the 0th index with `num - 1`, also `if b[num]: return num` is sufficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:12:06.563",
"Id": "492920",
"Score": "1",
"body": "To save some space you can simply do `b = [0] * (len(a) + 1)`. You know the elements are bound by `1 <= a[i] <= a.length` so why blindly initialize to the maximum (`10^5`)... Doing `num-1` adds one more operation per iteration and slows down - it is better to just have one slot not used..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:55:48.823",
"Id": "492928",
"Score": "1",
"body": "The list -- which is essentially one implementation of a set -- could be filled with `False` and `True` directly and `if b[num] == 1` could be replaced with `if b[num]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T12:09:08.480",
"Id": "493091",
"Score": "0",
"body": "Serious question: What does Codesignal really want --- creativity? speed? footprint? I don't want to distract into the standard discussions of \"Interview Questions,\" but maybe knowing the intent of the original question can better guide the answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:40:18.137",
"Id": "493162",
"Score": "1",
"body": "@CarlWitthoft, they don't specify any criteria for optimization (perhaps unfortunately) besides that the solution has to run under 4 seconds, which is effectively the same as no constraint at all. I'm just using those websites to get better at algorithms. I try to optimize for speed and then for memory, knowing there's usually a tradeoff. Then come here for advice on how to do things better. I think for me the main appeal of those websites is the addictive quality that keeps me going all day on this stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:45:09.080",
"Id": "493165",
"Score": "0",
"body": "@Tomerikoo, good point about `num-1` adding one more operation"
}
] |
[
{
"body": "<p>Perhaps, using a dictionary to keep account of already seen values?</p>\n<pre><code>from collections import defaultdict\n\ndef first_duplicate(given_list):\n seen = defaultdict(bool)\n for value in given_list:\n if seen[value]:\n return value\n seen[value] = True\n return -1\n</code></pre>\n<hr />\n<ol>\n<li>Function name should be <code>lower_snake_case</code>.</li>\n<li><code>defaultdict</code> initialises with default value as <code>False</code>. You can pass <code>None</code> instead of <code>bool</code></li>\n<li>Use better/descriptive names of variables.</li>\n<li>Since <code>if</code> clause is returning a value, using the <code>else</code> clause is not needed.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:55:13.640",
"Id": "492858",
"Score": "0",
"body": "Thank you for the advice, I didn't know about `defaultdict()`. Out of curiosity, why is the `lower_snake_case` better practice? I actually used to do that and switched to camel because that's what they use on that website."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:18:05.317",
"Id": "492869",
"Score": "9",
"body": "Because of PEP8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:35:01.020",
"Id": "493115",
"Score": "0",
"body": "For a worst case like `list(range(1, 10**5+1))` this not only takes about 4.7 as much time as the original (see my answer) but also about 6.6 times as much memory as the original (and even 7.9 times as much in 32-bit Python)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T23:46:27.647",
"Id": "250622",
"ParentId": "250621",
"Score": "10"
}
},
{
"body": "<p>I'll propose an alternate implementation, because dictionaries are good at storing key-value pairs and you don't care about the value:</p>\n<pre><code>def first_duplicate(given_list):\n seen = set()\n for value in given_list:\n if value in seen:\n return value\n seen.add(value)\n return -1\n</code></pre>\n<p>A set will buy you basically the same behaviour as the "keys of a dictionary" for these purposes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:28:30.590",
"Id": "493112",
"Score": "0",
"body": "It's nice and I usually would've written it like this as well, but given that the OP also asked \"Perhaps faster or using less memory\", I find it worth mentioning that in a worst case like `list(range(1, 10**5+1))`, this not only takes twice as much time as the original but also five times as much memory. (But I guess neither the 17 upvotes nor the OP's acceptance are concerned about that :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:35:26.100",
"Id": "493116",
"Score": "1",
"body": "@superbrain Certainly; it's not the fastest, but I would venture to say that it's the \"most canonical\", if there is such a thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:38:10.233",
"Id": "493118",
"Score": "0",
"body": "Yes, I certainly agree with that. Like I said I usually would've written it like this as well (probably have multiple times, even with the same name `seen`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:14:33.053",
"Id": "493124",
"Score": "2",
"body": "This approach applies to arbitrary lists. The OP's approach applies primarily to positive integer lists whose maximum is limited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:30:08.893",
"Id": "493150",
"Score": "0",
"body": "@GZ0 That's how it should be advertised :-) Not quite arbitrary, though. Needs hashable elements."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:24:00.557",
"Id": "250631",
"ParentId": "250621",
"Score": "17"
}
},
{
"body": "<p>Note that all the elements are positive, and the values are not greater than the length.<br />\nThere is a very clever method to find the solution in these cases.</p>\n<p>The idea is to mark the values by turning <code>a[value]</code> negative.<br />\nIf a duplicate exists, it will encounter <code>a[duplicate]</code> as negative.</p>\n<p>Here's the implementation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in a:\n if a[abs(i) - 1] > 0:\n a[abs(i) - 1] *= -1\n\n else:\n print(abs(i))\n break\n\nelse:\n print(-1)\n</code></pre>\n<p>Make sure to turn the values to 0-based indexing though!</p>\n<p>This approach is O(N) time complexity and O(1) extra space complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T08:53:22.417",
"Id": "492900",
"Score": "1",
"body": "It's *not* O(1) extra space complexity. The negative integer objects cost space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T09:00:53.913",
"Id": "492901",
"Score": "0",
"body": "@superbrain `int`s take constant space in theory, regardless of their sign. I'm not using more than what's provided (like `dict`s or `set`s, which take O(N) extra space complexity). I don't see how the sign affects the extra space _complexity_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T09:12:46.057",
"Id": "492903",
"Score": "2",
"body": "Each single int, as long as it's bounded by a constant as it is here, takes constant space. But you don't just have a single one here. If I give you let's say `a = list(range(1, N//2+1)) * 2`, then you'll create new int objects for the first N/2 elements, which costs Θ(N) extra space. Not O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:11:28.763",
"Id": "493000",
"Score": "2",
"body": "For example for `a = list(range(1, 314159)) * 2`, the `set` solution builds a set of those numbers that takes 8.4 MB extra space, while you build the negations of those numbers and take 8.8 MB extra space: [demo](https://repl.it/repls/AgileUnequaledJavascript#main.py). That's with 64-bit Python. On 32-bit Python, it's 4.2 MB for the set and 5.0 MB for your numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:20:44.767",
"Id": "493002",
"Score": "1",
"body": "@superbrain I see! I didn't know that. So in the end, my solution was worse :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:31:01.123",
"Id": "493006",
"Score": "2",
"body": "Well, in languages like C++ or Java, with primitive types like *their* int, you'd overwrite the original values with their negations indeed without using extra space. And if I weren't so mean to use `a = list(range(1, N//2+1)) * 2` but instead used `a = list(range(1, N+1))`, then you might also take only O(1) extra space. Because you'd create the new number objects but the original number objects would be deleted since there'd be no references to them anymore. Then the new objects could occupy the memory where the originals were. It's just that my second half references the same objects, ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:31:18.930",
"Id": "493007",
"Score": "1",
"body": "... so they can't get deleted until you reach the second half."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:41:07.153",
"Id": "493008",
"Score": "2",
"body": "Oops, check the demo again. 314159 is larger than allowed. 19661 is allowed and leads to 524 kB for the set and 550 kB for your negatives. That's btw the largest allowed one where set \"wins\" in this regard. At 19662, the set resizes to 2.1 MB. At the limit, i.e., with `a = list(range(1, 50_001)) * 2`, the set is still at 2.1 MB and your negatives reach 1.4 MB. So at that limit you do take less extra space than the set. Just not O(1) :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:04:43.997",
"Id": "493173",
"Score": "0",
"body": "@superbrain, do you have any recommendations for ressources to learn what you're talking about here? I studied some of it but what you're talking about goes way beyond what I know. It's fascinating though and I'd like to understand more than I do about what's really happening \"under the hood\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:00:49.703",
"Id": "493189",
"Score": "0",
"body": "@jeremyradcliff Not a particular resource, no. Mostly knowledge I gathered here and there over the years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:21:31.153",
"Id": "493193",
"Score": "0",
"body": "@superbrain, that makes sense, I'll just keep learning as I go along and hope it sticks over time :)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T07:33:23.623",
"Id": "250637",
"ParentId": "250621",
"Score": "7"
}
},
{
"body": "<p><strong>Benchmark</strong> and slightly improved versions of some solutions.</p>\n<p>Congratulations, in the worst case (<code>a = list(range(1, 10**5 + 1))</code>) your original solution is about 2-4.5 times <em>faster</em> than the solutions in the previous answers:</p>\n<pre><code> 5.45 ms 5.46 ms 5.43 ms original\n 4.58 ms 4.57 ms 4.57 ms original_improved\n25.10 ms 25.59 ms 25.27 ms hjpotter92\n11.59 ms 11.69 ms 11.68 ms Reinderien\n10.33 ms 10.47 ms 10.45 ms Reinderien_improved\n23.16 ms 23.07 ms 23.02 ms Sriv\n17.00 ms 16.97 ms 16.94 ms Sriv_improved\n</code></pre>\n<p>Done with Python 3.9.0 64-bit on Windows 10 64-bit.</p>\n<p><code>original_improved</code> is yours but faster by not doing <code> == 1</code> and by using <code>False</code> instead of <code>0</code>, as that's <a href=\"https://github.com/python/cpython/blob/b4d895336a4692c95b4533adcc5c63a489e5e4e4/Objects/object.c#L1383\" rel=\"nofollow noreferrer\">fastest to recognize as false</a>. And for smaller input lists it takes less space as it makes <code>b</code> smaller accordingly.</p>\n<p>Code:</p>\n<pre><code>from timeit import timeit\nfrom collections import defaultdict\n\ndef original(a):\n b = [0] * 100001\n for num in a:\n if b[num] == 1:\n return num\n else:\n b[num] = 1\n return -1\n\ndef original_improved(a):\n b = [False] * (len(a) + 1)\n for num in a:\n if b[num]:\n return num\n b[num] = True\n return -1\n\ndef hjpotter92(given_list):\n seen = defaultdict(bool)\n for value in given_list:\n if seen[value]:\n return value\n seen[value] = True\n return -1\n\ndef Reinderien(given_list):\n seen = set()\n for value in given_list:\n if value in seen:\n return value\n seen.add(value)\n return -1\n\ndef Reinderien_improved(given_list):\n seen = set()\n seen_add = seen.add # Suggestion by Graipher\n for value in given_list:\n if value in seen:\n return value\n seen_add(value)\n return -1\n\ndef Sriv(a):\n for i in a:\n if a[abs(i) - 1] > 0:\n a[abs(i) - 1] *= -1\n else:\n return abs(i)\n else:\n return -1\n\ndef Sriv_improved(a):\n for i in map(abs, a):\n if a[i - 1] > 0:\n a[i - 1] *= -1\n else:\n return i\n else:\n return -1\n\nfuncs = original, original_improved, hjpotter92, Reinderien, Reinderien_improved, Sriv, Sriv_improved\n\na = list(range(1, 10**5+1))\n\ntss = [[] for _ in funcs]\nfor _ in range(4):\n for func, ts in zip(funcs, tss):\n t = min(timeit(lambda: func(copy), number=1)\n for copy in (a.copy() for _ in range(50)))\n ts.append(t)\n for func, ts in zip(funcs, tss):\n print(*('%5.2f ms ' % (t * 1000) for t in ts[1:]), func.__name__)\n print()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T01:12:20.757",
"Id": "493213",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/115144/discussion-on-answer-by-superb-rain-return-first-duplicate)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:44:22.873",
"Id": "250645",
"ParentId": "250621",
"Score": "14"
}
},
{
"body": "<p>Using list comprehension, make a list of the numbers occurring more than once</p>\n<pre><code>i for i in a if a.count(i) > 1\n</code></pre>\n<p>Return the first match or -1 if no match was found</p>\n<pre><code>next((i for i in a if a.count(i) > 1), -1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:31:35.600",
"Id": "492931",
"Score": "3",
"body": "You totally live up to your name :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:51:47.470",
"Id": "492938",
"Score": "2",
"body": "@superbrain How much slower? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:58:15.723",
"Id": "492941",
"Score": "1",
"body": "In my answer's benchmark it would take about 17000 times as long as the original solution. Also: `> 2`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:07:41.107",
"Id": "492944",
"Score": "1",
"body": "Edited the 2. Of course I didn't try running it. I'm a bit disappointed the next doesn't prevent it from going through the whole list"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:28:11.727",
"Id": "250649",
"ParentId": "250621",
"Score": "4"
}
},
{
"body": "<h1>Memory</h1>\n<p>Your list implementation uses (depending on your architecture) 8 bytes per list element.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> import sys\n>>> b = [False] * 100001\n>>> sys.getsizeof(b)\n800064\n</code></pre>\n<p>Note: This is just the memory of the list structure itself. In general, the contents of the list will use additional memory. In the "original" version, this would be pointers to two integer constants (<code>0</code> and <code>1</code>); in the "original_improved" version, it would be storing pointers to the two boolean singletons (<code>False</code> and <code>True</code>). Since we're only storing references to two objects in each case, this additional memory is insignificant, so we'll ignore it.</p>\n<hr />\n<p>800kB of memory is not a huge amount, but to be polite, we can reduce it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import array\n\ndef aneufeld_array(a):\n b = array.array('b', (0,)) * (len(a) + 1)\n\n for num in a:\n if b[num]:\n return num\n b[num] = 1\n\n return -1\n</code></pre>\n<p><strong>Update</strong>: <code>bytearray</code> is a better choice than <code>array.array('b', ...)</code>!</p>\n<pre class=\"lang-py prettyprint-override\"><code>def aneufeld_bytearray(a):\n b = bytearray(len(a) + 1)\n\n for num in a:\n if b[num]:\n return num\n b[num] = 1\n\n return -1\n</code></pre>\n<p>The <code>bytearray(size)</code> creates a tightly packed of bytes. Unlike lists, which can store different kinds of things in each element of the list, the bytearray, as its name implies, will only store bytes.</p>\n<p>With this new structure, we now use only 1 byte per flag, so around 100kB of memory:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> b = bytearray(100001)\n>>> sys.getsizeof(b)\n100058\n</code></pre>\n<p>Performance wise, this solution is close to the original speed, so we're not giving up any significant speed while reducing the memory load to around 12.5%.</p>\n<hr />\n<p>We can still do better. Using an entire byte for a single flag is wasteful; we can squeeze 8 flags into each byte. The <a href=\"https://pypi.org/project/bitarray/\" rel=\"noreferrer\"><code>bitarray</code></a> class does all of the heavy lifting for us:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import bitarray\n\ndef aneufeld_bitarray(a):\n b = bitarray.bitarray(len(a) + 1)\n b.setall(False)\n\n for num in a:\n if b[num]:\n return num\n b[num] = True\n\n return -1\n</code></pre>\n<p>This gets us down to 12.5kB for the bit-array of flags. Unfortunately, this additional memory optimization comes with an additional speed hit, due to the bit packing and unpacking. The performance is still better than "Sriv_improved" performance, and we're using only 1/64th of the original memory requirement.</p>\n<hr />\n<p>Timing, on my machine:</p>\n<pre class=\"lang-none prettyprint-override\"><code> 4.94 ms 4.62 ms 4.55 ms original\n 3.89 ms 3.85 ms 3.84 ms original_improved\n20.05 ms 20.03 ms 19.78 ms hjpotter92\n 9.59 ms 9.69 ms 9.75 ms Reinderien\n 8.60 ms 8.68 ms 8.75 ms Reinderien_improved\n19.69 ms 19.69 ms 19.40 ms Sriv\n13.92 ms 13.99 ms 13.98 ms Sriv_improved\n 6.84 ms 6.84 ms 6.86 ms aneufeld_array\n 4.76 ms 4.80 ms 4.77 ms aneufeld_bytearray\n12.71 ms 12.65 ms 12.57 ms aneufeld_bitarray\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:32:02.430",
"Id": "493128",
"Score": "0",
"body": "@superbrain My bad - clearly I needed sleep. Fixed it, ... and then completely replaced it `bytearray`, which is far superior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:00:14.257",
"Id": "493136",
"Score": "0",
"body": "Yeah, using `repeat` is better in that sense, although it still costs more space (because the `array` overallocates) than `array.array('b', (0,)) * (len(a) + 1)`, which is also shorter and about 2000 (!) times faster (for the worst case length)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:08:49.850",
"Id": "493138",
"Score": "0",
"body": "@superbrain Clearly, Python needs an `array.array(type, length)` constructor, based on all the hoops we're going through to allocate an array of the desired size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:16:29.400",
"Id": "493139",
"Score": "0",
"body": "@superbrain Updated my times using your array multiplication suggestion. Nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:42:17.570",
"Id": "493143",
"Score": "0",
"body": "Ha! Didn't think it would be noticeable in the solution time. I had only tested repeat-vs-multiply in isolation and repeat took about 0.006 seconds, which I thought was irrelevant in the overall solution time, but I forgot that I print the solution times in milliseconds :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:24:38.220",
"Id": "493156",
"Score": "0",
"body": "Thank you for the detailed answer. I changed my accepted answer to yours (I hope that's fine etiquette wise) because I find it the most in depth and helpful in terms of optimization; I learned a lot by reading it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:25:46.457",
"Id": "250682",
"ParentId": "250621",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "250682",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T23:32:33.500",
"Id": "250621",
"Score": "15",
"Tags": [
"python",
"algorithm",
"array"
],
"Title": "Return first duplicate"
}
|
250621
|
<p><strong>Problem</strong></p>
<p>I'm trying to write a code in which <em>Q</em> questions are asked and each question contains two numbers <em>A</em> and <em>B</em>. For each question, I have to find the sum of all primes between integers <em>A</em> and <em>B</em> (inclusive). I've written a program that works, but it isn't fast enough to pass all the restrictions. Is there any way to improve the efficiency of my code?</p>
<p><strong>Restrictions</strong></p>
<p><em>1≤Q≤10^5</em></p>
<p><em>1≤A≤B≤10^5</em></p>
<p><em>Time limit: 0.6s</em></p>
<pre><code>import java.io.*;
import java.util.*;
public class sumofprimes{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static StringTokenizer st;
static boolean isPrime(int n){
if(n==1)return false;
for (int i=2; i*i<=n; i++)
if (n%i==0) return false;
return true;
}
static int sum(int a, int b){
int sum=0;
for(int i=b; i>=a; i--) {
boolean prime=isPrime(i);
if(prime) sum+=i;
}
return sum;
}
public static void main(String[] args)throws IOException{
int q=readInt();
for(int i=0; i<q; i++){
int a=readInt(), b=readInt();
System.out.println(sum(a,b));
}
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:13:38.170",
"Id": "492854",
"Score": "1",
"body": "In terms of really efficient. There’s no doubt in my mind that there are deep mathematical results you could use to compute the sum of primes directly. But for something more efficient then what you have I would suggest just precomputing all the primes up to 10^5 e.g. a typical prime sieve. If you like you could also precompute the partial sums."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:51:43.370",
"Id": "492857",
"Score": "3",
"body": "@Countingstuff I am afraid there are no math results you have in mind; some asymptotics perhaps. That said, you are absolutely right re preprocessing with a sieve and partial sums."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T23:03:56.630",
"Id": "493204",
"Score": "0",
"body": "Where is this problem from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T01:06:29.930",
"Id": "493212",
"Score": "0",
"body": "@vnp https://mathoverflow.net/questions/81443/fastest-algorithm-to-compute-the-sum-of-primes proposes something along the lines of what I had in mind, I don't really follow the marked answer but Johan Andersson's idea makes sense. Unfortunately it's the same complexity as using the best (albeit highly impractical) sieve I know, O(n^(0.5 + o(1)), so I guess you're right."
}
] |
[
{
"body": "<p>Nice implementation, it's already efficient but as noted in the comments can be improved. Few general suggestions:</p>\n<ul>\n<li><p><strong>Format the code</strong>: many IDE support auto formatting or you can use an online <a href=\"https://www.freecodeformat.com/java-format.php\" rel=\"nofollow noreferrer\">formatter</a>.</p>\n</li>\n<li><p><strong>Omitting brackets is not good practice</strong>: it's better to include the brackets to avoid confusion when reading or changing the code. See the difference from:</p>\n<pre><code>static boolean isPrime(int n){ \n if(n==1)return false; \n for (int i=2; i*i<=n; i++) \n if (n%i==0) return false;\n return true; \n} \n</code></pre>\n<p>To:</p>\n<pre><code>static boolean isPrime(int n) {\n if (n == 1) {\n return false;\n }\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n</li>\n<li><p>Arrange the methods from general to specific, it's easier to follow. From:</p>\n<pre><code>static boolean isPrime(int n){ \n}\n\nstatic int sum(int a, int b){ \n //call isPrime\n} \n\npublic static void main(String[] args)throws IOException{ \n // call readint\n // call sum\n} \n\nstatic String next () throws IOException {\n}\n\nstatic int readInt () throws IOException {\n // call next\n}\n</code></pre>\n<p>To:</p>\n<pre><code>public static void main(String[] args)throws IOException{ \n // call readint\n // call sum\n}\n\nstatic int readInt () throws IOException {\n // call next\n} \n\nstatic String next () throws IOException {\n}\n\nstatic int sum(int a, int b){ \n //call isPrime\n} \n\nstatic boolean isPrime(int n){ \n}\n</code></pre>\n</li>\n<li><p>The methods <code>readInt</code> and <code>next</code> can be replaced with <code>java.util.Scanner</code>:</p>\n<pre><code>Scanner scanner = new Scanner(System.in);\nint q = scanner.nextInt();\n</code></pre>\n</li>\n<li><p><strong>Close the resources</strong>: <code>br.close()</code> (or <code>scanner.close()</code>) at the end of <code>main</code> or if exceptions occur.</p>\n</li>\n<li><p><code>PrintWriter pr</code> is not used.</p>\n</li>\n<li><p>The method <code>sum(int a, int b)</code> does not sum two integers. A better name might be <code>sumPrimesBetween</code></p>\n</li>\n<li><p>StringTokenizer is discouraged for new code, from the docs:</p>\n<blockquote>\n<p>StringTokenizer is a legacy class that is retained for compatibility\nreasons although its use is discouraged in new code. It is recommended\nthat anyone seeking this functionality use the split method of String\nor the java.util.regex package instead.</p>\n</blockquote>\n</li>\n</ul>\n<h2>Performance</h2>\n<p>As mentioned in the comments, since you know the upper bound 10^5 you can precompute all the prime numbers in advance. The <code>main</code> logic can be:</p>\n<ol>\n<li>Precompute all prime numbers until 10^5: you can use an array of boolean initialized to true and then set the corresponding index to false if not prime. For example:</li>\n</ol>\n<pre><code>static void computePrimesUntil(int n) {\n isPrime = new boolean[n+1];\n Arrays.fill(isPrime, true);\n isPrime[0] = isPrime[1] = false;\n for (int i = 2; i <= n; i++) {\n if (isPrime[i] && (long) i * i <= n) {\n for (int j = i * i; j <= n; j += i){\n isPrime[j] = false;\n }\n }\n }\n}\n</code></pre>\n<p>Code inspired from <a href=\"https://cp-algorithms.com/algebra/sieve-of-eratosthenes.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<ol start=\"2\">\n<li>Parse all the questions from the user</li>\n<li>Output the sum of primes for each question</li>\n</ol>\n<p><strong>Note</strong>: depending on how the total running time is calculated, you need to consider the time to parse the input and print the results. The total running time also depends on the machine where you run the program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:28:46.923",
"Id": "492910",
"Score": "0",
"body": "No idea why you say \"it's already efficient\". It's absolutely not. Not even yours is, although it's a lot better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:37:00.147",
"Id": "492925",
"Score": "0",
"body": "Honestly, I've seen worse implementations of `isPrime`, at least OP uses the condition i*i<=n. Definitely there are more efficient solutions, my suggestion is for OP's problem. Feel free to post yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:51:05.467",
"Id": "492927",
"Score": "0",
"body": "Sure. An inefficient `isPrime` would make it three or four levels of inefficient rather than two or three. But two or three levels of inefficient are still not \"efficient\". I *might've* written one if the OP hadn't kept the source of the problem secret. Can't be bothered to write my own test suite if the OP can't be bothered to provide a link to where I get the actual test suite already ready for use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T00:39:06.760",
"Id": "493208",
"Score": "0",
"body": "@superbrain The question is from DMOJ and the link is https://dmoj.ca/problem/alexquiz2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T00:44:19.250",
"Id": "493209",
"Score": "0",
"body": "@PencilKnot Doesn't work for me, shows \"No such problem\"."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:53:34.987",
"Id": "250633",
"ParentId": "250625",
"Score": "5"
}
},
{
"body": "<p><strong>Style Guide</strong></p>\n<p>Please read a <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">style guide</a>. You should</p>\n<ul>\n<li>always use braces when using a loop or if-statements.</li>\n<li>add access modifiers</li>\n<li>make spaces between operators.</li>\n<li>Don't use <code>*</code>-imports.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.util.StringTokenizer;\n\npublic class SumOfPrimes {\n private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n private static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));\n private static StringTokenizer st;\n\n public static void main(String[] args) throws IOException { \n int q = readInt();\n for(int i = 0; i < q; i++) {\n int a = readInt();\n int b = readInt(); \n System.out.println(sum(a, b));\n }\n } \n\n private static boolean isPrime(int n) { \n if(n == 1) {\n return false; \n }\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true; \n } \n \n private static int sum(int a, int b) { \n int sum = 0; \n for(int i = b; i >= a; i--) { \n boolean prime = isPrime(i); \n if(prime) {\n sum += i;\n }\n } \n return sum; \n } \n\n private static String next () throws IOException {\n while (st == null || !st.hasMoreTokens()) {\n st = new StringTokenizer(br.readLine().trim());\n }\n return st.nextToken();\n }\n\n static int readInt () throws IOException {\n return Integer.parseInt(next());\n }\n}\n</code></pre>\n<p><strong>Tell the user what to do</strong></p>\n<p>When I first started the program, I didn't know what to do, because the program didn't tell me:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) throws IOException { \n System.out.println("How many calculations do you want to make?");\n int q = readInt();\n for(int i = 0; i < q; i++) {\n System.out.println("Enter the lower bound:");\n int a = readInt();\n System.out.println("Enter the upper bound:");\n int b = readInt(); \n System.out.println("Result:");\n System.out.println(sum(a, b));\n }\n} \n</code></pre>\n<p><strong>Input validation</strong></p>\n<p>Your program crashes when the user enters a string instead of a number. You can avoid that by using a function like the following instead of <code>next()</code> and <code>readInt()</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static int getUserInput(String var) {\n Scanner sc = new Scanner(System.in);\n int number;\n while(true) {\n try {\n System.out.print(var);\n number = sc.nextInt();\n if(number < 0) {\n throw new InputMismatchException();\n }\n return number; \n } \n catch(InputMismatchException e) {\n System.out.println("Enter a number >= 0.");\n sc.nextLine();\n }\n } \n}\n</code></pre>\n<p><strong>lower bound > upper bound</strong></p>\n<p>You should check if the user enters <code>a</code> and <code>b</code> so that <code>a > b</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) throws IOException { \n int q = getUserInput("How many calculations do you want to make?");\n for(int i = 0; i < q; i++) {\n int a = getUserInput("Enter the lower bound:");\n int b = getUserInput("Enter the upper bound:");\n\n if(a > b) {\n int c = a;\n a = b;\n b = c;\n }\n System.out.println("Result:");\n System.out.println(sum(a, b));\n }\n}\n</code></pre>\n<p><strong>Code</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.Scanner;\nimport java.io.IOException;\nimport java.util.InputMismatchException;\n\npublic class SumOfPrimes {\n\n public static void main(String[] args) { \n int q = getUserInput("How many calculations do you want to make?");\n for(int i = 0; i < q; i++) {\n int a = getUserInput("Enter the lower bound:");\n int b = getUserInput("Enter the upper bound:");\n\n if(a > b) {\n int c = a;\n a = b;\n b = c;\n }\n System.out.println("Result:");\n System.out.println(sum(a, b));\n }\n } \n\n private static boolean isPrime(int n) { \n if(n == 1) {\n return false; \n }\n for (int i = 2; i * i <= n; i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true; \n } \n \n private static int sum(int a, int b) { \n int sum = 0; \n for(int i = b; i >= a; i--) { \n boolean prime = isPrime(i); \n if(prime) {\n sum += i;\n }\n } \n return sum; \n }\n\n private static int getUserInput(String var) {\n Scanner sc = new Scanner(System.in);\n int number;\n while(true) {\n try {\n System.out.print(var);\n number = sc.nextInt();\n if(number < 0) {\n throw new InputMismatchException();\n }\n return number; \n } \n catch(InputMismatchException e) {\n System.out.println("Enter a number >= 0.");\n sc.nextLine();\n }\n } \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T22:20:43.963",
"Id": "493198",
"Score": "0",
"body": "Those prints will likely make it wrong, though. Meaning it'll get judged \"Wrong Answer\" because its output doesn't match the expected output. Interesting dilemma, I don't know whether I ever thought about it: How to make it work in both cases. My best idea is to try reading the first input with a timeout. If there's input within let's say 0.1 seconds, assume it's from the judge system or some other program (or a fast user who knows what they're doing). Otherwise, assume it's manual input by a human and show those instructions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T22:54:01.137",
"Id": "493202",
"Score": "0",
"body": "@superbrain Are you talking about possible unit tests here? If that is the case, you can just use the sum()-method directly and you will not have to think about outputs, just about returns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T23:00:06.277",
"Id": "493203",
"Score": "1",
"body": "To me it rather looks like one of those sites where the judge feeds the input via stdin and takes the output via stdout, not directly using any method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T02:40:34.027",
"Id": "493217",
"Score": "0",
"body": "@superbrain Ah ok. I didn't notice that. Thanks for the hint."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:58:49.313",
"Id": "250708",
"ParentId": "250625",
"Score": "0"
}
},
{
"body": "<p>In <a href=\"https://codereview.stackexchange.com/a/250633/71574\">this answer</a>, you are told that you can precompute the list of primes. But if space is not a concern, we can go further and precalculate the sums.</p>\n<p>Assuming we have an array <code>prime</code> such that <code>prime[x]</code> tells us if <code>x</code> is prime or not.</p>\n<pre><code>long[] primeSumUpTo = new long[prime.length];\n\n// this explicit initialization is not necessary as 0 is the default value\nprimeSumUpTo[0] = 0;\nfor (int i = 1; i < prime.length; i++) {\n primeSumUpTo[i] = primeSupUpTo[i - 1];\n if (prime[i]) {\n primeSumUpTo[i] += i;\n }\n}\n</code></pre>\n<p>Now if we want to know the sum of primes between <code>a</code> and <code>b</code> inclusive, we can just do a simple calculation.</p>\n<pre><code>long primeSumBetween = primeSumUpTo[b] - primeSumUpTo[a - 1];\n</code></pre>\n<p>Your original algorithm was <span class=\"math-container\">\\$\\mathcal{O}(qn^{1.5})\\$</span> where <span class=\"math-container\">\\$q\\$</span> is the number of questions and <span class=\"math-container\">\\$n\\$</span> is the size of the range. The revised form in the other answer is <span class=\"math-container\">\\$\\mathcal{O}(qn + n \\log \\log n)\\$</span>, which is somewhat better. But this version would be <span class=\"math-container\">\\$\\mathcal{O}(q + n \\log \\log n)\\$</span>. Note that if <span class=\"math-container\">\\$q\\$</span> and <span class=\"math-container\">\\$n\\$</span> are equal as in the worst case from the problem, this gives powers of 2.5, 2, and more than 1 but less than 2 respectively.</p>\n<p>Note that the actual questions may use a smaller range than <span class=\"math-container\">\\$n\\$</span>. That could cause a timing fail because this version always sums the full <span class=\"math-container\">\\$n\\$</span>. We can avoid this by reading all the questions first (using more memory again) and then limiting our sums to the actual limits. In pseudocode, from min(a) - 1 to max(b).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T18:46:47.577",
"Id": "493514",
"Score": "0",
"body": "Now we just need to use an O(n) sieve so you can replace the clunky \"more than 1 but less than 2\" with just \"1\" :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T05:09:57.597",
"Id": "250821",
"ParentId": "250625",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250633",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T00:50:35.993",
"Id": "250625",
"Score": "5",
"Tags": [
"java"
],
"Title": "Efficient way to calculate the sum of all primes between a range"
}
|
250625
|
<p>I have a very standard Flask website being built, more or less straight out of the documentation though am now at a point where I'm going a bit off the book and am probably being highly inefficient about how my code handles user-input changes to their account details.</p>
<p>My users will have access to an <code>account_details.html</code> page where they can view and update their profile information.</p>
<p>The <code>account_details.html</code> page displays the Keys from <code>User.user_variables()</code> along with their present values and has a form where users can input the details they wish to update with and then submit changes (see attached image).</p>
<p>The <code>account_details view</code> then, presently, does no validation checks whatsoever and updates the table. I was going to implement checks but then figured I am probably doing things wrongly since I'd begin hard-coding values like minimum char lengths etc.</p>
<p>I suspect I could be doing just about everything more efficiently.</p>
<p>Please can anyone advise what the best way to allow users to update their account details? Happy for all suggestions but can't seem to find much by googling.</p>
<p>Thanks!</p>
<p>Paul.</p>
<p>Here are my bare bones for User-class/form/view/page.</p>
<p><strong>User class</strong></p>
<pre><code>class User(UserMixin, db.Model):
"""
User model inheriting db.Model for use in the database
Note: user_type is default to customer, likely to change as site evolves
"""
id = db.Column(db.Integer, primary_key=True)
name_first = db.Column(db.String(3), nullable=False)
name_last = db.Column(db.String(3), nullable=False)
name_company = db.Column(db.String(3), nullable=False)
email = db.Column(db.String(3), nullable=False, unique=True)
tel_office = db.Column(db.String(11), nullable=False)
tel_mob = db.Column(db.String(11), nullable=False)
password = db.Column(db.String(8), nullable=False)
date_created_utc = db.Column(db.DateTime, nullable=False, default=datetime.utcnow())
user_type = db.Column(db.String(), nullable=False, default='customer')
def user_variables(self):
"""
:return: List of all user variables which are then used in account_details.html
the Keys are what users see on the page, the list[0] is what it's called in this Class
and the list[1] is grabbing the data from current_user
"""
user_details = {
'User ID': ['id', current_user.id],
'First Name': ['name_first', current_user.name_first],
'Last Name': ['name_last', current_user.name_last],
'Company': ['name_company', current_user.name_company],
'Email': ['email', current_user.email],
'Office Tel': ['tel_office', current_user.tel_office],
'Mobile Tel': ['tel_mob', current_user.tel_mob],
'Date Registered': ['date_created_utc', datetime.strftime(current_user.date_created_utc, '%d/%m/%Y')],
'Account Type': ['user_type', current_user.user_type]
}
return user_details
</code></pre>
<p><strong>User registration form</strong></p>
<pre><code>class RegistrationForm(FlaskForm):
"""
Registration form used in Register page
"""
name_first = StringField(label='First Name', validators=[DataRequired(message='blah')])
name_last = StringField(label='Last Name', validators=[DataRequired(message='blah')])
name_company = StringField(label='Company Name', validators=[DataRequired(message='blah')])
email = StringField(label='Email', validators=[Email(message='blah'), DataRequired("blah")])
tel_office = StringField(label='Tel: office', validators=[DataRequired(message='blah')])
tel_mob = StringField(label='Tel: mob', validators=[DataRequired(message='blah')])
password = PasswordField(label='Password', validators=[DataRequired(message='blah')])
password_confirm = PasswordField(label='Confirm password', validators=[EqualTo('password', message='blah')])
submit = SubmitField(label='Register')
</code></pre>
<p><strong>account_details view</strong></p>
<pre><code>@app.route('/account_details', methods=['GET', 'POST'])
def account_details():
if current_user.is_authenticated:
user_details = current_user.user_variables()
user = User.query.filter_by(id=current_user.id).first()
if request.method == 'POST':
updated_values_dict = request.form.to_dict()
for k, v in updated_values_dict.items():
# TODO validation checks
# TODO password change
# The 'name' paramater in each form-control is jinja template of
# update_{{user_details[key][0]}} hence the check for k == 'update_' etc.
if k == 'update_name_first':
user.name_first = v.rstrip()
if k == 'update_name_last':
user.name_last = v.rstrip()
if k == 'update_name_company':
user.name_company = v.rstrip()
if k == 'update_email':
user.email = v.rstrip()
if k == 'update_tel_office':
user.tel_office = v.rstrip()
if k == 'update_tel_mob':
user.tel_mob = v.rstrip()
db.session.commit()
return redirect(url_for('account_details'))
return render_template('account_details.html', user_details=user_details)
</code></pre>
<p><strong>account_details.html page</strong></p>
<pre><code>{% extends 'navbar.html' %}
{% block content %}
<div class="container-sm">
<div class="home-header">
{% with messages=get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{category}}" role="alert">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
<form method="POST">
<div class="card text-left">
<div class="card-body">
<table class="table table-striped table-dark shadow-lg">
{% for key in user_details.keys() %}
<tr>
<td>{{ key }}</td>
<td>{{ user_details[key][1] }}</td>
{% if key not in ['User ID', 'Date Registered', 'Account Type'] %}
<td>
<div class="form-group">
<input class="form-control" id="update_field" name="update_{{user_details[key][0]}}"
placeholder="Type to update {{ key }}">
</div>
</td>
{% else %}
<td></td>
{% endif %}
</tr>
{% endfor %}
</table>
</div>
<button type="submit" class="btn btn-primary btn-sm">Make Changes</button>
</form>
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p><a href="https://i.stack.imgur.com/1CfGg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1CfGg.png" alt="Image of the account_details.html page" /></a></p>
|
[] |
[
{
"body": "<p>At the least, this can be done more efficiently:</p>\n<pre><code> if k == 'update_name_first':\n user.name_first = v.rstrip()\n if k == 'update_name_last':\n user.name_last = v.rstrip()\n if k == 'update_name_company':\n user.name_company = v.rstrip()\n if k == 'update_email':\n user.email = v.rstrip()\n if k == 'update_tel_office':\n user.tel_office = v.rstrip()\n if k == 'update_tel_mob':\n user.tel_mob = v.rstrip()\n</code></pre>\n<p>can be</p>\n<pre><code>setattr(\n user,\n k.split('update_', 1)[-1],\n v.rstrip(),\n)\n</code></pre>\n<p>depending on how much validation you need to do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T00:17:32.093",
"Id": "493028",
"Score": "0",
"body": "Thanks, I will certainly look into setattr()"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T03:03:24.033",
"Id": "250630",
"ParentId": "250626",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T00:52:12.490",
"Id": "250626",
"Score": "3",
"Tags": [
"python",
"flask"
],
"Title": "Python Flask, best way for users to update profile details"
}
|
250626
|
<p>My purpose is to calculate the energy spectrum of three-dimensional turbulent flow from three velocity components. The calculation is too expensive. Therefore, I hope the calculation time can be reduced. The above code is a sample of calculating the energy spectrum. I expect to receive some suggestions on parallel computing using OpenMP for the energy <code>E[k]</code>. The size of <code>i</code> and <code>j</code> loops are 1000 000 while that of <code>k</code> is 100. Some parameters, <code>x, y, z</code> are velocity components and <code>d1</code> is velocity magnitude, are created for code structure. I desire that the calculation is designed well on a pc with 40 cores.</p>
<p>This code is compiled as g++ test.cpp -o run -fopenmp</p>
<p>How can i parallelize this following code using openmp:</p>
<pre><code>#include <iostream>
#include <math.h>
#include <vector>
#include <math.h>
#include <cmath>
#include <omp.h>
using namespace std;
int main()
{
int i,j,k;
int np = 1000000; // number of fluid particle
int kmax = 100; // wavenumber
double E[kmax+1] = {0.0}; //energy
// need to be parallelized
for (i = 0; i < np-1; i++){
for (j = i+1; j < np; j++){
double x = sin(double(2*i+j)/(3.0*np));//x,y,z,d1 for test.
double y = sin(double(i+j)/(2.0*np));//x,y,z are velocity
double z = sin(double(i*j)/np/np); //d1 velocity magnitude
double d1 = sqrt(x*x + y*y + z*z);
for (k = 1; k <= kmax; k++){
double d2 = k * d1;
E[k] += x + y + sin(d2) / d2;
}
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:37:16.863",
"Id": "492926",
"Score": "6",
"body": "Welcome to the Code Review site where we review working code and provide suggestions on how to improve that code, such as optimization. What we can't do is help you write new code or implement feature requests such as changing the code to use multi-threading. In the guide on asking questions that @AryanParekh suggested you read it explains that code that is not working as expected is off-topic and feature requests are code that that is not working as expected. Other than that the question is very well written."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:47:23.533",
"Id": "492935",
"Score": "1",
"body": "I don't think this code works as intended, because `i*j` overflows sometimes given that `np = 1000000`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:17:33.077",
"Id": "493057",
"Score": "0",
"body": "There's a fine line between *What about coding X thus* / *How to best code X* vs. *How to achieve X*. The question (starting with *no OMP pragma*) makes me think the latter intended, & [Surt's answer](https://codereview.stackexchange.com/a/250685) helpful, if off CR@SE's topic. (Accepting [pacmaninbw's answer](https://codereview.stackexchange.com/a/250648) instils doubt.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:28:19.657",
"Id": "493058",
"Score": "0",
"body": "I don't understand your algorithm as a FFT is the typical method for computing spectrums. Also this calculation looks incorrect because sin is only calculated from [0 .. 1] radians instead of 0 - 2*pi radians."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:30:14.687",
"Id": "493075",
"Score": "0",
"body": "@CWallach I know FFT; however, i do not know to calculate the energy spectrum of three dimensional turbulent flow from FFT. Because i calculate without FFT, the cost is N^2 operations, and it is too expensive. The data of three-dimensional velocity components (512Mb for each) needs to be input into the calculation. This is difficult to up data here. Therefore, i make a \"simple sample\" of the calculation, as shown in the above code. And i hoped to receive the suggestions to improve the calculation speed. The formula in code is not accurate for energy spectrum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:35:23.343",
"Id": "493077",
"Score": "0",
"body": "@greybeard I agree with you that \"Accepting pacmaninbw's answer instils doubt.\". I spent a lot of time to speed up the calculation. I did not find the solution and ask the support here. However, i tested some commands from openmp and i found a solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:45:43.417",
"Id": "493079",
"Score": "0",
"body": "using \"#pragma omp parallel for reduction(+:E[:]) private(jes,kes) schedule(dynamic)\", the calculation is speeded up. The suggestion by Jerry Coffin is also a nice solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:17:38.547",
"Id": "493140",
"Score": "1",
"body": "The FFT algorithm reduces the number of operations to N Log N from N^2. When you have millions of samples this is huge. A FFT will provide far greater speedup than anything else. Google 3D FFT."
}
] |
[
{
"body": "<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Include Files</h2>\n<p>You are currently including <code>math.h</code> 3 times, it is only necessary to do this once. Since you are using C++, stick with <code>#include <cmath></code>.</p>\n<h2>Declare the Variables as Needed</h2>\n<p>The code contains this line:</p>\n<pre><code> int i,j,k;\n</code></pre>\n<p>These are the variables you are using as loop control variables, they can therefore be declared in the loops themselves:</p>\n<pre><code> for (int i = 0; i < np-1; i++){\n for (int j = i+1; j < np; j++){\n ...\n }\n }\n</code></pre>\n<h2>Break the Code Into Functions to Make it Easier to Implement and Debug</h2>\n<p>Currently the code is all in <code>main()</code>, as programs grow and features get added the code would be to complex to easily update if it is all in <code>main()</code>. Also to achieve the ultimate goal of multi-threading for this program you will need to break the code up into multiple functions that can run on a separate core.</p>\n<pre><code>void FUNCTION_NAME(int i, int j, int np, double E[])\n{\n double x = sin(double(2*i+j)/(3.0*np));//x,y,z,d1 for test.\n double y = sin(double(i+j)/(2.0*np));//x,y,z are velocity\n double z = sin(double(i*j)/np/np); //d1 velocity magnitude\n double d1 = sqrt(x*x + y*y + z*z);\n\n for (k = 1; k <= kmax; k++){\n double d2 = k * d1;\n E[k] += x + y + sin(d2) / d2;\n }\n}\n\nint main()\n{\n int np = 1000000; // number of fluid particle\n int kmax = 100; // wavenumber\n double E[kmax+1] = {0.0}; //energy\n\n // need to be parallelized\n for (i = 0; i < np-1; i++){\n for (j = i+1; j < np; j++){\n FUNCTION_NAME(i, j, np, E[]);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T00:51:07.497",
"Id": "493029",
"Score": "0",
"body": "@pacmainbw Thank you very much for your suggestions. Based on your comments, I will optimize the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:11:54.177",
"Id": "250648",
"ParentId": "250627",
"Score": "5"
}
},
{
"body": "<p>So you need to parallelize it and wonder where you should write</p>\n<pre><code>#pragma omp parallel for\n</code></pre>\n<p>There are many permutations of this that might be more effective, see manual for more, but try to place it just before the first loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:53:40.960",
"Id": "250685",
"ParentId": "250627",
"Score": "1"
}
},
{
"body": "<p>In parallel programming, it's often useful to try to minimize the degree to which the threads work with the same data. In this case, you have all the threads doing updates to <code>E</code> almost constantly throughout execution.</p>\n<p>To minimize collisions, I'd allocate a separate instance of <code>E</code> for each iteration of the loop you decide to execute in parallel, then after you've done the main loops of the simulation, add an extra loop to sum up the values in the per-iteration storage for <code>E</code>.</p>\n<p>For example:</p>\n<pre><code>double E[kmax+1];\n\nstatic double Es[np+1][kmax+1];\n\n#pragma omp parallel for schedule(dynamic)\nfor (int i = 0; i < np - 1; i++) {\n for (int j = i + 1; j < np; j++) {\n\n double x = sin(double(2 * i + j) / (3.0 * np)); //x,y,z,d1 for test.\n double y = sin(double(i + j) / (2.0 * np)); //x,y,z are velocity\n double z = sin(double(i * j) / np / np); //d1 velocity magnitude\n double d1 = sqrt(x * x + y * y + z * z);\n\n for (int k = 1; k <= kmax; k++) {\n\n double d2 = k * d1;\n // E[k] += x + y + sin(d2) / d2;\n Es[i][k] += x + y + sin(d2) / d2;\n }\n }\n}\n\nfor (int i = 0; i < np; i++)\n for (int j = 0; j < kmax; j++)\n E[j] += Es[i][j];\n</code></pre>\n<p>To run a quick test, I reduced np to 10'000. For that number of particles, your code (with the <code>#pragma omp</code> line added) ran in about 14.7 seconds. Changing it as outlined above reduced that to about 4.1 seconds.</p>\n<h3>vector</h3>\n<p>Rather than allocating arrays, I'd use <code>std::vector</code> to store the data:</p>\n<pre><code>std::vector<double> E(kmax + 1);\n\nstd::vector<std::vector<double>> Es(np + 1, E);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:00:32.517",
"Id": "493073",
"Score": "0",
"body": "Oh, it is a very nice solution. I will apply this approach to other codes. Thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T08:29:50.677",
"Id": "250697",
"ParentId": "250627",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250697",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T01:29:41.373",
"Id": "250627",
"Score": "3",
"Tags": [
"c++",
"performance",
"c++11",
"openmp"
],
"Title": "Calculation of Energy Spectrum using C++"
}
|
250627
|
<p>I am trying to ensure type in the below method. How to reduce its cognitive complexity to below 15 from the current 27? It looks more readable as it is? Is there a way to break this down to make it more readable?</p>
<p>Shifting some of the checks to separate method will be one way but is there a better way?</p>
<pre><code>private Object ensureType(Class<?> expectedClass, Object value) {
if (value == null)
return null;
Class<?> valueClass = value.getClass();
if (expectedClass.isAssignableFrom(valueClass))
return value;
if (expectedClass.isAssignableFrom(String.class)) {
return value.toString();
}
if (expectedClass.isAssignableFrom(Date.class)) {
if (Number.class.isAssignableFrom(valueClass)) {
return new Date(((Number) value).intValue());
}
try {
return formatter.parse(value.toString());
} catch (ParseException e) {
throw new ClassCastException("argument " + value + " of type " + valueClass + " cannot be converted to "
+ expectedClass + ":" + e);
}
}
if (expectedClass.isAssignableFrom(Integer.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).intValue();
return Integer.parseInt(value.toString());
}
if (expectedClass.isAssignableFrom(Double.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).doubleValue();
return Double.parseDouble(value.toString());
}
if (expectedClass.isAssignableFrom(Float.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).floatValue();
return Float.parseFloat(value.toString());
}
if (expectedClass.isAssignableFrom(Short.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).shortValue();
return Short.parseShort(value.toString());
}
if (expectedClass.isAssignableFrom(Byte.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).byteValue();
return Byte.parseByte(value.toString());
}
if (expectedClass.isAssignableFrom(Long.class)) {
if (Number.class.isAssignableFrom(valueClass))
return ((Number) value).longValue();
return Long.parseLong(value.toString());
}
if (expectedClass.isAssignableFrom(Boolean.class)) {
return Boolean.parseBoolean(value.toString());
}
throw new ClassCastException(
"argument " + value + " of type " + valueClass + " cannot be converted to " + expectedClass);
}
</code></pre>
<p>PS: I am moving this question from Stackoverflow to CR as it was suggested in the comments.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T05:04:19.063",
"Id": "492881",
"Score": "1",
"body": "The site standard is for the title to simply state the task accomplished by the code, not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T05:08:52.863",
"Id": "492882",
"Score": "0",
"body": "The title should state what your code does, the body should explain your code thoroughly and you should post your **full** project here for us the review it. Moreover, take your time and read [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T11:35:22.047",
"Id": "492924",
"Score": "0",
"body": "You're trying to ensure type. What does this mean? Java is already enforcing type-safety, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:26:56.860",
"Id": "493662",
"Score": "0",
"body": "I'm sure there are other (better?) ways do this, however that depends on the bigger picture and what the use case for this is. Where do the \"expected class\" and the \"value\" come from? What kind of objects will the \"value\" be? How are the resulting objects used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-20T09:32:09.557",
"Id": "493663",
"Score": "0",
"body": "BTW, you may also want to look into Spring. One of it's basic features is a conversion framework with some basic conversion you have implemented built-in: https://www.baeldung.com/spring-type-conversions https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#core-convert"
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>private Object ensureType(Class<?> expectedClass, Object value) {\n</code></pre>\n<p>Your names could be slightly better, given that this function does not only ensure something, but also <em>converts</em> it.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Object convert(Class<?> targetClass, Object value) {\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> throw new ClassCastException(\n "argument " + value + " of type " + valueClass + " cannot be converted to " + expectedClass);\n</code></pre>\n<p>Given that the function converts, I find the <code>ClassCastException</code> inappropriate. An <code>IllegalStateException</code> or <code>IllegalArgumentException</code> might be better fitting.</p>\n<hr />\n<p>What you're doing here is complex, and there is not really an easier way to do it either. You have n classes that you want to map to m classes, so the complexity will always be there in one way or another. The best thing you can do is make it more readable. For example with extracting the converting parts into functions:</p>\n<pre class=\"lang-java prettyprint-override\"><code> // ...\n \n if (targetClass.isAssignableFrom(String.class)) {\n return convertToString(value);\n }\n\n if (targetClass.isAssignableFrom(Date.class)) {\n return convertToDate(value);\n }\n \n if (targetClass.isAssignableFrom(Integer.class)) {\n return convertToInteger(value);\n }\n \n // ...\n</code></pre>\n<p>That is as readable as it gets, in my opinion.</p>\n<p>If you <em>like</em> classes, you can always extract the conversion into a single class for each mapping, and then iterate over that:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface Converter {\n public Class<?> getTargetType();\n public Object convert(Object value);\n}\n\n// ...\n\nList<Converter> converters = new ArrayList<>();\nconverters.add(new StringConverter());\nconverters.add(new DateConverter());\nconverters.add(new IntegerConverter());\n// ...\n\n// ...\n\nfor (Converter converter : converters) {\n if (targetClass.isAssignableFrom(converter.getTargetType())) {\n return converter.convert(value);\n }\n} \n</code></pre>\n<p>This, however, has the downside to split everything over many classes. A possible remedy to that might be to use single functions in the same class, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>HashMap<Class<?>, Function<Object, Object>> converters = new HashMap<>();\nconverters.put(String.class, this::convertToString);\nconverters.put(Date.class, this::convertToDate);\nconverters.put(Integer.class, this::convertToInteger);\n// ...\n\n// ...\n\nfor (Entry<Class<?>, Function<Object, Object>> converterEntry : converters.entrySet()) {\n if (targetClass.isAssignableFrom(converterEntry.getKey())) {\n return converterEntry.getValue().apply(value);\n }\n} \n</code></pre>\n<p>That might be one of the easier readable and maintainable variants.</p>\n<p>There is another, completely insane option, actually, which I feel to need to point out. You can use the above setup, with a method for every conversion, and reflection to build this list dynamically. Something along these lines:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Integer convertToInteger(Object value);\nprivate Date convertToDate(Object value);\nprivate String convertToString(Object value);\n\n// Pseudo-Code follows:\n\nfor (Method method : getClass().getDeclaredMethods()) {\n if (method.getName().startsWith("convert")) {\n if (targetValue matches method return type\n && value matches first method parameter) {\n return method.invoke(this, value);\n }\n }\n}\n</code></pre>\n<p>But that should be an absolute last resort, as it is not quite easy to maintain without knowing what you've got at your hands there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:50:40.713",
"Id": "250671",
"ParentId": "250634",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250671",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T04:26:36.210",
"Id": "250634",
"Score": "3",
"Tags": [
"java",
"complexity"
],
"Title": "Ensuring if an object is Assignable from a class type"
}
|
250634
|
<p>I request data from a table in a database and each line comes as a dictionary like this one :</p>
<pre><code>{
"timestamp" : 1234657890,
"prices" : {
"AAA" : 111,
"BBB" : 222,
...
"ZZZ" : 999
}
}
</code></pre>
<p>From all those lines i wanted to create a dataframe like this:</p>
<pre><code>Timestamp AAA BBB ... ZZZ
1234657890 111 222 ... 999
1234567891 110 223 ... 997
...
1324657899 123 208 ... 1024
</code></pre>
<p>So i did :</p>
<pre><code>rawData = database_request()
listPrices = []
for row in rawData
tmp = {'timestamp': row['timestamp']}
tmp.update({name : price for name,price in row['prices'].items()})
listPrices.append(tmp)
df = pd.DataFrame(listePrices)
</code></pre>
<p>So i was wondering if there were a more pythonic way to do this ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T09:40:39.393",
"Id": "492905",
"Score": "1",
"body": "Does it only have `prices` and `timestamps` in the dictionary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T09:42:39.520",
"Id": "492906",
"Score": "0",
"body": "yes only those two fields"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:05:55.610",
"Id": "492929",
"Score": "1",
"body": "You need [`pd.json_normalize`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html#pandas-json-normalize) here."
}
] |
[
{
"body": "<p>Your <code>rawData</code> (which should be ideally named <code>raw_data</code>, python suggests a style guide to name variables and functions in <code>lower_snake_case</code>) is already in a list structure. You can manipulate this in place, without having to process the whole dataset manually.</p>\n<pre><code>for row in raw_data:\n row.update(row.pop("prices"))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:43:36.967",
"Id": "250642",
"ParentId": "250640",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250642",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T09:00:46.297",
"Id": "250640",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Create DataFrame from dictionary"
}
|
250640
|
<p>I have a program that starts a bunch of goroutines, feeds them data and when there is no more data, waits for the goroutines to finish. I use sync.WaitGroup. I am unsure if I am using correctly, in an idiomatic way or if there is a better solution.</p>
<h2>Background</h2>
<p>My real code reads a log file of disk-space and numbers of files backed up etc for several servers. The records are intermingled. From this data it produces a web-page report per server with graphs etc. It works but I believe I can more cleanly separate the functions if I use concurrency. This is a test program before I go ahead and refactor.</p>
<h2>Code (72 lines including data)</h2>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"fmt"
"strconv"
"strings"
"sync"
)
func main() {
p := newPool()
defer p.Close()
for _, line := range strings.Split(logData, "\n") {
f := strings.Fields(line)
yr, _ := strconv.Atoi(f[0])
sub := f[1]
amt, _ := strconv.Atoi(f[2])
r := logRec{yr, sub, amt}
p.Report(r)
}
}
type logRec struct {
when int
subject string
amount int
}
type pool struct {
reporters map[string]chan logRec
wg *sync.WaitGroup
}
func newPool() pool {
rs := make(map[string]chan logRec)
var wg sync.WaitGroup
return pool{reporters: rs, wg: &wg}
}
func (p *pool) Report(rec logRec) {
if _, ok := p.reporters[rec.subject]; !ok {
c := make(chan logRec)
p.wg.Add(1)
go func() {
defer p.wg.Done()
tot := 0
for r := range c {
tot += r.amount
}
fmt.Printf("Total for %s is %d\n", rec.subject, tot)
}()
p.reporters[rec.subject] = c
}
p.reporters[rec.subject] <- rec
}
func (p pool) Close() {
for _, c := range p.reporters {
close(c)
}
p.wg.Wait()
}
const logData = `2018 apples 9
2018 oranges 5
2019 apples 27
2019 lemons 13
2019 oranges 2
2020 oranges 1
2020 apples 16
2020 lemons 3`
</code></pre>
<h2>Output</h2>
<pre><code>Total for oranges is 8
Total for lemons is 16
Total for apples is 52
</code></pre>
<hr />
<h2>Question:</h2>
<p>Can I improve this? Is there a better way to wait or a more idiomatic use of WaitGroups?</p>
|
[] |
[
{
"body": "<p>Yes, since you are here for code review:</p>\n<ol>\n<li>Never ever ignore errors: <code>yr, _ := strconv.Atoi(f[0])</code></li>\n</ol>\n<pre><code> yr, err := strconv.Atoi(f[0])\n if err != nil {\n log.Fatal(err)\n }\n</code></pre>\n<ol start=\"2\">\n<li>You may use just one <code>strings.Split</code>/<code>strings.Fields</code> this way:</li>\n</ol>\n<pre><code> f := strings.Fields(logData)\n for i := 3; i <= len(f); i += 3 {\n yr, err := strconv.Atoi(f[i-3])\n if err != nil {\n log.Fatal(err)\n }\n amt, err := strconv.Atoi(f[i-1])\n if err != nil {\n log.Fatal(err)\n }\n r := logRec{yr, f[i-2], amt}\n p.Report(r)\n }\n</code></pre>\n<ol start=\"3\">\n<li>You are over complicating a simple <code>sum</code> function, You don't need channels here, just a map does the job: It is this <strong>simple</strong>:</li>\n</ol>\n<pre><code>package main\n\nimport (\n "fmt"\n "log"\n "strconv"\n "strings"\n)\n\nfunc main() {\n m := map[string]int{}\n f := strings.Fields(logData)\n for i := 3; i <= len(f); i += 3 {\n amt, err := strconv.Atoi(f[i-1])\n if err != nil {\n log.Fatal(err)\n }\n m[f[i-2]] += amt\n }\n fmt.Println(m)\n}\n\nconst logData = `2018 apples 9\n2018 oranges 5\n2019 apples 27\n2019 lemons 13\n2019 oranges 2\n2020 oranges 1\n2020 apples 16\n2020 lemons 3`\n\n</code></pre>\n<ol start=\"4\">\n<li>For concurrency sake: You only need concurrent map, nothing more:</li>\n</ol>\n<pre><code>package main\n\nimport (\n "fmt"\n "log"\n "strconv"\n "strings"\n "sync"\n)\n\ntype concurrentMap struct {\n sync.Mutex\n m map[string]int\n}\n\nfunc (p *concurrentMap) sum(item string, amount int) {\n p.Lock()\n p.m[item] += amount\n p.Unlock()\n}\n\nvar data = &concurrentMap{m: map[string]int{}}\n\nfunc main() {\n f := strings.Fields(logData)\n for i := 3; i <= len(f); i += 3 {\n amt, err := strconv.Atoi(f[i-1])\n if err != nil {\n log.Fatal(err)\n }\n data.sum(f[i-2], amt)\n }\n fmt.Println(data.m)\n}\n\nconst logData = `2018 apples 9\n2018 oranges 5\n2019 apples 27\n2019 lemons 13\n2019 oranges 2\n2020 oranges 1\n2020 apples 16\n2020 lemons 3`\n</code></pre>\n<ol start=\"5\">\n<li>Long running task example:</li>\n</ol>\n<pre><code>package main\n\nimport (\n "fmt"\n "log"\n "strconv"\n "strings"\n "sync"\n "time"\n)\n\ntype concurrentMap struct {\n m map[string]int\n sync.Mutex\n}\n\nfunc (p *concurrentMap) sum(item string, amount int) {\n p.Lock()\n p.m[item] += amount\n p.Unlock()\n}\nfunc (p *concurrentMap) show() {\n p.Lock()\n for k, v := range p.m {\n fmt.Printf("Total for %s is %d\\n", k, v)\n }\n p.Unlock()\n}\n\nvar data = &concurrentMap{m: map[string]int{}}\n\nfunc main() {\n go data.sum("oranges", 100)\n go data.sum("apples", 100)\n go data.sum("lemons", 100)\n\n go func() {\n f := strings.Fields(logData)\n for i := 3; i <= len(f); i += 3 {\n amt, err := strconv.Atoi(f[i-1])\n if err != nil {\n log.Fatal(err)\n }\n data.sum(f[i-2], amt)\n time.Sleep(1000 * time.Millisecond) // e.g. slow hard disk\n }\n }()\n\n t := time.NewTicker(1000 * time.Millisecond)\n defer t.Stop()\n for range t.C {\n data.show()\n fmt.Println()\n }\n}\n\nconst logData = `2018 apples 9\n2018 oranges 5\n2019 apples 27\n2019 lemons 13\n2019 oranges 2\n2020 oranges 1\n2020 apples 16\n2020 lemons 3`\n</code></pre>\n<p>And finally if your tasks will finish in time, you may use <code>sync.WaitGroup</code>:</p>\n<pre><code>package main\n\nimport (\n "fmt"\n "log"\n "strconv"\n "strings"\n "sync"\n "time"\n)\n\ntype concurrentMap struct {\n m map[string]int\n sync.Mutex\n}\n\nfunc (p *concurrentMap) sum(item string, amount int) {\n p.Lock()\n p.m[item] += amount\n p.Unlock()\n}\nfunc (p *concurrentMap) show() {\n p.Lock()\n for k, v := range p.m {\n fmt.Printf("Total for %s is %d\\n", k, v)\n }\n p.Unlock()\n}\n\nvar data = &concurrentMap{m: map[string]int{}}\n\nfunc main() {\n finished := &sync.WaitGroup{}\n finished.Add(1)\n go func() {\n defer finished.Done()\n data.sum("oranges", 100)\n data.sum("apples", 100)\n data.sum("lemons", 100)\n }()\n\n finished.Add(1)\n go func() {\n defer finished.Done()\n f := strings.Fields(logData)\n for i := 3; i <= len(f); i += 3 {\n amt, err := strconv.Atoi(f[i-1])\n if err != nil {\n log.Fatal(err)\n }\n data.sum(f[i-2], amt)\n time.Sleep(100 * time.Millisecond) // e.g. slow hard disk\n }\n }()\n\n finished.Wait()\n data.show()\n}\n\nconst logData = `2018 apples 9\n2018 oranges 5\n2019 apples 27\n2019 lemons 13\n2019 oranges 2\n2020 oranges 1\n2020 apples 16\n2020 lemons 3`\n</code></pre>\n<p>That is all.<br />\nI hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T09:14:42.250",
"Id": "494012",
"Score": "1",
"body": "Thanks for the thoughtful and detailed review. There's a lot there that I can apply to what I am doing and that will influence my future projects. I appreciate the effort taken. I have also re-read the help centre and [relevant meta](https://codereview.meta.stackexchange.com/q/5163/42109) so that I can construct future questions a little more in accordance with this site's charter."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-23T05:44:35.773",
"Id": "251050",
"ParentId": "250641",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T10:14:07.863",
"Id": "250641",
"Score": "3",
"Tags": [
"go",
"concurrency"
],
"Title": "Waiting for goroutines to finish"
}
|
250641
|
<p>I've reimplemented in C++ the basic interface implemented by Python's <code>threading.Event</code> class using a mutex and condition variable. I've inlined functions rather than pasted both the header and source file. My reimplementation also skips the timeout argument to <code>wait</code> since I don't need it. The code appears to work through basic testing (test shown below reimplementation), but I'm particularly concerned about thread safety -- is using a mutex to protect <code>isSet_</code> enough, or is there a way for a thread to get stuck waiting for an event that's already been set? Are there any other improvements I need to make?</p>
<p>Reimplementation:</p>
<pre><code>#include <mutex>
#include <condition_variable>
class Event {
private:
std::mutex isSetLock;
bool isSet_ = false;
std::mutex setTriggerLock;
std::condition_variable setTrigger;
public:
bool isSet () {
isSetLock.lock ();
bool isSetRet (isSet_);
isSetLock.unlock ();
return isSetRet;
};
void set () {
isSetLock.lock ();
isSet_ = true;
isSetLock.unlock ();
setTrigger.notify_all ();
};
void clear () {
isSetLock.lock ();
isSet_ = false;
isSetLock.unlock ();
};
void wait () {
if (!isSet ()) {
std::unique_lock <std::mutex> setTriggerUniqueLock (setTriggerLock);
setTrigger.wait (setTriggerUniqueLock);
}
};
};
</code></pre>
<p>Basic test:</p>
<pre><code>#include "Event.hpp"
#include <thread>
class Test {
Event event;
void thread_ () {
event.wait ();
};
public:
Test () {
std::thread thread (&Test::thread_, this);
event.set ();
thread.join ();
};
};
int main () {
Test test;
// Should exit immediately
};
</code></pre>
|
[] |
[
{
"body": "<p>You can simplify things using RAII.</p>\n<pre><code>bool isSet () {\n isSetLock.lock ();\n bool isSetRet (isSet_);\n isSetLock.unlock ();\n return isSetRet;\n};\n</code></pre>\n<p>Can be simplified to:</p>\n<pre><code>bool isSet () {\n std::lock_guard<std::mutex> lockGuard(isSetLock); // Calls lock.\n return isSet_;\n}; // Calls unlock\n // in destructor.\n</code></pre>\n<p>Why do you have two different mutexes? There should only be a single one:</p>\n<pre><code>void wait () {\n if (!isSet ()) {\n std::unique_lock <std::mutex> setTriggerUniqueLock (setTriggerLock);\n setTrigger.wait (setTriggerUniqueLock);\n }\n}\n</code></pre>\n<p>This should be:</p>\n<pre><code> std::unique_lock <std::mutex> setTriggerUniqueLock(isSetLock);\n while (isSet()) {\n setTrigger.wait(setTriggerUniqueLock);\n }\n</code></pre>\n<p>Note: While the thread is paused (waiting) in the condition variable the mutex is unlocked (so other threads can still lock the mutex). The thread is only released from the condition variable (after a notify) when it has re-acquired the lock.</p>\n<p>Note: You have to use <code>while</code> here (<strong>not</strong> if). After the thread is woken you need to retest the condition because another thread may have re-locked the <code>isSet_</code> variable before this thread re-acquired the lock.</p>\n<p>Note: The condition variable has this built in:</p>\n<pre><code> std::unique_lock <std::mutex> setTriggerUniqueLock(isSetLock);\n setTrigger.wait(setTriggerUniqueLock, [&](){return !isSet_WithoutNeedingToLockAsWeHaveTheLock()});\n</code></pre>\n<p>Note: After doing this your <code>notify_all()</code> should be on <code>setTrigger</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:03:48.933",
"Id": "250662",
"ParentId": "250647",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "250662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:04:48.847",
"Id": "250647",
"Score": "3",
"Tags": [
"c++",
"multithreading"
],
"Title": "C++ reimplementation of Python's threading.Event"
}
|
250647
|
<p>I try to create compare script using awk and another command and running successful.</p>
<p>But I think the script I create it's to long.</p>
<p>Is there anyone can shorten my script below ?</p>
<p>After plan A <code>shorten the code than</code>, plan B is :</p>
<pre><code> 1. I want eliminated a lot temp file (.txt), only need `lengkap.txt`
2. Put command in variable if can
</code></pre>
<p>It's my pleasure if anyone can help me</p>
Below is the code that I create based searching and trying.
<pre><code>#!/bin/bash
### Path Folder who will be compare ###
path1=/home/rio/apps1
path2=/home/rio/apps2
### Find all filename and convert to MD5 ###
find $path1 -type f | xargs md5sum > checksums.md5
find $path2 -type f | xargs md5sum > checksums2.md5
### Compare to find different folder ###
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums.md5 checksums2.md5 > hasil1.txt
awk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums2.md5 checksums.md5 > hasil2.txt
### Merge result of compare ###
awk '{print $0}' hasil1.txt hasil2.txt > perbedaan.txt
### Filter Just Filename Difference ###
cat perbedaan.txt | awk '{print $2}' > hasilperbedaan.txt
### File about result compare (just filename) ###
cekhasil=/home/rio/hasilperbedaan.txt
### Check if File result compare empty or not ###
if [ -s "$cekhasil" ]
then
echo " file exists and is not empty "
### Find All filename and date, after that put as we want ###
find $path1 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate1.txt
find $path2 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate2.txt
### Compare to get the date of filename ###
awk 'A[$1]++' hasilperbedaan.txt filedate1.txt > pre_hasil1.txt
awk 'A[$1]++' hasilperbedaan.txt filedate2.txt > pre_hasil2.txt
### Merge result of compare with date ###
awk '{print $0}' pre_hasil1.txt pre_hasil2.txt > lengkap.txt
else
echo " file does not exist, or is empty "
fi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:43:22.343",
"Id": "492933",
"Score": "4",
"body": "Welcome to Code Review Stack Exchange! You might find useful the advice on choosing a good title for a question. You can edit yours. https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:50:35.907",
"Id": "492937",
"Score": "3",
"body": "Please tell us what the code is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:58:32.863",
"Id": "493181",
"Score": "0",
"body": "one thing that seems fishy about the script is that it writes a lot of files in cwd, which are all not cleaned after the job is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T07:42:38.960",
"Id": "493231",
"Score": "0",
"body": "@pacmaninbw it's for compare folder with different server but same folder (example : apps)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T07:43:25.210",
"Id": "493232",
"Score": "0",
"body": "@hjpotter92, yes, I think so too. That's why need advice to shorten the script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T11:46:05.970",
"Id": "493250",
"Score": "0",
"body": "Please add `it's for compare folder with different server but same folder (example : apps)` to the question to make it clearer. Perhaps with a little more explanation."
}
] |
[
{
"body": "<p>Well, it took time to figure out what your program is doing. So I did shorten it in two phases.</p>\n<p>First phase: I removed all duplicate temporary files, and used a pipe when a temp file was used once.</p>\n<p>STEP1: you just make a checksum of all files in $path1 and $path2</p>\n<pre><code>### Find all filename and convert to MD5 ###\nfind $path1 -type f | xargs md5sum > checksums.md5\nfind $path2 -type f | xargs md5sum > checksums2.md5\n</code></pre>\n<p>You don't need 2 temp files, as path is included in filename. So you can replace this with a single <code>find</code>. I use <code>sort</code> to be able to use uniq afterwards:</p>\n<pre><code>find "$path1" "$path2" -type f | xargs md5sum | sort > cksum.md5\n</code></pre>\n<p>STEP2: you find unique checksums in both files, and get the corresponding filenames.</p>\n<pre><code>### Compare to find different folder ###\nawk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums.md5 checksums2.md5 > hasil1.txt\nawk 'NR==FNR{c[$1]++;next};c[$1] == 0' checksums2.md5 checksums.md5 > hasil2.txt\n\n### Merge result of compare ###\nawk '{print $0}' hasil1.txt hasil2.txt > perbedaan.txt\n\n### Filter Just Filename Difference ###\ncat perbedaan.txt | awk '{print $2}' > hasilperbedaan.txt\n</code></pre>\n<p>As we have a checksum-sorted file, we just filter with <code>uniq</code>, and get filenames.</p>\n<p><strong>Note</strong>: As we use a MD5 checksum (128 bits), length is 128bits / 8bits * 2hex=32</p>\n<pre><code>uniq -u -w32 cksum.md5 | awk '{print $2}' > "$cekhasil"\n</code></pre>\n<p>If you prefer awk to uniq, just compare previous record's $1 with current's.</p>\n<p>STEP 3: you match found entries with a new search (<code>find</code>) in the two source paths.</p>\n<pre><code>if [ -s "$cekhasil" ]\nthen\n echo " file exists and is not empty "\n ### Find All filename and date, after that put as we want ###\n find $path1 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate1.txt\n find $path2 -type f -ls | awk '{print $11" "$8" "$9" "$10 }' > filedate2.txt\n\n ### Compare to get the date of filename ###\n awk 'A[$1]++' hasilperbedaan.txt filedate1.txt > pre_hasil1.txt\n awk 'A[$1]++' hasilperbedaan.txt filedate2.txt > pre_hasil2.txt\n ### Merge result of compare with date ###\n awk '{print $0}' pre_hasil1.txt pre_hasil2.txt > lengkap.txt\nelse\n echo " file does not exist, or is empty "\nfi\n</code></pre>\n<p>Here, it is better to avoid new full <code>find</code>, and just loop over filenames.</p>\n<pre><code>if [ -s "$cekhasil" ]\nthen\n echo " file exists and is not empty "\n while read -r fn ; do\n ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'\n done < "$cekhasil" > lengkap2.txt\n\nelse\n echo " file does not exist, or is empty "\nfi\n</code></pre>\n<p>Alltogether, the script becomes:</p>\n<pre><code>#!/bin/bash\n\npath1=/home/br/dev/tools/bash\npath2=/home/br/dev/tools/bash2\noutfile=hasilperbedaan.txt\n\nfind "$path1" "$path2" -type f | xargs md5sum | sort > cksum.md5\n\nuniq -u -w32 cksum.md5 | awk '{print $2}' > "$outfile"\n\nif [ -s "$outfile" ]; then\n echo " file exists and is not empty "\n while read -r fn ; do\n ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'\n done < "$output" > lengkap2.txt\n\nelse\n echo " file does not exist, or is empty "\nfi\n</code></pre>\n<p>At this point, we can notice the 2 remaining temp files are used only once. We just get rid of them, and just <code>pipe</code> all together to get the output file.</p>\n<pre><code> #!/bin/bash\n \n path1=/home/br/dev/tools/bash\n path2=/home/br/dev/tools/bash2\n outputfile="lengkap-v2.txt"\n \n find "$path1" "$path2" -type f | xargs md5sum | sort |\n uniq -u -w32 | awk '{print $2}' |\n while read -r fn ; do\n ls -dils "$fn" | awk '{print $11" "$8" "$9" "$10 }'\n done > "$outputfile"\n [[ -s "$outputfile" ]] && echo " file exists and is not empty " ||\n echo " file does not exist, or is empty "\n</code></pre>\n<p><strong>Notes</strong>:</p>\n<ul>\n<li>I don't understand your second question: "Put command in variable if\ncan", so I skip that one.</li>\n<li>You should <strong>never</strong> use the output of <code>find</code> (except with <code>-print0</code> options) or <code>ls</code> as input of any command. But it is out of scope for this answer.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-23T15:04:16.160",
"Id": "256379",
"ParentId": "250651",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:32:35.340",
"Id": "250651",
"Score": "0",
"Tags": [
"bash",
"linux",
"awk"
],
"Title": "Compare script using awk and bash"
}
|
250651
|
<p>I have written a basic REST endpoint in Ktor and would like some pointers.</p>
<p><strong>Application.kt</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>@KtorExperimentalAPI
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(Authentication)
install(ContentNegotiation) {
gson {}
}
val materialRepository = MaterialRepository(environment.config.property("repo.ws").getString())
routing {
route("/api") {
materials(materialRepository)
}
}
}
</code></pre>
<p><strong>MaterialResource.kt</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>fun Route.materials(
repo: MaterialRepository
) {
route("/materials") {
get("/{id}") {
when (val idParam = call.parameters["id"]) {
is String -> {
val id = idParam.toIntOrNull()
if (id == null) {
call.respond(HttpStatusCode.NotFound)
} else {
when (val material = repo.get(id)) {
is Material -> call.respond(material)
else -> call.respond(HttpStatusCode.NotFound)
}
}
}
else -> call.respond(HttpStatusCode.BadRequest)
}
}
}
}
</code></pre>
<p><strong>MaterialRepository.kt</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>
class MaterialRepository(
val wsInput: String
) {
private var materials: Map<Int, Material> = HashMap()
init {
val jsonMaterials = Gson().fromJson(FileReader(wsInput), JsonMaterialTable::class.java)
materials = jsonMaterials.rows.map {
it.ID_WS to Material( /*...snip as the model is quite large...*/ )
}.toMap()
}
fun get(id: Int): Material? {
return materials[id]
}
}
</code></pre>
<p>It feels like I am not using the whole power of kotlin and writing too much boilerplate. I am following the general guidelines of Kotlin and Ktor tutorials, but I still think this is too compliated and could be massively improved in terms of readability and general best practices before I continue writing the whole rest of the application.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:33:05.940",
"Id": "250652",
"Score": "1",
"Tags": [
"rest",
"kotlin"
],
"Title": "Basic REST API in Ktor"
}
|
250652
|
<p>The below code ran in 2:26 which is way too slow especially as it's only 1/3rd of the total (the remaining 2/3rd does something very similar just on different sections). Is there something I can do to speed this up? RangeCount = 625 and TimelineCount = 156 which are obviously large numbers (total is around 100k rows) but when RangeCount was 200 (30k rows) the code ran in 3 seconds...not sure why it's gone so slow now.</p>
<p>Link to sample: <a href="https://drive.google.com/file/d/1QHHtWad6_giWETZcAKw8-Qaq7Y6JJ4NX/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1QHHtWad6_giWETZcAKw8-Qaq7Y6JJ4NX/view?usp=sharing</a></p>
<p>Edit: I believe I have discovered the issue - the table in Dash Data was an Excel table. I changed it from being an Excel table to just normal cells and it ran the whole code in 4 seconds. Can someone explain to me why the table is so slow or how I could improve the speed of it, please??</p>
<pre><code>Sub copy_to_dash_data()
Dim i, j As Integer
Dim wsCalcs As Worksheet
Dim wsDashData As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim FirstRow As Long
Dim RangeCount As Long
Dim TimelineCount As Long
Dim LastCell As Long
Dim PasteCell As Long
Dim InvoiceDetailsColumnCount As Long
Dim NamedRange As Range
Dim StartTime As Double
Dim TimeElapsed As String
'timer calculation
StartTime = Timer
'set calcs to manual, disable user events and disable screen updating
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'setup sheet names for easy reference
Set wsCalcs = ThisWorkbook.Sheets("Calcs")
Set wsDashData = ThisWorkbook.Sheets("Dash Data")
'find last row and column of Dash Data and clear contents
LastRow = wsDashData.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Application.Match("P&L Amount", wsDashData.Rows(1), 0)
wsDashData.Range(Cells(2, 1).Address, Cells(LastRow, LastCol).Address).ClearContents
'count the number of rows in the first Calc block and the timeline block
FirstRow = wsCalcs.Range(Names("Invoice_Details")).Row
LastRow = wsCalcs.Range(Names("Invoice_Details")).Rows.Count + FirstRow - 1
RangeCount = wsCalcs.Range(Names("Invoice_Details")).Rows.Count - 1
TimelineCount = wsCalcs.Range(Names("Months_and_Years_Timeline")).Columns.Count - 1
'month start, month end and year rows from Calcs values transfer to Dash Data a number of times equal to the number of rows in the Calc block (e.g. number of invoices)
PasteCell = Application.Match("Month Start", wsDashData.Rows(1), 0)
For i = 1 To RangeCount
wsDashData.Range(Cells(2 + (TimelineCount * (i - 1)), PasteCell).Address, Cells(1 + (TimelineCount * i), PasteCell + 2).Address) = _
Application.Transpose(wsCalcs.Range(Names("Months_and_Years_Timeline")))
Next i
'enable events and screen updating
Application.ScreenUpdating = True
Application.EnableEvents = True
Calculate
'code complete!
TimeElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox ("Code complete in " & TimeElapsed), vbInformation
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:48:28.850",
"Id": "492936",
"Score": "0",
"body": "Is the code here in the question indented the same way it is in the VBA module?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:53:11.873",
"Id": "492949",
"Score": "0",
"body": "Yes... is that a problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:12:42.037",
"Id": "492956",
"Score": "0",
"body": "No, just checking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:05:20.717",
"Id": "492964",
"Score": "1",
"body": "You need to describe exactly what the code is doing. Sample data or a mock workbook download would help. Does `Months_and_Years_Timeline` values change during each iteration of the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:11:49.373",
"Id": "492965",
"Score": "0",
"body": "This snippet takes the months and years timeline which is just the month start, month end and year for every month from 2018 to 2030 (156 columns) and transposes it rangecount number of times (625 times) into a data table in the dash data tab."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:29:27.463",
"Id": "492968",
"Score": "0",
"body": "Sample data here: https://drive.google.com/file/d/1QHHtWad6_giWETZcAKw8-Qaq7Y6JJ4NX/view?usp=sharing\n\nNo, the Months and Years Timeline doesn't change so it's just copying and pasting data 625 times essentially. The other data that comes in does change with each iteration but I thought this was the easiest bit to explain."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:33:31.813",
"Id": "250653",
"Score": "1",
"Tags": [
"performance",
"vba"
],
"Title": "VBA Data dump code using transpose and timeline duplication"
}
|
250653
|
<p>I am trying to learn Go and as way of throwing myself in the deep-end I thought it would be cool to try building a web framework instead of using an already existing solution. I'm coming from the JavaScript world so all the type and interface stuff is new to me as well. I was wondering if this is an acceptable approach to doing something.</p>
<p>Essentially, I am trying to take a request that someone might send to a server and check some information about it to determine whether or not it should be allowed to move on. Specifically, in this example I am looking to see if the request method from a client is the same as the one the user of this framework intended an endpoint to be used with.</p>
<p>To do so, I am using middleware to access the req data, however I am unsure if this is ok... Here is my code, any feedback or suggestions would be much appreciated.</p>
<p>Running of the server:</p>
<pre><code>var mux = http.NewServeMux()
func (r *Router) Run(c RunConfig) {
log.Fatal(http.ListenAndServe(c.Port, mux))
}
</code></pre>
<p>Small portion of my router code:</p>
<pre><code>func checkMethod(next http.Handler, method string) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
fmt.Printf("checkMethod\n \tMehtod: %v\n \tpath: %v\n", r.Method, r.URL.Path)
if method == r.Method {
next.ServeHTTP(rw, r)
} else {
fmt.Println("Wrong method")
}
})
}
// GET is a receiver function of Router and is used to create a route with a GET request.
// path {string}
// handler {http.HandlerFunc}
func (r *Router) GET(path string, handler http.HandlerFunc) {
r.tree[path] = createNode(path, "GET", handler)
mux.Handle(path, checkMethod(handler, "GET"))
}
</code></pre>
<p>It seems to work but is this an acceptable solution? Is there any reason not to do this? Would it scale?</p>
<p>Please let me know if you have questions or need to see more code (although this is more-or-less it right now).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:40:11.453",
"Id": "250654",
"Score": "3",
"Tags": [
"go"
],
"Title": "Checking data on an incoming request in Go"
}
|
250654
|
<p>I'm a CS professor and provided this code as a small piece of a refactoring assignment:</p>
<pre><code>private double getTotalPrice(int quantity, double itemPrice) {
if (quantity == 13) {
return itemPrice * 12; // Baker's dozen
}
else if (quantity >= 6) {
return itemPrice * quantity * .95;
} else {
return itemPrice * quantity;
}
}
</code></pre>
<p>Students are supposed to remove inappropriate magic numbers, but, when discussing the above code with them, I realized I don't know the best way to improve the above code. I'm not interested in improving performance, just teaching how to write clean and maintainable code.</p>
<p><strong>Updates</strong></p>
<p>I realize there are other problems with the code, some intentional. What I am most interested in is how to name the magic numbers.</p>
<p>The purpose of the code is to determine the total price for an order of up to 13 items (limit in place to prevent hoarding). My priorities are readability and maintainability.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:00:34.173",
"Id": "492963",
"Score": "1",
"body": "Thank you, @Emma. I have them use the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html), which seems more up-to-date than the Oracle one and also because I worked at Google for many years. I'll share the former article with them. I also assign portions of _Effective Java_, which is the course textbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:20:52.573",
"Id": "492990",
"Score": "2",
"body": "Also: Please, please, when discussing that code, always point out that using floating point for money just *begs* for trouble."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:55:34.423",
"Id": "493023",
"Score": "2",
"body": "@Bobby, you are absolutely right. A later part of the assignment is converting the doubles to `BigDecimal`. Effective Java is my Bible, and that is Psalm -- I mean Item -- 60."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T11:03:54.677",
"Id": "493083",
"Score": "1",
"body": "@Ellen To play devil's advocate: A double has 18 signifcant digits. Hence in reality `BigDecimal` only makes sense for very specific situations where you do a loooong list of calculations on some values and want to keep a specific property. For things like a simple price using a fixed point number will work just as well. In your use case using a double and rounding at the end to the actual significant digits (2 or maybe 3 for most use cases) will give exactly the same result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T04:02:42.863",
"Id": "493455",
"Score": "0",
"body": "There is an argument that this question should be closed as Unclear What You're Asking. You don't provide a description of what the function is supposed to do. So we have to guess from inspecting the code. For example, if the quantity is 14, this code will set the price as `14 * .95 * itemPrice`. Is that correct? Or should it be `13 * itemPrice`? Or `12.95 * itemPrice`? Note that a customer could achieve the second price simply by making two separate purchases. In the future, please provide a problem statement for what the code is supposed to solve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T19:50:01.990",
"Id": "493525",
"Score": "0",
"body": "@mdfst13 I have added an explicit purpose for the code."
}
] |
[
{
"body": "<p><strong>Refactoring</strong></p>\n<p>The first thing I'd do is remove the redundant <code>else</code> statements. If you return from every branch, then there's really no need for the <code>else</code> clauses, they're just adding noise.</p>\n<p><strong>Constants?</strong></p>\n<p>It seems like there's some scope for constants / or lookups since there's some numbers floating around that seem to have meaning (discount amount, discount trigger threshold) etc. If you're labelling a number with a comment (baker's dozen), it's a good indication that it could be replaced with a constant to 'name' the value.</p>\n<p><strong>What are you really be looking for?</strong></p>\n<p>However, for me, I think the code actually serves more to prompt questions about whether or not it is performing as desired. If it is performing as expected, then it's the type of pricing system I hate (because it relies on the customer to optimize their own purchases).</p>\n<p>If I buy 12 items, I'm charged for 12 at the discounted rate.</p>\n<p>If I buy 13, I'm charged for 12 items at the standard rate.</p>\n<p>If I buy 14, I'm charged for 14 at the discounted rate. This is more expensive than me buying 13, then buying a single item as a separate transaction.</p>\n<p>Is this correct? Are you hitting me with the postage? Why don't I get 26 for the price of 24?</p>\n<p>etc...</p>\n<p><strong>Constants Revisited</strong></p>\n<p>I think some of the above contribute to your difficulty coming up with constants... I'd go with something like this:</p>\n<pre><code>private static double getTotalPrice(int quantity, double itemPrice) {\n if (quantity == SPECIAL_ONE_OFF_DISCOUNT_QUANTITY) {\n return itemPrice * (SPECIAL_ONE_OFF_DISCOUNT_QUANTITY - 1);\n }\n if (quantity >= TRIGGER_DISCOUNT_QUANTITY) {\n return itemPrice * quantity * DISCOUNT_MULTIPLIER;\n }\n return itemPrice * quantity;\n}\n</code></pre>\n<p>I'm using 'SPECIAL_ONE_OFF_DISCOUNT_QUANTITY', because it really is a special one off amount, with the current logic. It doesn't duplicate at 26 etc. I've got rid of the '12' constant, because really it's just 1 less than the trigger amount. Having a 'ONE_OFF_DISCOUNTTED_QUANTITY' constant might make sense if you could see the need to pay for 10 when you bought 13 for example, however this seems a it unnecessary.</p>\n<p>As I said, I'd prefer to rework the logic so that you always pay the lowest amount + so that discounts are additive. This changes the output prices, so obviously wouldn't be possible if it didn't actually make sense to the client. It does allow some of the constants to have different names though:</p>\n<pre><code>private static double getTotalPrice(int quantity, double itemPrice) {\n var chargeableQuantity = quantity - quantity / BUY_X_GET_ONE_FREE_QUANTITY;\n var valueMultiplier = chargeableQuantity >= TRIGGER_DISCOUNT_QUANTITY ? DISCOUNT_MULTIPLIER : 1;\n\n return itemPrice * chargeableQuantity * valueMultiplier;\n}\n</code></pre>\n<p>I think 'BUY_X_GET_ONE_FREE_QUANTITY' is a better name than 'SPECIAL_ONE_OFF_DISCOUNT_QUANTITY', but it only really makes sense if buying twice the amount results in twice the discount...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:53:26.350",
"Id": "492962",
"Score": "2",
"body": "Yes, there are problems with the logic of the discount. I may have the students improve that as well. What I really want people's opinions on, however, is how the constants should be named."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:01:40.327",
"Id": "492974",
"Score": "1",
"body": "@EllenSpertus I've expanded my constants suggestions, however as with everything name based... it's very subjective and there's no 'right' answers...just obviously wrong ones"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T12:25:13.727",
"Id": "493092",
"Score": "0",
"body": "I'm going to claim that using constants _is_ obviously wrong, whatever you call them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:38:11.810",
"Id": "493095",
"Score": "0",
"body": "@Useless wrong in general, or just in this case? Context obviously has an impact, but I think it's a lot easier to argue that a constant `TEN=11` is obviously wrong than constants are always wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:55:55.410",
"Id": "493103",
"Score": "0",
"body": "I think that `SPECIAL_ONE_OFF_DISCOUNT_QUANTITY` looks pretty suspicious. Obviously I'm importing my real-world expectation of store discounting behaviour into the question when I assume the values are likely to change, but I think when you know something's value and aren't sure how to name it - that's often a strong indicator it should be treated as data instead of inserted into the code at all."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:24:33.500",
"Id": "250657",
"ParentId": "250655",
"Score": "8"
}
},
{
"body": "<p>Other points:</p>\n<ul>\n<li>This is Java, so it's important that your method be marked <code>static</code> given that it is forced to be a class member</li>\n<li>Make a temporary variable <code>double subTotal = itemPrice * quantity;</code> to avoid duplication of the multiplication on the bottom</li>\n<li>When you do factor out magic numbers, whether they belong as class members or locals depends on the rest of the class, which you haven't shown. If the rest of the class reuses these constants then they belong as <code>static final</code> members. Otherwise, just make them local <code>final</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:51:59.163",
"Id": "492961",
"Score": "2",
"body": "You're absolutely right that I forgot to make the method static. My question was really how to name the constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T03:51:00.017",
"Id": "493454",
"Score": "0",
"body": "@EllenSpertus Just to be clear, while you are welcome to suggest areas for review, it is always open for answerers to critique any and all aspects of the code and ignore your suggestions. In this, Code Review is somewhat different from other SE sites. It's less about questions and answers and more about code and observations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:43:49.747",
"Id": "250658",
"ParentId": "250655",
"Score": "5"
}
},
{
"body": "<p>Another possibility would be an object-oriented approach in which we use the concept of <a href=\"https://en.wikipedia.org/wiki/Abstraction_(computer_science)\" rel=\"nofollow noreferrer\">abstraction</a>.</p>\n<p><img src=\"https://github.com/rgabisch/presentations/raw/master/object-oriented-programming/images/abstraction.png\" alt=\"\" /></p>\n<p>For this we could abstract the logic <code>quantity == 13</code> as a method with the sigiture <code>isOneOffDiscountFor(int quantity)</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private boolean isOneOffDiscountFor(int quantity) {\n return quantity == 13;\n}\n\nprivate boolean isCheaperDiscountFor(int quantity) {\n return quantity >= 6;\n}\n\nprivate double calculateOneOffDiscountFor(double price) {\n return price * 12;\n}\n\nprivate double calculateCheaperDiscountFor(double price, int quantity) {\n return calculateWithoutDiscount(price, quantity) * .95\n}\n\nprivate double calculateWithoutDiscount(double price, int quantity) {\n return price * quantity\n}\n\nprivate double getTotalPrice(int quantity, double itemPrice) {\n if (isOneOffDiscountFor(quantity)) {\n return calculateOneOffDiscountFor(itemPrice); // Baker's dozen\n }\n \n if (isCheaperDiscountFor(quantity)) {\n return calculateCheaperDiscountFor(itemPrice, quantity);\n }\n\n return calculateWithoutDiscount(itemPrice, quantity);\n}\n</code></pre>\n<hr />\n<p>We can go further, because now we have included the word <em>Discount</em> everywhere in the newly added method names - which is an indication that we can encapsulate these methods in a separate object. That leads us to the next basic principle of object-oriented programming: <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"nofollow noreferrer\">encapsulation</a></p>\n<p><img src=\"https://github.com/rgabisch/presentations/raw/master/object-oriented-programming/images/encapsulation.png\" alt=\"\" /></p>\n<pre class=\"lang-java prettyprint-override\"><code>class Discount {\n \n public boolean isOneOffFor(int quantity) {\n return quantity == 13;\n }\n\n public boolean isCheaperFor(int quantity) {\n return quantity >= 6;\n }\n\n public double calculateOneOffFor(double price) {\n return price * 12;\n }\n\n public double calculateCheaperFor(double price, int quantity) {\n return calculateWithout(price, quantity) * .95\n }\n\n public double calculateWithout(double price, int quantity) {\n return price * quantity\n }\n\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>private final Discount discount;\n\nprivate double getTotalPrice(int quantity, double itemPrice) {\n if (discount.isOneOffFor(quantity)) {\n return discount.calculateOneOffFor(itemPrice);\n }\n \n if (discount.isCheaperFor(quantity)) {\n return discount.calculateCheaperFor(itemPrice, quantity);\n }\n\n return discount.calculateWithout(itemPrice, quantity);\n}\n</code></pre>\n<p>An advantage of this variant is that through the encapsulation we achieve that the object more closely follow the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>, which in turn would make our code easier to test and more maintainable.</p>\n<p>We can make the discount dynamic if a constructor is added to the <code>Discount</code> that makes the discount-values variable.</p>\n<hr />\n<p><em>The self-drawn pictures are taken from my <a href=\"https://github.com/rgabisch/presentations/tree/master/object-oriented-programming\" rel=\"nofollow noreferrer\">Github Repository about the Principles of Objekt-Oriented-Programming</a>, in which the principle of <a href=\"https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)\" rel=\"nofollow noreferrer\">inheritance</a> and <a href=\"https://en.wikipedia.org/wiki/Polymorphism_(computer_science)\" rel=\"nofollow noreferrer\">polymorphism</a> are also visualized.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:27:15.550",
"Id": "493074",
"Score": "0",
"body": "Whilst isn't a bad approach, some of it isn't intuitive (does it make sense to ask a Discount to calculate how much something costs without applying a discount)? Consider if it would be better for the `Discount` class to actually model the discount. So, rather than calculating the price after applying the discount, it calculated the amount of any discount that needed to be applied to the final price. Consider `isOneOffFor` and `calculateOneOffFor` which seem tightly coupled, modelling a discount, you could roll them together into a `calculateOneOffDiscount` which might be better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:09:32.727",
"Id": "250673",
"ParentId": "250655",
"Score": "6"
}
},
{
"body": "<p>One additional suggestion regarding the <code>.95</code> constant:</p>\n<p>In sales, it's more natural to express the discount percents instead of the factor</p>\n<pre><code>private static final double QUANTITY_DISCOUNT_PERCENT = 5.0;\nprivate static final double QUANTITY_DISCOUNT_FACTOR = 0.01 * (100.0 - QUANTITY_DISCOUNT_PERCENT);\n...\nreturn itemPrice * quantity * QUANTITY_DISCOUNT_FACTOR;\n</code></pre>\n<p>(As already mentioned, using double arithmetic isn't a good idea...)</p>\n<p>And (maybe it's overkill, but anyway):</p>\n<p>Generalizing the two different discount approaches, this asks for a <code>DiscountRule</code> interface with at least two implementations: <code>QuantityPercentDiscount</code> and <code>OneForFreeDiscount</code>, an ordered list of discount rules, and code that chooses the first applicable rule for a given quantity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:21:56.773",
"Id": "250698",
"ParentId": "250655",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>What I am most interested in is how to name the magic numbers.</p>\n</blockquote>\n<p>Alternative opinion - none of the numbers should be in code in the first place. Every answer with named constants is just wrong. They should all be in <strong>data</strong>.</p>\n<p>Assumptions:</p>\n<ol>\n<li>pricing rules are all predicated only on quantity</li>\n<li>pricing rules change more frequently than business logic</li>\n<li>if you buy 26 of something, you should be charged for two baker's dozens (2 * 12 = 24), not for simply "at least six" (26 * 0.95 = 24.7)</li>\n</ol>\n<p>Pseudocode:</p>\n<pre><code>double getTotalPrice(int quantity, double itemPrice, OrderedDiscountList rules)\n{\n double totalPrice = 0.0;\n int remaining = quantity;\n\n // require this is ordered with the largest quantity rule first\n for (rule in rules) {\n if (remaining >= rule.quantity) {\n int affected = remaining / rule.quantity;\n remaining = remaining % rule.quantity;\n totalPrice += affected * itemPrice * rule.multiplier;\n }\n }\n // so long as the last rule has quantity=1 and multiplier=1.0\n // we don't need to special-case anything in code\n return totalPrice;\n}\n</code></pre>\n<p>configured with something like</p>\n<pre><code>OrderedDiscountList defaultRules =\n{\n { .quantity = 13, .multiplier = 12.0/13 },\n { .quantity = 6, .multiplier = 0.95 },\n { .quantity = 1, .multiplier = 1.0 }\n};\n</code></pre>\n<p>which could easily be read from JSON or similar when you want to update your price list without editing code.</p>\n<p>NB. It's probably better to use a rational/ratio type than double for the multiplier, although I don't think we're hitting any rounding errors in this particular case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:46:03.163",
"Id": "493097",
"Score": "0",
"body": "At first glance it looks like this might give unexpected results for 14, 15, 16... You get the discount for the first 13, however because you're only left with 1,2,3 etc which is less than the trigger level for the 6 discount, so you get charged the full amount for these. I like the approach, and this is pseudocode so it would be fixed during implementation but I think it demonstrates that there's a trade-off between the complexity of the implementation and likelihood of change. If discounts change frequently then the extra work is justified, but if they change rarely, then it may not be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:52:19.233",
"Id": "493101",
"Score": "0",
"body": "You're absolutely right! I didn't try to replicate the existing logic precisely. I mean, that's partly because I assume it was mistaken in the first place (eg. for the multiple baker's dozens case), but I'm just guessing at the desired spec. You could also use the same `OrderedDiscountList` to find the lowest possible total price instead of just using the current greedy algorithm."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T11:16:37.377",
"Id": "250701",
"ParentId": "250655",
"Score": "4"
}
},
{
"body": "<p>For me, the best production code is the code that is concise and simple, especially with respect to the amount of branching. The following code slightly changes the semantics (in a good way, I think) and unifies the multiplication:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private double getTotalPrice(int quantity, double itemPrice) {\n // Charge for 13 as if it were only 12\n if (quantity == 13) quantity = 12;\n\n // Reduce item price for bulk purchases\n if (quantity >= 6) itemPrice *= 0.95;\n\n return quantity * itemPrice;\n}\n</code></pre>\n<p>There are several good things to say about code like this.</p>\n<ul>\n<li>It's simple and easy to understand</li>\n<li>It's self-contained and doesn't depend on other functions/constants</li>\n<li>The comments make it clear what each step is doing, and the steps are applied in a clear linear order (which prompts the reader to consider what would happen if they were run in a different order--if the bulk discount threshold were also 13, it would make a difference...). This structure also helps avoid the pitfall in the original code where you don't get the bulk discount when you buy exactly 13 things!</li>\n</ul>\n<p>Would this code really be improved by coming up with a new constant like <code>BUY_X_GET_ONE_FREE_QUANTITY</code> to stand in for 13? I would argue no, because that constant will probably live somewhere else in the program and will require an extra "hop" for a reader to check it. The net result is a bit more obfuscation of your code. It seems especially unproductive to hide this magic number inside a constant because most people will readily recognize 13 as the baker's dozen number.</p>\n<p>Of course, in a real software system many other considerations might apply, such as:</p>\n<ul>\n<li>Do I need to use these numbers in other functions, such as perhaps the test suite? Maybe then I need static constants.</li>\n<li>Do I want to be able to configure these numbers like <code>13</code>, <code>6</code>, and <code>0.95</code> via a configuration system, or is it okay to bake them into the program? If it's the former, then many other considerations might apply, involving how the configuration is done and how powerful it needs to be.</li>\n</ul>\n<p>FWIW, if I were free to overengineer this as much as I wanted, I would probably try to model it as a series of "promotions" which are applied via function composition. This would be more scalable and might work well at a bigger company, where different teams within the company might want to apply their own promotions to the pricing structure without stepping on each other's toes too much. For example: (in a pseudocode language because Java doesn't support tuples...)</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Each promotion may transform the quantity and/or item price\nprivate [int, double] bakersDozenPromotion(int quantity, double itemPrice) {\n if (quantity == 13) return [12, itemPrice];\n else return [quantity, itemPrice];\n}\nprivate [int, double] bulkDiscountPromotion(int quantity, double itemPrice) {\n if (quantity >= 6) return [quantity, itemPrice * 0.95];\n else return [quantity, itemPrice];\n}\n// ...other promotions\n\nprivate double getTotalPrice(int quantity, double itemPrice) {\n const allPromotions = compose(\n bakersDozenPromotion, \n bulkDiscountPromotion, \n ...\n )\n const [finalQuantity, finalItemPrice] = allPromotions(quantity, itemPrice);\n\n return finalQuantity * finalItemPrice;\n}\n</code></pre>\n<p>By shifting the focus from "configuring individual constants" to "configuring individual promotion functions," we break the problem down more clearly into logical pieces. For example, in a real system we could imagine configuring our program by passing in a YAML file like the following, which even non-engineers at the company could edit:</p>\n<pre class=\"lang-yaml prettyprint-override\"><code>promotions:\n bakers-dozen:\n enabled: true\n extra-free-unit-at: 13\n bulk-discount:\n enabled: true\n threshold: 6\n price-multiplier: 0.95\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:37:22.530",
"Id": "250738",
"ParentId": "250655",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250657",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T12:45:22.290",
"Id": "250655",
"Score": "10",
"Tags": [
"java"
],
"Title": "Computing quantity-based discounts"
}
|
250655
|
<p><strong>EDIT_START:</strong> I want to thank all people for giving me such good answers! It's hard for me to choose any answer over another, because I see that all of your answers are valid and good in their own perspective. I want to clarify my own question. My question is <strong>not</strong> "How do I not use GOTO?", but my question is "How do I use GOTO in a better way?". This implicates that I want to use GOTO for program room/state transition at all costs. This is for educational purpose and for discovering the limits of C. I will give out a bounty as soon as possible to my question, to give back a reward. Anyway thank you all! I'll place a LABEL for ya all in my program ;-) <strong>EDIT_END:</strong></p>
<p>I was discussing with someone about using GOTO at stackoverflow. May someone teach me some hidden tricks in using GOTO? Do you have some suggestions for improvement? You may enjoy my little adventure game, give it a try. ^^</p>
<p>PS play the game before you read the source, otherwise you get spoiled</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
enum _directions{
DIR_0 = 0b0000,
DIR_E = 0b0001,
DIR_W = 0b0010,
DIR_WE = 0b0011,
DIR_S = 0b0100,
DIR_SE = 0b0101,
DIR_SW = 0b0110,
DIR_SWE = 0b0111,
DIR_N = 0b1000,
DIR_NE = 0b1001,
DIR_NW = 0b1010,
DIR_NWE = 0b1011,
DIR_NS = 0b1100,
DIR_NSE = 0b1101,
DIR_NSW = 0b1110,
DIR_NSWE = 0b1111
} DIRECTIONS;
void giveline(){
printf("--------------------------------------------------------------------------------\n");
}
void where(int room, unsigned char dir){
printf("\nYou are in room %i. Where do you want GOTO?\n", room);
if(dir & 8) printf("NORTH: W\n");
else printf(".\n");
if(dir & 4) printf("SOUTH: S\n");
else printf(".\n");
if(dir & 2) printf("WEST: A\n");
else printf(".\n");
if(dir & 1) printf("EAST: D\n");
else printf(".\n");
}
char getdir(){
char c = getchar();
switch(c){
case 'w' :
case 'W' :
return 'N';
case 's' :
case 'S' :
return 'S';
case 'a' :
case 'A' :
return 'W';
case 'd' :
case 'D' :
return 'E';
case '\e' :
return 0;
}
return -1;
}
int main(int argc, char *argv[]){
START:
printf("THE EVIL GOTO DUNGEON\n");
printf("---------------------\n");
printf("\nPress a direction key \"W, A, S, D\" followed with 'ENTER' for moving.\n\n");
char dir = -1;
ROOM1:
giveline();
printf("Somehow you've managed to wake up at this place. You see a LABEL on the wall.\n");
printf("\"Do you know what's more evil than an EVIL GOTO DUNGEON?\"\n");
printf("You're wondering what this cryptic message means.\n");
where(1, DIR_SE);
do{
dir = getdir();
if(dir == 'S') goto ROOM4;
if(dir == 'E') goto ROOM2;
}while(dir);
goto END;
ROOM2:
giveline();
printf("Besides another LABEL, this room is empty.\n");
printf("\"Let's play a game!\"\n");
where(2, DIR_W);
do{
dir = getdir();
if(dir == 'W') goto ROOM1;
}while(dir);
goto END;
ROOM3:
giveline();
printf("Man, dead ends are boring.\n");
printf("Why can't I escape this nightmare?\n");
where(3, DIR_S);
do{
dir = getdir();
if(dir == 'S') goto ROOM6;
}while(dir);
goto END;
ROOM4:
giveline();
printf("Is this a real place, or just fantasy?\n");
printf("\"All good things come in three GOTOs.\"\n");
where(4, DIR_NSE);
do{
dir = getdir();
if(dir == 'N') goto ROOM1;
if(dir == 'S') goto ROOM7;
if(dir == 'E') goto ROOM5;
}while(dir);
goto END;
ROOM5:
giveline();
printf("This is a big river crossing. I guess I need to JUMP.\n");
where(5, DIR_SWE);
do{
dir = getdir();
if(dir == 'S') goto ROOM8;
if(dir == 'W') goto ROOM4;
if(dir == 'E') goto ROOM6;
}while(dir);
goto END;
ROOM6:
giveline();
printf("This place doesn't look very promising.\n");
where(6, DIR_NSW);
do{
dir = getdir();
if(dir == 'N') goto ROOM3;
if(dir == 'S') goto ROOM9;
if(dir == 'W') goto ROOM5;
}while(dir);
goto END;
ROOM7:
giveline();
printf("\"Give a man a LOOP and you feed him FOR a WHILE;\n");
printf(" teach a man a GOTO and you feed him for a RUNTIME.\"\n");
where(7, DIR_NE);
do{
dir = getdir();
if(dir == 'N') goto ROOM4;
if(dir == 'E') goto ROOM8;
}while(dir);
goto END;
ROOM8:
giveline();
printf("This looks like an endless LOOP of rooms.\n");
where(8, DIR_NW);
do{
dir = getdir();
if(dir == 'N') goto ROOM5;
if(dir == 'W') goto ROOM7;
}while(dir);
goto END;
ROOM9:
giveline();
printf("You've found your old friend Domino. He doesn't looks scared, like you do.\n");
printf("\n\"Listen my friend,\n");
printf(" If you want to escape this place, you need to find the ESCAPE KEY.\"\n");
printf("\nWhat does this mean?\n");
where(9, DIR_N);
do{
dir = getdir();
if(dir == 'N') goto ROOM6;
}while(dir);
goto END;
printf("You never saw me.\n");
END:
giveline();
printf("The End\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:54:34.127",
"Id": "492950",
"Score": "17",
"body": "If this program is an attempt to produce evidence of justified `goto` use, I think it's missed the mark."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:00:51.683",
"Id": "492952",
"Score": "0",
"body": "It isn't. But I would like to know how to program such program, a program which uses in a clever way GOTO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T14:20:58.857",
"Id": "492957",
"Score": "18",
"body": "I'm honestly not sure what you're looking for. If you come to a code review forum, which emphasizes best practices, and ask _how do I do this bad thing in a clever manner?_, people are probably still just going to tell you not to do the bad thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:34:00.007",
"Id": "492969",
"Score": "7",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:48:28.600",
"Id": "492971",
"Score": "0",
"body": "@pacmaninbw Sorry about that. I was just editing some typos, and improved some spellings. The code is unchanged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:04:58.993",
"Id": "492999",
"Score": "2",
"body": "As for \"hidden tricks\": with GCC you can have [computed gotos](https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:15:24.457",
"Id": "493013",
"Score": "0",
"body": "@G.Sliepen Thank you for that good hint. I especially appreciate the following: \"You may not use this mechanism to jump to code in a different function. If you do that, totally unpredictable things happen.\" **I Too Like to Live Dangerously.** ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T01:29:04.917",
"Id": "493030",
"Score": "13",
"body": "@paladin - `goto`-ing to code in another function isn't unpredictable, it's explicitly *illegal*. Labels have function scope, so they aren't visible outside the function where they're defined (just like local variables). If you want to jump between functions you'll have to use `setjmp()`/`longjmp()`, but those are *very* good ways to screw up your stack and crash your program in new and interesting ways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:48:15.360",
"Id": "493041",
"Score": "2",
"body": "In GCC, you can declare a function inside a function, and from that function access variables in the outer function, and you can pass a pointer to that function to another function and call it from there. Don't ever return it though. The spec literally says if you return one from the scope it's declared in, \"all hell breaks loose\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:34:01.380",
"Id": "493152",
"Score": "1",
"body": "Re: Edit - I'm pretty sure most of us got the fact that you wanted to use smarter ways to use `goto` it is quite possible many of use don't believe there is a smart way to use a `goto`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:23:30.980",
"Id": "493176",
"Score": "1",
"body": "Note that \"GOTO considered harmful\" wasn't Djikstra's original title, and he was annoyed with the publisher for changing it. His argument was that structured programming that let you do code folding without missing anything was a good idea. There's absolutely no reason you can't do that with goto, it's just more work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:15:38.010",
"Id": "493261",
"Score": "0",
"body": "Please do not edit the question after answers have been posted. Everyone needs to be able to see what the reviewers were referring to. [What to do after the question has been answered.](https://codereview.stackexchange.com/help/someone-answers)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:40:26.843",
"Id": "493306",
"Score": "7",
"body": "There *are* a handful of good uses of `goto` in C, but it is not a good general-purpose mechanism for branching. Consider that in contrast, Java reserved `goto` as a language keyword, but never implemented it, and it isn't particularly missed there. What relevant features does Java have that C does not? Mostly it's labeled `break` and `continue` statements and exceptions. Good uses of `goto` in C are pretty much all for situations that would most likely be addressed by one of those features instead in Java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T05:53:58.707",
"Id": "493342",
"Score": "0",
"body": "@bta To be clear, `goto` into another function is illegal in C, but it wasn't/isn't illegal in many languages that came before (including Pascal, which tries hard to discourage `goto` by making it awkward to use: only numeric labels, etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T23:06:19.540",
"Id": "493440",
"Score": "0",
"body": "You can make your code much better by using a data driven approach. Which may be a better area of research than trying to abuse goto."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:42:50.543",
"Id": "493446",
"Score": "0",
"body": "I added a link to what I consider a really good example of using `goto` statements as a finite state machine (before you posted your bounty). The code is not inline because it's not mine to post. I don't anticipate a better answer appearing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:55:05.533",
"Id": "493447",
"Score": "0",
"body": "@Joshua I only want to win more knowledge. By the way, I know many other applications where a simple **goto** is just better than anything else. Unfortunately there are not many up-to-date \"standards\" articulated _how to use goto_ in a sane way, because most programmer say it's the devils tool and even don't dare to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T12:35:22.010",
"Id": "493813",
"Score": "0",
"body": "@paladin using goto just makes the code so confusing for other people who read your code, I read `goto a`, but where is `a`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T02:41:23.430",
"Id": "493888",
"Score": "0",
"body": "@paladin Don't assume that a sane way to use `goto` exists. Most languages place limits on `goto` to discourage its use and avoid many of its problems. It's hard to design a complex language when control flow can jump anywhere unpredictably, so neutering `goto` is almost *required* in order to implement certain language features reliably. I don't think C is the language for what you want to do. You want a language with an unrestricted `goto`, like assembly, Fortran, or BASIC. The latter seems particularly suited to this sort of program."
}
] |
[
{
"body": "<p>The <code>goto</code> debate is ancient, from the year 1966 when Edgar Dijkstra came up with a famous paper called "Go To Statement Considered Harmful". This was controversial and the debate is still going on to this day. Still, most of his conclusions are also valid to this day and most uses of <code>goto</code> is considered harmful <a href=\"https://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"noreferrer\"><em>spaghetti programming</em></a>.</p>\n<p>However, there's a broad consensus that some uses of <code>goto</code> are acceptable. Specifically:</p>\n<ul>\n<li><code>goto</code> should only be used to jump downwards, never upwards.</li>\n<li><code>goto</code> should only be used for the sake of error handling and centralized clean-up at the end of a function.</li>\n</ul>\n<p>This is an old "design pattern" that I believe/fear originates from BASIC which had "on error goto..." as it's preferred way of error handling. Basically it's <em>only</em> considered OK to use <code>goto</code> like in this made-up example:</p>\n<pre><code>status_t func (void)\n{\n status_t status = OK;\n\n stuff_t* stuff = allocate_stuff();\n ...\n\n while(something)\n {\n while(something_else)\n {\n status = get_status();\n if(status == ERROR)\n {\n goto error_handler; // stop execution and break out of nested loops/statements\n }\n }\n }\n \n goto ok;\n\n error_handler:\n handle_error(status);\n\n ok:\n cleanup(stuff);\n return status;\n}\n</code></pre>\n<p>Use of <code>goto</code> as in the above example is considered acceptable. There are two obvious benefits: clean way of breaking out of nested statements and centralized error handling and clean-up at the end of the function, avoiding code repetition.</p>\n<p>Still it is possible to write the same thing with <code>return</code> and a wrapper function, which I personally find much cleaner and avoids the "goto considered harmful" debate:</p>\n<pre><code>static status_t internal_func (stuff_t* stuff)\n{\n status_t status = OK;\n \n ...\n \n while(something)\n {\n while(something_else)\n {\n status = get_status();\n if(status == ERROR)\n {\n return status;\n }\n }\n }\n\n return status;\n}\n\nstatus_t func (void)\n{\n status_t status;\n\n stuff_t* stuff = allocate_stuff(); \n\n status = internal_func(stuff);\n\n if(status != OK)\n {\n handle_error(status);\n }\n\n cleanup(stuff);\n return status;\n}\n</code></pre>\n<p>EDIT:</p>\n<p>I posted a separate lengthy answer <a href=\"https://codereview.stackexchange.com/a/250703/5474\">here</a> regarding everything not goto-related. Including a proposal for how to rewrite the whole program using a proper state machine design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:19:02.800",
"Id": "493034",
"Score": "0",
"body": "Are you sure that isn't a big finite state machine using GOTO to change state (room)? There's better ways to write it (returning function pointers occurs to me), but they're farther along in teaching than the code I see in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:30:55.677",
"Id": "493059",
"Score": "4",
"body": "@Joshua Since I work mainly with embedded systems, I've seen a whole lot of broken FSMs and there are multiple ways to get them horribly wrong without involving goto. My personal belief is that each state should just return a status to a centralized caller - then a combined decision-maked/error handler reads that status and determines which state to shift to _from one single location in the code_. Separate state application logic from state transition logic. Otherwise it is very easy to get spaghetti programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:32:25.283",
"Id": "493060",
"Score": "0",
"body": "@Joshua If you implement the state machine with function-pointer look-up tables or `switch` etc is less important. The function pointer version is easier to read & maintain, but you can write readable code without that too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T12:05:09.683",
"Id": "493089",
"Score": "3",
"body": "@Joshua Using function pointers for a state machine is most likely many times slower than using gotos/a switch with loop due to the extra indirection on most CPUs. Depends on the use case whether that's acceptable, but given we're talking C it might be important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:37:53.980",
"Id": "493117",
"Score": "2",
"body": "Once you start following rules for GOTO you are simply reinventing structured programming. GOTO never went away. It's just typically hidden behind abstractions that enforce these rules for you. Be formal about GOTO and you can avoid spaghetti on your own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:32:16.783",
"Id": "493179",
"Score": "0",
"body": "At this point I wouldn't consider the debate \"ongoing.\" I would say there are deniers that, willfully or otherwise, refuse to concede in a decided contest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:20:31.033",
"Id": "493191",
"Score": "0",
"body": "@GammaGames This shall be no contest. I think there are many good arguments against using such tools and are also some good arguments for using such tools. It depends on the situation. What I'm really interested in is, how would an experienced programmer use GOTO, in a way that ensures code readability or gives significant performance advantages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:40:29.133",
"Id": "493290",
"Score": "0",
"body": "@paladin If you want readability, use the control structures developed over the last several decades that prioritize readability over practically everything else. In terms of performance though, global variables and goto run significantly faster than oodles of function calls because you don't have to wait on stack manipulation. But it takes careful design to not become an unreadable mess, and 80% of programming time is maintenance, so you're usually better off with the cleaner structure except in specific circumstances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T16:57:50.557",
"Id": "493301",
"Score": "1",
"body": "\"Use of goto as in the above example is considered acceptable\" - citation needed. Considered by whom? Personally I'd consider it unacceptable and would refuse to pass it if I saw it in a peer review. The goto could trivially be avoided with \"&& status != ERROR\" in the while conditions. It offers no additional advantages and ends up with slightly weird convoluted flow through the function... as \"hey I've found a case where goto is necessary!\" always does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:06:15.750",
"Id": "493303",
"Score": "0",
"body": "@BittermanAndy Imagine a machine which processes sensor data and has to apply very fast different cases/states for does sensor data, because if your program needs to much time for processing, the sensor data would become invalid. A decentralized jump would give significant performance advantages against an centralized jumping routine. The performance advantage would increase significantly with higher amount of cases. But I'll see the same problem, more cases produce less maintainable code, while using GOTO. So this is my question, how to use GOTO in a way to remain more or less maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T22:53:59.857",
"Id": "493330",
"Score": "1",
"body": "Weird take. \"How do I make this code, that I have measured and found to be performing insufficiently well, perform better\" would be a valid question. \"How do I use this specific construct there is no need to use, to achieve something that it is not capable of achieving\", I mean, OK, if that's what you want to be spending your time thinking about, I guess it's your time to waste if you want. In any case I was addressing the claim that the example in this answer is \"considered acceptable\" which to me is tenuous, and the use of goto here achieves nothing that could not be achieved without it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:42:12.960",
"Id": "493380",
"Score": "0",
"body": "Third point where it can be useful is breaking out of _nested_ loops in C (where `break` can only break out from one, unlike e.g. Perl's `break`). Though if you're going to do that, you might want to consider just splitting the loops in a function, and then use `return` instead of `break`. But sometimes that inner function would be too small or too intertwined with the outer one for that to make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:40:08.463",
"Id": "493540",
"Score": "0",
"body": "@BittermanAndy MISRA-C:2012 Rule 15.2, Rule 15.4. CERT-C [MEM12-C](https://wiki.sei.cmu.edu/confluence/display/c/MEM12-C.+Consider+using+a+goto+chain+when+leaving+a+function+on+error+when+using+and+releasing+resources). MISRA originally banned goto but that rule was relaxed in the latest version. And no, you cannot trivially break out of multiple nested loops/statements when there are multiple error checks, by using a status variable. Often such code can and should be rewritten though. I never use goto myself, but the return code version demonstrated in the answer."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:02:30.007",
"Id": "250659",
"ParentId": "250656",
"Score": "22"
}
},
{
"body": "<h2>Lack of Error Checking on User Input</h2>\n<p>The function <code>getdir()</code> should check for valid input, perhaps is should receive an array of valid directions. When an invalid direction is entered there should be a message to the user that the input was invalid.</p>\n<h2>DRY Code</h2>\n<p>The use of <code>goto</code> is forcing you to repeat code that shouldn't be repeated such as</p>\n<pre><code> where(2, DIR_W);\n do {\n dir = getdir();\n if (dir == 'W') goto ROOM1;\n } while (dir);\n goto END;\n</code></pre>\n<h2>Spaghetti Code</h2>\n<p>The entire program seems to be an example of how to write <a href=\"https://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"noreferrer\">Spaghetti Code</a> which is unstructured code that is very difficult to write, debug and maintain.</p>\n<p>The code would actually be smaller and more understandable if it was structured and used <code>while</code> loops or <code>for</code> loops.</p>\n<h2>Using Binary in ENUM</h2>\n<p>The more characters you type the easier it is to make a mistake. Since Bits are important in the enum I would suggest using Octal or Hexadecimal, preferably Hexadecimal. Each enum could then be defined using one character.</p>\n<p>Rather than using magic numbers in the code, define masks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:44:39.877",
"Id": "492980",
"Score": "0",
"body": "Thank you for your reply. My function `getdir()` does check for valid input and returns -1 at invalid input. What you call as \"DRY Code\" I see as some kind of \"object\", isn't it? I agree to your term \"Spaghetti Code\", but I should've mentioned that I've drawn a \"room map\" before programming with pen and paper. With this map, the code is very easy to understand. I use my `goto` only for jumping between the rooms/states. PS I see my binary enum as some kind of jump table, using bitmasks would reduce program speed. But I agree about making mistakes with these kinds of enums."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:18:57.967",
"Id": "493026",
"Score": "0",
"body": "DRY Code refers to [Don't Repeat Yourself](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). Dry code can be implemented either using functions or loops depending on the code being used. In this case a loop would probably be good enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T07:05:51.173",
"Id": "493065",
"Score": "3",
"body": "Regarding binary, it is also not standard C and should be avoided for that reason alone."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T15:18:40.330",
"Id": "250661",
"ParentId": "250656",
"Score": "9"
}
},
{
"body": "<p>The program you give as an example would be better-designed as a finite state machine. The states could be implemented as mutually-recursive tail calls, which a modern compiler would optimize to jump instructions, just like a <code>goto</code>. You could then represent the states as function pointers and eliminate the <code>switch</code>.</p>\n<p>Joshua has a demonstration of code somewhat like that, and Lundin refines it, but it might be better to have each room call the next room function mutually tail-recursively, until the game is over and the last room function finally returns a value. For example, it might return the score.</p>\n<p>An optimizing compiler will compile the tail call, since it is to a function with the same type, as an unconditional jump. That is also how it would compile a <code>goto</code>. Since you are no longer discombobulating the C parser by making a function return a pointer to a function of the same type, you no longer need to cast function pointers to different types. You also no longer need to have invalid null function pointers in your program that would crash it if they are ever called. Doing it this way would preserve type safety and let the compiler ensure that you are actually calling valid code.</p>\n<p>The next step might be to observe that most or all of these rooms perform the same operations on different data, write this code as a single function that takes a data structure, and pass along the room data as a parameter of the function. This could be a pointer to <code>static</code> data, or an index into an array of rooms. Either is a constant-time look-up, simpler and more efficient than a <code>switch</code> block.</p>\n<p>If you do need more than one type of room with different code, and you pass around both room data and a function pointer to the room code, you have reinvented polymorphic objects with data members and methods.</p>\n<p>I’ve used a <code>goto</code> once myself, not counting programs I wrote in BASIC as a child. It was to break out of multiple levels of a nested loop. I considered, but rejected, refactoring those levels of the loop as a function I could <code>return</code> from, or creating a loop-control variable. I don’t regret it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:23:06.460",
"Id": "493036",
"Score": "0",
"body": "Good for finding finite state machine. However you miss `goto` is directly writing a finite state machine. I've seen truly terrible `goto` abuse but this isn't it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:30:57.220",
"Id": "493037",
"Score": "0",
"body": "@Joshua I realize that the `goto` labels could be considered states in a FSM, yes. No argument there. In the spirit of a code review: it’s no more efficient to do it this way, and much less maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:42:18.543",
"Id": "493038",
"Score": "2",
"body": "My experience is the reverse. The switch is harder to maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:44:47.863",
"Id": "493040",
"Score": "0",
"body": "@Joshua I suggested a way to eliminate the `switch`, so that works out nicely!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T00:26:09.510",
"Id": "250687",
"ParentId": "250656",
"Score": "4"
}
},
{
"body": "<p>I'll take an alternative tack from the other answerers: Your code organization is <em>not bad</em>, and all that remains to do is <em>eliminate redundancy</em>. Notice that every room in your game has the same basic structure:</p>\n<pre><code>ROOM7:\ngiveline();\nprintf("\\"Give a man a LOOP and you feed him FOR a WHILE;\\n");\nprintf(" teach a man a GOTO and you feed him for a RUNTIME.\\"\\n");\nwhere(7, DIR_NE);\ndo{\n dir = getdir();\n if(dir == 'N') goto ROOM4;\n if(dir == 'E') goto ROOM8;\n}while(dir);\ngoto END;\n</code></pre>\n<p>If we had a macro something like <code>DEFINE_ROOM</code>, we could just write</p>\n<pre><code>DEFINE_ROOM(7, DIR_NE,\n "\\"Give a man a LOOP and you feed him FOR a WHILE;\\n"\n " teach a man a GOTO and you feed him for a RUNTIME.\\"\\n",\n 'N', ROOM4,\n 'E', ROOM8\n);\n</code></pre>\n<p>It's pretty complicated to write a C macro that can take an arbitrary number of room exits, so instead, I'll write separate macros for each combination of room directions.</p>\n<pre><code>#define DEFINE_ROOM_NE(num, desc, roomN, roomE) \\\n ROOM##num: giveline(); printf(desc); \\\n where(num, DIR_NE); \\\n while (dir = getdir()) { \\\n if (dir == 'N') goto roomN; \\\n if (dir == 'E') goto roomE; \\\n } \\\n goto END;\n#define DEFINE_ROOM_NW(num, desc, roomN, roomW) \\\n ROOM##num: giveline(); printf(desc); \\\n where(num, DIR_NW); \\\n while (dir = getdir()) { \\\n if (dir == 'N') goto roomN; \\\n if (dir == 'W') goto roomW; \\\n } \\\n goto END;\n</code></pre>\n<p>In fact, wait a minute, we can do better! Notice that if you enter a bogus direction, you just go around the loop again. So I can add a <code>SAME##n</code> label to do this:</p>\n<pre><code>#define DEFINE_ROOM(dirs, num, desc, roomN, roomS, roomE, roomW) \\\n ROOM##num: giveline(); printf(desc); \\\n where(num, DIR_##dirs); \\\n while (dir = getdir()) { \\\n if (dir == 'N') goto roomN; \\\n if (dir == 'S') goto roomS; \\\n if (dir == 'E') goto roomE; \\\n if (dir == 'W') goto roomW; \\\n SAME##num: ; \\\n } \\\n goto END;\n#define DEFINE_ROOM_N(n, roomN, d) DEFINE_ROOM(N, n, d, roomN, SAME##n, SAME##n, SAME##n)\n#define DEFINE_ROOM_S(n, roomS, d) DEFINE_ROOM(S, n, d, SAME##n, roomS, SAME##n, SAME##n)\n#define DEFINE_ROOM_E(n, roomE, d) DEFINE_ROOM(E, n, d, SAME##n, SAME##n, roomE, SAME##n)\n#define DEFINE_ROOM_W(n, roomW, d) DEFINE_ROOM(W, n, d, SAME##n, SAME##n, SAME##n, roomW)\n#define DEFINE_ROOM_NS(n, roomN, roomS, d) DEFINE_ROOM(NS, n, d, roomN, roomS, SAME##n, SAME##n)\n[...]\n</code></pre>\n<p>And now your whole game fits in an appropriate number of lines:</p>\n<pre><code>DEFINE_ROOM_SE(1, ROOM4, ROOM2,\n "Somehow you've managed to wake up at this place. You see a LABEL on the wall.\\n"\n "\\"Do you know what's more evil than an EVIL GOTO DUNGEON?\\"\\n"\n "You're wondering what this cryptic message means.\\n"\n);\nDEFINE_ROOM_W(2, ROOM1,\n "Besides another LABEL, this room is empty.\\n"\n);\nDEFINE_ROOM_S(3, ROOM6,\n "Man, dead ends are boring.\\n"\n "Why can't I escape this nightmare?\\n"\n);\nDEFINE_ROOM_NSE(4, ROOM1, ROOM7, ROOM5,\n "Is this a real place, or just fantasy?\\n"\n "\\"All good things come in three GOTOs.\\"\\n"\n);\nDEFINE_ROOM_SWE(5, ROOM8, ROOM4, ROOM6,\n "This is a big river crossing. I guess I need to JUMP.\\n"\n);\nDEFINE_ROOM_NSW(6, ROOM3, ROOM9, ROOM5,\n "This place doesn't look very promising.\\n"\n);\nDEFINE_ROOM_NE(7, ROOM4, ROOM8,\n "\\"Give a man a LOOP and you feed him FOR a WHILE;\\n");\n " teach a man a GOTO and you feed him for a RUNTIME.\\"\\n"\n); \nDEFINE_ROOM_NW(8, ROOM5, ROOM7,\n "This looks like an endless LOOP of rooms.\\n"\n);\nDEFINE_ROOM_N(9, ROOM6,\n "You've found your old friend Domino. He doesn't looks scared, like you do.\\n"\n "\\n\\"Listen my friend,\\n"\n " If you want to escape this place, you need to find the ESCAPE KEY.\\"\\n"\n "\\nWhat does this mean?\\n"\n);\n</code></pre>\n<p>I see you're intending to add more motion verbs, such as <code>JUMP</code>. Do you see how to fit <code>JUMP</code> into this pattern? How many motion verbs can you support before this one-macro-per-kind-of-room pattern starts to break down?</p>\n<p>The next step is to stop writing macros that <em>directly generate code</em> and start writing macros that generate <em>data tables</em>, which are then passed to code that knows how to loop over the table's entries and do something for each entry (such as test, "Did the user enter the motion verb in column 1? if so, goto the room in column 2").</p>\n<p>For a (classic!) worked example, see <a href=\"http://www.literateprogramming.com/adventure.pdf\" rel=\"nofollow noreferrer\">Donald Knuth's CWEB port of <em>Adventure</em></a>, or my own C99 port <a href=\"https://github.com/Quuxplusone/Advent/blob/master/ODWY0350/advent.c\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:43:46.387",
"Id": "493039",
"Score": "0",
"body": "So what happens when we try to add ROOM3A?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:01:55.183",
"Id": "493043",
"Score": "0",
"body": "@Joshua: Well, `void where(int room, unsigned char dir)` isn't really set up to handle non-numeric room numbers. But if you wanted to have a 3A, you could change that function's signature to `where(const char *room, unsigned char dir)` and then insert a `#` character in `where(#num, DIR_##dirs)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:47:45.410",
"Id": "493063",
"Score": "3",
"body": "Code repetition is bad practice and should be avoided. But turning your program into a secret macro language hell is extremely bad practice! This is like putting out a small kitchen fire by dropping a bomb on the building. If I'm a C programmer tasked to maintain a C program, I already know the C language. I should expect to find that one, not some secret macro language that I now have to study and learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:24:26.847",
"Id": "493194",
"Score": "0",
"body": "@Lundin By that logic, I should never use any libraries aside from the standard library. I already know the C language; I shouldn't have to study and learn a \"secret function language\". The macros halve the code size, make the logic very clear, and the definitions are right there with the rest of the code. And you definitely *can* read them, because you know the C language and macros are a part of that. (That said, it would probably be better to have a single DEFINE_ROOM macro, with a NONE value that you can pass in for directions that aren't available, rather than having 15 similar macros.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:29:38.620",
"Id": "493539",
"Score": "0",
"body": "@Ray I guess you haven't maintained many \"macro jungles\" like this then. It's a nightmare. Errors are subtle, compiler warnings point at strange lines, no type safety, horrible to debug and so on. The original goto spaghetti with code repetition is still better than this alternative."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T01:20:54.053",
"Id": "250688",
"ParentId": "250656",
"Score": "5"
}
},
{
"body": "<p>The code you've written is more or less a state machine, written the way that one might be constructed in assembly language. A technique like that technically <em>works</em>, but it doesn't scale well and you can wind up with problems that are extremely hard to debug. Your code only needs a small tweak to use the more traditional C-language way to implement a state machine, which is easier to read, maintain, and debug.</p>\n<pre class=\"lang-c prettyprint-override\"><code>int main(int argc, char *argv[])\n{\n int state = START;\n char dir = -1;\n while(1)\n {\n switch (state)\n {\n case START:\n printf("THE EVIL GOTO DUNGEON\\n");\n printf("---------------------\\n");\n printf("\\nPress a direction key \\"W, A, S, D\\" followed with 'ENTER' for moving.\\n\\n");\n state = ROOM1;\n break;\n \n case ROOM1:\n giveline();\n printf("Somehow you've managed to wake up at this place. You see a LABEL on the wall.\\n");\n printf("\\"Do you know what's more evil than an EVIL GOTO DUNGEON?\\"\\n");\n printf("You're wondering what this cryptic message means.\\n");\n where(1, DIR_SE);\n do{\n dir = getdir();\n if(dir == 'S') { state = ROOM4; break; }\n if(dir == 'E') { state = ROOM2; break; }\n }while(dir);\n break;\n \n case ROOM2:\n giveline();\n printf("Besides another LABEL, this room is empty.\\n");\n printf("\\"Let's play a game!\\"\\n");\n where(2, DIR_W);\n do{\n dir = getdir();\n if(dir == 'W') { state = ROOM1; break; }\n }while(dir);\n break;\n \n ...\n \n case END:\n giveline();\n printf("The End\\n");\n return 0;\n }\n }\n}\n</code></pre>\n<p>The code is mostly the same as before, with only a few small tweaks:</p>\n<ul>\n<li>Added the enclosing loop and switch</li>\n<li>Changed labels from <code>ROOMX:</code> to <code>case ROOMX:</code></li>\n<li>Changed jumps from <code>goto ROOMX;</code> to <code>state = ROOMX; break;</code></li>\n<li>Defined constants for <code>START</code>, <code>ROOMX</code>, etc (not shown)</li>\n</ul>\n<p>Structuring your code in this way makes it more readable and avoids a lot of problems that <code>goto</code> spaghetti can have. It's a lot easier to ensure that you don't unintentionally fall through from one room's code into the next one (if you somehow bypass the code that sets a new state, you simply stay in the same room and try again). You also avoid many limitations of <code>goto</code>, like the inability to "jump over" the declaration of a variable-length array (see example 2 in section 6.8.6.1 of the <a href=\"http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf\" rel=\"noreferrer\">C99 language spec</a>). You can also add an explicit <code>default</code> case to intelligently handle any unexpected or erroneous room selections.</p>\n<p>This type of structure also opens up all sorts of avenues for improvement. You could take the contents of each <code>case</code> and wrap it up in a function, and each case could be simplified to <code>case ROOMX: state = do_roomx(); break;</code>. With each room's code encapsulated, you could unit test rooms individually.</p>\n<p>You could also notice that each room's code follows a predictable sequence (<code>giveline()</code> -> print description -> <code>where()</code> -> read input -> select next room) and write a generic function <code>do_room(struct room_data* room)</code> that could handle any arbitrary room. You'd then create a data structure <code>struct room_data</code> that holds all the information needed for each room (description text, movement directions, where each exit leads, etc). This would be more similar to how a game engine works. Your code would become shorter and more generic, and each individual room would be implemented as <em>data</em> instead of <em>code</em>. You could even store the room data in an external file, and then you'd have a generic game engine that you wouldn't have to recompile every time you wanted to modify your maze.</p>\n<hr>\n<p>Asking "How do I use GOTO in a better way?" is akin to asking "How can I punch myself in the face in a better way?" The answer is: You don't. Using <code>goto</code> like you're doing is incompatible with any definition of the word "better" that I'm aware of. You're taking a construct that C handles natively (a <code>switch</code> block) and have re-implemented it using explicit jumps. You get less functionality and more potential problems. The only way to approach "better" is to drop the unnecessary <code>goto</code>s.</p>\n<p>Remember that the C language is just a thin, portable veneer on top of assembly language. <code>goto</code> is a wrapper around your CPU's "jump" instruction. None of the CPUs that I know of have instructions comparable to things like <code>switch</code> or <code>for</code>. These are syntactic sugar that the compiler rewrites for you into a sequence powered by "jump" instructions. For example, a simple loop like this:</p>\n<pre><code>for (i = 0; i < limit; i++)\n{\n ... code ...\n}\n</code></pre>\n<p>is treated as if it was written like this:</p>\n<pre><code> i = 0;\nLOOP_START:\n if (!(i < limit))\n goto LOOP_END;\n ... code ...\nLOOP_CONTINUE:\n i++;\n goto LOOP_START;\nLOOP_END:\n</code></pre>\n<p>A <code>continue</code> statement would be equivalent to <code>goto LOOP_CONTINUE</code>, and a <code>break</code> statement would be equivalent to <code>goto LOOP_END</code>.</p>\n<p>A <code>switch</code> block is implemented similarly. Each case is a block of code with a label, and the <code>switch</code> jumps to a label based on the input value. <code>break</code> jumps to the end. This is generally similar to the way that you wrote your code. The key difference is that a <code>switch</code> block doesn't jump directly between cases. If you want to execute more than one case, you use a loop to run the <code>switch</code> block more than once.</p>\n<p>Ultimately, the <code>switch</code> version and the <code>goto</code> version likely look almost identical once they're compiled. When you use <code>switch</code>, you give the compiler the chance to avoid certain problems such as ensuring that you're not jumping into the scope of a local variable while skipping over its initializer. When you write the <code>goto</code>-based version, the compiler will compile your code as written and trust that you know what you're doing. If you insist on using <code>goto</code> explicitly, you'll end up running into the sort of problems that led people to invent things like <code>switch</code> in the first place. When using <code>goto</code> "at all costs", those costs are frequently a program that behaves inconsistently and unpredictably. If you're looking for advice on how to program poorly, you're in the wrong place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:45:29.297",
"Id": "493062",
"Score": "2",
"body": "State machines like these are not using `goto` but they are still spaghetti programming. Particularly nasty spaghetti if you need each state to become a function, it quickly turns into an unreadable mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:49:50.963",
"Id": "493099",
"Score": "2",
"body": "@Lundin, I strongly disagree. State machines are the right tool for many important jobs: parsing [regular languages](https://link.medium.com/oHMjt1CzBab), designing [event-driven systems](https://en.wikipedia.org/wiki/UML_state_machine) like [UIs](http://macoscope.com/blog/applications-as-state-machines/), modeling [concurrent systems](http://www.doc.ic.ac.uk/ltsa/), and more. (Hat tip [Devender Mishra](https://www.quora.com/What-are-applications-of-finite-state-machines/answer/Devender-Mishra) and [AJed](https://cs.stackexchange.com/a/10330/33791).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:52:00.460",
"Id": "493100",
"Score": "0",
"body": "Why \"more or less a state machine\"? This looks like a perfect example of a state machine to me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:14:07.800",
"Id": "493109",
"Score": "1",
"body": "@Vectornaut I didn't argue against the use of state machines, I argued against the use of \"stateghetti\" where each state jumps around to other states in a decentralized manner. I just posted a version with properly written, centralized decision making [here](https://codereview.stackexchange.com/questions/250656/a-small-goto-text-adventure-game/250703#250703)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:52:34.517",
"Id": "493187",
"Score": "2",
"body": "@Lundin - I'm not saying that the provided code is the best solution, simply showing how a fairly minimal change to the existing code can set OP on a path to something much more maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:59:01.507",
"Id": "493188",
"Score": "1",
"body": "@Vectornaut - I said \"more or less a state machine\" because the original code wasn't explicitly tracking state, just jumping around. A real state machine would be able to tell what state it was currently in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:56:48.353",
"Id": "493195",
"Score": "0",
"body": "Switch statements are just gotos in different clothing. The only difference here is that the room state is in a specific variable rather than the program counter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:45:07.357",
"Id": "493227",
"Score": "0",
"body": "@Beefster With the major difference that switch statements are conditional and can only \"jump\" downwards inside their own local scope, not all over the place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:23:35.850",
"Id": "493304",
"Score": "2",
"body": "Small nitpick: OPs code goes to END if getdir(); returns 0. That‘s a hidden state transition from every room to END wich is missing from your translation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T12:03:49.903",
"Id": "493383",
"Score": "0",
"body": "_\"The code you've written is more or less a state machine, written the way that one might be constructed in assembly language.\"_ -- nngh, I wouldn't write it like that in C or in assembler, or in anything. Those room descriptions and connections call for a data structure to store them in. We can bikeshed about which kind of a data structure, but that's a different story ;)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T01:23:09.613",
"Id": "250689",
"ParentId": "250656",
"Score": "21"
}
},
{
"body": "<p>I'm looking at the <code>goto</code> usage in this program, and I'm going to be controversal here and say it's not that bad. I've seen much worse. Here is a list of things this program does not do.</p>\n<ul>\n<li>This program never uses <code>goto</code> to go around a variable initialization except where the value is clearly thrown out.</li>\n<li>This program never does a <code>goto</code> into an inner block. All operational <code>goto</code> statements go to the outermost block.</li>\n<li>This program does not in fact have haphazard use of <code>goto</code>. All the <code>goto</code> operations center around one operation. (Looks like two, but the strings indicate it is in fact one.)</li>\n</ul>\n<p>I've seen the recommendation to build a loop-switch for the state machine. I've done that before. I'm tired of debugging it. (Oh look there's even an answer.) It's harder to do state machines in loop-switch than it is to do them in <code>goto</code> statements.</p>\n<p>But looking at the code it is clearly <em>not</em> a tight loop. Nobody cares about microseconds of performance around the loop. We can do better these days. To get back to the ease of <code>goto</code> while still maintaining the scope niceties we can do function state machines. This is higher up the learning ladder, and not everybody gets here early.</p>\n<p>It looks as follows: The casts are necessary as the type simply can't be expressed in the type system.</p>\n<pre><code>typedef void (*funcptr)(void);\ntypedef funcptr (*ptrfuncptr)();\n\nint main(int argc, char *argv[])\n{\n ptrfuncptr state = START;\n while (state)\n state = (pfuncptr)state();\n}\n\nfuncptr START()\n{\n printf("THE EVIL GOTO DUNGEON\\n");\n printf("---------------------\\n");\n printf("\\nPress a direction key \\"W, A, S, D\\" followed with 'ENTER' for moving.\\n\\n");\n return (funcptr)ROOM1;\n}\n\nfuncptr ROOM1()\n{\n giveline();\n printf("Somehow you've managed to wake up at this place. You see a LABEL on the wall.\\n");\n printf("\\"Do you know what's more evil than an EVIL GOTO DUNGEON?\\"\\n");\n printf("You're wondering what this cryptic message means.\\n");\n where(1, DIR_SE);\n do{\n dir = getdir();\n if(dir == 'S') return (funcptr)ROOM4;\n if(dir == 'E') return (funcptr)ROOM2;\n }while(dir);\n return NULL;\n}\n// ...\n</code></pre>\n<p>You should not call these ROOM1, ROOM2, ROOM3, etc. If you did that, an array would have suited you better. You should give these all descriptive names. Furthermore, you should change where to take a <code>const char *</code> rather than an <code>int</code> as its first argument.</p>\n<p>If you want to win the <code>goto</code> debate, use a lexer as an example. There's just not much else anymore where it's the best way anymore. <a href=\"https://gist.github.com/tomtheisen/cf6afee1210b9625181bb3c23ea0f204#file-csvreader-cs\" rel=\"noreferrer\">https://gist.github.com/tomtheisen/cf6afee1210b9625181bb3c23ea0f204#file-csvreader-cs</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T04:17:05.370",
"Id": "493050",
"Score": "1",
"body": "It’s technically illegal to use `NULL` as a function pointer. More importantly, it’s not type-safe. Since the function pointer gets called immediately, you might be better off implementing it as a tail-recursive call, also eliminating the need for a type cast. Thanks to tail-recursion elimination, this will compile to a jump instruction—just like a `goto`. Then the function could actually return a value when the game is over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T04:18:17.043",
"Id": "493051",
"Score": "0",
"body": "But this approach works, and I’ve used it for small programs myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:41:24.590",
"Id": "493061",
"Score": "2",
"body": "This is not how you implement a state machine using function pointers. The fact that you are using function pointer casts means that something is fundamentally wrong and dangerous in your code. You do like [this](https://electronics.stackexchange.com/a/96415/6102) except you should also centralize state change decision making for more complex FSMs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T10:52:09.087",
"Id": "493082",
"Score": "0",
"body": "Thank you for your reply. May I ask a silly question, but what clearly advantage gives someone when using this technique? Isn't this function pointer thing nothing more than to reinvent a label and a goto? (Sorry for my stupid question.) PS I also saw the linked example from @Lundin, which seems to go for the same approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:08:17.833",
"Id": "493107",
"Score": "1",
"body": "@paladin I posted [another answer](https://codereview.stackexchange.com/a/250703/5474) with an example of how to use function pointers to create a finite state machine. Check it out - it is very different from the original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:26:57.820",
"Id": "493111",
"Score": "2",
"body": "@Davislor \"It’s technically illegal to use NULL as a function pointer.\" That's plain wrong. NULL is a null pointer constant and C17 6.3.2.3/3 makes the following guarantee, emphasis mine: \"An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare **unequal to a pointer to any object or function**.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:28:48.607",
"Id": "493113",
"Score": "0",
"body": "@Davislor I think you maybe mixed it up with converting between `void*` and function pointers? Because that is not ok - `void*` may only be used as a generic object pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:28:12.613",
"Id": "493126",
"Score": "0",
"body": "@Lundin I’ll correct that sentence. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:56:37.757",
"Id": "493134",
"Score": "1",
"body": "@Lundin: The whole point is to get rid of the enum. If you can write down the signature for a function that returns itself, I'll get rid of the cast."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T02:41:42.483",
"Id": "250690",
"ParentId": "250656",
"Score": "9"
}
},
{
"body": "<blockquote>\n<p>May someone teach me some hidden tricks in using GOTO?</p>\n</blockquote>\n<p><code>goto</code> is kind of a one trick pony. But is part of a family of control transfer constructs. All the looping and decision structures are in a sense a <em>refined</em> or specialized application of a goto. So from that pov, using <code>goto</code> is advisable only if it cannot be done with any of the "normal" control structures like <code>if</code>, <code>while</code>, <code>for</code> etc.</p>\n<p>The next level up is function calls. A function call is a super-powered <code>goto</code>. Not only can you jump and execute a named piece of code, but you can also jump back right where you came from. Plus you can pass arguments and return a value, if desired.</p>\n<p>Another level up is making use of function pointers. A pointer to a function can be saved in a variable or an array. It can be passed to and returned from functions. <em>For a state machine like in the question, I'd be very tempted to organize the rooms into an array of function pointers. But I'd probably use a lot of macros, too.</em></p>\n<p>The next level up from functions is <code>setjmp</code>/<code>longjmp</code>. These let you jump back across several levels of the call stack. It's sometimes useful to have a <code>setjmp</code> call in the main loop or initialization of the program and then the program can restart or bail-out if it runs into certain recoverable errors.</p>\n<p>I suppose the next level up might be signal handlers and/or forking off child processes. Or maybe loading a dynamic library.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:06:30.457",
"Id": "493106",
"Score": "3",
"body": "I wouldn't recommend anyone to use `setjmp` for any purpose. It has all the problems of goto but also comes with lots of other plain dangerous undefined behavior too. A lot of these constructs are obsolete crap from ancient Unix days when dinosaurs walked the earth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:29:39.297",
"Id": "493141",
"Score": "2",
"body": "Even when I also see the dangers of those tools, I would like to thank _luser droog_ anyway for his summarizing. I started to learn programming with Java, a \"safe hazard free\" environment. For some time I'm exploring C and its capacities. I'm interested also in using the dangerous things, more from a philosophical perspective than from a real \"do I want to use this?\" perspective. To see what's possible. I'm not an experienced programmer, but I've the opinion, that it's always wise to know about all opportunities. I really enjoy to discover those opportunities and I'm eager to learn how to use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:29:28.733",
"Id": "493361",
"Score": "2",
"body": "@paladin If you want to explore \"dangerous things\" and get close to the metal, I recommend learning assembly. If you're writing in C, you want to avoid the \"dangerous things\" and do things the correct, idiomatic way. Pretty much anything is \"possible\", like blowing off your foot with a shotgun. I don't recommend trying it, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:33:52.263",
"Id": "493378",
"Score": "0",
"body": "Excellent answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T11:37:01.650",
"Id": "493379",
"Score": "0",
"body": "@paladin `I'm interested also in using the dangerous things, more from a philosophical perspective than from a real \"do I want to use this?\"` Careful here code review is for code working as expected and your code does work, but philosophical perspective makes this too hypothetical and opinion based. Hypothetical questions are off-topic on Code Review and Opinion Based questions are off-topic on many of the stack exchange sites."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:35:13.220",
"Id": "493443",
"Score": "1",
"body": "Unfortunately the topic _how to use goto_ seems to be opinion biased everywhere in the programmer universe ;-)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T04:35:34.733",
"Id": "250695",
"ParentId": "250656",
"Score": "5"
}
},
{
"body": "<p>My <a href=\"https://codereview.stackexchange.com/a/250659/5474\">previous review</a> focused solely on the use of <code>goto</code>. Since then, various answers about state machines and code repetition have popped up. So here is another answer regarding everything else except <code>goto</code> & suggestions for how you could rewrite this better.</p>\n<p><strong>C Language</strong></p>\n<ul>\n<li>Binary literals are not standard C and should therefore be avoided. I can see why you added them as self-documenting code to make sense of the bit masking in the <code>where</code> function. But it probably doesn't make much sense to use bit-fields for this program to begin with - plain numbers might be more readable.</li>\n<li>The <code>\\e</code> escape sequence is not standard C and therefore non-portable. Ironically, escape key has no standardized escape sequence.</li>\n<li>Never use <code>void func ();</code> empty parenthesis. This is obsolete style in C and means "accept any parameter", which makes such functions less type safe. Instead use <code>void func (void);</code>. (C and C++ are different here.)</li>\n<li>Assinging <code>-1</code> to a <code>char</code> is non-portable, since the <code>char</code> type has implementation-defined signedness and might be unsigned on some systems. As a rule of thumb, never use <code>char</code> for anything but text and particularly never use it for any form of arithmetic.</li>\n<li>Unintuitively, <code>getchar</code> returns an <code>int</code>, not a <code>char</code>. Because it may return EOF. Make a habit of always using an <code>int</code> for the result, even though I don't think it matters in this case.</li>\n</ul>\n<p><strong>Style/best practices</strong></p>\n<ul>\n<li><p>Your enum should be changed to <code>typedef enum { ... } typename;</code> and then use variables of type <code>typename</code> when you refer to the enumeration constants, not some int or char etc.</p>\n</li>\n<li><p>Use consistent coding style with indention and line breaks. It is very hard to read code such as this:</p>\n<pre><code>if(dir & 8) printf("NORTH: W\\n");\nelse printf(".\\n");\nif(dir & 4) printf("SOUTH: S\\n");\nelse printf(".\\n");\n</code></pre>\n<p>Instead, do this (optionally with <code>{ }</code>) :</p>\n<pre><code>if(dir & 8) \n printf("NORTH: W\\n");\nelse \n printf(".\\n");\n</code></pre>\n</li>\n<li><p>Ideally all C programs exist in multiple files. In which case it is custom to make local functions <code>static</code>.</p>\n</li>\n</ul>\n<p><strong>Program design</strong></p>\n<ul>\n<li><p>The "spaghetti" in this program isn't as much the fault of <code>goto</code> as the fault of decentralizing room changes (state machine changes) and placing them all over the code. Switching out <code>goto</code> for a state/room variable doesn't fix this, it's "stateghetti" instead of "spaghetti", just a different flavour of the same thing.</p>\n<p>My recommended practice for state machines is to centralize all decision making to one single place. Preferably together with error handling. The ideal state machine looks like this:</p>\n<pre><code> for(;;)\n {\n status = state_machine[state]();\n state = decision_maker(status);\n }\n</code></pre>\n<p>Here the state application logic has been separated from state transition logic. So we don't have to dig through all individual states to figure out which one that caused a state change to what. Everything is centralized inside the "decision_maker", including optional error handling.</p>\n<p>I'll make an example for how this can be applied to your code at the bottom of this post.</p>\n</li>\n<li><p>As pointed out in other reviews, this program suffers from a lot of code repetition, which is always a bad thing, particularly during maintenance. This can be fixed by placing all repeated code in the caller and only place room-specific things inside the room logic code. If we rewrite this to a proper state machine, we can fix that problem at the same time.</p>\n</li>\n</ul>\n<p>After a complete make-over, I came up with a <code>main</code> looking like this:</p>\n<pre><code>int main (void)\n{\n printf("THE EVIL GOTO DUNGEON\\n");\n printf("---------------------\\n");\n printf("\\nPress a direction key \\"W, A, S, D\\" followed with 'ENTER' for moving.\\n\\n");\n\n int current_room = 1;\n\n for(;;)\n {\n giveline();\n ROOM[current_room]();\n \n int next_room;\n do\n {\n next_room = get_next_room(getdir(), current_room);\n } while(next_room == 0);\n current_room = next_room;\n } \n \n printf("You never saw me.\\n");\n\n giveline();\n printf("The End\\n");\n return 0;\n}\n</code></pre>\n<p>Unfortunately, this version lacks any means to escape the dungeon, since my compiler didn't support <code>\\e</code>. Otherwise the <code>for(;;)</code> should be replaced with <code>while(stuck_in_dungeon)</code>.</p>\n<p>The key features here is the <code>ROOM</code> function pointer array, which is a state machine. All decision making has been given to a function called <code>get_next_room</code>, which is the only function that knows how rooms are connected, and which rooms you have access to based on the current one. It's essentially just one big table based on <code>switch</code>:</p>\n<pre><code>static int get_next_room (direction dir, int current_room)\n{\n switch(current_room)\n {\n case 1:\n if(dir == 'S') return 4;\n if(dir == 'E') return 2;\n break;\n case 2:\n if(dir == 'W') return 1;\n break;\n\n ...\n</code></pre>\n<p>Complete code follows. Only briefly tested, but the key here is to look at the state machine logic instead of spaghetti.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\n#define ROOMS 9\n\ntypedef enum {\n DIR_0,\n DIR_E,\n DIR_W,\n DIR_WE,\n DIR_S,\n DIR_SE,\n DIR_SW,\n DIR_SWE,\n DIR_N,\n DIR_NE,\n DIR_NW,\n DIR_NWE,\n DIR_NS,\n DIR_NSE,\n DIR_NSW,\n DIR_NSWE,\n} direction;\n\n\ntypedef void room_func (void);\n\nstatic void room1 (void);\nstatic void room2 (void);\nstatic void room3 (void);\nstatic void room4 (void);\nstatic void room5 (void);\nstatic void room6 (void);\nstatic void room7 (void);\nstatic void room8 (void);\nstatic void room9 (void);\n\nroom_func* const ROOM [ROOMS+1] = \n{\n NULL, // invalid room\n room1,\n room2,\n room3,\n room4,\n room5,\n room6,\n room7,\n room8,\n room9,\n};\n\nstatic int get_next_room (direction dir, int current_room);\n\nstatic void giveline(void);\nstatic void where(int room, direction dir);\nstatic char getdir (void);\n\nint main (void)\n{\n printf("THE EVIL GOTO DUNGEON\\n");\n printf("---------------------\\n");\n printf("\\nPress a direction key \\"W, A, S, D\\" followed with 'ENTER' for moving.\\n\\n");\n\n int current_room = 1;\n\n for(;;)\n {\n giveline();\n ROOM[current_room]();\n \n int next_room;\n do\n {\n next_room = get_next_room(getdir(), current_room);\n } while(next_room == 0);\n current_room = next_room;\n } \n \n printf("You never saw me.\\n");\n\n giveline();\n printf("The End\\n");\n return 0;\n}\n\n\nstatic void room1 (void)\n{\n printf("Somehow you've managed to wake up at this place. You see a LABEL on the wall.\\n");\n printf("\\"Do you know what's more evil than an EVIL GOTO DUNGEON?\\"\\n");\n printf("You're wondering what this cryptic message means.\\n");\n where(1, DIR_SE);\n}\n\nstatic void room2 (void)\n{\n printf("Besides another LABEL, this room is empty.\\n");\n printf("\\"Let's play a game!\\"\\n");\n where(2, DIR_W);\n}\n\nstatic void room3 (void)\n{\n printf("Man, dead ends are boring.\\n");\n printf("Why can't I escape this nightmare?\\n");\n where(3, DIR_S);\n}\n\n\nstatic void room4 (void)\n{\n printf("Is this a real place, or just fantasy?\\n");\n printf("\\"All good things come in three GOTOs.\\"\\n");\n where(4, DIR_NSE);\n}\n\nstatic void room5 (void)\n{\n printf("This is a big river crossing. I guess I need to JUMP.\\n");\n where(5, DIR_SWE);\n}\n\nstatic void room6 (void)\n{\n printf("This place doesn't look very promising.\\n");\n where(6, DIR_NSW);\n}\n\nstatic void room7 (void)\n{\n printf("\\"Give a man a LOOP and you feed him FOR a WHILE;\\n");\n printf(" teach a man a GOTO and you feed him for a RUNTIME.\\"\\n");\n where(7, DIR_NE);\n}\n\nstatic void room8 (void)\n{\n printf("This looks like an endless LOOP of rooms.\\n");\n where(8, DIR_NW);\n}\n\nstatic void room9 (void)\n{\n printf("You've found your old friend Domino. He doesn't look scared, like you do.\\n");\n printf("\\n\\"Listen my friend,\\n");\n printf(" If you want to escape this place, you need to find the escape sequence.\\n");\n printf("\\nWhat does this mean? There no standardized escape sequence for the ESCAPE KEY!\\n");\n printf("\\nAAAAAH!!!\\n");\n where(9, DIR_N);\n}\n\nstatic int get_next_room (direction dir, int current_room)\n{\n switch(current_room)\n {\n case 1:\n if(dir == 'S') return 4;\n if(dir == 'E') return 2;\n break;\n case 2:\n if(dir == 'W') return 1;\n break;\n case 3:\n if(dir == 'S') return 6;\n break;\n case 4:\n if(dir == 'N') return 1;\n if(dir == 'S') return 7;\n if(dir == 'E') return 5;\n break;\n case 5:\n if(dir == 'S') return 8;\n if(dir == 'W') return 4;\n if(dir == 'E') return 6;\n break;\n case 6:\n if(dir == 'N') return 3;\n if(dir == 'S') return 9;\n if(dir == 'W') return 5;\n break;\n case 7:\n if(dir == 'N') return 4;\n if(dir == 'E') return 8;\n break;\n case 8:\n if(dir == 'N') return 5;\n if(dir == 'W') return 7;\n break;\n case 9:\n if(dir == 'N') return 6;\n break;\n }\n return 0;\n}\n\nstatic void giveline(void){\n printf("--------------------------------------------------------------------------------\\n");\n}\n\nstatic void where(int room, direction dir){\n printf("\\nYou are in room %i. Where do you want GOTO?\\n", room);\n if(dir & 8) printf("NORTH: W\\n");\n else printf(".\\n");\n if(dir & 4) printf("SOUTH: S\\n");\n else printf(".\\n");\n if(dir & 2) printf("WEST: A\\n");\n else printf(".\\n");\n if(dir & 1) printf("EAST: D\\n");\n else printf(".\\n");\n}\n\nstatic char getdir (void){\n char c = getchar();\n switch(c){\n case 'w' :\n case 'W' :\n return 'N';\n case 's' :\n case 'S' :\n return 'S';\n case 'a' :\n case 'A' :\n return 'W';\n case 'd' :\n case 'D' :\n return 'E';\n }\n return -1;\n}\n</code></pre>\n<p>Unfortunately this also ruined all the goto puns :(</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:41:03.103",
"Id": "493132",
"Score": "0",
"body": "Thank you very much for your reply. I'm using GCC compiler. I didn't know that using binary literals aren't C-conform, nor `\\e` is, I'll keep that in mind. If it isn't to much trouble for you, may you explain a bit more detailed about the `void func();`-thing? May I use this \"accept any argument\" also to my advantage? I knew about the `getchar()`, but I decided to use it exactly as I did, because I knew it wouldn't matter. Is that bad practice too? I appreciate your work very much, especially the idea with those function pointers. But somehow, I also like my GOTOs, maybe I'm too inexperienced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:59:09.227",
"Id": "493135",
"Score": "1",
"body": "The standard escape sequence for escape is \\033 (ASCII won)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T16:02:49.167",
"Id": "493137",
"Score": "0",
"body": "But now you can't even have holes in your state enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:52:58.513",
"Id": "493228",
"Score": "2",
"body": "@paladin Empty `()` _can_ be abused for function pointer compatibility tricks, but since it's formally obsolete style and may get removed from the C language, you shouldn't use it. See https://stackoverflow.com/a/63775659/584518. As for gotos, once you've had the \"goto considered harmful\" debate some 20-30 times, you'll avoid that keyword just for peace of mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:55:26.173",
"Id": "493229",
"Score": "0",
"body": "@Joshua Yeah but writing magic numbers isn't good practice either. Especially not octal magic numbers. In theory, other systems than ASCII may be present - the old & tiresome \"but what if they are using EBCDIC\" argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:57:21.363",
"Id": "493230",
"Score": "1",
"body": "@Joshua \"But now you can't even have holes in your state enum\" I take it you mean holes in the function pointer table? That's good! Why would I want holes in it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:29:46.743",
"Id": "493305",
"Score": "0",
"body": "@Lundin Thank you for this information regarding empty `()`. So would it be possible to create some kind of method overloading while using this \"obsolete\" syntax? In my opinion, not to use a syntax, because someone says it's a bad thing, is just stupid. PEEK + POKE wasn't also supposed to be a user friendly syntax command, but there where reasons to use those commands while programming a C64."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T08:27:42.453",
"Id": "493360",
"Score": "1",
"body": "@paladin No, you don't get any form of overloading from empty parameter lists, nor can you exploit them for any other benefit. This is simply an *obsolete* feature of the language, from a time before C was standardized, when the language behaved very differently. With an empty parameter list in the declaration, each time you called the function, the compiler would deduce the parameters based on the arguments you specified, using the default promotion rules. It was a mess. Functions should always be declared with the parameters they actually accept. If none, `(void)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T01:39:35.143",
"Id": "493445",
"Score": "0",
"body": "@Lundin: Maintenance taking a state out would require renumbering all states past it. I don't like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T06:26:12.373",
"Id": "493538",
"Score": "0",
"body": "@Joshua No, there's no need for that. This specific example is silly with room1 etc, in a normal use-case each state would have a meaningful name for that state instead."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:00:12.093",
"Id": "250703",
"ParentId": "250656",
"Score": "6"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/questions/250656/a-small-goto-text-adventure-game/250688#250688\">Quuxplusone's answer</a> briefly mentioned making this data-driven, and I've fleshed out the idea here.</p>\n<p>The key realization is that each room varies based only on a few pieces of information: a numeric label, a description string, a set of valid directions, and the label of the room that each valid direction leads to. The original implementation deals with this information using similar code repeated in every 'block'. Implemented that way, making a uniform change requires many modifications in many places, which is error-prone.</p>\n<p>Since all of the per-room behavior only depends on a few pieces of information, there is no need to repeat slightly modified code (whether in labeled blocks referenced by <code>goto</code>, cases in a <code>switch</code> statement, or functions referenced using function pointers), which leads to a better realization of the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't Repeat Yourself</a> principle. Instead of repeated code, you can have a relatively small amount of unique code that acts as required based on external data.</p>\n<p>To implement a data-driven approach, some kind of data structure can be used to store the relevant details about each room. Since a room may theoretically have up to 4 neighbors, an easy way to store the neighbors would be as an array of 4 room ids. If we define a constant to represent an invalid room id, the room id stored in each entry directly indicates whether that direction is valid, so there is no need to store the list of valid directions separately.</p>\n<p>Since there is a data structure representing a room, we can pass the current room's structure to the various functions that need information about it (<code>where</code> in the original code, and an improved version of <code>getdir</code> that includes looping on invalid inputs) instead of passing the various values separately. This allows some of the benefits of encapsulation, in that future versions of the function can use different fields of the room information structure without requiring every invocation to change.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stddef.h>\n#include <limits.h>\n#include <stdint.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <assert.h>\n\ntypedef uint_least32_t ROOM_ID;\n#define PRI_ROOM_ID PRIuLEAST32\n#define INVALID_ROOM_ID UINT_LEAST32_MAX\n\ntypedef enum {\n NORTH = 0, //The first 4 values are used as indices, so the exact value matters\n EAST = 1,\n WEST = 2,\n SOUTH = 3,\n ESCAPE_DIRECTION //This is not used as an index, so its value doesn't matter\n} DIRECTION;\n\ntypedef struct {\n ROOM_ID id;\n const char *description;\n ROOM_ID target_ids[4];\n} ROOM;\n\nconst ROOM all_rooms[] = {\n {1, "Somehow you've managed to wake up at this place. [...]", {INVALID_ROOM_ID, 2, INVALID_ROOM_ID, 4}},\n //...\n};\n\nconst ROOM *find_room(ROOM_ID room_id)\n{\n size_t i;\n for(i = 0; i < sizeof(all_rooms)/sizeof(all_rooms[0]); ++i)\n {\n if(all_rooms[i].id == room_id)\n {\n return &all_rooms[i];\n }\n }\n return NULL;\n}\n\n//Precondition: room is not NULL\nvoid display_where(const ROOM *room)\n{\n const struct {\n DIRECTION dir;\n const char *str;\n } descriptions[4] = {{NORTH, "NORTH: W"}, {SOUTH, "SOUTH: S"}, {WEST, "WEST: A"}, {EAST, "EAST: D"}};\n size_t i;\n assert(room != NULL);\n printf("\\nYou are in room %" PRI_ROOM_ID ". Where do you want GOTO?\\n", room->id);\n for(i = 0; i < 4; ++i)\n {\n if(room->target_ids[descriptions[i].dir] != INVALID_ROOM_ID)\n {\n puts(descriptions[i].str);\n }\n else\n {\n puts(".");\n }\n }\n}\n\n//Precondition: room is not NULL\nDIRECTION get_dir(const ROOM *room)\n{\n while(1)\n {\n int c = getchar();\n switch(c){\n case 'w' :\n case 'W' :\n if(room->target_ids[NORTH] != INVALID_ROOM_ID)\n {\n return NORTH;\n }\n break;\n case 's' :\n case 'S' :\n if(room->target_ids[SOUTH] != INVALID_ROOM_ID)\n {\n return SOUTH;\n }\n break;\n //...\n case '\\e' :\n return ESCAPE_DIRECTION;\n }\n }\n}\n\nint main(void)\n{\n const ROOM_ID FIRST_ROOM_ID = 1;\n const ROOM *room = NULL;\n printf("THE EVIL GOTO DUNGEON\\n");\n printf("---------------------\\n");\n printf("\\nPress a direction key \\"W, A, S, D\\" followed with 'ENTER' for moving.\\n\\n");\n\n room = find_room(FIRST_ROOM_ID);\n while(room)\n {\n DIRECTION dir;\n puts("--------------------------------------------------------------------------------");\n puts(room->description);\n display_where(room);\n dir = get_dir(room);\n if(dir == ESCAPE_DIRECTION)\n {\n break;\n }\n else\n {\n room = find_room(room->target_ids[dir]);\n }\n }\n}\n</code></pre>\n<p>I'm sure many improvements upon the above are possible, but I think this sufficiently demonstrates the basic idea of data-driven code.</p>\n<hr />\n<p>Comments on aspects of the original code besides code repetition:</p>\n<p>Defining every combination of values in a bitmask is unnecessary, since a primary benefit of using bitflags in the first place is that they can be manipulated using bitwise operators. For example, in room 6, instead of using <code>where(6, DIR_NSW)</code> you could use <code>where(6, DIR_N | DIR_S | DIR_W)</code>. Following this practice overall would mean you can get rid of 11 constant definitions and you wouldn't need to remember which order the flags are listed in the combination values.</p>\n<p>Related to using bitfields, your code would be more clear if you used your constants instead of magic numbers. For example, in your <code>where</code> function you could use <code>if(dir & DIR_N)</code> instead of <code>if(dir & 8)</code>. To get in a habit that is more generally applicable (even when flags are multi-bit values), you may want to standardize on something like <code>if((dir & DIR_N) == DIR_N)</code>.</p>\n<p>If you're going to keep your code structure, you could improve it by making <code>getdir</code> accept a description of valid directions as a parameter and have it internally loop until a valid direction is selected. With that change, you could remove all the <code>do</code>/<code>while</code> loops surrounding each invocation (but not the loop body - you still want to actually act on the input).</p>\n<p>You could also somewhat reduce the code repetition by creating a function that handles displaying the room and getting the next direction. A signature like <code>DIRECTIONS handle_room(int id, const char *description, DIRECTIONS dirs)</code> might work. Combined with the previous suggestions, each room's code could be made much much shorter, with only the branching repeated.</p>\n<pre class=\"lang-c prettyprint-override\"><code> ROOM6:\n dir = handle_room(6, "This place doesn't look very promising.\\n", DIR_N | DIR_S | DIR_W);\n if(dir == 'N') goto ROOM3;\n if(dir == 'S') goto ROOM9;\n if(dir == 'W') goto ROOM5;\n goto END;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:37:48.253",
"Id": "493324",
"Score": "0",
"body": "Thank you for your reply. I'm answering to your _\"Comments on aspects of the original code besides code repetition:\"_: I know about the fact of bit-mask operations, but don't do they increase runtime? Using `DIR_N | DIR_S | DIR_W` may need more CPU-cycles than just passing a constant. I agree to your statement of not using magic numbers, but I didn't wanted to change the already posted source. I saw that argument of `getdir()` checking for valid input by itself, but in perspective to my code, this would be redundant and unnecessary. I would reduce the code repetition, but at cost of runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:44:51.197",
"Id": "493325",
"Score": "1",
"body": "Modern (for a very loose definition of modern) optimizing compilers will optimize expressions that contain only constants by evaluating the expression during compilating and inserting just the end result in the output. At runtime, `DIR_N | DIR_S | DIR_W` will be exactly the same as if you wrote `14` instead. Making `getdir()` loop inside the function might speed up execution, since it would reduce overall code size (which allows more code to fit in the cache). `handle_room` might imperceptibly slow things down by a few cycles, but it could have saved significant developer time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:28:53.357",
"Id": "250706",
"ParentId": "250656",
"Score": "8"
}
},
{
"body": "<p>I suggest reading Donald Knuth's article <em>Structured Programming With</em> <code>goto</code> <em>statements</em> (1974) Originally published in Computing Surveys 6, and the second chapter of his book <em>Literate Programming</em>. There he makes excellent points on both sides of the <code>goto</code> debate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T00:14:10.687",
"Id": "493334",
"Score": "0",
"body": "Thank you for this suggestion. I looked into it, it looks solid, but a bit outdated. I know that structured text made the usage of **goto** nearly unneeded. I also know about the advantages of **goto**, that's why I'm using it in the first place. What I really would like to see is an up to date recommendation of when and how to use goto. Especially syntax for constructing \"custom multi-dimensional and interleaving loops with variable labels\", just the total nightmare used in an accurate way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:48:58.530",
"Id": "250762",
"ParentId": "250656",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250695",
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T13:47:42.637",
"Id": "250656",
"Score": "17",
"Tags": [
"c",
"adventure-game"
],
"Title": "A small GOTO text adventure game"
}
|
250656
|
<p>I currently have a Template Workbook set up that has charts and graphs updating when new data is plugged into the Data Tables.<br />
The Data Tables are fixed ranges, and won't change.</p>
<p>The Macro is within the Template Workbook, which is why the below code doesn't set variables for each of the worksheets within the Template Workbook, and <code>Code Names</code> are used for each Worksheet name.</p>
<p>I know the below code is a very basic array code, and works. However, Is there a more condensed way to perform this array macro?
I have researched, but can't seem to find an example of multiple ranges and assigning values from the <code>Source Workbook - Multiple Worksheets</code> to the <code>Template Workbook - Multiple Worksheets</code>.</p>
<pre><code>Sub Main()
'Turn off screen updates and automatic calculations
Application.ScreenUpdating = False
Application.Calculation = xlManual
Application.DisplayAlerts = False
Dim wbDataSource As Workbook
Dim ws As Worksheet
Set wbDataSource = Workbooks("Segment Trends Data.xlsx")
For Each ws In wbDataSource.Worksheets
With ws
If .Index <> 1 Then
Dim Data(13) As Variant
Data(0) = Worksheets("Report1").Range("A1").Value2
Data(1) = Worksheets("Report1").Range("A5:H11").Value2
Data(2) = Worksheets("Report2").Range("A1").Value2
Data(3) = Worksheets("Report2").Range("A5:H11").Value2
Data(4) = Worksheets("Report3").Range("A1").Value2
Data(5) = Worksheets("Report3").Range("A5:H11").Value2
Data(6) = Worksheets("Report4").Range("A1").Value2
Data(7) = Worksheets("Report4").Range("A5:H11").Value2
Data(8) = Worksheets("Report5").Range("A1").Value2
Data(9) = Worksheets("Report5").Range("A5:H11").Value2
Data(10) = Worksheets("Report6").Range("A1").Value2
Data(11) = Worksheets("Report6").Range("A5:H11").Value2
Data(12) = Worksheets("Report7").Range("A1").Value2
Data(13) = Worksheets("Report7").Range("A5:H11").Value2
End If
End With
Next ws
wbDataSource.Close SaveChanges:=False
With wsTTLUSCYTD
.Range("A1").Value2 = Data(0)
.Range("A5:H11").Value2 = Data(1)
End With
With wsCintiCYTD
.Range("A1").Value2 = Data(2)
.Range("A5:H11").Value2 = Data(3)
End With
With wsCOLCYTD
.Range("A1").Value2 = Data(4)
.Range("A5:H11").Value2 = Data(5)
End With
With wsDaytonCYTD
.Range("A1").Value2 = Data(6)
.Range("A5:H11").Value2 = Data(7)
End With
With wsIndyCYTD
.Range("A1").Value2 = Data(8)
.Range("A5:H11").Value2 = Data(9)
End With
With wsLouisCYTD
.Range("A1").Value2 = Data(10)
.Range("A5:H11").Value2 = Data(11)
End With
With wsCoreMktCYTD
.Range("A1").Value2 = Data(12)
.Range("A5:H11").Value2 = Data(13)
End With
Calculate
Dim TemplatePath As String
TemplatePath = "C:\Users\cday\OneDrive - udfinc.com\Budgeting Presentation_Working Files\"
ActiveWorkbook.SaveAs Filename:=TemplatePath & "Segment Trends - CYTD - Budget Template" & ".xlsm", FileFormat:=52
'Turn screen updates and automatic calculations back on
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
End Sub
</code></pre>
<p>Using Debug.Print, the data is pulling from the <code>wbDataSource</code> worksheets within the Loop.
<a href="https://i.stack.imgur.com/bnlf2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bnlf2.png" alt="Debug.Print" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T19:27:01.170",
"Id": "493841",
"Score": "1",
"body": "Does this code work for you? There are a few problems that jump out to me right away: you are opening up `wbDataSource`, but when you're pulling data from the `ReportX` worksheets, you're not getting data from the `wbDataSource` workbook. The data is actually coming from whatever your `ActiveWorkbook` is currently (and it's **not** `wbDataSource`!). Also, you are looping through all the worksheets in a workbook, but it's not necessary because you are explicitly specifying which worksheet's data is copied to a `Data` array slot. Assigning the other sheet objects (`wsCintiCYTD`) is not shown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:49:54.130",
"Id": "493963",
"Score": "0",
"body": "@PeterT Yes, this works for me. I'm not sure why you're saying the data is not coming from `wbDataSource`, because I am using `For each ws in `wbDataSurce.worksheets`, `With ws` to the the `.value2` of each range. I specified the worksheet by it's name: `Worksheets(\"Report1\").range` `Worksheets(\"Report2\").range`, etc.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-22T17:51:00.837",
"Id": "493964",
"Score": "0",
"body": "@PeterT I didn't need to assign the other sheet objects, that are receiving the data, because the module is within that Workbook with `Code Names`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T13:33:44.033",
"Id": "494346",
"Score": "0",
"body": "In your `For Each ws In wbDataSource.Worksheets` loop, your only reference to anything in `wbDataSource` is when you are checking `.Index` because that is explicitly using the `With ws` clause. So your reference is really `If ws.Index <> 1 Then`. Inside that loop, there are no other references to `ws`. Also, all of your `.Value2` references are accessing the ***currently active worksheet***, NOT necessarily `wbDataSource`. Simply opening another workbook doesn't guarantee to make it active. And nothing in your `With ws` clause is used for any of the `.Value2` references."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T13:36:05.133",
"Id": "494347",
"Score": "0",
"body": "Additionally, let's say your `wbDataSource` workbook has 12 worksheets. Your loop to set the `Data` array accessing the exactly same data 12 times, completely regardless of how many worksheets there are, or what is on those worksheets. There's no reason to loop since you're explicitly getting 14 `.Value2` values from very specific worksheets. So the loop is not necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T14:22:38.997",
"Id": "494351",
"Score": "0",
"body": "@PeterT I guess I don't understand what you're saying. When I use `Debug.Print`, it's pulling the values from the `wbDataSource`. The Loop is going through each worksheet within the `wbDataSource` except Sheet 1. I added a picture to the original post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T14:29:51.393",
"Id": "494352",
"Score": "0",
"body": "@PeterT In regards to not needing the loop. I get what you're saying, but then I loose my reference to the `wbDataSource`. So how would I go about getting those Data Values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-09T16:03:39.013",
"Id": "496014",
"Score": "0",
"body": "If you are just trying to condense the code to make it more readable, you could consider using [bracket notation](https://codegolf.stackexchange.com/a/137344/61846) for reading your cell value. Building off of PeterT's answer, you could then condense the first line of the with statement to `Data(0) = [Report1!A1]`. Note that the `value2` is implied here, if you want the range you would have to add a `set` to the beginning of that statement."
}
] |
[
{
"body": "<p>The comment discussion in the original post directly relate to the differences between the <code>ActiveWorkbook</code> and <code>ThisWorkbook</code>. While you code may indeed work, it's not a guarantee. <a href=\"https://www.automateexcel.com/vba/activeworkbook-thisworkbook/\" rel=\"nofollow noreferrer\">This reference</a> (and <a href=\"https://analystcave.com/vba-tip-day-activeworkbook-vs-thisworkbook/\" rel=\"nofollow noreferrer\">this one</a>) have good explanations to illustrate the differences between how you reference a workbook and why you should always pay specific attention to references (whether it's to the <code>Workbook</code> or <code>Worksheet</code> or <code>Range</code>).</p>\n<p>As explained in the comments, because you specifically identify the worksheet for all the <code>.Value2</code> data, you don't need to loop through all the worksheets. This will reduce the setup of your array to</p>\n<pre><code>Dim wbDataSource As Workbook\nSet wbDataSource = Workbooks("Segment Trends Data.xlsx")\n\nDim Data(13) As Variant\nWith wbDataSource\n Data(0) = .Worksheets("Report1").Range("A1").Value2\n Data(1) = .Worksheets("Report1").Range("A5:H11").Value2\n Data(2) = .Worksheets("Report2").Range("A1").Value2\n Data(3) = .Worksheets("Report2").Range("A5:H11").Value2\n Data(4) = .Worksheets("Report3").Range("A1").Value2\n Data(5) = .Worksheets("Report3").Range("A5:H11").Value2\n Data(6) = .Worksheets("Report4").Range("A1").Value2\n Data(7) = .Worksheets("Report4").Range("A5:H11").Value2\n Data(8) = .Worksheets("Report5").Range("A1").Value2\n Data(9) = .Worksheets("Report5").Range("A5:H11").Value2\n Data(10) = .Worksheets("Report6").Range("A1").Value2\n Data(11) = .Worksheets("Report6").Range("A5:H11").Value2\n Data(12) = .Worksheets("Report7").Range("A1").Value2\n Data(13) = .Worksheets("Report7").Range("A5:H11").Value2\nEnd With\n</code></pre>\n<p>Notice that I've changed the <code>With</code> clause to reference the <code>wbDataSource</code> workbook so that's it's very clear where all your data is coming from.</p>\n<p>The code you've written actually doesn't need an array, in fact the array obscures what the code is really trying to do. What exactly is <code>Data(0)</code> or <code>Data(11)</code>? You might find it tedious, but I would more clearly define what information all those variables hold. As an example</p>\n<pre><code>Dim reportTitle As String\nDim reportDescription As String\nDim regionNumber As Long\nDim regionManager As String\n\nWith wbDataSource\n reportTitle = .Worksheets("Report1").Range("A1").Value2\n reportDescription = .Worksheets("Report1").Range("A5:H11").Value2\n regionNumber = .Worksheets("Report2").Range("A1").Value2\n regionManager = .Worksheets("Report2").Range("A5:H11").Value2\n ...\nEnd With\n</code></pre>\n<p>Now when you come back to make an update to your code in six months, you don't have to remember what each of those array slots actually means.</p>\n<p>Finally, getting back to the original question of your post, there's no magic or easy way to make the assignments to multiple destination worksheets. You've already defined the code names for each of the sheets, so the VBA you have is about as simple as you can make it. I still recommend the change to more descriptive variable names to make it clear which data you are copying to the destination worksheets.</p>\n<pre><code>With wsTTLUSCYTD\n .Range("A1").Value2 = reportTitle\n .Range("A5:H11").Value2 = reportDescription\nEnd With\n\nWith wsCintiCYTD\n .Range("A1").Value2 = regionNumber\n .Range("A5:H11").Value2 = regionManager\nEnd With\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T13:24:35.417",
"Id": "251205",
"ParentId": "250663",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:07:24.690",
"Id": "250663",
"Score": "1",
"Tags": [
"array",
"vba",
"excel"
],
"Title": "Looking for a more condensed method of assigning values by using arrays and fixed ranges"
}
|
250663
|
<p>This script opens a basic form which allows one to search all files in a directory for instances of a string, before outputting results to a textbox and CSV (found in the script location). Each line outputted is of the format:</p>
<blockquote>
<p>Word <strong>{string}</strong> in <strong>{file}</strong> on line <strong>{line number}</strong>: <strong>{full line}</strong></p>
</blockquote>
<p><strong>Steps:</strong></p>
<ol>
<li>Specify Directory</li>
<li>Input string you would like to search for</li>
<li>Toggle ignore case on or off</li>
<li>Click Go.</li>
</ol>
<p><strong>Notes:</strong></p>
<p>This is not completely finished yet. Script will only search basic TXT files. I'm also a beginner with Tkinter/GUIs, so haven't moved buttons around, etc. I've just added the buttons & labels one after the other. This will eventually be rectified. There's also an issue where if I'm searching a large directory of files, the form will look like it's frozen until it's finished searching. Finally, I may have went overboard on some of the error handling. I'm newish to this as well.</p>
<p>I'm trying to be a better programmer, particularly with structuring and readability, so any constructive criticism would be much appreciated.</p>
<p><a href="https://i.stack.imgur.com/jKEaa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jKEaa.png" alt="enter image description here" /></a></p>
<pre><code>from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
import pandas as pd
import tkinter as tk
import os
import re
import sys
################ FUNCTIONS ################
def save_to_file(wordlist):
"""Save list to CSV format and save CSV to script directory"""
script_directory = os.path.dirname(sys.argv[0]) # Path where script is being run from
df = pd.DataFrame(data={"Results": wordlist})
df.to_csv(script_directory+"/mycsv.csv", sep=",", index=False, line_terminator='\n')
def print_to_textbox(wordlist):
"""Print all lines in wordlist to textbox"""
for lines in wordlist:
text_box.insert("end", "\n"+lines)
if len(wordlist) == 0:
text_box.insert("1.0", "\nNothing To Display")
def browse_button():
"""Button will open a window for directory selection"""
global folder_path
selected_directory = filedialog.askdirectory()
folder_path.set(selected_directory)
def search_files():
"""Search all files in specified directory"""
folderPath = folder_path.get()
searchString = string_entry.get()
text_box.delete("1.0", tk.END)
# Set word case option on/off.
if var1.get() == 1:
IGNOREWORDCASE = True
else:
IGNOREWORDCASE = False
# List to store all lines where string is found.
wordlist = []
# Loop through all files and search for string, line by line.
for (path, directories, files) in os.walk(folderPath, topdown=True):
for file in files:
filepath = os.path.join(path, file)
try:
with open(filepath, 'r') as currentfile:
for lineNum, line in enumerate(currentfile, 1):
line = line.strip()
match = re.search(searchString, line, re.IGNORECASE) if IGNOREWORDCASE else re.search(searchString, line)
if match:
word = f"Word '{searchString}' in '{file}' on line {lineNum}: {line}"
wordlist.append(word)
except IOError as ex:
words = f"Error; {file}; {ex}"
wordlist.insert(0, words)
except EnvironmentError as ex:
words = f"Error; {file}; {ex}"
wordlist.insert(0, words)
except OSError as ex:
words = f"Error; {file}; {ex}"
wordlist.insert(0, words)
except UnicodeDecodeError as ex:
words = f"Error; {file}; {ex}"
wordlist.insert(0, words)
except:
words = f"Error; {file}"
wordlist.insert(0, words)
# Print all lines to text box.
print_to_textbox(wordlist)
# Save to file.
save_to_file(wordlist)
################ TKINTER SCRIPT ################
# Setup Window.
window = tk.Tk()
window.geometry("900x500")
window.title("String Search")
# Button to select directory.
select_directory = tk.Button(window, text = "Select Directory", command=browse_button)
select_directory.pack()
# Label to store chosen directory.
folder_path = tk.StringVar()
directory_label = tk.Label(window, textvariable = folder_path, bg="#D3D3D3", width=70)
directory_label.pack()
# Entry to type search string.
string_entry = tk.Entry(window, bg="#D3D3D3")
string_entry.pack()
# Check button to turn ignore case on/off.
var1 = tk.IntVar()
stringCase_select = tk.Checkbutton(window, text='Ignore Case',variable=var1, onvalue=1, offvalue=0)
stringCase_select.pack()
# Button to run main script.
go_button = tk.Button(window, text="Go", command=search_files)
go_button.pack()
# Button to quit the app.
quit_button = tk.Button(window, text = "Quit", command=window.quit)
quit_button.pack()
# Text box to display output of main text.
text_box = ScrolledText(width=110, borderwidth=2, relief="sunken", padx=20)
text_box.pack()
# Button to clear the text box display.
clear_button = tk.Button(window, text = "Clear", command = lambda: text_box.delete("1.0", tk.END))
clear_button.pack()
# Run an event loop.
window.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>Consider using PEP-484 type hints for your function signatures.</p>\n<p>Use a linter like <code>pyflakes</code>, <code>flake8</code> or <code>black</code> that will give you a number of suggestions about your code format.</p>\n<p>Move your <code>TKINTER SCRIPT</code> into one or more functions, instead of in global scope.</p>\n<p>Use <code>pathlib</code>, so that this:</p>\n<pre><code>script_directory+"/mycsv.csv\n</code></pre>\n<p>can be</p>\n<pre><code>Path(script_directory) / 'mycsv.csv'\n</code></pre>\n<p>If <code>var1.get()</code> returns 0/1, then you can simply write</p>\n<pre><code>IGNORE_WORD_CASE = bool(var1.get())\n</code></pre>\n<p>though you should give <code>var1</code> a more meaningful name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T17:00:32.243",
"Id": "492981",
"Score": "0",
"body": "Thank you. I don't know much about type hints, but I'll look them up. And great additional suggestions. Is it standard practice to have the main tkinter script into a function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T17:13:20.833",
"Id": "492983",
"Score": "0",
"body": "@AaronWright you can have an Object-oriented approach too, check this [What is the best way to structure a tkinter application?](https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:10:07.033",
"Id": "492988",
"Score": "0",
"body": "@AryanParekh Thanks. Yes I have this (and another) script I would like to convert to OOP style. However I'm struggling with it a bit. Do you know where I could find a good, simple, OOP program with Tkinter so I could see the general structure? The examples given in that link show how you might start it, but it would be good to see a full script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:10:56.550",
"Id": "493025",
"Score": "0",
"body": "OOP is an option, but not the only one. It's also possible to simply throw everything into a `main` function, which would still be better than what you have (particularly for unit testing)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:26:48.043",
"Id": "250665",
"ParentId": "250664",
"Score": "2"
}
},
{
"body": "<h1>PEP-8</h1>\n<p>To maintain consistency while writing code, Python code follows the <a href=\"https://www.python.org/dev/peps/pep-0008/#:%7E:text=Use%20the%20function%20naming%20rules,invoke%20Python%27s%20name%20mangling%20rules.\" rel=\"nofollow noreferrer\">PEP-8</a> naming convention. For example</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#:%7E:text=Use%20the%20function%20naming%20rules,invoke%20Python%27s%20name%20mangling%20rules.\" rel=\"nofollow noreferrer\">Source</a></p>\n<blockquote>\n<p>Function names should be lowercase, with words separated by\nunderscores as necessary to improve readability.</p>\n<p>Variable names follow the same convention as function names.</p>\n</blockquote>\n<p>The library that you are currently using, which is <code>tkinter</code> also follows the same naming convention. You can see that classes like <code>Button</code>,<code>Canvas</code>, and <code>StringVar()</code>. All follow the <code>CamelCase</code> since they are classes.</p>\n<h1>Positioning widgets in your application</h1>\n<p>Although <code>.pack()</code> works, you will soon see its limits when you start trying to position the widgets in specific places, like an <strong>exit button</strong> typically stays in the corner, A <strong>title</strong> usually is placed at the top. In these scenarios <code>.pack()</code> is just very limited.</p>\n<p>A common way is to use <code>.place()</code> to position widgets in your application. It has many arguments like <code>bordermode</code> and <code>anchor</code> to customize your task, the two main are <code>x</code> and <code>y</code> which are basically just the horizontal and vertical points at which your widget will be placed.</p>\n<p>Here is a simple Tkinter window of <code>geometry("500x500")</code> I have created to show the usage of <code>place()</code>. It also has a <code>Label</code> as a simple widget.<br><Br>\n<a href=\"https://i.stack.imgur.com/MAQds.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MAQds.png\" alt=\"window\" /></a></p>\n<p>Example: <code>widget.place(x = 300,y = 50)</code></p>\n<p><a href=\"https://i.stack.imgur.com/O0Bbp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O0Bbp.png\" alt=\"window2\" /></a></p>\n<p>You get to decide where you want to place your widgets accurately.</p>\n<h1>Structuring a <code>Tk</code> application</h1>\n<p>@Reinderien suggested your <code>TKINTER_SCRIPT</code> into a function. This makes sense because you already have good functions like <code>search_files()</code>, why would you have your Tkinter application in the main scope?</p>\n<p>While some might disagree, my suggestion is that you opt for an <strong>Object-oriented approach</strong>, which will help keep your code clean. In your situation, it makes sense to have a single <code>MainApplication()</code> class. Here is a simple example of what that would look like</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MainApplication:\n def __init__(self,window,size = "500x500"):\n self.window = window\n window.geometry(size)\n self.entry_box = # Entry box widget\n self.title = # Title label \n # More widgets that are relevant to MainApplication\n\n def close_application():\n # print any messages on window like "Thank you for using..."\n self.window.close()\n\nroot = tk.Tk()\nwindow = MainApplication(root)\n\nroot.mainloop()\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/17466561/best-way-to-structure-a-tkinter-application\">Structuring a Tkinter application</a></p>\n<h2>Small suggestions</h2>\n<ul>\n<li>Use <code>root.iconbitmap( #icon image )</code> to set a <code>16x16</code> icon for your tkinter application, this will appear instead of the little feather that comes</li>\n<li><code>Tkinter</code> has a huge variety of widgets, it is possible that you might find a new one from this <a href=\"http://effbot.org/tkinterbook/tkinter-classes.htm\" rel=\"nofollow noreferrer\">list of main widgets</a> that might be perfect for your application.</li>\n<li><a href=\"https://docs.python.org/dev/library/tkinter.messagebox.html\" rel=\"nofollow noreferrer\">message boxes in tkinter</a> will be suitable for when a user might do something wrong, or maybe you want to get a confirmation.</li>\n</ul>\n<p>Example of a message box <br><br><br>\n<a href=\"https://i.stack.imgur.com/FIy0u.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FIy0u.png\" alt=\"yn\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:28:58.763",
"Id": "492991",
"Score": "1",
"body": "This is brilliant, thanks! I'll take a look through all this tonight and tomorrow and let you know how I get on. Still trying to wrap my head around OOP. For the sample you've provided, should I be keeping my functions (e.g. `search_files()`) as functions and adding them as methods inside the MainApplication Class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:35:37.393",
"Id": "492992",
"Score": "0",
"body": "@AaronWright No, `search_files` has nothing to do with your GUI, hence you should either keep a class that would handle the files, or a few functions would work too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:21:26.590",
"Id": "493003",
"Score": "1",
"body": "Okay. I'll aim to create another class to deal with this. I presume all the widgets for the form will need to be declared within the `MainApplication` Class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:23:17.267",
"Id": "493004",
"Score": "0",
"body": "@AaronWright Yes, I feel like you should have a look at some good programs made in tkinter. You can find several on github. This will give you some nice ideas"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:29:39.513",
"Id": "493018",
"Score": "1",
"body": "Thanks. I'll take a look! I have tried to find a good script on GitHub but never had much luck. Do you have any suggestions? I'm also trying to covert my other script that I submitted here (regarding a book library) to an tkinter application and have been struggling to implement it. It may be too advanced for me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:06:06.557",
"Id": "250669",
"ParentId": "250664",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:08:27.940",
"Id": "250664",
"Score": "5",
"Tags": [
"python",
"tkinter",
"gui"
],
"Title": "Python Tkinter GUI - Search Files In Directory For Instances Of A String"
}
|
250664
|
<p>I have a method that receives 2 params:</p>
<ul>
<li>first one is an array of objects of type { group1: string, group2: string, measure: number, ... }</li>
<li>second one is a string</li>
</ul>
<p>I also have an <em>enum</em> <strong>GroupColumns</strong></p>
<pre><code>enum GroupColumns {
ColumnTypeX = 'Column Type X',
ColumnTypeY = 'Column Type Y',
ColumnTypeZ = 'Column Type Z'
}
</code></pre>
<p>This method computes the sum of all the measures for a certain group type when the second parameter matches the second group and the first group is equal to any group found in GroupColumns enum.</p>
<pre class="lang-js prettyprint-override"><code> private ComputeSpecificColumnMeasure(data: Array<IDynamic<any>>, groupType: String): number {
let measure: number = 0;
data.forEach(el => {
if (el.group2 === groupType && (el.group1 === GroupColumns.ColumnTypeX || el.group1 === GroupColumns.ColumnTypeY || el.group1 === GroupColumns.ColumnTypeZ )) {
measure += el.measure;
}
});
return measure;
}
</code></pre>
<p>I do not like the verifications inside the if. If I somehow want to add more columns(unlikely) I would need to expand it, or create another method only to check if group1 is equal to any GroupColumns.</p>
<p>Any opinions?</p>
<p>How can I make this code scalable and optimized</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:44:04.323",
"Id": "492979",
"Score": "2",
"body": "Welcome to Code Review! Since the majority of developers want their code to be *scalable* and *optimized*, the current question title, applies to too many posts on this site. 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), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:37:13.307",
"Id": "493185",
"Score": "1",
"body": "I [changed the title](https://codereview.stackexchange.com/posts/250666/revisions#rev-arrow-58d41dbb-de09-4b8a-b9c1-66ac6eacaa2d) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>If possible, I'd change the <code>GroupColumns</code> to be an array instead. That way, all you need to do is use <code>.includes</code> to see if an item is included in it. Other improvements can be:</p>\n<p><strong>Let TS automatically infer types when possible</strong>. You only need to denote the type of a variable or the type of a return value when TS can't do so on its own. TS can automatically determine that <code>ComputeSpecificColumnMeasure</code> returns a number. It can also determine that <code>measure</code> will be a number, so there's no need to denote the type of either of those.</p>\n<p><strong>Avoid String type</strong> The "String" type is something created via the String constructor, eg <code>const str = new String('data');</code>. This is almost never what you want - for a normal string, use the <code>string</code> (primitive) type instead. (TSLint rule: <a href=\"https://palantir.github.io/tslint/rules/ban-types/\" rel=\"nofollow noreferrer\"><code>ban-types</code></a>)</p>\n<p><strong>Avoid <code>any</code></strong> You have <code>data: Array<IDynamic<any>></code>. <code>any</code> should be avoided in TypeScript whenever possible, because it's so flexible - it loses type safety. If you don't know what the type will be, use <code>unknown</code> instead, which is type-safe.</p>\n<p>For a small example of a problem with <code>any</code>:</p>\n<pre><code>const fn = (arg: any) => {\n console.log(arg.toFixed(2));\n}\n</code></pre>\n<p>This will not throw a TS error, but it's likely to throw a runtime error unless the argument passed happens to be a number. Using <code>unknown</code> instead <em>will</em> throw a TS error - it'll force you to narrow the type first before calling a particular method on it.</p>\n<pre><code>const fn = (arg: unknown) => {\n if (typeof arg === 'number') {\n console.log(arg.toFixed(2));\n }\n}\n</code></pre>\n<p>Even if the value that's <code>any</code> isn't being used in the function, it'd good practice to avoid <code>any</code> when possible anyway. (TSLint rule: <a href=\"https://palantir.github.io/tslint/rules/no-unsafe-any/\" rel=\"nofollow noreferrer\"><code>no-unsafe-any</code></a>)</p>\n<p><strong>Capitalization</strong> Conventionally, only a <em>few things</em> use PascalCase in JS:</p>\n<ul>\n<li>Namespaces (eg <code>React</code>)</li>\n<li>Classes</li>\n<li>Enums, sometimes</li>\n</ul>\n<p>A plain method should probably use the standard <code>camelCase</code> instead.</p>\n<pre><code>const groupColumns = [\n 'Column Type X',\n 'Column Type Y',\n 'Column Type Z'\n] as const; // Use "as const" to prevent automatic widening to `string[]`\n\nprivate computeSpecificColumnMeasure(data: Array<IDynamic<unknown>>, groupType: string) {\n let measure = 0;\n data.forEach(el => {\n if (el.group2 === groupType && groupColumns.includes(el.group1)) {\n measure += el.measure;\n }\n });\n return measure;\n}\n</code></pre>\n<p>Or, you could use <code>.filter</code> and <code>reduce</code> if you wished:</p>\n<pre><code>private computeSpecificColumnMeasure(data: Array<IDynamic<unknown>>, groupType: string) {\n return data\n .filter(el => el.group2 === groupType && groupColumns.includes(el.group1))\n .reduce((measureSoFar, el) => measureSoFar + el.measure, 0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:10:47.497",
"Id": "493055",
"Score": "0",
"body": "Just to expand, if it is needed to be enum (in other places maybe), one can use `Object.keys(GroupColumns).map(k => GroupColumns[k]).includes(group)`, but ofc, best to prepare the array before the loop..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:53:45.673",
"Id": "250667",
"ParentId": "250666",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250667",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T16:32:07.493",
"Id": "250666",
"Score": "2",
"Tags": [
"javascript",
"performance",
"typescript"
],
"Title": "Computing the sum of all measures for a certain group type"
}
|
250666
|
<p>I am creating a library management system. Presently am done creating the Book and BookItem class. Can you point any thing you feel isn't necessary, inefficient or a general bad practice so I could learn from it and grow in my programming career</p>
<p><strong>Book.hh</strong></p>
<pre><code>#ifndef BOOK_HH
#define BOOK_HH
/*****************************************************************
* Name: Book.hh
* Author: Samuel Oseh
* Purpose: Book class method-function prototype
* ***************************************************************/
#include <string>
class Book {
public:
/* method function */
Book() = default;
~Book(){}
virtual std::string getStatus() const = 0;
virtual std::string getType() const = 0;
};
#endif
</code></pre>
<p><strong>BookItem.hh</strong></p>
<pre><code>#ifndef BOOKITEM_HH
#define BOOKITEM_HH
/*****************************************************************
* Name: BookItem.hh
* Author: Samuel Oseh
* Purpose: BookItem class method-function prototype
* ***************************************************************/
#include "Book.hh"
#include <string>
#include <ctime>
class BookItem : Book{
private:
/* data */
std::string name;
std::string author;
std::string pubDate;
std::string isbn;
std::string status;
std::string type;
bool onlineCopy{false};
/* utility function */
bool validatePubDate( std::string date ) const;
public:
BookItem() = default;
BookItem( const std::string &name, const std::string author, const std::string pubDate, \
const std::string isbn, const std::string status, const std::string type, bool onlineCopy = false );
BookItem( const BookItem &bookItem ) { *this = std::move(bookItem); }
BookItem& operator=( const BookItem &bookItem );
void setStatus( std::string status );
void setType( std::string status );
std::string getStatus() const { return status; };
std::string getType() const { return type; }
void setOnlineCopy() { onlineCopy = true; }
bool hasOnlineCopy() { return onlineCopy; }
std::string giveName() const { return name; }
std::string giveAuthor() const { return author; }
std::string givePubDate() const { return pubDate; }
std::string giveIsbn() const { return isbn; }
static const std::string *const statusPtr;
static const std::string *const typePtr;
~BookItem(){}
};
#endif
</code></pre>
<p><strong>BookItem.cc</strong></p>
<pre><code>/*****************************************************************
* Name: BookItem.cc
* Author: Samuel Oseh
* Purpose: BookItem class method-function definitions
* ***************************************************************/
#include <iostream>
#include <stdexcept>
#include "BookItem.hh"
std::string statusCopy[5] = { "RESERVED", "AVAILABLE", "UNAVAILABLE", "REFERENCE", "LOANED" };
std::string typeCopy[] = {"ART", "BASIC MEDICAL SCIENCES", "LAW", "PROGRAMMING", "COMPUTER SCIENCE", "NURSING", "PHARMARCY", "MAGAZINE",\
"ARTICLE", "JOURNAL", "BANKING", "NEWSLETTER"};
const std::string *const BookItem::typePtr = typeCopy;
const std::string *const BookItem::statusPtr = statusCopy;
BookItem:: BookItem( const std::string &nme, const std::string author, const std::string pubDate, \
const std::string isbn, const std::string status, const std::string type, bool onlineCopy ) : Book() {
this->name = name;
this->author = author;
if ( validatePubDate( pubDate ) )
this->pubDate = pubDate;
else
throw std::invalid_argument("Invalid publication date");
this->isbn = isbn;
setStatus( status );
setType( type );
this->onlineCopy = onlineCopy;
}
BookItem &BookItem::operator=( const BookItem &bookItem ) {
name = bookItem.name;
author = bookItem.author;
pubDate = bookItem.pubDate;
isbn = bookItem.pubDate;
status = bookItem.status;
type = bookItem.type;
onlineCopy = bookItem.onlineCopy;
return *this;
}
bool BookItem::validatePubDate( std::string date ) const {
struct tm tm;
if ( strptime( date.c_str(), "%d/%m/%y", &tm ) )
return true;
return false;
}
void BookItem::setStatus( std::string status ) {
for ( const std::string *p = begin(statusCopy); p != end(statusCopy); ++p ) {
if ( *p == status ) {
this->status = status;
return;
}
}
throw std::invalid_argument("Invalid Status");
}
void BookItem::setType( std::string type ) {
for ( const std::string *p = begin(typeCopy); p != end(typeCopy); ++p ) {
if ( *p == type ) {
this->type = type;
return;
}
}
throw std::invalid_argument("Invalid Type");
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:39:14.793",
"Id": "493044",
"Score": "2",
"body": "Can you include more details? Like what the purpose of those classes is and how they are supposed to be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:52:41.443",
"Id": "493064",
"Score": "0",
"body": "From the headers, I have no idea what instances will be good for. (`/* method function */` is a no-no comment, more so preceding a C++ constructor. `Book() = default` with no other constructors & explicit empty destructors?!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T08:04:41.770",
"Id": "493068",
"Score": "0",
"body": "They are classes to a bigger picture. am making a library management system, so the system would eventually need books"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T11:09:12.707",
"Id": "493084",
"Score": "1",
"body": "Considering it's not doing much yet, I don't think it makes sense to review it at this point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T11:23:57.170",
"Id": "493085",
"Score": "0",
"body": "These days libraries loan out more than just books, so the Book class should probably not be named book, and BookItem should be renamed Book. Other than that there isn't much to review yet."
}
] |
[
{
"body": "<ol>\n<li><p>First issue is that I don't see why you make it via OOP. Why <code>Book</code> is an interface? It has almost zero functionality. Use interface for objects with complex functionality when you have several possible implementations. While the Book class can only serve for <code>downcasting</code> which in itself is best avoided unless necessary. Also it has a bug that the destructor isn't virtual - it needs to be virtual when you work with abstract classes / polymorphism.</p>\n</li>\n<li><p>Throwing in a constructor is a bad idea in general and especially in OOP cases. If classes weren't fully constructed then a destructor might mess up and corrupt the code leading to UBs - so to throw in a constructor programmer needs to make sure that such issues do not occur and there are some complex cases where it is non-trivial. You should avoid it by storing date not as a string but as a dedicated class/struct. And let user call the conversion from string when needed. If the conversion fails than throw will happen outside of the constructor.</p>\n</li>\n<li><p><code>BookItem& operator=( const BookItem &bookItem );</code> why implement it? Just default it or don't write at all. And declaring destructor <code>~BookItem(){}</code> is pointless. Also you are missing move assignment and move constructor.</p>\n</li>\n<li><p>You should use <code>enum class</code> for <code>BookType</code> and <code>BookStatus</code>. No idea why you use a string - it is just a waste and confusion for users. Just add general string to/from enum conversions.</p>\n</li>\n<li><p><code>std::string giveName() const ...</code> and similar have weird names. WTF does <code>giveName</code> means? I don't understand it. It should be <code>getName</code> and same for other <code>giveXXX</code> replace it with <code>getXXX</code>. Furthermore, books don't have names: they have titles. So replace "name" with "title".</p>\n</li>\n<li><p>The functions <code>std::string giveAuthor()</code> and the like return <code>std::string</code> which potentially make an unnecessary allocation and allocations are slow and cause memory fragmentation in the long run. You can avoid it by either returning const reference <code>const std::string&</code> or <code>std::string_view</code>.</p>\n</li>\n<li><p><code>void setOnlineCopy()</code> ... also doesn't follow naming conventions. People use <code>set</code> to supply interface to set value to given property like <code>void setX(int x){mX = x;}</code> but here you just set the boolean to true. Declare the function like <code>void setOnlineCopyStatus(bool bHasOnlineCopy)</code>.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:45:43.990",
"Id": "493045",
"Score": "1",
"body": "would avoid setters and getters completely, they're evil"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T04:29:36.893",
"Id": "493053",
"Score": "1",
"body": "@AryanPerekh yeah, generally they are useless waste of code but sometimes there is needed some additional functionality that can be put with the getter/setter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T07:58:19.303",
"Id": "493066",
"Score": "0",
"body": "I was trying to avoid getters and setters..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T08:02:28.603",
"Id": "493067",
"Score": "0",
"body": "How do i make an enum class static.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T08:36:34.277",
"Id": "493070",
"Score": "2",
"body": "@theProgrammer why would need enum class static?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:38:26.790",
"Id": "250691",
"ParentId": "250668",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250691",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:02:38.060",
"Id": "250668",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"classes"
],
"Title": "Library Management System with OOP"
}
|
250668
|
<p>I've written a Python program to analyse a huge C++ code base in excess of millions of lines of code. The job of the program is simply to search for all C and C++ style comments and extract all the comments which contain specific keywords and phrases and to write those comments to an associated file. So far the program works well enough. It's fairly quick and easy to configure and it does the job, but it doesn't search anywhere near as fast as I would like it to and I would like some advice on how to make things run faster.</p>
<p><strong>Configuration</strong></p>
<p>The program is very quick and easy to configure. If you'd like to search a codebase for a single expression all you have to do is pass it that expression as an argument and the directory to search in and it will do the rest for you. To search for comments containing the word "hack" in the src/ directory you could simply write:</p>
<pre><code>./main.py -e hack -s ./src/
</code></pre>
<p>If you want to pass many expressions however, you need to use a specially crafted JSON file and pass the name of that file as an argument. An example JSON file might look like this:</p>
<pre><code>[
{
"hack-stuff": [
"hack",
"hacked",
"hacky"
]
},
"WARNING",
"DANGER",
[
"bad",
"badly"
]
]
</code></pre>
<p>The file is then passed to the program like such:</p>
<pre><code>./main.py -f test-words.json -s ./src/
</code></pre>
<p>This will create four files: "hack-stuff", "WARNING", "DANGER" and "bad". The file "hack-stuff" will be where all comments containing the words hack, hacked and hacky will be placed, "bad" will be where all comments containing "bad" and "badly" will be placed, and "WARNING" and "DANGER" will be where comments containing "WARNING" and "DANGER" will be placed respectively. This example demonstrates the three ways (string, list or dictionary) you can specify which comments matches you want to place in which files.</p>
<p><strong>Program Structure</strong></p>
<p>At the core of the program is the SourceWalker class which contains all the internal logic required to analyse the codebase and write the comments to their respective files. There is also a main function in a separate file which reads the arguments into their relevant variables and performs the JSON processing (if necessary) before then initialising and running an instance of the class via the walk() method.</p>
<p><strong>Performance</strong></p>
<p>I've tried a number of things to make the program as performant as possible, including incorporating multiprocessing which yielded huge improvements, but I'm not sure what I can do to make it any faster at this point. The main slowdown is caused by the for loop within _process_files() on line 117. This is the part of the program which runs in each of the child processes and searches through each file looking for valid comments before checking them against a series of pre-compiled regular expressions to see if they match one of the expressions we're looking for. I'm sure there are better ways of extracting the comments from each file and then searching through them but I'm not sure what they would be. Any suggestions here would be greatly appreciated.</p>
<p><strong>Additional Comments</strong></p>
<p>While performance is my main concern here, I'd also appreciate any feedback on the correctness and style of my program. It seems to work as intended but I can't guarantee there aren't some edge cases I've missed during my testing.</p>
<p><strong>The Code</strong></p>
<p><strong>main.py</strong></p>
<pre><code>#!/usr/bin/python3
import sys
import json
import os
import argparse
import SourceWalker
def initialiseParser():
parser = argparse.ArgumentParser(description = "Search the contents of comments within source code files")
parser.add_argument("--file_name", "--file", "-f", help = "Name of the file containing the JSON list of expressions to search for", type = str)
parser.add_argument("--source-dir", "--src", "-s", help = "The root directory of the source files to search over", type = str)
parser.add_argument("--output-dir", "--out", "-o", help = "The directory the output files will be placed in", type = str)
parser.add_argument("--expression", "--expr", "-e", help = "The expression to search for within the source comments", type = str)
parser.add_argument("--language", "--lang", "-l", help = "The style of comments to look for within the file", type = str)
return parser
def main():
parser = initialiseParser()
args = parser.parse_args()
if args.source_dir:
source_dir = args.source_dir
else:
sys.exit("Source directory must be specified!")
if args.file_name:
file_name = args.file_name
input_file = open(file_name, "r")
expressions = json.loads(input_file.read())
elif args.expression:
expressions = []
expressions.append(str(args.expression))
else:
sys.exit("Error: Expression or file containing expressions must be specified!")
output_dir = "./comments/"
if args.output_dir:
output_dir = args.output_dir
if not os.path.exists(output_dir):
os.makedirs(output_dir)
walker = SourceWalker.SourceWalker(source_dir, output_dir, expressions, extensions=[ ".c", ".cpp", ".h", ".cxx" ])
walker.walk()
if "input_file" in locals():
input_file.close()
return
if __name__=="__main__":
main()
</code></pre>
<p><strong>SourceWalker.py</strong>
#!/usr/bin/python3</p>
<pre><code>import sys
import json
import re
import os
import multiprocessing
import codecs
from pathlib import Path
class SourceWalkerException(Exception):
"""
Raised when there is an error processing the given expressions
TODO: Make error handling more informative and clean up. Should display a message to the user explaing what went wrong and close all open files.
"""
pass
class SourceWalker:
_output_file_names = []
_regexes = {}
_expr_file_names = {}
def __init__(self, source_dir, output_dir, expr_list, encoding = "ISO-8859-1", process_count = 12, extensions = [ ".c", ".h" ]):
try:
if not os.path.exists(source_dir) or not os.path.exists(output_dir):
raise NotADirectoryError
if process_count < 1:
raise SourceWalkerException("Process count cannot be less than one!")
codecs.lookup(encoding)
if not isinstance(extensions, list):
raise SourceWalkerException("Extensions must be passed as a list!")
for extension in extensions:
if extension[0] != '.':
raise SourceWalkerException("Extensions must start with a \'.\'!")
elif len(extension) <= 1:
raise SourceWalkerException("Extensions must be more than one character long!")
except NotADirectoryError as exception:
raise SourceWalkerException("Directory does not exist! " + str(exception))
else:
self._source_dir = source_dir
self._output_dir = output_dir
self._encoding = encoding
self._expr_list = expr_list
self._process_count = process_count
self._extensions = extensions
self._process_expr_list()
def _process_expr_list(self):
for expr in self._expr_list:
try:
if isinstance(expr, list):
if len(expr) == 0:
raise SourceWalkerException("Expression list cannot be empty!")
output_file_name = expr[0]
if not isinstance(output_file_name, str):
raise SourceWalkerException("Expression sub-lists can only contain strings!")
for sub_expr in expr:
if not isinstance(sub_expr, str):
raise SourceWalkerException("Expression sub-lists can only contain strings!")
elif sub_expr in self._regexes.keys():
raise SourceWalkerException("Expressions can only appear once in the expression list!")
self._regexes[sub_expr] = re.compile("\s+%s(\s|,|:|;|\n)+" % (sub_expr)) # Naieve regex to catch expressions
self._expr_file_names[sub_expr] = self._output_dir + output_file_name
self._output_file_names.append(self._output_dir + output_file_name)
elif isinstance(expr, dict):
if len(expr.keys()) == 0:
raise SourceWalkerException("Expression dictionary cannot be empty!")
output_file_name = list(expr)[0]
if not isinstance(expr[output_file_name], list):
raise SourceWalkerException("Expression dictionary cannot be empty!")
for sub_expr in expr[output_file_name]:
if not isinstance(sub_expr, str):
raise SourceWalkerException("Expression sub-lists can only contain strings!")
elif sub_expr in self._regexes.keys():
raise SourceWalkerException("Expressions can only appear once in the expression list!")
self._regexes[sub_expr] = re.compile("\s+%s(\s|,|:|;|\n)+" % (sub_expr))
self._expr_file_names[sub_expr] = self._output_dir + output_file_name
self._output_file_names.append(self._output_dir + output_file_name)
elif isinstance(expr, str):
if expr in self._regexes.keys():
raise SourceWalkerException("Expressions can only appear once in the expression list!")
self._output_file_names.append(self._output_dir + expr)
self._regexes[expr] = re.compile("\s+%s(\s|,|:|;|\n)+" % (expr))
self._expr_file_names[expr] = self._output_dir + expr
else:
raise SourceWalkerException("Expression list can only contain dictionaries, lists, and strings!")
except SourceWalkerException as exception:
self.cleanup()
raise
def _process_files(self, input_files, output_files, mutexes): # Find way to process different types of source file, I'd rather not be limited to C only...
for file_name in iter(input_files.get, None):
with open(file_name, "r", encoding = self._encoding) as file_object:
in_multi_comment = False
in_single_comment = False
in_string = False
prev_char = ''
comment = ''
for line_num, line in enumerate(file_object, 1):
for char in line:
if char == '/':
if in_string or in_single_comment:
prev_char = char
continue
if prev_char == '*':
in_multi_comment = False
comment += char
for expr in self._regexes.keys():
if self._regexes[expr].search(comment):
mutexes[expr].acquire()
os.write(output_files[expr], ("%s: %s %s\n" % (file_name, str(line_num), comment)).encode())
mutexes[expr].release()
comment = ''
elif prev_char == '/':
in_single_comment = True
comment += prev_char
elif char == '*':
if in_string or in_single_comment or in_multi_comment:
if in_single_comment or in_multi_comment:
comment += char
prev_char = char
continue
if prev_char == '/':
in_multi_comment = True
comment += prev_char
elif char == '"':
if prev_char == '\\' or in_single_comment or in_multi_comment:
prev_char = char
continue
in_string = not in_string
prev_char = char
if in_single_comment or in_multi_comment:
comment += char
if in_single_comment:
in_single_comment = False
for expr in self._regexes.keys():
if self._regexes[expr].search(comment):
mutexes[expr].acquire()
os.write(output_files[expr], ("%s: %s %s" % (file_name, str(line_num), comment)).encode())
mutexes[expr].release()
comment = ''
def walk(self):
input_files = multiprocessing.Queue(0)
processes = []
mutexes = {}
output_files = {}
for fname in self._output_file_names:
try:
file_handle = os.open(fname, os.O_WRONLY | os.O_CREAT)
mutex = multiprocessing.Lock()
except IOError:
for file in output_files.keys():
output_files[file].close()
raise SourceWalkerException("Error: Could not open output file %s, skipping!" % fname)
for expr in self._expr_file_names.keys():
if self._expr_file_names[expr] == fname:
output_files[expr] = file_handle
mutexes[expr] = mutex
for root, dirs, file_names in os.walk(self._source_dir):
for file_name in file_names:
if any(ext in Path(file_name).suffix for ext in self._extensions):
input_files.put(os.path.join(root, file_name))
for i in range(self._process_count):
input_files.put(None)
for cur_process in range(self._process_count):
process = multiprocessing.Process(target = self._process_files, args = (input_files, output_files, mutexes))
processes.append(process)
process.start()
for i in range(1, self._process_count):
processes[i].join()
for file in output_files.keys(): # Close the file associated with each expression
try:
os.close(output_files[file]) # Since multiple expressions can be associated with the same file we need to avoid invalid file closures
except:
pass
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T18:15:16.690",
"Id": "493309",
"Score": "1",
"body": "The indentation shown here is incorrect starting at `__init__`. This file wouldn't be able to run; please edit your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:07:54.410",
"Id": "493312",
"Score": "1",
"body": "@Reinderien It runs fine on my machine, looks like SO must have borked my indentation. I'll fix in in a second."
}
] |
[
{
"body": "<p>If I understand your description, you're only looking for comments but you are searching through the full code base every time. Since comments are normally a small part of the code (less than 10%?) I suggest doing a pre-process step first where you simply extract all the comments and then do the actual search on those.</p>\n<p>By "extract" I mean save the comment in separate files so that you can search only in those files.</p>\n<p>For repeated searches in the same codebase, this should help since the preprocessing can be done once and then the actual search has less text to look through.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T09:41:33.137",
"Id": "493237",
"Score": "0",
"body": "This sounds like a good idea, I'll add some functionality to separate the comments out for multiple searches. What would you recommend I do to track changes in source code files to speed up extractions run on ever changing code bases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:12:58.407",
"Id": "493241",
"Score": "1",
"body": "I don't know how your setup looks, but it seems reasonable to set up a scheduled job (every 24h? every 2h?) to extract the comments and replace the older comments files, which would keep this up to date and always run the search on the most recent files. You could also configure a github trigger/hook or just read the repo every few minutes to trigger a new extraction on every update if that's needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:14:09.293",
"Id": "493242",
"Score": "1",
"body": "If this is used widely by many users, I might consider uploading the comments into ElasticSearch and making that available to others to search in. This is more work of course, but may make it more useful."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T22:32:36.103",
"Id": "250678",
"ParentId": "250670",
"Score": "3"
}
},
{
"body": "<p>You can specify <a href=\"https://docs.python.org/3/library/argparse.html#required\" rel=\"nofollow noreferrer\">required arguments</a> in <code>argparse</code> rather than handling them yourself. You can also specify <a href=\"https://docs.python.org/3/library/argparse.html#default\" rel=\"nofollow noreferrer\">defaults</a>, for example for <code>output_dir</code>.</p>\n<p><a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\"><code>os.makedirs</code></a> takes <code>exist_ok=True</code> to indicate that it should only create the directory if it doesn't exist yet.</p>\n<p>The <code>extensions</code> argument to the <code>SourceWalker</code> constructor probably shouldn't be hardcoded.</p>\n<p>Use <code>with open(file_name, "r") as file_handle:</code> to make sure the file is always closed when leaving that context. On a related note, <code>locals()</code> should IMO only be used as a last resort, since it's hard to follow code where strings are used to refer to variables and IDEs can't do anything useful with that code. For example, if you were to rename <code>input_file</code> to <code>input_file_path</code> (I'd recommend that in any case) it would be trivial to forget to change the string reference.</p>\n<p>I would recommend using <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><code>black</code></a> and <a href=\"https://pypi.org/project/isort/\" rel=\"nofollow noreferrer\"><code>isort</code></a> to format the code. It'll be closer to idiomatic style that way, with no manual work.</p>\n<p>After formatting I would recommend running <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\"><code>flake8</code></a> to find other non-idiomatic code. For example it looks like the <code>SourceWalker</code> code is broken - the methods are at the same level as the class definition.</p>\n<p>Creating an exception with a static string, such as <code>SourceWalkerException("Process count cannot be less than one!")</code>, is a code smell. It's not <em>necessarily</em> bad, but like boolean parameters it usually means something should be pulled apart. In this case it would be better to have a separate exception class for a too low process count (and the other error conditions), which could be something as simple as <code>ProcessCountTooLowError</code>. That way the only thing passed to an exception constructor (if anything) is whatever <em>dynamic</em> content can be used to debug that exception. Also, this means that if you ever end up wanting to handle the exception you can <code>except ProcessCountTooLowError</code> rather than having to parse the error message inside a generic <code>except SourceWalkerException</code>. (Oh, and custom exception classes should end in <code>Error</code>, not <code>Exception</code>.)</p>\n<p>Rather than checking for things like whether the output directory exists I would let the application fail once it reaches the code which tries to write to that directory. This is called "time of check to time of use" - basically, whether the directory exists when you make that check has no bearing on whether it exists when the code actually tries to use it. It is also too narrow a check, since, for example, the directory could also not be writable by the current user, or the filesystem could be full.</p>\n<p>On a similar note, running <code>codecs.lookup(encoding)</code> to check the encoding exists before actually using it in a completely different call seems like it could easily be an incomplete check. It might be better to constrain the encoding <em>parameter</em> <code>options</code> to only the available encodings. That way it's checked as early as possible, the users get a nice actionable error and the help text shows the possible values.</p>\n<p>The plural of "regex" is "regex<strong>e</strong>s".</p>\n<p><a href=\"https://docs.python.org/3/reference/compound_stmts.html#function-definitions\" rel=\"nofollow noreferrer\">Don't use mutable default arguments</a> (<a href=\"https://stackoverflow.com/q/1132941/96588\">discussion</a>). On a related note, when should you use default arguments at all? Two rules of thumb:</p>\n<ol>\n<li>If the default is not actually ever used because all the calls specify a value, the default is pointless.</li>\n<li>If <em>none</em> of the calls override the default it is also pointless - it might as well be a variable or constant.</li>\n</ol>\n<p><code>if not isinstance(extensions, list):</code> is not idiomatic; it should be perfectly valid to pass in any iterable such as a <code>tuple</code>.</p>\n<p>Constructors should, in general, do nothing more complex than setting field values. Once that's done a <code>run</code>, <code>process</code> or other method should be run separately to do the actual processing. I don't remember where I first saw this explained clearly, but see for example <a href=\"https://stackoverflow.com/q/14694982/96588\">Why is using side effects bad practice in JavaScript constructors?</a> and <a href=\"https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html\" rel=\"nofollow noreferrer\">Constructors Must Be Code-Free</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:21:45.550",
"Id": "493244",
"Score": "0",
"body": "`codecs.lookup(encoding)` will raise an exception if an invalid encoding type is passed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:37:25.097",
"Id": "493246",
"Score": "0",
"body": "Could you explain that last part? Why should constructors only set field values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T17:58:03.370",
"Id": "493308",
"Score": "0",
"body": "Updated in response to your comments."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:15:44.410",
"Id": "250681",
"ParentId": "250670",
"Score": "3"
}
},
{
"body": "<h2>List literals</h2>\n<pre><code> expressions = []\n expressions.append(str(args.expression))\n</code></pre>\n<p>should just be</p>\n<pre><code> expressions = [str(args.expression)]\n</code></pre>\n<h2>Pathlib</h2>\n<p>This:</p>\n<pre><code>if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n</code></pre>\n<p>should use the shiny new <code>pathlib</code> equivalent:</p>\n<pre><code>Path(output_dir).mkdir(exist_ok=True)\n</code></pre>\n<p>The same module can be used for</p>\n<pre><code>if not os.path.exists(source_dir) or not os.path.exists(output_dir):\n</code></pre>\n<h2>Variable existence</h2>\n<pre><code>if "input_file" in locals():\n input_file.close()\n</code></pre>\n<p>is sketchy. Usually the way to indicate in Python that a variable has a value or not is to potentially take <code>None</code>, not to potentially be undeclared. You can even mark it as maybe-none using the <code>Optional</code> type hint.</p>\n<h2>Return</h2>\n<p>The single <code>return</code> at the end of <code>main()</code> is redundant.</p>\n<h2>Dictionary length</h2>\n<pre><code>if len(expr.keys()) == 0:\n</code></pre>\n<p>can be</p>\n<pre><code>if len(expr) == 0:\n</code></pre>\n<p>or even</p>\n<pre><code>if not expr:\n</code></pre>\n<h2>Regex compilation</h2>\n<pre><code> self._regexs[sub_expr] = re.compile("\\s+%s(\\s|,|:|;|\\n)+" % (sub_expr))\n</code></pre>\n<p>needs, at the least, a leading <code>r</code> to make that string literal raw.</p>\n<p>Generally, taking input from a file and treating it as a non-validated sub-regular-expression is a bad idea. It's not <code>eval</code>-level bad, but it's not good. Are these actual regular expressions, or just substrings? If they're only substrings, call <code>escape</code> on them before inserting them into your outer regular expression.</p>\n<p>If they actually are their own regular expression, you'll want to <em>at least</em> put each one in its own non-capturing group in the outer expression, to avoid nasty surprises.</p>\n<h2>Chained exceptions</h2>\n<pre><code>except NotADirectoryError as exception:\n raise SourceWalkerException("Directory does not exist! " + str(exception))\n</code></pre>\n<p>should be</p>\n<pre><code>except NotADirectoryError as exception:\n raise SourceWalkerException("Directory does not exist! " + str(exception)) from exception\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T18:32:04.703",
"Id": "250757",
"ParentId": "250670",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T18:34:22.613",
"Id": "250670",
"Score": "5",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"multiprocessing"
],
"Title": "Analysing a Huge Codebase with Python"
}
|
250670
|
<p>I've written my first "real" Python application. I've never worked much with Python before, so I'd like to receive feedback on how I can structure the application to make it follow the way Python programs usually are.</p>
<p>This is very much from a "readability" perspective, but getting feedback on general structure as well as my use of classes, naming of methods and use of comments would be great to get other's opinion on.</p>
<p><a href="https://github.com/sbrattla/swarmconstraint" rel="nofollow noreferrer">https://github.com/sbrattla/swarmconstraint</a></p>
<p>The use case for this application is real. I manage a Docker Swarm, but I need a service (aka task in Docker Swarm) to only run in a couple of nodes participating in that swarm. However, if I use placement constraints (constraint a service to specific nodes) and the nodes which the service is constrained to go down - then the service goes down as well. So, the application will remove the placement constraints if specified nodes goes down so that the service can "fallback" to other nodes.</p>
<pre><code>#!/usr/bin/python3
import argparse
import docker
import json
import logging
import re
import string
import time
class SwarmConstraint:
def __init__(self, args):
self.args = args
self.initClient()
self.logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)-25s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(logging.DEBUG)
if (not self.args['watch']):
raise Exception('At least one node to watch must be provided.')
if (not self.args['toggle']):
raise Exception('At least one node to toggle must be provided.')
if (not self.args['label']):
raise Exception('At least one label must be provided.')
if (not self.args['prefix']):
raise Exception('A prefix must be provided.')
self.logger.info('Watch {watch}.'.format(watch=','.join(self.args['watch'])))
self.logger.info('Toggle the label(s) {labels} on {toggle}.'.format(labels=','.join(self.args['label']), toggle=','.join(self.args['toggle'])))
self.logger.info('Prefix disabled labels with {prefix}.'.format(prefix=self.args['prefix']))
def run(self):
# Collect availability for watched nodes, and keep track of the collective
# availability for all the watched nodes.
nodes = self.getNodes()
allWatchedNodesUnavailable = True
for nodeId in nodes:
watchNode = nodes[nodeId]
if (not self.args['watch'] or watchNode['hostname'] not in self.args['watch']):
continue
if (self.isNodeAvailable(watchNode) == True):
allWatchedNodesUnavailable = False
break;
if (allWatchedNodesUnavailable):
self.logger.warn('All watched nodes are unavailable.')
else:
self.logger.debug('One or more watched nodes are available.')
# Disable or enable labels depending on the collective availability for all
# the watched nodes.
for nodeId in nodes:
toggleNode = nodes[nodeId]
if (self.args['toggle'] and toggleNode['hostname'] not in self.args['toggle']):
continue
if (allWatchedNodesUnavailable):
self.disableLabels(toggleNode, self.args['label'], self.args['prefix'])
else:
self.enableLabels(toggleNode, self.args['label'], self.args['prefix'])
def getSocket(self):
return 'unix://var/run/docker.sock'
def initClient(self):
# Initialize the docker client.
socket = self.getSocket()
self.client = docker.DockerClient(base_url=socket)
def getNodes(self):
# Returns all nodes.
allNodes = self.client.nodes.list();
allNodesMap = {}
for node in allNodes:
allNodesMap[node.id] = {
'id' : node.id,
'available' : True if node.attrs['Spec']['Availability'] == 'active' else False,
'hostname': node.attrs['Description']['Hostname'],
'role' : node.attrs['Spec']['Role'],
'platform' : {
'os' : node.attrs['Description']['Platform']['OS'],
'arch' : node.attrs['Description']['Platform']['Architecture']
},
'labels' : node.attrs['Spec']['Labels'],
}
return allNodesMap
def isNodeAvailable(self, node):
return node['available']
def disableLabels(self, node, labels, prefix):
# Disable labels on a node by adding a prefix to each label. The node will only be
# updated if at least one of the provided labels are currently enabled.
matchingNode = next(iter(self.client.nodes.list(filters={'id':node['id']})), None)
if (matchingNode is None):
return
spec = matchingNode.attrs['Spec']
update = False
for label in labels:
if (label not in spec['Labels']):
continue
nodeLabelKey = label
nodeLabelVal = spec['Labels'][nodeLabelKey]
spec['Labels'].update(self.prefixNodeLabel(nodeLabelKey, nodeLabelVal, prefix))
spec['Labels'].pop(nodeLabelKey, None)
update = True
self.logger.info('Disabling the label "{key}={val} on {node}".'.format(key=nodeLabelKey, val=nodeLabelVal, node=node['id']))
if (update):
matchingNode.update(spec)
return True
else:
return False
def enableLabels(self, node, labels, prefix):
# Enable labels on a node by removing the prefix from each label. The node will only be
# updated if at least one of the provided labels are currently disabled.
matchingNode = next(iter(self.client.nodes.list(filters={'id':node['id']})), None)
if (matchingNode is None):
return
spec = matchingNode.attrs['Spec']
update = False
for label in labels:
label = self.prefixLabel(label, prefix)
if (label not in spec['Labels']):
continue
nodeLabelKey = label
nodeLabelVal = spec['Labels'][nodeLabelKey]
spec['Labels'].update(self.unPrefixNodeLabel(nodeLabelKey, nodeLabelVal, prefix))
spec['Labels'].pop(nodeLabelKey, None)
update = True
self.logger.info('Enabling the label "{key}={val} on {node}".'.format(key=nodeLabelKey, val=nodeLabelVal, node=node['id']))
if (update):
matchingNode.update(spec)
return True
else:
return False
def prefixLabel(self, label, prefix):
# Split and prefix a label into a dictionary holding the prefixed key and the value separately.
return '{prefix}.{key}'.format(prefix=prefix, key=label)
def isNodeLabelPrefixed(self, key, prefix):
# Evaluates if a node label is prefixed
return True if key.find(prefix) > -1 else False;
def prefixNodeLabel(self, key, val, prefix):
# Prefix a node label.
label = {'{prefix}.{key}'.format(prefix=prefix,key=key) : '{val}'.format(val=val)}
return label
def unPrefixNodeLabel(self, key, val, prefix):
# Remove prefix from a node label.
key = key.replace('{prefix}.'.format(prefix=prefix), '')
label = {'{key}'.format(prefix=prefix,key=key) : '{val}'.format(val=val)}
return label
class FromFileAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
super(FromFileAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, path, option_string=None):
if (path):
data = None
with open(path) as f:
data = json.load(f)
if (data is None):
return
if ('watch' in data):
namespace.watch += data['watch']
if (data['toggle']):
namespace.toggle += data['toggle']
if ('label' in data):
namespace.label += data['label']
return
def main():
parser = argparse.ArgumentParser(description='Toggles one or more constraints depending on node availability')
parser.add_argument('--watch', metavar='watch', action='append', default=[], help='A node which availability is to be watched.')
parser.add_argument('--toggle', metavar='toggle', action='append', default=[], help='A node for which constraints are to be toggled. Defaults to all nodes.')
parser.add_argument('--label', metavar='label', action='append', default=[], help='A label which is to be toggled according to availability for watched nodes.')
parser.add_argument('--prefix', metavar='prefix', default='disabled', help='The prefix to use for disabled labels. Defaults to "disabled".')
parser.add_argument('fromFile', action=FromFileAction, help='A file which holds configurations.')
args = vars(parser.parse_args())
se = SwarmConstraint(args)
while(True):
try:
se.run()
time.sleep(10)
except KeyboardInterrupt:
break
except Exception as err:
print(err)
break
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:27:30.633",
"Id": "493005",
"Score": "0",
"body": "Thanks @BCdotWEB, updated accordingly! I hope this makes it a bit easier for people to understand what I'd like feedback on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:11:19.030",
"Id": "493011",
"Score": "1",
"body": "@Emma is that a built-in functionality of ZooKeeper?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:02:23.137",
"Id": "493016",
"Score": "1",
"body": "@Emma so, what the application here does is that it turns Docker Swarm's placement constraints (hard constraints) into soft constraints. You mention both ZooKeeper, Terraform and Ansible in your comment. Are we on the same page? The tools you mention, such as ZooKeeper, is quite a handful in itself to run. Would you suggest setting up a cluster of ZooKeeper instances just to implement this functionality? Would you use Ansible to watch availability of individual services, and similarly use Ansible to react to availability changes? I use SaltStack for provisioning. Not sure I'd use it for this?"
}
] |
[
{
"body": "<p>Welcome to Code Review!</p>\n<h2>PEP-8</h2>\n<p>In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.</p>\n<p>Functions and variables should be named in a <code>lower_snake_case</code>, classes as <code>UpperCamelCase</code>, and constants as <code>UPPER_SNAKE_CASE</code>.</p>\n<p>You do not need to specify parentheses around the conditional checks in <code>if-</code>/<code>elif-</code> clauses.</p>\n<p>Indentation for the program should follow a 4-whitespace for each indent level style.</p>\n<h2>f-strings over str.format</h2>\n<p>Of the 2 of following, which would you prefer? (both do the same thing)</p>\n<ul>\n<li><code>f"{var} value"</code></li>\n<li><code>"{var} value".format(var=var)</code></li>\n</ul>\n<p>The former is called f-string, and is newly introduced in python 3.</p>\n<h2>argparse</h2>\n<p>You are gathering all arguments from the command line using <code>argparse</code> package, yet instead of letting argparse set those as <code>required</code>, you are validating in the class initialisation.</p>\n<h2>Magic string</h2>\n<p>The unix socket address appears to be a constant, and doesn't really need to be associated with the class method. Unless you plan for this to be also provided from the cli, let it be defined as a constant value. Same goes for logging formatter etc.</p>\n<h2>Useless complexity</h2>\n<p>You gather all nodes from the docker swarm client into a variable, whose only purpose is to get iterated upon, with no further reference to it. Iterate without storing a separate variable.</p>\n<p>Generating the node object's dictionary can be separated into its own method, which received a node and returns the dictionary you need.</p>\n<p>The node aggregation is defined as <code>get_nodes</code> (the correct naming convention), and still for the <code>disable_labels</code>/<code>enable_labels</code> etc, you aggregate nodes with its own node aggregator.</p>\n<p>As an example, the node aggregator can be done as:</p>\n<pre><code>@staticmethod\ndef process_node(node):\n spec = node.attrs["Spec"]\n description = node.attrs["Description"]\n return {\n "id": node.id,\n "available": spec["Availability"] == "active",\n "hostname": description["Hostname"],\n "role": spec["Role"],\n "platform": {\n "os": description["Platform"]["OS"],\n "arch": description["Platform"]["Architecture"],\n },\n "labels": spec["Labels"],\n }\n\ndef get_nodes(self):\n return {\n node.id: self.process_node(node)\n for node in self.client.nodes.list()\n }\n</code></pre>\n<p>Notice in the above the <code>node["available"]</code> attribute. You don't need the if-else statement there.</p>\n<h2>Comments</h2>\n<p>The comments as they are, <em>are completely <strong>useless</strong></em>. If you have something like:</p>\n<pre><code>def init_client(self):\n # Initialize the docker client.\n</code></pre>\n<p>then the comment serves no real purpose, as <code>init_client</code> is self-explanatory name. If you <strong>do</strong> want to add comments, perhaps specify how the function does things (though the code should be doing that).</p>\n<h2>Duplicated code</h2>\n<p>Both the functions <code>enable_labels</code> and <code>disable_labels</code> have a majority of the code common in them. This should be extracted to its own function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T23:37:38.400",
"Id": "250683",
"ParentId": "250672",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250683",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T19:06:19.757",
"Id": "250672",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Docker Swarm Constraint Service (Microservices)"
}
|
250672
|
<p>I work on a code-base that uses <code>xml</code> to set up problems and specify model parameters. I've created a script that I run in tandem with our code. This script will store important model information parsed from the most recent <code>xml</code> file and eventually end up in a LaTeX document. This script will help me keep track of model parameters I've tried and aid in reproducibility.</p>
<p>One problem I've come across is that, as I change model parameters, certain nodes will be deleted from the <code>xml</code> file and cause my script to crash. Instead, I've created a solution that will attempt to parse what I want, but if it doesn't find it, it will just return an empty dictionary.</p>
<p>This leads me to merging a bunch of dictionaries and I'm not quite sure this is the most idiomatic/efficient way. For this code-review I would like any feedback on how to approach this problem better, plus any styling or formatting suggestions.</p>
<p>Here is a sample <code>xml</code> file <strong>./low_tax/il_train.xml</strong>:</p>
<pre class="lang-xml prettyprint-override"><code><Simulation>
<Models>
<ROM name="arma" subType="ARMA">
<P>2</P>
<Q>2</Q>
<Fourier>8760, 2190, 168, 24, 12, 8, 6, 3</Fourier>
<Segment grouping='interpolate'>
<subspace pivotLength='168' shift='zero'>HOUR</subspace>
</Segment>
</ROM>
<PostProcessor>
<KDD>
<Features>TOTALLOAD</Features>
<SKLtype>cluster|KMeans</SKLtype>
<n_clusters>12</n_clusters>
</KDD>
</PostProcessor>
</Models>
<Samplers>
<MonteCarlo>
<samplerInit>
<limit>8</limit>
<initialSeed>42</initialSeed>
</samplerInit>
</MonteCarlo>
</Samplers>
</Simulation>
</code></pre>
<p>Here is the python code:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
from pathlib import Path
import xml.etree.cElementTree as ET
from datetime import datetime
def search_node(root: ET.Element, node: str, children: list) -> dict:
"""
Return dictionary containing information requested from node children.
@In: root, ET.Element, root node of xml tree.
@In: node, str, a string containing xpath to parent node of interest.
@In: children, list, a list of expected children nodes.
@Out: dict, a dictionary containing retrieved information for node.
"""
node_str = node + "/{child}"
values = {
# This information will be placed in LaTeX table;
# Therefore, we need to preemptively escape underscores.
k.replace("_", "\_"): root.findtext(node_str.format(child=k)) for k in children
}
return values
def parse_xml(xml_file: Path) -> dict:
"""
Parse model information from xml file.
@In: xml_file, Path, path to current specified xml_file.
@Out: dict, a dictionary of information parsed from xml.
"""
root = ET.parse(xml_file).getroot()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-7]
# Information parsed from xml file.
case_info = {
"state": xml_file.name.split("_")[0].upper(),
"strategy": xml_file.resolve().parent.name,
}
model_info = search_node(root, "Models/ROM", ["P", "Q", "Fourier"])
model_info = {**model_info, **root.find("Models/ROM/Segment/subspace").attrib}
pp_info = search_node(
root,
"Models/PostProcessor/KDD",
["SKLtype", "n_clusters", "tol", "random_state"],
)
samp_info = search_node(root, "Samplers/MonteCarlo/samplerInit", ["limit"])
misc_info = {"created": now}
# Merge all dictionaries
# This should allow us to not fail on missing nodes
info_dict = {**case_info, **model_info, **pp_info, **samp_info, **misc_info}
# Drop any keys with None values to filter the table
filtered = {k: v for k, v in info_dict.items() if v is not None}
info_dict.clear()
info_dict.update(filtered)
return info_dict
if __name__ == "__main__":
xml_file = Path("./low_tax/il_train.xml").resolve()
model_info = parse_xml(xml_file)
print(model_info)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:37:20.460",
"Id": "493014",
"Score": "0",
"body": "which docs parser do you use for the `@In/@Out` type parameter description?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:44:25.093",
"Id": "493015",
"Score": "0",
"body": "I'm pretty sure it's supposed to be doxygen but our documentation tools have fallen severely behind. I think it broke a while back and we haven't had the funding to fix it. A mess I know :/"
}
] |
[
{
"body": "<p>Nice, type hints! One thing I might start with, after working with a strict mypy configuration, is to make the type declarations stricter, and then enforce that strictness. For example, a type of <code>list</code> is equivalent to <code>list[Any]</code>. In the case of the <code>children</code> parameter you know more than that: it's <code>list[str]</code>. mypy has an <a href=\"https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-disallow-any-generics\" rel=\"nofollow noreferrer\">option to disallow "any" generics</a>.</p>\n<p>In the same vein you can use <a href=\"https://mypy.readthedocs.io/en/stable/more_types.html#typeddict\" rel=\"nofollow noreferrer\"><code>TypedDict</code></a> to specify the types of the contents of your <code>dict</code>s. You can specify <a href=\"https://mypy.readthedocs.io/en/stable/more_types.html#totality\" rel=\"nofollow noreferrer\"><code>total=False</code></a> if some of the entries in the <code>dict</code> are optional.</p>\n<p><strong><a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a></strong> are the recommended way to create strings mixing literals and variable values. For example, <code>node_str = node + "/{child}"</code> would be written <code>node_str = f"{node}/{{child}}"</code>.</p>\n<p>Single letter variables should be avoided in general. <code>k</code> is used in different places with different meanings; in the first place it should probably be <code>child</code>.</p>\n<p><code>strftime("%Y-%m-%d %H:%M:%S.%f")[:-7]</code> can be simplified to <code>strftime("%Y-%m-%d %H:%M:%S")</code>.</p>\n<p>The <code>if v is not None</code> filter should probably be in the <code>search_node</code> function. That way you won't have to do the whole filling a variable, copying out the non-<code>None</code> values and replacing the variable rigmarole.</p>\n<p>I would probably replace <code>node_str</code> with something like <code>child_xpath</code>, and <code>children</code> with something like <code>child_element_names</code>, for clarity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T22:49:05.130",
"Id": "250679",
"ParentId": "250674",
"Score": "3"
}
},
{
"body": "<p>The effect of merging the dicts, without actually creating a new dict, can be done using <a href=\"https://docs.python.org/3.7/library/collections.html#collections.ChainMap\" rel=\"nofollow noreferrer\"><code>collections.ChainMap</code></a>.</p>\n<p>Rather than clearing <code>info_dict</code>, updating it from <code>filtered</code> and returning it, just return <code>filtered</code>.</p>\n<pre><code>from collections import ChainMap\n\n# Merge all dictionaries\n# a key gets it's value from earlier dicts\ninfo_dict = ChainMap(misc_info, samp_info, pp_info, model_info, case_info)\n\n# Drop any keys with None values to filter the table\nfiltered = {k: v for k, v in info_dict.items() if v is not None}\nreturn filtered\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:14:54.393",
"Id": "250720",
"ParentId": "250674",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:11:28.370",
"Id": "250674",
"Score": "3",
"Tags": [
"python",
"performance",
"parsing",
"xml",
"hash-map"
],
"Title": "Handle missing children nodes when parsing XML into a dictionary"
}
|
250674
|
<p>I'm posting two solutions for LeetCode's "Print FooBar Alternately". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/print-foobar-alternately/" rel="nofollow noreferrer">Problem</a></h3>
<p>Suppose you are given the following code:</p>
<pre><code>class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
</code></pre>
<p>The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.</p>
<h3>Example 1:</h3>
<pre><code>Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
</code></pre>
<h3>Example 2:</h3>
<pre><code>Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.
</code></pre>
<h3>Code 1 using <code>.notify_all()</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(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
#include <thread>
#include <mutex>
#include <functional>
struct FooBar {
FooBar(const int num) : num(num) {}
void foo(const std::function<void()> printFoo) {
for (std::size_t iter = 0; iter < num; ++iter) {
std::unique_lock<std::mutex> locked(coordinator);
stream_status.wait(locked, [&]() {
return !bar_is_on_flag;
});
printFoo();
bar_is_on_flag = true;
stream_status.notify_all();
}
return;
}
void bar(const std::function<void()> printBar) {
for (std::size_t iter = 0; iter < num; ++iter) {
std::unique_lock<std::mutex> locked(coordinator);
stream_status.wait(locked, [&]() {
return bar_is_on_flag;
});
printBar();
bar_is_on_flag = false;
stream_status.notify_all();
}
return;
}
private:
int num;
std::mutex coordinator;
std::condition_variable stream_status;
bool bar_is_on_flag = false;
};
</code></pre>
<h3>Code 2 using <code>.notify_one()</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(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
#include <thread>
#include <mutex>
#include <functional>
struct FooBar {
FooBar(const int num) : num(num) {}
void foo(const std::function<void()> printFoo) {
for (std::size_t iter = 0; iter < num; ++iter) {
std::unique_lock<std::mutex> locked(coordinator);
stream_status.wait(locked, [&]() {
return !bar_is_on_flag;
});
printFoo();
bar_is_on_flag = true;
stream_status.notify_one();
}
return;
}
void bar(const std::function<void()> printBar) {
for (std::size_t iter = 0; iter < num; ++iter) {
std::unique_lock<std::mutex> locked(coordinator);
stream_status.wait(locked, [&]() {
return bar_is_on_flag;
});
printBar();
bar_is_on_flag = false;
stream_status.notify_one();
}
return;
}
private:
int num;
std::mutex coordinator;
std::condition_variable stream_status;
bool bar_is_on_flag = false;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:50:45.993",
"Id": "493020",
"Score": "1",
"body": "Unless I am missing something obvious, there is no difference between Code 1 and Code 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:55:17.167",
"Id": "493022",
"Score": "2",
"body": "Oh. It is almost impossible to notice. Now I see. I don't think there is any difference in this context, neither functionally not performance wise."
}
] |
[
{
"body": "<p>Congratulations on the correct use of the C++11 condition variables! As mentioned by vnp, there will be no difference functionally or performance wise in this specific case, as there is only ever one thread waiting while the other notifies. Some possible improvements though:</p>\n<h1>Unnecessary <code>return</code> statements</h1>\n<p>You don't need a <code>return</code> statement at the end of a <code>void</code> function.</p>\n<h1>Consider notifying without holding the lock</h1>\n<p>If you hold the lock while calling <code>notify_one()</code> or <code>notify_all()</code> on a condition variable, it is possible that the other thread will be woken up, which immediately tries to lock the mutex, but if the notifying thread still holds it it will fail. This might then cause the thread to immediately do call the kernel to wait for the mutex to be unlocked. So it is better to surround the part that really needs locking with curly braces, and put the notify call outside it:</p>\n<pre><code>for (...)\n{\n {\n std::unique_lock<std::mutex> locked(coordinator);\n stream_status.wait(locked, ...);\n print(...);\n bar_is_on_flag = ...;\n }\n\n stream_status.notify_one();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:27:07.227",
"Id": "250721",
"ParentId": "250675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "250721",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T20:56:56.857",
"Id": "250675",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"comparative-review"
],
"Title": "LeetCode 1115: Print FooBar Alternately"
}
|
250675
|
<p>I have created a lot of spigot plugins in my "career" as a developer for a bunch of Minecraft servers, but every time I start writing a new plugin, I basically "reinvent" the structure of my main plugin class, always so it fits best into what I consider to be a readable plugin, that also other developers that will work with these plugins after me can do so without getting a headache.</p>
<p>My most recent Main-Class looks like this:</p>
<pre class="lang-java prettyprint-override"><code>package com.clanplugin;
import java.math.RoundingMode;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scoreboard.Scoreboard;
import com.earth2me.essentials.api.UserDoesNotExistException;
import com.clanplugin.commands.ClanCommand;
import com.clanplugin.commands.CommandRegistry;
import com.clanplugin.commands.implementation.AcceptCommand;
import com.clanplugin.commands.implementation.CreateCommand;
import com.clanplugin.commands.implementation.DeleteCommand;
import com.clanplugin.commands.implementation.DerankCommand;
import com.clanplugin.commands.implementation.InfoCommand;
import com.clanplugin.commands.implementation.InviteCommand;
import com.clanplugin.commands.implementation.InvitesCommand;
import com.clanplugin.commands.implementation.KickCommand;
import com.clanplugin.commands.implementation.LeaveCommand;
import com.clanplugin.commands.implementation.ListCommand;
import com.clanplugin.commands.implementation.MoneyCommand;
import com.clanplugin.commands.implementation.UprankCommand;
import com.clanplugin.commands.implementation.RejectCommand;
import com.clanplugin.commands.implementation.RevokeCommand;
import com.clanplugin.commands.implementation.SetCbCommand;
import com.clanplugin.commands.implementation.SetLeaderCommand;
import com.clanplugin.commands.implementation.SetNameCommand;
import com.clanplugin.commands.implementation.SetTagCommand;
import com.clanplugin.commands.implementation.ShowMaxClanMemberCommand;
import com.clanplugin.commands.implementation.ToggleMoneyCommand;
import com.clanplugin.commands.implementation.ToplistCommand;
import com.clanplugin.database.DatabaseConnector;
import com.clanplugin.database.DatabaseMethods;
import com.clanplugin.listener.PlayerConnectListener;
import com.clanplugin.listener.PlayerDisconnectListener;
import com.clanplugin.listener.TagSetterListener;
import com.clanplugin..manager.ClantagCache;
import com.clanplugin..manager.MessageManager;
import net.ess3.api.Economy;
public class Main extends JavaPlugin {
private static CommandRegistry commandRegistry;
private static Main plugin;
public static HashMap<Player, Long> lastUseOfCommand = new HashMap<Player, Long>();
public void onEnable() {
plugin = this;
saveDefaultConfig();
registerCommands();
registerListeners();
loadDatabase();
setDataUponReload();
}
public void onDisable() {
DatabaseConnector.disconnect();
System.out.println(MessageManager.disabledPluginConsoleMessage());
plugin = null;
}
public static Main getInstance() {
return plugin;
}
private void loadDatabase() {
DatabaseConnector.connect();
DatabaseMethods.initialiseDatabaseTables();
}
private void registerCommands() {
this.getCommand("clan").setExecutor(new ClanCommand());
commandRegistry = new CommandRegistry();
commandRegistry.registerCommand(new ShowMaxClanMemberCommand());
commandRegistry.registerCommand(new ListCommand());
commandRegistry.registerCommand(new LeaveCommand());
commandRegistry.registerCommand(new DeleteCommand());
commandRegistry.registerCommand(new InvitesCommand());
commandRegistry.registerCommand(new ToplistCommand());
commandRegistry.registerCommand(new MoneyCommand());
commandRegistry.registerCommand(new ToggleMoneyCommand());
commandRegistry.registerCommand(new InviteCommand());
commandRegistry.registerCommand(new AcceptCommand());
commandRegistry.registerCommand(new RejectCommand());
commandRegistry.registerCommand(new KickCommand());
commandRegistry.registerCommand(new RevokeCommand());
commandRegistry.registerCommand(new InfoCommand());
commandRegistry.registerCommand(new SetTagCommand());
commandRegistry.registerCommand(new SetNameCommand());
commandRegistry.registerCommand(new SetLeaderCommand());
commandRegistry.registerCommand(new UprankCommand());
commandRegistry.registerCommand(new DerankCommand());
commandRegistry.registerCommand(new SetCbCommand());
commandRegistry.registerCommand(new CreateCommand());
}
public static CommandRegistry getCommandRegistry() {
return commandRegistry;
}
private void registerListeners() {
getServer().getPluginManager().registerEvents(new PlayerConnectListener(), this);
getServer().getPluginManager().registerEvents(new PlayerDisconnectListener(), this);
getServer().getPluginManager().registerEvents(new TagSetterListener(), this);
}
private void setDataUponReload() {
for(Player player : Bukkit.getOnlinePlayers()) {
if (DatabaseMethods.isPlayerInClan(player.getUniqueId())) {
String playerUUID = DatabaseMethods.getPlayerUUID(player.getUniqueId());
if (playerUUID.equals(player.getUniqueId().toString()))
DatabaseMethods.addPlayerName(player.getName(), player.getUniqueId());
ClantagCache.put(player, DatabaseMethods.getClanTagByClanID(DatabaseMethods.getClanIDByPlayerUuid(player.getUniqueId())));
}
PlayerConnectListener.joinTimes.put(player, System.currentTimeMillis());
}
}
@SuppressWarnings("deprecation")
public static void updateScoreBoard(Player player) {
try {
if (player == null || player.getScoreboard() == null) {
return;
}
Scoreboard board = player.getScoreboard();
if (Bukkit.getOnlinePlayers().size() == 0) {
board.getTeam("onlineplayers").setPrefix(" " + "0" + "/" + "" + Bukkit.getServer().getMaxPlayers());
} else {
board.getTeam("onlineplayers")
.setPrefix("" + Bukkit.getOnlinePlayers().size() + "/" + Bukkit.getServer().getMaxPlayers());
}
try {
board.getTeam("Kontostandcheck")
.setPrefix("" + Economy.getMoneyExact(player.getName()).setScale(2, RoundingMode.DOWN) + "$");
} catch (IllegalStateException | IllegalArgumentException | UserDoesNotExistException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("[ClanSystem] This is not the live environement or the scoreboard configuration has changed. Please review carefully.");
e.printStackTrace();
}
}
}
</code></pre>
<p>It would be great to get some fresh idea's what can be improved, maybe not only regarding the spigot-related stuff, but also maybe some general bad habits I might have. Thanks a lot in advance! If you have any questions to some functionality of the classes feel free to ask me about it in the comments :)</p>
|
[] |
[
{
"body": "<p>Your formatting is partly off, use a code-formatter.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class Main extends JavaPlugin {\n</code></pre>\n<p>I'm not familiar anymore with the Bukkit naming convetions, but this should most likely be called <code>SpigotPlugin</code>. <code>Main</code> is kinda reserved for main classes which are the main entry point for applications.</p>\n<hr />\n<p>Do you require the static instance mechanic? If you can, you should avoid it.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static HashMap<Player, Long> lastUseOfCommand = new HashMap<Player, Long>();\n</code></pre>\n<p>This seems to be never used.</p>\n<p>Also, given that is a static map, one can most likely come up with a better API when required. For example, handing the current instance to the created listeners.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println(MessageManager.disabledPluginConsoleMessage());\n</code></pre>\n<p>If I remember right, Bukkit does sport a logging solution, you should use that.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>this.getCommand("clan").setExecutor(new ClanCommand());\n</code></pre>\n<p>You're inconsistent regarding your <code>this</code> usage.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>PlayerConnectListener.joinTimes.put(player, System.currentTimeMillis());\n</code></pre>\n<p>I'm not sure if that is part of your code, but be aware that <code>currentTimeMillis</code> is wall-clock time. That means it observes leap-seconds, time zone changes and the like. So given the following setup:</p>\n<pre class=\"lang-java prettyprint-override\"><code>long start = System.currentTimeMillis();\n\n// Let 5 seconds pass.\n\nlong elapsed = System.currentTimeMillis() - start;\n</code></pre>\n<p><code>elapsed</code> can be any value, from most likely "5000" to "500000" or even "-25000".</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>board.getTeam("onlineplayers").setPrefix(" " + "0" + "/" + "" + Bukkit.getServer().getMaxPlayers());\n// ...\nboard.getTeam("onlineplayers")\n .setPrefix("" + Bukkit.getOnlinePlayers().size() + "/" + Bukkit.getServer().getMaxPlayers());\n</code></pre>\n<p>What are these constructs? I'm not a friend of "empty string casts", if you can, be explicit about it, for example with <code>Integer.toString()</code>, or use <code>String.format()</code> or similar:</p>\n<pre class=\"lang-java prettyprint-override\"><code>board.getTeam("onlineplayers").setPrefix(String.format("0/%i",\n Bukkit.getServer().getMaxPlayers()));\n// ...\nboard.getTeam("onlineplayers").setPrefix(String.format("%i/%i",\n Integer.valueOf(Bukkit.getOnlinePlayers().size()),\n Integer.valueOf(Bukkit.getServer().getMaxPlayers()));\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if (Bukkit.getOnlinePlayers().size() == 0) {\n</code></pre>\n<p>There's not really a point in observing this just to build the string differently, just alw3ays use the else path.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> try {\n board.getTeam("Kontostandcheck")\n .setPrefix("" + Economy.getMoneyExact(player.getName()).setScale(2, RoundingMode.DOWN) + "$");\n } catch (IllegalStateException | IllegalArgumentException | UserDoesNotExistException e) {\n e.printStackTrace();\n }\n</code></pre>\n<p>As said previously, you want to log errors properly.</p>\n<pre class=\"lang-java prettyprint-override\"><code> } catch (Exception e) {\n System.out.println("[ClanSystem] This is not the live environement or the scoreboard configuration has changed. Please review carefully.");\n e.printStackTrace();\n }\n</code></pre>\n<p>Same here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:01:24.427",
"Id": "250715",
"ParentId": "250676",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250715",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-14T21:48:16.327",
"Id": "250676",
"Score": "4",
"Tags": [
"java",
"minecraft"
],
"Title": "Spigot Plugin: Generic form of the plugin's main class"
}
|
250676
|
<p>I've written a simple util-method in my spigot plugin to check if a message contains a valid minecraft colour code. A valid minecraft colour code consists of a <code>&</code> followed by a hex digit: <code>0</code> to <code>f</code>. Minecraft itself exchanges all <code>&</code> by a <code>§</code>, for reasons that would take too long to explain, it's not possible for the users to send messages to the server directly. Therefore <code>&</code> is generally used as a replacement.</p>
<p>I now have to check at some point, if the message the user sent to the server is coloured, which is the reason this method exists. Here are some quick examples, how it does work:</p>
<pre><code>string value - return value
"Simple String" - false
"Smith&Wesson" - false
"&4This would be red." - true
"%aGreen &2Darker Green &0 Darkest Green" - true
"&& Omega &&" - false
</code></pre>
<p>Here's my code. It does what it's supposed to do, but for some reason it still seems unneccesary clunky to me. Any improvement is welcome :)</p>
<pre class="lang-java prettyprint-override"><code> public static boolean isMessageColoured(String message) {
char[] arr = message.toCharArray();
for (int i = 0; i < message.length() - 2; i++) {
if (arr[i] == '&' && "0123456789abcdef".contains(Character.toString(arr[i + 1]))) {
return true;
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to Code Review.</p>\n<ul>\n<li>Your code returns false for the message "hello&9", because the method doesn't check the last character. Change the condition in the for-loop to <code>message.length() - 1</code>.</li>\n</ul>\n<p>An alternative is to use a regular expression:</p>\n<pre><code>public static boolean isMessageColoured(String message) {\n return message.matches(".*&[a-f0-9].*");\n}\n</code></pre>\n<p>This regular expression matches at least one occurrence of <code>&[a-f0-9]</code> in the message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:40:10.300",
"Id": "493078",
"Score": "4",
"body": "I think OP is saying that writing a message that includes `&9` would mean every character after `&9` would be displayed in the color that `&9` represents, therefor ending a message with `&9` wouldn't mean anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T10:08:56.493",
"Id": "493080",
"Score": "1",
"body": "Exactly as @JonnyHenly said - everything after a colour code is displayed colourful. The codes themselves are not visible in the displayed message. But thanks for the suggestion with the regex :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:33:45.057",
"Id": "493114",
"Score": "2",
"body": "@JonnyHenly is it still a valid colour code though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:57:34.373",
"Id": "493154",
"Score": "0",
"body": "But the message is not coloured, therefore the method shall return false :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:29:40.543",
"Id": "493158",
"Score": "0",
"body": "@monamona Then your method is wrong. It would return true for `&a `, `&a&b`, `&a &b` etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:48:32.613",
"Id": "493168",
"Score": "0",
"body": "Those messages are actually considered to be coloured spaces ^^, and Indeed, combining two colour codes is also considered a valid message ^^ - also a coloured space ^^"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:43:59.787",
"Id": "250693",
"ParentId": "250686",
"Score": "8"
}
},
{
"body": "<p>There is no need to convert <code>String</code> to <code>char[]</code> array. Individual characters are accessible via <code>String.charAt</code> method.</p>\n<p>There is also no need to explicitly spell out the hexadecimals. Consider <code>Character.digit(message.charAt[i+1], 16) != -1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T06:14:16.493",
"Id": "493056",
"Score": "3",
"body": "Is there a typo? charAt[] vs. charAt()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:32:09.517",
"Id": "493076",
"Score": "0",
"body": "Is `Character.digit(message.charAt(i + 1), 16) != -1` not bulky (a lot more going on than just `Character.digit`)? The way I see it, you're expecting an ASCII why not just stick with the `char` array and bounds check the index after `'&'` in the loop -- `char next = arr[i+1]; if(arr[i] == '&' && (('0' <= next && next <= '9') || ('a' <= next && next <= 'f'))` -- is there an upside or downside to doing it this way?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T03:48:15.617",
"Id": "250694",
"ParentId": "250686",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250693",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T00:19:42.310",
"Id": "250686",
"Score": "4",
"Tags": [
"java",
"minecraft"
],
"Title": "Find minecraft colour codes in string"
}
|
250686
|
<p>Given a string representation of data, I want to extract the information into its corresponding object.</p>
<p>However,</p>
<p>If the string has "|" separators then these should be considered options and need to be picked at random.</p>
<p>If the string data has numbers shown as a range "1-10" then a random value should be chosen between the range. It should also preserve the numerical datatype i.e int or float</p>
<p>I.e</p>
<p>"(1-3,1,1)" returns either (1, 1, 1), (2, 1, 1) or (3, 1, 1)</p>
<p>"(0.2-0.4,1,1)" returns either (0.2, 1, 1), (0.3, 1, 1) or (0.4, 1, 1)</p>
<p>"foo|bar|foobar" returns either "foo", "bar" or "foobar"</p>
<p>"[1-2,1,2]|foo|bar|[1,8-10,99]" could return :</p>
<p>"foo","bar", [1, 1, 2], [2, 1, 2], [1, 8, 99], [1, 9, 99] or [1, 10, 99]</p>
<p>This is what I have and it works well. But I cant help think it could be achieved in a more concise way. Let me know what I could have done better.</p>
<pre><code>import re
import random
import ast
def randomize_by_pipe(st_value):
"""
Used to split strings with the pipe character and randomly choose and option.
:param: st_value - (str)
"""
if not st_value is None:
st_arr = st_value.split("|")
random.shuffle(st_arr)
return st_arr[0]
else:
return st_value
def randomise_range(text):
if text is None:
return text
else:
matches = re.findall("\d*\.*\d*-{1}\d*\.*\d*",text)
for match in matches:
startingPos = 0
position = text.find(match, startingPos)
while True:
position = text.find(match, startingPos)
if position > -1:
txt = text[position:position+len(match)]
txt = rand_no_from_string(txt)
new_text = text[0:position+len(match)].replace(match,str(txt))
text = new_text + text[position+len(match):]
else:
break
try:
return ast.literal_eval(text)
except ValueError:
return text
def rand_no_from_string(txt):
is_int = False
txt_arr = txt.split("-")
num_arr = [float(x) for x in txt_arr]
if int(num_arr[0]) == num_arr[0]:
mul = 1
is_int = True
else:
#new section to deal with the decimals
mul = 10 ** len(str(num_arr[0]).split(".")[1])
num_arr = [x*mul for x in num_arr]
if num_arr[0] > num_arr[1]:
num_arr[1], num_arr[0] = num_arr[0], num_arr[1]
val = random.randint(num_arr[0],num_arr[1])/mul
return int(val) if is_int else val
</code></pre>
<p>Run with:</p>
<pre><code>text="(108-100,0.25-0.75,100)|Foo|Bar|[123,234,234-250]"
randomise_range(randomize_by_pipe(text))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:37:38.583",
"Id": "493094",
"Score": "0",
"body": "So which function handles those strings like \"(0.2-0.4,1,1)\" and \"[1-2,1,2]|foo|bar|[1,8-10,99]\"? None of the three you showed seems to be able to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:47:07.800",
"Id": "493098",
"Score": "0",
"body": "@superbrain works fine for me. Have you seen the \"Run with\" section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T13:57:13.623",
"Id": "493104",
"Score": "0",
"body": "Oops, I actually did manage to miss that. So is this how to always run it? Then I think there should be a function to do that. Also, I just tried `text = \"(0.2-0.4,1,1)\"`, which you say returns either (0.2, 1, 1), (0.3, 1, 1) or (0.4, 1, 1), and it didn't work. I got (0.324, 1, 1) iinstead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:13:45.720",
"Id": "493108",
"Score": "0",
"body": "@superbrain you are correct. I will have to make an adjustment to take into account the decimals of the float to accommodate this. It should work as follows. 0.2-0.4 would only produce 0.2,0.3,0.4 && 0.20-0.22 would produce 0.20,0.21,0.22 etc etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:48:58.577",
"Id": "493122",
"Score": "0",
"body": "@superbrain i've tweaked it now."
}
] |
[
{
"body": "<h2>Type hinting</h2>\n<p>Instead of having helpdocs declare the types of function parameters, why not go with type hinting?</p>\n<h2>Complexity</h2>\n<p>Your code currently has too many moving parts. You define 2 different functions to parse the data, and they <strong>both</strong> need to be called in chain. This should be done by a single parsing function.</p>\n<p>Let the parser get data text, then the parser should be handling first parsing using <code>pipe</code> and later using the numerical ranges.</p>\n<h2>Selection from a list</h2>\n<p>Your <code>randomize_by_pipe</code> shuffles the list, and selects the 0th value. You can instead let <code>random.choice</code> do the job.</p>\n<h2><code>range</code> parsing</h2>\n<p>I think range parsing can be improved a little. How about the following flow:</p>\n<ol>\n<li>Remove <code>[</code> and <code>]</code> from the given text.</li>\n<li>Split from <code>,</code>.</li>\n<li>For each section of the split, try parsing as <code>float</code> (or <code>int</code>, depending on your dataset)</li>\n<li>In case of float conversion error, let the <code>rand_no_from_string</code> get a value.</li>\n</ol>\n<h2>regex</h2>\n<p>You have a regex, but you're not making full/elegant use of it. Instead of matches, you can group the results, and operate on those groups. The pattern itself can also be <a href=\"https://regex101.com/r/5zvgwW/2\" rel=\"nofollow noreferrer\">a little optimised</a>:</p>\n<pre><code>\\d+(?:\\.\\d+)?-\\d+(?:\\.\\d+)?\n</code></pre>\n<hr />\n<p>A rewrite, for eg:</p>\n<pre><code>from re import sub, Match\nfrom random import choice, randint\n\n\ndef randomise_range(match: Match):\n given_range = match.group(0).split("-")\n low, high = map(float, given_range)\n if low > high:\n low, high = high, low\n if low.is_integer():\n return str(randint(int(low), int(high)))\n multiplier = 10 ** len(given_range[0].split(".")[-1])\n low = int(low * multiplier)\n high = int(high * multiplier)\n return str(randint(low, high) / multiplier)\n\n\ndef extract_range(text: str = None):\n if not text:\n return text\n return sub(r"\\d+(?:\\.\\d+)?-\\d+(?:\\.\\d+)?", randomise_range, text)\n\n\ndef parse(text: str = None):\n if not text:\n return text\n selection = choice(text.split("|"))\n if selection[0] in ('[', '('):\n return extract_range(selection)\n return selection\n\n\nif __name__ == "__main__":\n examples = (\n "(1-3,1,1)",\n "(0.2-0.4,1,1)",\n "foo|bar|foobar",\n "(108-100,0.25-0.75,100)|Foo|Bar|[123,234,234-250]",\n "[1-2,1,2]|foo|bar|[1,8-10,99]",\n )\n for text in examples:\n print(parse(text))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:57:22.810",
"Id": "493153",
"Score": "0",
"body": "I hate regex, and I cant get what you've given me to work. Can you give me an example of how I can group them. For some reason regex just goes over my head. Its just so alien to my brain. Maybe you have a good resource for it I can read up on? I know its powerful and I should learn it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:19:22.560",
"Id": "493155",
"Score": "1",
"body": "click the link, regex101 provides a detailed explanation of the expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:29:22.433",
"Id": "493157",
"Score": "0",
"body": "You are amazing. Jeez that websites good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:31:31.870",
"Id": "493159",
"Score": "0",
"body": "I cant believe it even generates you the python code "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:40:58.027",
"Id": "493163",
"Score": "0",
"body": "@LewisMorris there is also https://www.debuggex.com/ :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:54:52.160",
"Id": "493170",
"Score": "0",
"body": "@LewisMorris also added a rewritten code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T18:55:48.950",
"Id": "493171",
"Score": "0",
"body": "Man, I wish I had time to learn everything. I just cant fit it all in! Thanks so much for your updated answer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T12:52:37.630",
"Id": "250702",
"ParentId": "250696",
"Score": "5"
}
},
{
"body": "<p>Here's an implementation whose major endeavour, when compared with your implementation as well as that of the accepted answer, is separation of parsing and execution. It's unclear whether this is important for you, but it's generally good design, and is likely faster to re-execute once parsed:</p>\n<pre><code>import re\nfrom numbers import Real\nfrom random import randint, choice\nfrom typing import Union, Callable\n\n\nclass Pattern:\n chunk_pat = re.compile(\n r'([^|]+)' # group: within a chunk, at least one non-pipe character\n r'(?:' # non-capturing group for termination character\n r'\\||$' # pipe, or end of string\n r')' # end of termination group\n )\n\n option_pat = re.compile(\n r'([^,]+)' # at least one non-comma character in an option\n r'(?:' # non-capturing group for termination character\n r',|$' # comma, or end of string\n r')' # end of termination group\n )\n\n range_pat = re.compile(\n r'^' # start\n r'('\n r'[0-9.]+' # first number group\n r')-('\n r'[0-9.]+' # second number group\n r')'\n r'$' # end\n )\n\n def __init__(self, pattern: str):\n chunk_strs = Pattern.chunk_pat.finditer(pattern)\n\n self.tree = tuple(\n self.parse_chunk(chunk[1])\n for chunk in chunk_strs\n )\n\n @staticmethod\n def choose_in_group(group: tuple) -> tuple:\n for option in group:\n if isinstance(option, Callable):\n yield option()\n else:\n yield option\n\n def choose(self) -> Union[str, tuple]:\n group = choice(self.tree)\n\n if isinstance(group, tuple):\n return tuple(self.choose_in_group(group))\n return group\n\n @staticmethod\n def precis_parse(as_str: str) -> (Real, int):\n if '.' in as_str:\n return float(as_str), len(as_str.rsplit('.', 1)[-1])\n return int(as_str), 0\n\n @classmethod\n def make_choose(cls, start: Real, end: Real, precis: int):\n if precis:\n factor = 10**precis\n start = int(start * factor)\n end = int(end * factor)\n def choose():\n return randint(start, end) / factor\n\n else:\n def choose():\n return randint(start, end)\n\n return choose\n\n @classmethod\n def parse_options(cls, options: str):\n for option in cls.option_pat.finditer(options):\n range_match = cls.range_pat.match(option[1])\n if range_match:\n start_str, end_str = range_match.groups()\n start, start_n = cls.precis_parse(start_str)\n end, end_n = cls.precis_parse(end_str)\n yield cls.make_choose(start, end, max(start_n, end_n))\n else:\n # Fall back to one raw string\n yield option[1]\n\n @classmethod\n def parse_chunk(cls, chunk: str):\n if (\n chunk[0] == '(' and chunk[-1] == ')' or\n chunk[0] == '[' and chunk[-1] == ']'\n ):\n return tuple(cls.parse_options(chunk[1:-1]))\n\n # Fall back to returning the raw string\n return chunk\n\n\ndef test():\n p = Pattern('foo|(bar,3-4,50,6.3-7,92-99)')\n\n for _ in range(20):\n print(p.choose())\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:12:01.313",
"Id": "250724",
"ParentId": "250696",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "250702",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T07:36:14.430",
"Id": "250696",
"Score": "5",
"Tags": [
"python",
"parsing",
"regex",
"pattern-matching"
],
"Title": "Separating data from string representation of objects, with added extras"
}
|
250696
|
<p>I developed this code for a vertical debounce counter for the PIC micro (PIC16F57). The code is called every 512 microseconds. It takes 5 bits from PORTB and compares it to a last known debounced state. If an active input has been stable for 64 calls it is accepted as changed. Though it is sufficiently good for the current application, I am interested in possible improvements to speed up overall execution time. I am not interested in prematurely leaving the loop in case there is nothing to update.</p>
<pre><code> cblock 0x08
gpcounter:1 ; general purpose counter
debstate:1
delta:1
toggle:1
vcounter:6
endc
; Button debounce
; A button state is considered stable if it has not changed in 64 polls each 512 usec
debounce ; Read input state. Only bits 0-4 are inputs
movf PORTB, W
andlw 0x1f
; Any input bits that have changed with respect to the last known state
; will be set to 1's in delta and toggle.
; delta remains fixed, toggle will act as a carry while looping
; Because toggle bits will be reset only, toggle will always be a subset of delta.
xorwf debstate, W
movwf delta
movwf toggle
; Load first counter row in index register
movlw vcounter
movwf FSR
; Counter has 6 rows
movlw 0x06
movwf gpcounter
debounceloop ; Reset row for all bits which have not changed states
movf delta, W
andwf INDF, F
; Flip row bits according to toggle mask.
; Because the 1's in toggle are a subset of those in delta,
; any reset counter bits can never be toggled back to 1
movf toggle, W
xorwf INDF, F
; If any bits were toggled from 1 to 0, retain carry bit, else discard it
comf INDF, W
andwf toggle, F
; We're done with this row
incf FSR, F
decfsz gpcounter, F
goto debounceloop
; toggle will now contain 1's for any counters
; that have overflown, so it can be used as xor mask
; to update the last known debounced state
movf toggle, W
xorwf debstate, F
retlw 0x00
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:43:14.577",
"Id": "493119",
"Score": "0",
"body": "Is this for school? The question is important, because under nearly all circumstances it's a bad idea to use this device."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T05:12:05.717",
"Id": "493224",
"Score": "0",
"body": "@Rienderien This is not schoool, I am not even a student. Sometimes we just need to work with what is available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T12:14:56.527",
"Id": "493255",
"Score": "0",
"body": "I don't blame you, if this is hobby work. My advice will not change because we strive for production quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T10:22:04.557",
"Id": "493375",
"Score": "0",
"body": "@Rienderien School work, hobby project. You are making a lot of assumptions. I am not interested in discussions about what I should or should not use. I am looking for possible improvements on an existing algorithm,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T12:31:57.147",
"Id": "493384",
"Score": "0",
"body": "Good news! There's an easy way to preclude this assumption: tell us more about the project."
}
] |
[
{
"body": "<h2>Device selection</h2>\n<p>I guess the reason you're on the PIC16F57 is that you're a hobbyist, and this device was the one on hand. I can nearly guarantee that, for a production application, you can find a device from Microchip that is newer, cheaper, smaller and more capable.</p>\n<p>One change that most new PICs include is selectable Schmitt-trigger input mode, which will help with your debounce or even eliminate the need for software debounce, depending on your specifications. Your current device has no Schmitt trigger selection register (chapter 6), and only a limited number of special-purpose pins that have Schmitt trigger inputs (chapter 11.3).</p>\n<p>Another feature you can take advantage of is software-enabled weak pullup, which - given that you're monitoring a button - is likely to simplify your circuit, which you have not shown. This is commonly available in new PICs.</p>\n<p>Yet another feature you could use is integrated pin change detection, commonly available in new PICs - the <code>IOCI</code> module. This can potentially reduce your power consumption, since you wouldn't have to run a polling loop - you could set up a timer, set up <code>IOCI</code>, and then if the timer fires before an <code>IOCI</code> the button event is valid. If an <code>IOCI</code> fires before the timer expires, reset the timer. Some devices can actually go to sleep while this happens and wake up for either interrupt.</p>\n<h2>Typo</h2>\n<p><code>overflown</code> = <code>overflowed</code></p>\n<h2>Assembly</h2>\n<p>I don't recognize the flavour of assembly you're using, perhaps because I'm used to the assembler bundled with contemporary releases of MPLABX. But any self-respecting assembler should be able to:</p>\n<ul>\n<li>Accept <code>6</code> instead of <code>0x06</code>, the latter having no need for hexadecimal representation. The same with <code>0x00</code>.</li>\n<li>Include a device-specific header file with symbols for <code>PORTB</code> so that the magic number <code>0x1F</code> can be replaced by what you're actually doing, which is</li>\n</ul>\n<pre><code>andlw PORTA0_MASK |\n PORTA1_MASK |\n PORTA2_MASK |\n PORTA3_MASK |\n PORTA4_MASK;\n</code></pre>\n<p>All (official) PIC environments offer such symbols in their header files, and using them will make your project more maintainable.</p>\n<h2>General approach</h2>\n<p>It seems deeply strange to me that you're debouncing five buttons all at once. I would expect, for the current device you have,</p>\n<ul>\n<li>Poll for <em>one</em> button press - you can check all pins of <code>PORTA</code> at once using the <code>Z</code> flag</li>\n<li>When you hear a button press, assign a mask variable that monitors only that button pin</li>\n<li>Poll until either the time expires (you can use <code>TIMER0</code> and its prescaler to get 32ms) or the button is released</li>\n<li>Poll on that pin only, using your mask, until 32 ms are up</li>\n</ul>\n<p>For most applications you'll only care to process one button at a time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T15:52:09.910",
"Id": "250707",
"ParentId": "250699",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T09:46:35.813",
"Id": "250699",
"Score": "2",
"Tags": [
"performance",
"assembly",
"embedded"
],
"Title": "Debounce counter for PIC micro - Suggestions for improvement"
}
|
250699
|
<p>This is a personal project which I created solely to torture my friends ;)</p>
<p>I'm pretty sure you've heard about <a href="https://play.typeracer.com/" rel="noreferrer">typeracer</a>.<br />
And if you have friends like mine who are faster than you, you'd surely be frustrated.<br />
This is a program that removes your frustration by automating it.</p>
<pre class="lang-py prettyprint-override"><code>from time import sleep
from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.webdriver.chrome.options import Options
class TypeRacerBot:
def __init__(self, driver, is_private, link, wpm=70):
self.driver = driver
self.is_private = is_private
self.wpm = wpm
self.link = link
self.driver.get(self.link)
sleep(2)
if self.is_private:
while not self.can_join_race():
pass
self.enter_private_race()
else:
self.enter_race()
sleep(2)
while not self.has_started():
pass
self.type_text(self.get_text())
def enter_race(self):
""" Click the link to enter a new race """
self.driver.find_element_by_partial_link_text('Enter a typing race').click()
def enter_private_race(self):
""" Click the link to enter a new race """
self.driver.find_element_by_partial_link_text('join race').click()
def race_again(self):
""" Click the link to race again """
self.driver.find_element_by_partial_link_text('Race Again').click()
def has_started(self):
""" Returns whether the race has started or not """
return self.driver.find_element_by_css_selector(
'table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(2) > td > input'
).is_enabled()
def can_join_race(self):
""" Returns whether the cool-down between private races has ended """
return len(self.driver.find_elements_by_partial_link_text('join race')) > 0
def get_text(self):
""" Returns the text you are supposed to type """
return self.driver.find_elements_by_css_selector(
'table > tbody > tr:nth-child(2) > td > table > tbody'
' > tr:nth-child(1) > td > table > tbody > tr:nth-child(1) > td > div > div'
)[3].text
def type_text(self, text):
""" Types the text with an average WPM of the parameter words_per_minute. """
textbox = self.driver.find_element_by_css_selector(
'table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(2) > td > input'
)
words = text.split()
pause_time = 60 / self.wpm if self.wpm else 0
for word in words:
textbox.send_keys(word + ' ')
if pause_time:
sleep(pause_time)
def main():
is_private = input('Is the race private? (y/n): ').lower() == 'y'
if is_private:
link = input('Please enter the link of the race: ')
else:
link = 'https://play.typeracer.com'
wpm = int(input('Please enter the WPM you would like (0 for max speed): '))
options = Options()
options.add_argument('--start-maximized')
driver = webdriver.Chrome('chromedriver.exe', options=options)
while True:
try:
TypeRacerBot(driver, is_private, link, wpm)
except UnexpectedAlertPresentException:
pass
print()
input('Press enter to start new race')
wpm = int(input('Please enter the WPM you would like (0 for max speed): '))
if __name__ == '__main__':
main()
</code></pre>
<p>You can participate in a public or private race without any issues.</p>
<p>With an average PC, the maximum speed clocks up to 500 WPM.<br />
When setting a custom speed, the actual speed differs a lot from the target, due to selenium being a bit slow.</p>
<p>Right now, I don't think the code is very <em>enjoyable</em> to read.<br />
How do I make it look better, and how do I increase the performance of the program?</p>
<p>Thanks a lot!</p>
|
[] |
[
{
"body": "<p>I encourage you to examine the site in closer detail. So many instances of Selenium use are at the wrong layer of abstraction and this is no different.</p>\n<p>The site communicates with XHR request; one example is:</p>\n<pre><code>POST https://play.typeracer.com/gameserv;jsessionid=B45A6C283A7C20091095F4BCD6DA1B42\n\nRequest:\n\n7|1|6|https://play.typeracer.com/com.typeracer.guest.Guest/|5CBFBDCD9A4D280D027FF3A5E637DC0C|_|joinSinglePlayerGame|y|1w|1|2|3|4|1|5|5|0|1|0|6|crLHRPFB|\n\nResponse:\n\n//OK[4,17,1.602780248399E12,0,-5,4000,3,16,15,14,0,13,4060062,12,11,10,9,8,7,0,0,0,6,"crLHRPFB",5,1,4,1.602780252399E12,1,3,487716,2,0,1,["1h","13","12","2w","1w","15","1i","B00WO1YUQS","Tame Impala","sleepyaf123","","https://data.typeracer.com/pit/profile?user\\u003Dsleepyaf123","32","Let It Happen","All this running around. I can\\u0027t fight it much longer. Something\\u0027s trying to get out. And it\\u0027s never been closer. If my ticker fails, make up some other story. But if I never come back, tell my mother I\\u0027m sorry.","1j","27"],1,7]\n</code></pre>\n<p>The "stuff to type" is in there. It'll take a little more work to complete the rest of the necessary reverse-engineering, but in general this process is made simple by the developer tools of any modern browser. Once you have the adequate insight into how the application works, drop Selenium in favour of raw Requests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:23:18.953",
"Id": "493147",
"Score": "0",
"body": "+1 because \"_drop Selenium in favour of raw Request_\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T17:19:37.007",
"Id": "250712",
"ParentId": "250705",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T14:58:01.787",
"Id": "250705",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"selenium",
"webdriver",
"automation"
],
"Title": "Automating TypeRacer using selenium"
}
|
250705
|
<p>I have solved problem 10608 on UVA Online Judge using Python 3.5.1. My solution works, but it takes too long to run when the online judge evaluates it.</p>
<h3><a href="https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1549" rel="noreferrer">Problem</a></h3>
<p>There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends
and B and C are friends then A and C are friends, too.
Your task is to count how many people there are in the largest group of friends.</p>
<h3>Input</h3>
<p>Input consists of several datasets. The first line of the input consists of a line with the number of test
cases to follow.</p>
<p>The first line of each dataset contains tho numbers N and M, where N is the number of town’s
citizens (1 ≤ N ≤ 30000) and M is the number of pairs of people (0 ≤ M ≤ 500000), which are known
to be friends. Each of the following M lines consists of two integers A and B (1 ≤ A ≤ N, 1 ≤ B ≤ N,
A ̸= B) which describe that A and B are friends. There could be repetitions among the given pairs.</p>
<h3>Output</h3>
<p>The output for each test case should contain (on a line by itself) one number denoting how many people
there are in the largest group of friends on a line by itself.</p>
<p>Sample Input</p>
<pre><code>2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
</code></pre>
<p>Sample Output</p>
<pre><code>3
7
</code></pre>
<pre><code>testCases = int(input())
for x in range(testCases):
temp = input().split()
N = int(temp[0])
M = int(temp[1])
nodes = []
edges = []
for _ in range(M):
temp = input().split()
A = int(temp[0])
B = int(temp[1])
edges.append([A, B])
counter = 0
for y in range(N):
counter += 1
nodes.append(counter)
hashmap = {}
for h in range(len(nodes)):
neighbours = []
for j in range(len(edges)):
if edges[j].__contains__(nodes[h]):
index_of_node = edges[j].index(nodes[h])
if index_of_node == 0:
neighbours.append(edges[j][1])
hashmap[h + 1] = neighbours
else:
neighbours.append(edges[j][0])
hashmap[h + 1] = neighbours
current_group = 0
highest_group = 0
def reset_array():
visited = []
for _ in range(1, N + 2):
visited.append(False)
return visited
visited = reset_array()
def dfs(at):
if visited[at]:
return
else:
visited[at] = True
global current_group
current_group += 1
if at in hashmap:
neighbours = hashmap[at]
for next in neighbours:
dfs(next)
else:
return
counter = 0
for i in range(len(nodes)):
dfs(i + 1)
if current_group > highest_group:
highest_group = current_group
visited = reset_array()
current_group = 0
print(highest_group)
</code></pre>
|
[] |
[
{
"body": "<h2>Review of your code</h2>\n<hr />\n<ul>\n<li><p>You should <a href=\"https://stackoverflow.com/a/16535868/9751583\">mostly</a> prefer the <code>in</code> operator instead <code>__contains__</code>. See @HeapOverflow's comment for more details.</p>\n</li>\n<li><p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, you should not prefer CamelCase for variable names. Use snake_case instead.</p>\n</li>\n</ul>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code>temp = input().split()\nN = int(temp[0])\nM = int(temp[1])\n</code></pre>\n<p>Can be replaced with</p>\n<pre class=\"lang-py prettyprint-override\"><code>M, N = [int(x) for x in input().split()]\n</code></pre>\n<p>And the same applies for a similar case.</p>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code> counter = 0\n for y in range(N):\n counter += 1\n nodes.append(counter)\n</code></pre>\n<p><code>nodes</code> is just equal to the values from <code>1</code> to <code>N</code>, which is just equal to <code>list(range(1, N+1))</code><br />\nTherefore, you can remove <code>counter</code> completely.</p>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code> if index_of_node == 0:\n neighbours.append(edges[j][1])\n hashmap[h+1] = neighbours\n else:\n neighbours.append(edges[j][0])\n hashmap[h+1] = neighbours\n</code></pre>\n<p>Since <code>hashmap[h+1] = neighbours</code> is executed regardless of the if statement, you can move it outside the scope.</p>\n<hr />\n<pre class=\"lang-py prettyprint-override\"><code>def reset_array():\n visited = []\n for _ in range(1, N+2):\n visited.append(False)\n return visited\n</code></pre>\n<p><code>visited</code> is basically just equal to <code>[False] * (N+1)</code>.<br />\nThe whole function can be replaced to <code>return [False] * (N+1)</code></p>\n<p>Also, this is a personal preference, but you don't have to use a function for this.</p>\n<hr />\n<h2>Function <code>dfs</code></h2>\n<ul>\n<li><code>next</code> is an inbuilt function's name, and therefore it should be avoided.</li>\n<li><code>neighbours = hashmap[at]</code> Since this is used only once, the assignment is unnecessary</li>\n<li><code>else: return</code> this is unnecessary, as the function does that anyway</li>\n</ul>\n<p>Here's how <code>dfs</code> might look after applying the above changes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def dfs(at):\n global current_group\n\n if visited[at]:\n return\n\n visited[at] = True\n current_group += 1\n\n if at in hashmap:\n for next_ in hashmap[at]:\n dfs(next_)\n</code></pre>\n<hr />\n<h2>Faster Algorithm</h2>\n<p>The <code>dfs</code> will take <code>O(N)</code> time, and since it's executed <code>N</code> times, the time complexity will be <code>O(N^2)</code> which is clearly not feasible.</p>\n<p>A <a href=\"https://cp-algorithms.com/data_structures/disjoint_set_union.html\" rel=\"nofollow noreferrer\">disjoint set union</a> on the other hand, will take a <a href=\"https://cp-algorithms.com/data_structures/disjoint_set_union.html#toc-tgt-4\" rel=\"nofollow noreferrer\">lot lesser time</a>.</p>\n<p>Here's my accepted code that uses DSU:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(int(input())):\n n, m = map(int, input().split())\n dsu = [-1] * n\n\n for _ in range(m):\n u, v = map(int, input().split())\n u -= 1\n v -= 1\n\n while dsu[u] >= 0:\n u = dsu[u]\n\n while dsu[v] >= 0:\n v = dsu[v]\n\n if u == v:\n continue\n\n if u > v:\n u, v = v, u\n\n dsu[u] = dsu[u] + dsu[v]\n dsu[v] = u\n\n print(-min(dsu))\n</code></pre>\n<p>In case you have any queries about the above code, do ask me in the comments.</p>\n<hr />\n<p>Also, I guess you're switching to python from java judging by the fact you named a variable <code>hashmap</code>. If that's the case, welcome to world of python!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T23:16:20.350",
"Id": "493205",
"Score": "2",
"body": "The answer you linked to doesn't say that we should always use `in` instead of `__contains__`. And I occasionally do use the latter for higher speed, for example like `map(s.__contains__, a)` or `filter(s.__contains__, a)`. I think that's good usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T06:33:32.393",
"Id": "493225",
"Score": "1",
"body": "@HeapOverflow My bad, I completely forgot that case, I'll edit my answer to fix that point. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T21:15:18.847",
"Id": "250725",
"ParentId": "250717",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250725",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:21:44.243",
"Id": "250717",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"graph",
"depth-first-search"
],
"Title": "Graph: Depth First Search (N citizens with pairs of friends)"
}
|
250717
|
<p>I am learning and trying to implement the best practice for snake and ladder game.</p>
<p><strong>Rules of the game</strong></p>
<blockquote>
<ol>
<li>The board will have 100 cells numbered from 1 to 100.</li>
<li>The game will have a six sided dice numbered from 1 to 6 and will always give a
random number on rolling it.</li>
<li>Each player has a piece which is initially kept outside the board (i.e., at position 0).</li>
<li>Each player rolls the dice when their turn comes. Based on the dice value, the
player moves their piece forward that number of cells. Ex: If the
dice value is 5 and the piece is at position 21, the player will put
their piece at position 26 now (21+5).</li>
<li>A player wins if it exactly reaches the position 100 and the game ends there.</li>
<li>After the dice roll, if a piece is supposed to move outside position 100, it does not move.</li>
<li>The board also contains some snakes and ladders. Each
snake will have its head at some number and its tail at a smaller
number. Whenever a piece ends up at a position with the head of the
snake, the piece should go down to the position of the tail of that
snake.</li>
<li>Each ladder will have its start position at some number and
end position at a larger number. Whenever a piece ends up at a
position with the start of the ladder, the piece should go up to the
position of the end of that ladder.</li>
<li>There could be another snake/ladder at the tail of the snake or the end position of the ladder and the piece should go up/down
accordingly.</li>
</ol>
</blockquote>
<p><strong>Assumptions</strong></p>
<blockquote>
<ul>
<li>There won’t be a snake at 100.</li>
<li>There won’t be multiple snakes/ladders at the same start/head point.</li>
<li>It is possible to reach 100, i.e., it is possible to win the game.</li>
<li>Snakes and Ladders do not form an infinite loop.</li>
</ul>
</blockquote>
<pre><code>class Snake:
def __init__(self, start, end):
self.start = start
self.end = end
</code></pre>
<pre><code>class Ladder:
def __init__(self, start, end):
self.start = start
self.end = end
</code></pre>
<pre><code>class Board:
def __init__(self, size = 100):
self.size = size
self.snake_list = []
self.ladder_list = []
def add_snake(self, snake):
self.snake_list.append(snake)
def add_ladder(self, ladder):
self.snake_list.append(ladder)
</code></pre>
<pre><code>class Dice:
dice_count = 1
@staticmethod
def roll():
return random.randint(1 * Dice.dice_count, 6 * Dice.dice_count)
</code></pre>
<pre><code>class Player:
def __init__(self, name):
self.name = name
</code></pre>
<pre><code>class PlayerPosition:
def __init__(self, player, position):
self.player = player
self.position = position
def update_position(self, new_position):
self.position = new_position
</code></pre>
<pre><code>class Game:
def __init__(self, board):
self.board = board
self.players_position = []
def add_players(self, player, position=0):
player_position = PlayerPosition(player, position)
self.players_position.append(player_position)
def check_win_condition(self, position):
if position == self.board.size:
return True
return False
def check_for_snake(self, new_position):
for snake in self.board.snake_list:
start, end = snake.start, snake.end
if start == new_position:
return end
def check_for_ladder(self, new_position):
for ladder in self.board.ladder_list:
start, end = ladder.start, ladder.end
if start == new_position:
return end
def find_new_position(self, new_position):
if self.check_for_snake(new_position):
return self.check_for_snake(new_position)
elif self.check_for_ladder(new_position):
return self.check_for_ladder(new_position)
else:
return new_position
def start(self):
still_playing = len(self.players_position)
while(still_playing):
for player_position in self.players_position:
dice_value = Dice.roll()
current_position = player_position.position
new_position = current_position + dice_value
if new_position < self.board.size:
new_position = self.find_new_position(new_position)
player_position.update_position(new_position)
print(player_position.player.name, 'moved from', current_position, 'to', new_position)
if self.check_win_condition(new_position):
print("player", player_position.player.name, "wins!")
player_position.update_position(new_position + 1)
still_playing -= 1
</code></pre>
<pre><code>class GameRunner:
@classmethod
def run_game(cls):
board = Board()
s1 = Snake(62, 5)
s2 = Snake(33, 6)
s3 = Snake(49, 9)
s4 = Snake(56, 53)
s5 = Snake(98, 64)
s6 = Snake(88, 16)
s7 = Snake(93, 73)
s8 = Snake(95, 75)
l1 = Ladder(2,37)
l2 = Ladder(27, 46)
l3 = Ladder(10, 32)
l4 = Ladder(51, 68)
l5 = Ladder(61, 79)
l6 = Ladder(65, 84)
l7 = Ladder(71, 91)
l8 = Ladder(81, 100)
board = Board()
board.add_ladder(l1)
board.add_ladder(l2)
board.add_ladder(l3)
board.add_ladder(l4)
board.add_ladder(l5)
board.add_ladder(l6)
board.add_ladder(l7)
board.add_ladder(l8)
board.add_snake(s1)
board.add_snake(s2)
board.add_snake(s3)
board.add_snake(s4)
board.add_snake(s5)
board.add_snake(s6)
board.add_snake(s7)
board.add_snake(s8)
player1 = Player("python")
player2 = Player("java")
player3 = Player("go")
game = Game(board)
game.add_players(player1)
game.add_players(player2)
game.add_players(player3)
game.start()
</code></pre>
<p><code>GameRunner.run_game()</code></p>
<p>Please suggest places of improvements and corrections on this.</p>
|
[] |
[
{
"body": "<h2>Unnecessary classes</h2>\n<p>The snake, ladder and dice classes are not at all useful. They can simply be replaced with a namedtuple or a dataclass.</p>\n<p>Similarly, player and playerposition should both be a single class element. A player object should be responsible for keeping track of their position.</p>\n<h2>Verbosity</h2>\n<p>s1, s2, ... s8 and similary l1, l2, ... l8 are not really used. Keep a tuple of positions, and iterate over them, calling either <code>add_ladder</code> or <code>add_snake</code> accordingly.</p>\n<h2>Control flow</h2>\n<p>The position updates should happen at the player's end, and not the game. The print statement for when player position gets updated would happen inside player class. The game's object is only to control and validate moves.</p>\n<p>There are no statements showing when a player encounters a ladder or a snake. just their position changes in that verbose print statement mesh.</p>\n<h2>Double execution</h2>\n<pre><code> if self.check_for_snake(new_position):\n return self.check_for_snake(new_position)\n elif self.check_for_ladder(new_position):\n return self.check_for_ladder(new_position)\n else:\n return new_position\n</code></pre>\n<p>You have the same function being called twice, twice. For a major set of the board cells, there is neither a snake, nor a ladder. Yet, you keep calling both the functions.</p>\n<h2>Alternatives</h2>\n<h3>Dice roll</h3>\n<pre><code>sum(random.choices(range(1, 7), k=dice_count))\n</code></pre>\n<h3>Win condition</h3>\n<pre><code>def check_win_condition(self, position):\n return position == self.board.size\n</code></pre>\n<h3>Snake head or ladder base check</h3>\n<p>Keep an account using a <code>set</code> or <code>tuple</code> for board's snakes and ladder being added. Board should validate if a position has either snake's head or ladder's base there. You are currently iterating over all the snakes and ladders (twice, as mentioned above) for each position, whereas a lookup would be <span class=\"math-container\">\\$ O(1) \\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T11:47:59.330",
"Id": "493251",
"Score": "0",
"body": "Just too many irrelevant classes"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T22:15:49.167",
"Id": "250727",
"ParentId": "250718",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T19:30:25.440",
"Id": "250718",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"programming-challenge"
],
"Title": "Snake and ladder problem oops application"
}
|
250718
|
<p>I am writing a GenericDeserializer for Apache Kafka. My class implements <code>IDeserializer<T></code> from <code>Confluent.Kafka.Net</code> package. I need to supply a Deserialize method which has this signature, <code>T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)</code>. But I also need to use <code>Deserializers</code> class of Confluent because it implements some low level details such as decoding a big endian message from network as primitive types, as byte array, as UTF8 string etc. How can I simplify this method. One example of simplification may be removing the use of casts which I introduced to make the compiler happy.</p>
<p>My logic in this method is like this, use every supported type in already implemented <code>Deserializers</code> class. For other types that are not deserialized with the help of this class, use Json Serialization. Here is my code:</p>
<pre><code>public class GenericDeserializer<T> : IDeserializer<T>
{
public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
{
var type = typeof(T);
if (type == typeof(double))
{
var retVal = Deserializers.Double.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(float))
{
var retVal = Deserializers.Single.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(int))
{
var retVal = Deserializers.Int32.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(long))
{
var retVal = Deserializers.Int64.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(Null))
{
var retVal = Deserializers.Null.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(string))
{
var retVal = Deserializers.Utf8.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (type == typeof(byte[]))
{
var retVal = Deserializers.ByteArray.Deserialize(data, isNull, context);
return (T) (object) retVal;
}
if (isNull)
{
return default;
}
return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
}
}
</code></pre>
<p>Here is the source of <code>Deserializers</code> class from <code>Confluent.Kafka</code>
<a href="https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/src/Confluent.Kafka/Deserializers.cs" rel="noreferrer">https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/src/Confluent.Kafka/Deserializers.cs</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:48:53.130",
"Id": "493186",
"Score": "0",
"body": "See https://docs.microsoft.com/en-us/dotnet/api/system.type.gettypecode?view=netcore-3.1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:45:09.933",
"Id": "493267",
"Score": "0",
"body": "@RickDavin We can handle simple primitive types with `GetTypeCode`. But how do we handle the types such as `byte[]` or `Null` (a type in Confluent library)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:03:56.603",
"Id": "493275",
"Score": "0",
"body": "I don't think it's a particularly good idea to deliver `default`of a struct if the method has been told that you should deserialize to `null`. You should instead be deserializing to `double?`, `long?`, etc., and not using `default`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:37:24.313",
"Id": "493286",
"Score": "0",
"body": "@Reinderien We cannot make a `Nullable<T>` type if `T` is not a ValueType, we have to introduce a struct constraint but that breaks generic method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:38:29.770",
"Id": "493287",
"Score": "1",
"body": "Right; I'm not saying to return `Nullable<T>` when `T` is a struct; I'm saying that you shouldn't accept `T` as a struct at all. This can be enforced on generics."
}
] |
[
{
"body": "<p>You can get rid of the branching in the <code>Deserialize</code> method and instead move that logic to a place that is executed only once - the construction place. An instance of your <code>GenericDeserializer<T></code> will always execute the same branch for any input, because the instance is already tied to a specific output type T. For the types like int, and double where you use their implementation just return their implementation, use your implementation for the rest.</p>\n<pre><code>class JsonDeserializer<T> : IDeserializer<T>\n{\n public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)\n {\n if (isNull)\n {\n return default;\n }\n \n return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()\n {\n PropertyNameCaseInsensitive = true\n });\n }\n}\n\n\nIDeserializer<T> CreateDeserializer<T>()\n{\n var type = typeof(T);\n\n if (type == typeof(double))\n {\n return (IDeserializer<T>) Deserializers.Double;\n }\n\n if (type === typeof(long))\n {\n return (IDeserializer<T>) Deserializers.Int64;\n }\n\n // ...\n\n return new JsonDeserializer<T>();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T11:43:32.720",
"Id": "493249",
"Score": "0",
"body": "This way, we do not get rid of branching, but move it into `CreateDeserializer<T>` method. There is also redundancy in writing deserializers for every supported type, we do not actually need these classes because we can return `Deserializers.Double` directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:36:28.407",
"Id": "493263",
"Score": "0",
"body": "@ndogac aha, i didnt know they already implement the interface, And it didn't make sense to me why wouldnt you return them directly if they did. And that's exactly what i suggest you do then..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:39:39.800",
"Id": "493265",
"Score": "0",
"body": "And sry, i didnt imply you use the CreateDeserializer<T> as Is. It was just an example of a calling code. I meant you get rid of the branching everytime the Deserialize method Is called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:42:38.917",
"Id": "493266",
"Score": "0",
"body": "Unfortunately, we cannot return `Deserializers.Double` for example, if the return type is `IDeserializer<T>` and we are returning `IDeserializer<double>`, the cast will be required again and we have the same readability problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T13:48:05.847",
"Id": "493268",
"Score": "0",
"body": "In the updated code example, I get *DoubleDeserializer is not assignable to IDeserializer<T>* error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:51:19.537",
"Id": "493320",
"Score": "0",
"body": "@ndogac Well, I'm sorry. I don't work with C# too often. I didn't realize the cast is needed in C#. I have rewritten my answer to target just the aspect of executing the branching only once."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T05:18:22.343",
"Id": "250736",
"ParentId": "250719",
"Score": "0"
}
},
{
"body": "<p>You can define a mapping between <code>Type</code>s and the <code>Deserializers</code>. You can do this for example like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class GenericDeserializer<T> : IDeserializer<T>\n{\n private readonly ImmutableDictionary<Type, object> _deserializers =\n new Dictionary<Type, object>\n {\n { typeof(double), Deserializers.Double },\n { typeof(float), Deserializers.Single },\n { typeof(int), Deserializers.Int32 },\n { typeof(long), Deserializers.Int64 },\n { typeof(Null), Deserializers.Null },\n { typeof(string), Deserializers.Utf8 },\n { typeof(byte[]), Deserializers.ByteArray },\n }.ToImmutableDictionary();\n}\n</code></pre>\n<p>You can't use the <code>IDeserializer<T></code> in the Dictionary's Value type parameter that's why it is an <code>object</code>.</p>\n<p>Then all you need to do is to make a lookup call and try to cast the value to <code>IDeserializer<T></code></p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (_deserializers.ContainsKey(typeof(T)))\n{\n var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;\n ...\n}\n</code></pre>\n<p>If the type was found then you can make branching based on the <code>isNull</code> value:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (_deserializers.ContainsKey(typeof(T)))\n{\n var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;\n var retVal = deserializer.Deserialize(data, isNull, context);\n return !isNull ? retVal : default;\n}\n</code></pre>\n<p>If it is not found then you can use the <code>JsonSerializer</code> as your fallback.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()\n{\n PropertyNameCaseInsensitive = true\n});\n</code></pre>\n<hr />\n<p>The final code would look like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class GenericDeserializer<T> : IDeserializer<T>\n{\n private readonly ImmutableDictionary<Type, object> _deserializers =\n new Dictionary<Type, object>\n {\n { typeof(double), Deserializers.Double },\n { typeof(float), Deserializers.Single },\n { typeof(int), Deserializers.Int32 },\n { typeof(long), Deserializers.Int64 },\n { typeof(Null), Deserializers.Null },\n { typeof(string), Deserializers.Utf8 },\n { typeof(byte[]), Deserializers.ByteArray },\n }.ToImmutableDictionary();\n\n public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)\n {\n if (_deserializers.ContainsKey(typeof(T)))\n {\n var deserializer = _deserializers[typeof(T)] as IDeserializer<T>;\n var retVal = deserializer.Deserialize(data, isNull, context);\n return !isNull ? retVal : default;\n }\n\n return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()\n {\n PropertyNameCaseInsensitive = true\n });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T14:54:14.463",
"Id": "493273",
"Score": "1",
"body": "I like this solution, but if `typeof(T)` does not exist in dictionary and it will throw `KeyNotFoundException`, am I wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T14:56:36.687",
"Id": "493274",
"Score": "0",
"body": "@ndogac Yepp, you are right, I've just amended my answer to overcome on this issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T21:03:55.917",
"Id": "493323",
"Score": "1",
"body": "`TryGetValue` is better than `ContainsKey` because you can lookup through dictionary once instead of twice. Also `JsonSerializerOptions` can be static/single instance/lazy. Also the logic is different from the initial code. @ndogac, fyi"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T06:35:55.323",
"Id": "493343",
"Score": "1",
"body": "@aepot Yes, it can be further optimized. I just wanted to share the core idea to avoid code duplication (calling the Deserialize method), you can use mapping."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T14:46:37.603",
"Id": "250753",
"ParentId": "250719",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250753",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:07:55.790",
"Id": "250719",
"Score": "6",
"Tags": [
"c#",
"generics",
"serialization",
"apache-kafka"
],
"Title": "Simplify Generic Method"
}
|
250719
|
<p>I build an addition chain (more information about addition chains: <a href="https://en.wikipedia.org/wiki/Addition_chain" rel="nofollow noreferrer">Wikipedia</a>) calculator that produces shorter chains than chains with the length equal to the number that's being tried to achieve.</p>
<p>It doesn't always produces the shortest chains (if were talking about a big number). However still gives a pretty short chain compared to the max sized chain the number would get.</p>
<p>It is faster than, brute-force calculating (but obv. less accurate in finding the shortest chain (like I said above)), since it relies on an algorithm (I'm not sure if an algorithm is the right word, but basically I just used logical steps to find a short chain). Basically it starts from the given number and goes backwards to 1.</p>
<hr />
<p><strong>It works as followed:</strong></p>
<ol>
<li>Check if the number is even or odd, if it's odd check if it's a prime number.</li>
<li>If it's an even number, just divide by 2. If it's odd find the biggest factor and divide the number by it, till the factor itself is reached. If it's a prime number, subtract it by 1 and follow the steps for an even number</li>
<li>Step 1 and 2 are always repeated, and before (before and after would duplicate the values, so only 'before') every action, the current state of the number is added to a list</li>
</ol>
<p>(It is also checking if every number had (n+1)/2 length of chains, so there's a tiny step for that, but that's not very important. This was an extra thing I did, for my math class.)</p>
<p>So let's say we have 5, it's an odd number so we subtract by 1 to get an even number: 4. Now we divide it by 2 and get 2, since 2 is also an even number we divide again and we got to 1 and the program stops and prints the list which is: [5, 4, 2, 1] (which is the shortest possible addition chain (I know that this only works for tiny numbers btw, for big numbers it still shortens the chain (of max size) a lot which is cool for me))</p>
<hr />
<p>I am learning programming by myself and haven't touched sort/search algorithms, what could I have done better in terms of the quality of my code or even the logical steps I use to calculate?</p>
<hr />
<pre><code>n = int(input()) # kan tot 8 cijfers snel(<1min), na 8 traag
BewijsN = (n + 1) / 2
List1 = []
def IsEven(n):
if n % 2 == 0:
return True
else:
return False
def IsPrime(n):
for x in range(n - 2):
x += 2
if n % x == 0:
return False
return True
def BigFactorCheck(n):
for x in range(n):
x += 1
if n % (n - x) == 0:
return n - x
while n > 1:
if IsEven(n) == False:
if IsPrime(n):
List1.append(n)
n += -1 # Prim naar even
else: # Oneven
List1.append(n)
BigFactor = BigFactorCheck(n)
for x in range((n // BigFactor) - 2):
x += 1
List1.append(n - BigFactor * x)
n = n - BigFactor * (x + 1) # lelijk, maar werkt
while IsEven(n):
List1.append(n)
n = n // 2
if n == 1:
List1.append(n)
List1.sort()
print(len(List1), List1)
if len(List1) - 1 <= BewijsN:
print(True, len(List1) - 1, "<=", BewijsN)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T22:48:19.527",
"Id": "493201",
"Score": "3",
"body": "In case I'm not the only one utterly confused what the hell this is talking about :-), see [Addition chain](https://en.wikipedia.org/wiki/Addition_chain). A definition and a good example would be helpful at the start of this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T10:35:51.620",
"Id": "493245",
"Score": "0",
"body": "You're right, edited the question and added a Wikipedia link"
}
] |
[
{
"body": "<h1>Code Organization</h1>\n<p>Code should be organized in such a way that someone reading the code doesn't have to scroll up and down in order to understand the code. For instance, you should not have:</p>\n<pre><code>mainline code\nfunction definitions\nmainline code\n</code></pre>\n<p>Instead, the mainline code should all be together at the bottom:</p>\n<pre><code>function definitions\nmainline code\n</code></pre>\n<h1>Naming</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a> lists a number of <s>rules</s> guidelines that should be followed throughout Python code. One such guideline is:</p>\n<ul>\n<li>function and variable names should be in <code>snake_case</code>; <code>MixedCase</code> is reserved for class names.</li>\n</ul>\n<p>So <code>BewijsN</code> and <code>List1</code> should become <code>bewijs_n</code> and <code>list_1</code>. Similarly, <code>IsEven</code>, <code>IsPrime</code> and <code>BigFactorCheck</code> should be <code>is_even</code>, <code>is_prime</code>, and <code>big_factor_check</code>.</p>\n<p><code>List1</code> is especially ugly. There is no <code>List2</code>, <code>List3</code> and so on, so why is there a <code>1</code> in that name? <code>number_chain</code> might make a better name.</p>\n<h1>Boolean Test</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def IsEven(n):\n if n % 2 == 0:\n return True\n\n else:\n return False\n</code></pre>\n<p>The function body reads approximately:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if something is True:\n return True\n else:\n return False\n</code></pre>\n<p>Since <code>something</code> will be <code>True</code> in the "then" clause, instead of returning the literal <code>True</code>, we could return <code>something</code>. Similarly, when <code>something</code> is <code>False</code>, in the "else" clause, instead of returning the literal <code>False</code>, we could also return <code>something</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if something is True:\n return something \n else:\n return something\n</code></pre>\n<p>At this point, we can see the <code>if ... else</code> is irrelevant; in both cases, we <code>return something</code>. So we can optimize this to:</p>\n<pre class=\"lang-py prettyprint-override\"><code> return something \n</code></pre>\n<p>specifically:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_even(n):\n return n % 2 == 0\n</code></pre>\n<h1>Range</h1>\n<p>The <code>IsPrime</code> function has this code:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for x in range(n - 2):\n x += 2\n</code></pre>\n<p>This is confusing and inefficient. Confusing because the loop variable <code>x</code> starts at <code>0</code>, and is modified inside the loop, increasing it to <code>2</code>; what is it on the next iteration? Of course, the modification inside the loop body is lost when the next iteration begins, but that will often confuse a newcomer to Python.</p>\n<p>It is inefficient, since because adding <code>2</code> each time through the loop is an unnecessary operation, which takes time. Numbers are objects, and every time a computation changes a number, the old number object is dereferenced (and possibly destroyed), and a new number object may be created. It is far faster to simply loop over the correct range: <code>range(2, n)</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(n):\n for x in range(2, n):\n if n % x == 0:\n return False\n return True\n</code></pre>\n<p>This loop can actually be simplified and sped up, using the <code>all(...)</code> function and a generator expression:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(n):\n return all(n % x != 0 for x in range(2, n))\n</code></pre>\n<p>There are many things you can do to further speed up this <code>is_prime</code> function. If the number would be divisible by an even number larger than 2, it would have already been divisible by 2, so you can call that out as a special case, and then only consider odd numbers 3 and up, using <code>range(3, n, 2)</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_prime(n):\n if n > 2 and n % 2 == 0:\n return False\n\n return all(n % x != 0 for x in range(3, n, 2))\n</code></pre>\n<p>Also, looking for factors larger than <span class=\"math-container\">\\$sqrt(n)\\$</span> is inefficient, since if <span class=\"math-container\">\\$x > sqrt(n)\\$</span> was a factor, then <span class=\"math-container\">\\$n / sqrt(n) < sqrt(n)\\$</span> would also be a factor, and you would have already encountered it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from math import isqrt\n\ndef is_prime(n):\n if n > 2 and n % 2 == 0:\n return False\n\n return all(n % x != 0 for x in range(3, isqrt(n) + 1, 2))\n</code></pre>\n<p>Due to <code>isqrt(n)</code>, this will crash if called with a negative value. Crashing is bad. What did your function do? <code>IsPrime(-10)</code> returned <code>True</code>, which is incorrect, which is arguably worse than crashing. At least if you crash, you know something went wrong, and get a stack trace you can debug. A wrong result is harder to debug, since you don't know where it went wrong. While we're at it, neither <code>0</code> nor <code>1</code> should return <code>True</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from math import isqrt\n\ndef is_prime(n):\n if n < 2 or (n > 2 and n % 2 == 0):\n return False\n\n return all(n % x != 0 for x in range(3, isqrt(n) + 1, 2))\n</code></pre>\n<p>This is faster and more correct. You could improve it even further, with more advanced prime checking, such as the <a href=\"/questions/tagged/sieve-of-eratosthenes\" class=\"post-tag\" title=\"show questions tagged 'sieve-of-eratosthenes'\" rel=\"tag\">sieve-of-eratosthenes</a>.</p>\n<h1>Big Factor Check</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def BigFactorCheck(n):\n for x in range(n):\n x += 1\n\n if n % (n - x) == 0:\n return n - x\n</code></pre>\n<p>On the last iteration, <code>x</code> initially is <code>n-1</code>, but you add 1 to it, so <code>x</code> actually would be <code>n</code>. Then <code>n % (n - x)</code> would be <code>n % (n - n)</code>, or <code>n % 0</code>, which is a division by zero! Eek. Fortunately, you never reach the last iteration; the previous iteration would test <code>n % 1 == 0</code>, which should always be true. Still, dangerous code.</p>\n<p>Again, <code>for x in range(n)</code> and <code>x += 1</code> could simply become <code>for x in range(1, n+1)</code>. But you don't simply want <code>x</code>; you want <code>n - x</code>. Why not just loop starting a <code>n-1</code>, and go down until you reach <code>n - (n-1)</code>? You don't even need to try the <code>n % 1 == 0</code> iteration; you could stop before reaching 1, and simply return 1 if you get to the end of the <code>for</code> loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def big_factor_check(n):\n for x in range(n - 1, 1, -1):\n if n % x == 0:\n return x\n return 1\n</code></pre>\n<h1>Main function</h1>\n<p>Your mainline code is complex enough to warrant its own function. You could even add a main-guard, so you can import this function into other programs if you want to use it, without executing the mainline code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def addition_chain(n):\n number_chain = []\n while n > 1:\n # your computations here\n\n number_chain.sort()\n return number_chain\n\nif __name__ == '__main__':\n n = int(input())\n bewijs_n = (n + 1) / 2\n chain = addition_chain(n)\n print(len(chain), chain)\n if len(chain) - 1 <= bewijs_n:\n print(True, len(chain) - 1, "<=", bewijs_n)\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:15:29.653",
"Id": "493277",
"Score": "0",
"body": "Um, who deleted my comment pointing out that \"sped up\" is misinformation? That claim is still there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:35:21.180",
"Id": "493318",
"Score": "0",
"body": "You need to remove the final colon from `return n % 2 == 0:` and I would not spend so much time on how to make `IsPrime` better; just recommend using the Sieve of Eratosthenes straightaway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T23:08:27.300",
"Id": "250729",
"ParentId": "250722",
"Score": "6"
}
},
{
"body": "<p>Some suggestions:</p>\n<ul>\n<li>Write English, not something like "BewijsN", "lelijk, maar werkt" and "kan tot 8 cijfers snel(<1min), na 8 traag" which barely anyone here can understand.</li>\n<li>It fails for <code>n = 1</code>, producing <code>[]</code> instead of <code>[1]</code>.</li>\n<li>Use a prompt, like <code>input("Enter the target for the addition chain: ")</code></li>\n<li><code>.sort()</code> => <code>.reverse()</code>, since you build descending numbers. It won't make the overall solution much faster, but sorting gives the reader the wrong and confusing impression that it's not just descending.</li>\n<li>Improving <code>is_prime</code> alone like AJNeufeld showed doesn't improve your complexity from O(n) to something better, as your <code>BigFactorCheck</code> is also only O(n). For example, <code>BigFactorCheck(95)</code> checks 94, 93, 92, ..., 21, 20 before it finds 19 and stops. Much faster to search the <em>smallest</em> factor, i.e., 2, 3, 4, 5 and then <em>compute</em> the biggest as 95/5. Also, your prime check already finds the smallest factor, so if you don't throw that away, you can use that instead of searching for it again.</li>\n<li>Your <code>else: # Oneven</code> branch subtracts <code>BigFactor</code> from <code>n</code> multiple times. Or rather it subtracts multiples of <code>BigFactor</code> from <code>n</code> and doesn't update <code>n</code> yet. I think the former, subtracting <code>BigFactor</code> from <code>n</code> multiple times (actually updating <code>n</code>), would save code and make it simpler. I'm not gonna try it, though, since I'd want to compare the modification with the original by running both and comparing the results, and since your main code is not in a nice function that takes n and returns the chain, this is not as easy as it should be. So: make the main code such a function.</li>\n<li><code>if IsEven(n) == False:</code> => <code>if not IsEven(n):</code></li>\n<li><code>n += -1</code> => <code>n -= 1</code></li>\n<li><code>n = n - ...</code> => <code>n -= ...</code></li>\n<li><code>n = n // 2</code> => <code>n //= 2</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T12:26:41.213",
"Id": "250750",
"ParentId": "250722",
"Score": "3"
}
},
{
"body": "<h3>Improved implementation</h3>\n<p>Here's an improved implementation of the same algorithm, incorporating stuff from the other answers:</p>\n<pre><code>from math import isqrt\n\ndef smallest_factor(n):\n for i in range(2, isqrt(n) + 1):\n if n % i == 0:\n return i\n\ndef addition_chain(n):\n chain = []\n while n:\n if small := smallest_factor(n):\n big = n // small\n for _ in range(small - 1):\n chain.append(n)\n n -= big\n else:\n chain.append(n)\n n -= 1\n chain.reverse()\n return chain\n</code></pre>\n<h3>Demo</h3>\n<p>Demo output for several n, with how long it took, how long the chain is, and the (possibly abbreviated) chain:</p>\n<pre><code>n=1 5.15 μs len=1 [1]\nn=2 5.01 μs len=2 [1, 2]\nn=3 9.16 μs len=3 [1, 2, 3]\nn=4 481.24 μs len=3 [1, 2, 4]\nn=5 356.58 μs len=4 [1, 2, 4, 5]\nn=6 10.75 μs len=4 [1, 2, 3, 6]\nn=7 17.10 μs len=5 [1, 2, 3, 6, 7]\nn=8 451.55 μs len=4 [1, 2, 4, 8]\nn=9 381.45 μs len=5 [1, 2, 3, 6, 9]\nn=10 372.24 μs len=5 [1, 2, 4, 5, 10]\nn=123 426.09 μs len=10 [1, 2, 4, 5, 10, 20, 40, 41, 82, 123]\nn=123456789 2178.51 μs len=3630 [1, 2, 3, 6, 9, '...', 13717421, 27434842, 41152263, 82304526, 123456789]\n</code></pre>\n<p>Code producing the above output:</p>\n<pre><code>from time import perf_counter as timer\n\ndef abbreviated(chain):\n if len(chain) <= 10:\n return chain\n return chain[:5] + ['...'] + chain[-5:]\n \nfor n in [*range(1, 11), 123, 123456789]:\n t0 = timer()\n chain = addition_chain(n)\n t1 = timer()\n print(f'{n=} {(t1 - t0) * 1e6:.2f} μs ', f'len={len(chain)}', abbreviated(chain))\n</code></pre>\n<h3>An observation</h3>\n<p>Note that there's no need to special-case when n is even, and I left it out in the code. Your treatment was to divide it by 2. By treating 2 the same as any other factor, we instead subtract n/2 once. That's equivalent. Sure, that might make even cases slightly slower, but they're very fast anyway, so it doesn't really matter.</p>\n<h3>A simpler and better alternative</h3>\n<p>Consider this much simpler alternative:</p>\n<pre><code>def addition_chain(n):\n chain = []\n while n:\n chain.append(n)\n if n % 2:\n n -= 1\n else:\n n //= 2\n chain.reverse()\n return chain\n</code></pre>\n<p>Same demo as before:</p>\n<pre><code>n=1 2.32 μs len=1 [1]\nn=2 2.17 μs len=2 [1, 2]\nn=3 2.85 μs len=3 [1, 2, 3]\nn=4 2.55 μs len=3 [1, 2, 4]\nn=5 2.58 μs len=4 [1, 2, 4, 5]\nn=6 2.64 μs len=4 [1, 2, 3, 6]\nn=7 3.26 μs len=5 [1, 2, 3, 6, 7]\nn=8 2.01 μs len=4 [1, 2, 4, 8]\nn=9 2.58 μs len=5 [1, 2, 4, 8, 9]\nn=10 5.20 μs len=5 [1, 2, 4, 5, 10]\nn=123 4.21 μs len=12 [1, 2, 3, 6, 7, '...', 30, 60, 61, 122, 123]\nn=123456789 14.99 μs len=42 [1, 2, 3, 6, 7, '...', 30864196, 30864197, 61728394, 123456788, 123456789]\n</code></pre>\n<p>Note that this is much faster and produces a much shorter chain for n=123456789: length 42 instead of length 3630 from your original algorithm. While your original algorithm produces long chains when a smallest factor is large, this simpler algorithm always produces chains of length O(log n).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T14:06:19.127",
"Id": "250751",
"ParentId": "250722",
"Score": "4"
}
},
{
"body": "<h2>Internationalization</h2>\n<p>I'd like to expand on the difference between code-language and i18n (internationalisation) / localisation (l10n).</p>\n<p>This is a good idea (please excuse my Google translate):</p>\n<pre><code># Will be fast up to 8 digits; will be slow after 8\nn = int(input(\n 'Voer het nummer in'\n))\n</code></pre>\n<p>User-facing content should be in the language of the user. This can be very simple (as in the above example with a hard-coded locale), or very complicated, based on your requirements. There are some Python packages such as <a href=\"https://docs.python.org/3.8/library/locale.html\" rel=\"noreferrer\">https://docs.python.org/3.8/library/locale.html</a> that will support this effort.</p>\n<p>This can be problematic:</p>\n<pre><code># Ik begrijp dit, maar mijn collega's misschien niet\n# kan tot 8 cijfers snel(<1min), na 8 traag\n</code></pre>\n<p>For better or worse, English is the de-facto language of programming and engineering. Nearly all of the workplaces I've been in have been multi-lingual, and English is a standard - just like Python itself - that we all agree on to facilitate communication. This is particularly important for open-source collaboration on the internet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:59:33.973",
"Id": "493295",
"Score": "2",
"body": "@Emma It's a valid point, and of course there will be some workplaces that are \"engineering-localised\"; but this is an advice site. If I had to give a programmer advice to be more career-marketable in the international community, I stand by my suggestion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T15:50:07.483",
"Id": "250754",
"ParentId": "250722",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "250729",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:29:16.083",
"Id": "250722",
"Score": "8",
"Tags": [
"python",
"mathematics"
],
"Title": "\"Kinda\" addition chain calculator"
}
|
250722
|
<p>Related to this question: <a href="https://codereview.stackexchange.com/questions/250676/spigot-plugin-generic-form-of-the-plugins-main-clas">Spigot Plugin: Generic form of the plugin's main clas</a></p>
<p>I've created a Clan-Plugin, in which I have one "main" command, which is simply <code>/clan</code>. Then there are several sub-commands, e.g. <code>/clan leave</code>, <code>/clan money</code>, etc. There are also subcommands that require multiple arguments, like <code>/clan create</code>, where you have to provide details about the clan you want to create.</p>
<p>My very basic problem is, that spigot only offers the possibility to implement commands based on the first word, and not the arguments. What you have to do is manually differ between the subcommands, and then execute the code. In the past I did this by having a massive if-elseif-elseif-... construct in the executor method of the command, with the code of the sub-commands being placed in methods. However, that made this class become really massive oover the time, until it hit the 1000 lines recently. I really thought I should refactor the command, so I came up with the following idea (which I successfully implemented).</p>
<p>I created a base class for all subcommands, <code>AbstractCommand</code>, and a Child Class (which is still abstract) for sub-commands, that have to be confirmed before being executed (e.g. deletion of the clan) <code>AbstractConfirmCommand</code>. Also I wrote a little <code>CommandRegistry</code>-Class to store all the implementations of the AbstractCommand, and find the proper one to execute when necessary. Then in my Main class (which can be found in above link, if there is anyone interested), I register all the Implementations of AbstractCommand. My "Spigot-ClanCommand-Class" has now shrunk down to 80 lines, with which I'm quite happy to be honest. However, I'm not experienced at all with abstract classes, and am not even sure if an abstract class was the better choice over an interface. Here's my code, I hope I could make it clear what it's supposed to do.</p>
<p>AbstractCommand:</p>
<pre class="lang-java prettyprint-override"><code>import org.bukkit.command.Command;
import org.bukkit.entity.Player;
public abstract class AbstractCommand {
protected final String commandName;
protected AbstractCommand(String commandName) {
this.commandName = commandName;
}
public abstract void execute(Player player, Command cmd, String arg2, String[] args);
public String getCommandName() {
return commandName;
}
}
</code></pre>
<p>AbstractConfirmCommand:</p>
<pre class="lang-java prettyprint-override"><code>import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import com.clanplugin.manager.MessageManager;
public abstract class AbstractConfirmCommand extends AbstractCommand {
private int requiredPositionOfConfirm = 1;
protected AbstractConfirmCommand(String commandName) {
super(commandName);
}
protected void setConfirmPosition(int position) {
requiredPositionOfConfirm = position;
}
@Override
public void execute(Player player, Command cmd, String arg2, String[] args) {
if (args.length < requiredPositionOfConfirm || args.length > requiredPositionOfConfirm + 1) {
player.sendMessage(MessageManager.badNumberOfArguments());
return;
}
if (args.length == requiredPositionOfConfirm) {
withoutConfirm(player, cmd, arg2, args);
return;
}
if (args.length == requiredPositionOfConfirm + 1) {
if (args[requiredPositionOfConfirm].equalsIgnoreCase("confirm")) {
withConfirm(player, cmd, arg2, args);
} else {
withoutConfirm(player, cmd, arg2, args);
}
return;
}
}
protected abstract void withoutConfirm(Player player, Command cmd, String arg2, String[] args);
protected abstract void withConfirm(Player player, Command cmd, String arg2, String[] args);
}
</code></pre>
<p>CommandRegistry:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.HashSet;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import com.clansystem.manager.MessageManager;
public class CommandRegistry {
private HashSet<AbstractCommand> registeredCommands;
public CommandRegistry() {
registeredCommands = new HashSet<AbstractCommand>();
}
public void registerCommand(AbstractCommand command) {
registeredCommands.add(command);
}
public void executeCommand(Player player, Command cmd, String arg2, String[] args) {
for (AbstractCommand registeredCommand : registeredCommands) {
if (registeredCommand.getCommandName().equalsIgnoreCase(args[0])) {
registeredCommand.execute(player, cmd, arg2, args);
return;
}
}
player.sendMessage(MessageManager.getHelpMessage());
}
}
</code></pre>
<p>ClanCommand:</p>
<pre class="lang-java prettyprint-override"><code>public class ClanCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String arg2, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Clan-Commands können nur von Spielern ausgeführt werden.");
return true;
}
Player player = (Player) sender;
//Some checks which are irrelevant here... (e.g. command cooldown, permission-check etc)
if (args.length == 0) {
player.sendMessage(MessageManager.getHelpMessage());
return true;
}
Main.getCommandRegistry().executeCommand(player, cmd, arg2, args);
return true;
}
}
</code></pre>
<p>Finally, I'll append an example of an implementation of AbstractCommand:</p>
<pre class="lang-java prettyprint-override"><code>import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import com.clanplugin.commands.AbstractCommand;
import com.clanplugin.manager.MessageManager;
import com.clanplugin.utils.PermissionUtils;
public class ShowMaxClanMemberCommand extends AbstractCommand {
public ShowMaxClanMemberCommand() {
super("maxmember");
}
@Override
public void execute(Player player, Command cmd, String arg2, String[] args) {
int limit = PermissionUtils.getTotalClanMembersAllowed(player);
player.sendMessage(MessageManager.getMaxMemberMessage(limit));
}
}
</code></pre>
<p>What I want to know is, if the basic idea of creating an abstract class is "good practice", and how I can improve my construct. Also I'm pretty new to the site, and I'm not sure if this is too much code for one post. If so, please tell me :)</p>
|
[] |
[
{
"body": "<p>Nice implementation and refactoring, few suggestions:</p>\n<h2>AbstractCommand class</h2>\n<blockquote>\n<p>I created a base class for all subcommands, <code>AbstractCommand</code>.</p>\n</blockquote>\n<ul>\n<li><p>I think a better name is <code>SubCommand</code>. The type of the class doesn't need to be in the name.</p>\n</li>\n<li><p>The instance variable <code>commandName</code> can be shorten to <code>name</code>, since it's implicit that it's the subcommand name.</p>\n</li>\n<li><p>The second argument of the method <code>execute</code> is called <code>arg2</code>, a better name could be <code>label</code>.</p>\n</li>\n<li><p>The method <code>execute</code> returns nothing. How to know the result of the command? How to handle errors and exceptions? Consider to return at least a boolean.</p>\n</li>\n</ul>\n<h2>AbstractConfirmCommand class</h2>\n<p>This class seems to check if the <code>confirm</code> argument is where is supposed to be and then invoke <code>withConfirm</code> or <code>withoutConfirm</code> accordingly. There is no example of a subclass so I'll limit the review to what I see:</p>\n<ul>\n<li>The chain of <code>if()-return</code> should be replaced with <code>if()-else if()-else</code>. No need for the empty return.</li>\n<li>A better class name could be <code>ConfirmedCommand</code></li>\n<li>Pushing common behavior up to a parent class is ok, but I am not sure if splitting the method <code>execute</code> to <code>withConfirm</code> and <code>withoutConfirm</code> is a good idea. You are basically forcing all subclasses to implement two methods instead of one.</li>\n</ul>\n<h2>CommandRegistry class</h2>\n<ul>\n<li>If it's a registry, it shouldn't execute the commands. That is the job of the <code>CommandExecutor</code>.</li>\n<li>Instead of a <code>Set</code> consider using a <code>Map<String,SubCommand></code>, it's way more efficient for retrieving data.</li>\n</ul>\n<p>I suggest to add a method <code>addCommand</code> to <code>ClanCommand</code> (which is your <code>CommandExecutor</code>) and store the subcommands in a map.</p>\n<h2>ClanCommand class</h2>\n<ul>\n<li>Since it implements <code>CommandExecutor</code>, I would call it <code>ClanCommandExecutor</code>.</li>\n<li>Same as before, instead of a chain of <code>if()-return true-if()-return true</code> consider to find the conditions to fail first with <code>if this than return false</code>, then use <code>if-else if-else</code>, and finally return true.</li>\n</ul>\n<p>There is a design pattern called <a href=\"https://www.baeldung.com/java-command-pattern\" rel=\"nofollow noreferrer\">Command</a> which I suggest you to check out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T11:16:07.807",
"Id": "493248",
"Score": "1",
"body": "Good points :) I changed the names accordingly, the only point that I'd like to address is that forcing an implementation of withConfirm and withoutConfirm is the use case of the confirm command. There are always two different ways of handling the command, which are repeatedly necessary in the implementations of the class :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T03:45:57.663",
"Id": "250734",
"ParentId": "250723",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "250734",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T20:34:48.137",
"Id": "250723",
"Score": "6",
"Tags": [
"java",
"minecraft"
],
"Title": "Base Class System for splitting a spigot command in subcommands"
}
|
250723
|
<p>This code takes a list of EBITDA amounts (for a hypothetical business), and computes a loan that would fund that business with working capital in periods of loss. When the business has positive EBITDA again, the loan is paid off. The loan also charges interest.</p>
<p>Some specific questions I have</p>
<ul>
<li>I am not sure the way <code>wcLoanCalc</code> calls <code>wcLoanR</code> is the most beautiful solution. Is there something more elegant I could do?</li>
<li>It feels awkward to have such huge statements to update the <code>LoanPeriod</code> type, but I like having a single type name and hold all this data. Is there a better way?</li>
<li>Is there a more general way I could implement printing out the table? Presumably there is some nice library for doing this</li>
</ul>
<p>I'm grateful for any and all feedback!</p>
<pre><code>-- Compute Working Capital Loan using Haskell
import Data.List
import Text.Printf
-- | Hold all information about a single period of loan amortization
data LoanPeriod = LoanPeriod
{ cashAvail :: Double
, draw :: Double
, ds :: Double
, principal :: Double
, interest :: Double
, balance :: Double
}
instance Show LoanPeriod
where
show lp = printf "%-10.2f %-10.2f %-10.2f %-10.2f %-10.2f %-10.2f"
(cashAvail lp)
(draw lp)
(ds lp)
(principal lp)
(interest lp)
(balance lp)
type WCLoanAmort = [LoanPeriod]
-- | Test the wcLoanCalc function
wcLoanTest :: WCLoanAmort
wcLoanTest = wcLoanCalc testEbitda testInterestRate
where
testEbitda = [100.0, 30.0, -50.0, -10.0, 20.0, 40.0, 60.0, -100.0, 120.0, 30.0]
testInterestRate = 0.12
-- | Print the result of the wcLoanTest
wcLoanTestPrint :: IO ()
wcLoanTestPrint = loanTable wcLoanTest
-- | Print out a WCLoanAmort as a table
loanTable :: WCLoanAmort -> IO ()
loanTable lpList =
putStrLn $
printf "%-10s %-10s %-10s %-10s %-10s %-10s\n"
"Cash" "Draw" "DS" "Prin" "Int" "Bal" ++
concat ["---------- " | x <- [1..6]] ++ "\n" ++
concat [show lp ++ "\n" | lp <- lpList]
-- | Calculate a working capital loan
wcLoanCalc :: [Double] -> Double -> WCLoanAmort
wcLoanCalc ebitda interestRate =
wcLoanR ebitda interestRate []
-- | Recursively compute each period of working-capital loan
wcLoanR :: [Double] -> Double -> WCLoanAmort -> WCLoanAmort
wcLoanR (ebitda:es) interestRate loanData
| es == [] = newLoanData
| otherwise = wcLoanR es interestRate newLoanData
where
startBalance = case length loanData of
0 -> 0.0
_ -> balance (last loanData)
newInterest = startBalance * interestRate / 12.0
newDraw = - min ebitda 0.00
newDS = max 0.0 $ min ebitda (startBalance + newInterest)
newPrincipal = newDS - newInterest
newBalance = startBalance + newDraw - newPrincipal
newLoanData = loanData ++ [newLoanPeriod]
newLoanPeriod = LoanPeriod
{ cashAvail = ebitda
, draw = newDraw
, ds = newDS
, principal = newPrincipal
, interest = newInterest
, balance = newBalance}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T22:07:52.257",
"Id": "250726",
"Score": "5",
"Tags": [
"haskell",
"finance"
],
"Title": "Compute a Working Capital Loan"
}
|
250726
|
<p>This is actually an extension of the already written Matrix Library from <a href="https://codereview.stackexchange.com/questions/236728/a-matrix-library-in-c">this post</a>.
This Matrix class is the result of the changes made thanks to <a href="https://codereview.stackexchange.com/a/236729/215715">this answer</a> by Toby Speight, and having added a few other functionalities.</p>
<p>The library is composed of a few classes namely: a Fraction which contains the numbers that will be used in library, the Matrix class and the newly LA Vector class which contains functions such as:</p>
<pre><code>bool is_linearly_dependent(std::initializer_list<Vector> vec_set);
bool is_linear_combination(std::initializer_list<Vector> vec_set, Vector vec);
bool spans_space(std::initializer_list<Vector> vec_set);
std::vector<Vector> row_space_basis(Matrix mx);
std::vector<Vector> null_space(Matrix mx);
</code></pre>
<p>The library is compiled in GCC 10.2.0, using boost format from boost 1.74.0, in Codeblocks on Windows 10.
While using boost format I ran into an unknown compiler error which I think I solved applying the changes suggested <a href="https://github.com/boostorg/format/issues/67#issuecomment-546911466" rel="noreferrer">by this answer</a> in this boostorg/format issue.</p>
<p>Fraction.h</p>
<pre><code>#ifndef FRACTION_H_INCLUDED
#define FRACTION_H_INCLUDED
#include <iostream>
#include <ostream>
#include <cstring>
#include <assert.h>
class Fraction
{
long long gcf(long long a, long long b);
void simplify();
public:
long long num;
long long den;
Fraction(long long _num = 0, long long _den = 1) : num{std::move(_num)}, den{std::move(_den)}
{
assert(_den != 0);
simplify();
}
Fraction (Fraction n, Fraction d) : num(n.num * d.den), den(n.den * d.num)
{
assert(den != 0);
simplify();
}
friend std::ostream& operator<< (std::ostream& os, const Fraction& fr);
std::string to_string() const;
bool is_integer()
{
return den == 1;
}
explicit operator bool() const
{
return num != 0;
}
bool operator== (const Fraction& fr) const
{
return num == fr.num && den == fr.den;
}
bool operator!= (const Fraction& fr) const
{
return !(*this == fr);
}
bool operator== (int n) const
{
return (n * den) == num;
}
bool operator!= (int n) const
{
return !(*this == n);
}
Fraction operator-() const
{
return { -num, den };
}
Fraction operator+() const
{
return *this;
}
long double to_double()
{
return double(num) / den;
}
float to_float()
{
return double(num) / den;
}
Fraction operator++()
{
num += den;
return *this;
}
Fraction operator++(int)
{
Fraction fr = *this;
++(*this);
return fr;
}
Fraction operator--()
{
num -= den;
return *this;
}
Fraction operator--(int)
{
Fraction fr = *this;
--(*this);
return fr;
}
Fraction operator+(const Fraction& fr) const;
Fraction operator/(const Fraction& fr) const;
Fraction operator-(const Fraction& fr) const;
Fraction operator*(const Fraction& fr) const;
friend Fraction operator+(const Fraction& fr, long long n);
friend Fraction operator+(long long n, const Fraction& fr);
friend Fraction operator-(const Fraction& fr, long long n);
friend Fraction operator-(long long n, const Fraction& fr);
friend Fraction operator/(const Fraction& fr, long long n);
friend Fraction operator/(long long n, const Fraction& fr);
friend Fraction operator*(const Fraction& fr, long long n);
friend Fraction operator*(long long n, const Fraction& fr);
void operator+= (const Fraction& fr);
void operator-= (const Fraction& fr);
void operator*= ( const Fraction& fr);
void operator/= (const Fraction& fr);
void operator+=(long long n);
void operator-=(long long n);
void operator*=(long long n);
void operator/=(long long n);
};
Fraction pow_fract(const Fraction& fr, int x);
#endif // FRACTION_H_INCLUDED
</code></pre>
<p>Fraction.cpp</p>
<pre><code>#include "Fraction.h"
#include <iostream>
#include <ostream>
#include <sstream>
using namespace std;
std::ostream& operator<< (std::ostream& os, const Fraction& fr)
{
if(fr.den == 1)
os << fr.num;
else
os << fr.num << "/" << fr.den;
return os;
}
string Fraction::to_string() const
{
ostringstream os;
os << *this;
return os.str();
}
long long Fraction::gcf(long long a, long long b)
{
if( b == 0)
return abs(a);
else
return gcf(b, a%b);
}
void Fraction::simplify()
{
if (den == 0 || num == 0)
{
num = 0;
den = 1;
}
// Put neg. sign in numerator only.
if (den < 0)
{
num *= -1;
den *= -1;
}
// Factor out GCF from numerator and denominator.
long long n = gcf(num, den);
num = num / n;
den = den / n;
}
Fraction Fraction::operator- (const Fraction& fr) const
{
Fraction sub( (num * fr.den) - (fr.num * den), den * fr.den );
int nu = sub.num;
int de = sub.den;
sub.simplify();
return sub;
}
Fraction Fraction::operator+(const Fraction& fr) const
{
Fraction addition ((num * fr.den) + (fr.num * den), den * fr.den );
addition.simplify();
return addition;
}
Fraction Fraction::operator*(const Fraction& fr) const
{
Fraction multiplication(num * fr.num, den * fr.den);
multiplication.simplify();
return multiplication;
}
Fraction Fraction::operator / (const Fraction& fr) const
{
Fraction sub(num * fr.den, den * fr.num);
sub.simplify();
return sub;
}
Fraction operator+(const Fraction& fr, long long n)
{
return (Fraction(n) + fr);
}
Fraction operator+(long long n, const Fraction& fr)
{
return (Fraction(n) + fr);
}
Fraction operator-(const Fraction& fr, long long n)
{
return (fr - Fraction(n));
}
Fraction operator-(long long n, const Fraction& fr)
{
return (Fraction(n) - fr);
}
Fraction operator/(const Fraction& fr, long long n)
{
return (fr / Fraction(n));
}
Fraction operator/(long long n, const Fraction& fr)
{
return (Fraction(n) / fr);
}
Fraction operator*(const Fraction& fr, long long n)
{
return (Fraction(n) * fr);
}
Fraction operator*(long long n, const Fraction& fr)
{
return (Fraction(n) * fr);
}
void Fraction::operator+=(const Fraction& fr)
{
*this = *this + fr;
}
void Fraction::operator-=(const Fraction& fr)
{
*this = *this - fr;
}
void Fraction::operator/=(const Fraction& fr)
{
*this = *this / fr;
}
void Fraction::operator*=(const Fraction& fr)
{
*this = *this * fr;
}
void Fraction::operator+=(long long n)
{
*this = *this + n;
}
void Fraction::operator-=(long long n)
{
*this = *this - n;
}
void Fraction::operator*=(long long n)
{
*this = *this * n;
}
void Fraction::operator/=(long long n)
{
*this = *this / n;
}
Fraction pow_fract(const Fraction& fr, int x)
{
Fraction p(fr);
for(int i = 0; i < x - 1; ++i)
p *= fr;
return p;
}
</code></pre>
<p>Matrix.h</p>
<pre><code>#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <vector>
#include <ostream>
#include <assert.h>
#include "Fraction.h"
namespace L_Algebra
{
class Matrix
{
private:
std::size_t rows_num;
std::size_t cols_num;
std::vector<Fraction> data;
Fraction& at(std::size_t r, std::size_t c)
{
return data.at( r * cols_num + c );
}
const Fraction& at(std::size_t r, std::size_t c) const
{
return data.at(r * cols_num + c);
}
public:
Matrix () = default;
Matrix(std::size_t r, std::size_t c, Fraction n = 0 ) : rows_num(r), cols_num(c), data(r * c, n)
{
assert(r > 0 && c > 0);
}
Matrix(std::size_t r, std::size_t c, std::initializer_list<Fraction> values ) : rows_num(r), cols_num(c), data(values)
{
assert(r > 0 && c > 0);
assert(values.size() == size());
}
Matrix(std::initializer_list<std::initializer_list<Fraction>> values );
friend std::ostream& operator<<(std::ostream& out, const Matrix& mx);
//friend std::vector<Fraction> operator<<(std::ostream& os, std::vector<Fraction> diag);
explicit operator bool() const
{
return ! is_zero();
}
bool operator== (const Matrix& mx) const
{
return data == mx.data;
}
bool operator!= (const Matrix& mx) const
{
return !(*this == mx);
}
Matrix operator-()
{
return ( (*this) * (-1) );
}
Matrix operator+()
{
return (*this);
}
Matrix operator+(const Matrix& mx) const;
Matrix operator-(const Matrix& mx) const;
Matrix operator*(const Matrix& mx) const;
Matrix& operator+=(const Matrix& mx);
Matrix& operator-=(const Matrix& mx);
Matrix& operator*=(const Matrix& mx);
Matrix& operator*=(const Fraction& n);
friend Matrix operator*(const Matrix& mx, Fraction n);
friend Matrix operator*(Fraction n, const Matrix& mx);
Matrix operator/(const Fraction& n) const;
Fraction& operator()(std::size_t r, std::size_t c)
{
return at(r,c);
}
const Fraction& operator()(std::size_t r, std::size_t c) const
{
return at(r,c);
}
constexpr std::size_t size() const
{
return rows_num * cols_num;
}
void clear()
{
data.clear();
}
void resize(int r, int c, long long n = 0)
{
data.clear();
data.resize( r * c, n );
rows_num = r;
cols_num = c;
}
size_t rows() const
{
return rows_num;
}
size_t cols() const
{
return cols_num;
}
static Matrix Identity(int n);
static Matrix Constant(int r, int c, long long n);
bool is_square() const
{
return rows_num == cols_num;
}
bool is_identity() const;
bool is_symmetric() const;
bool is_skewSymmetric() const;
bool is_diagonal() const;
bool is_zero() const;
bool is_constant() const;
bool is_orthogonal() const;
bool is_invertible() const;
bool is_linearly_dependent() const;
bool is_linearly_independent() const;
bool is_upperTriangular() const;
bool is_lowerTriangular() const;
bool is_consistent() const;
Matrix transpose() const;
Fraction determinant() const;
Matrix inverse() const;
Matrix adjoint() const;
Matrix gaussElimination() const;
Matrix gaussJordanElimination() const;
Fraction trace() const;
std::size_t rank() const;
std::vector<Fraction> main_diagonal();
std::vector<Fraction> secondary_diagonal();
friend Matrix transitionMatrix(Matrix from, Matrix to);
private:
void swapRows(int row1, int row2);
bool pivotEqualTo_one_Found(int pivot_row, int pivot_col, int& alternative_pivot_row );
bool pivotNot_zero_Found(int pivot_row, int pivot_col, int& col_dif_zero );
bool firstNumberNot_zero(int row_num, int& num_coluna_num_dif_zero);
void changePivotTo_one(int row_num, Fraction constant);
void zeroOutTheColumn(int row_num, int num_pivot_row, Fraction constant);
bool has_one_row_zero() const;
};
extern std::ostream& operator << (std::ostream& os, const std::vector<Fraction>& v);
} // L_Algebra namespace
#endif // MATRIX_H_INCLUDED
</code></pre>
<p>Matrix.cpp</p>
<pre><code>#include "Matrix.h"
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <numeric>
#include <iomanip>
#include <boost/format.hpp>
using namespace std;
namespace L_Algebra
{
Matrix::Matrix(std::initializer_list<std::initializer_list<Fraction>> values )
{
size_t len = 0;
for(auto iter = values.begin(); iter != values.end(); ++iter)
if(iter->size() != 0)
{
len = iter->size();
break;
}
assert(len > 0);
for(auto iter = values.begin(); iter != values.end(); ++iter)
{
if(iter->size() != 0)
assert(iter->size() == len);
if(iter->size() == 0)
for(size_t i = 0; i < len; ++i)
data.push_back(0);
else
for(auto iterj = iter->begin(); iterj != iter->end(); ++iterj)
data.push_back(*iterj);
}
rows_num = values.size();
cols_num = len;
}
bool Matrix::has_one_row_zero() const
{
bool has;
for(int i = 0; i < rows_num; ++i)
{
has = true;
for(int j = 0; j < cols_num; ++j)
if(at(i,j) != 0)
{
has = false;
break;
}
if(has)
return true;
}
return false;
}
ostream& operator<<(ostream& os, const Matrix& mx)
{
size_t width = 1;
for(const auto element : mx.data)
{
auto w = element.to_string().size();
if(width < w)
width = w;
}
string w = "%" + to_string(width + 4) + "d";
for (int i = 0; i < mx.rows(); i++)
{
for (int j = 0; j < mx.cols(); j++)
os << boost::format(w.c_str()) % mx.at(i, j);
os << '\n';
}
return os;
}
// to print the diagonal
std::ostream& operator<<(std::ostream& os, const std::vector<Fraction>& v)
{
for (auto e: v)
os << e << " ";
return os;
}
Matrix Matrix::operator+(const Matrix& mx) const
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
Matrix addition(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
addition.at(i, j)= at(i, j) + mx.at(i, j);
return addition;
}
Matrix Matrix::operator-(const Matrix& mx) const
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
Matrix sub(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
sub.at(i, j) = at(i, j) - mx.at(i, j);
return sub;
}
Matrix Matrix::operator*(const Matrix& mx) const
{
assert(cols_num == mx.rows_num);
Matrix multiplication(rows_num, mx.cols_num);
for(int i = 0; i < rows_num; ++i)
for (int j = 0; j < mx.cols_num; ++j)
for(int x = 0; x < cols_num; ++x)
multiplication.at(i,j) += at(i, x) * mx.at(x, j);
return multiplication;
}
Matrix& Matrix::operator*=(const Matrix& mx)
{
assert(cols_num == mx.rows_num);
return *this = (*this * mx);
}
Matrix& Matrix::operator-=(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
transform(data.begin(), data.end(), mx.data.begin(), data.end(), minus{});
return *this;
}
Matrix& Matrix::operator+=(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
transform(data.begin(), data.end(), mx.data.begin(), data.end(), plus{});
return *this;
}
Matrix operator*(const Matrix& mx, Fraction n)
{
Matrix multiplication(mx.rows_num, mx.cols_num);
for(int i = 0; i < mx.rows_num; ++i)
for(int j = 0; j < mx.cols_num; ++j)
multiplication.at(i, j) = mx.at(i, j) * n;
return multiplication;
}
Matrix operator*(Fraction n, const Matrix& mx)
{
Matrix multiplication(mx.rows_num, mx.cols_num);
for(int i = 0; i < mx.rows_num; ++i)
for(int j = 0; j < mx.cols_num; ++j)
multiplication.at(i, j) = mx.at(i, j) * n;
return multiplication;
}
Matrix& Matrix::operator*=(const Fraction& n)
{
return *this = *this * n;
}
Matrix Matrix::operator/(const Fraction& n) const
{
assert(n != 0);
Matrix division(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
division.at(i, j) = at(i, j) / n;
return division;
}
Matrix Matrix::Identity(int n)
{
assert(n > 0);
Matrix mx(n,n);
for(int i = 0; i < n; ++i)
mx.at(i, i) = 1;
return mx;
}
Matrix Matrix::Constant(int r, int c, long long n)
{
Matrix mx(r,c, n);
return mx;
}
bool Matrix::is_identity() const
{
if(! is_square())
return false;
return *this == Identity(cols_num);
}
bool Matrix::is_symmetric() const
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(at(i,j) != at(j,i))
return false;
return true;
}
bool Matrix::is_skewSymmetric() const
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = i+1; j < cols_num; ++j)
if(at(i,j) != -at(j,i))
return false;
return true;
}
bool Matrix::is_diagonal() const
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(i != j)
if( at(i, j) != 0 )
return false;
return true;
}
bool Matrix::is_zero() const
{
return all_of( data.begin(), data.end(), [ ] (const auto& x)
{
return x == 0;
} );
}
bool Matrix::is_constant() const
{
return adjacent_find( data.begin(), data.end(), not_equal_to{} ) == data.end();
}
bool Matrix::is_orthogonal() const
{
if(! is_square())
return false;
return (*this * transpose() == Identity(cols_num));
}
bool Matrix::is_invertible() const
{
return this->determinant() != 0;
}
bool Matrix::is_linearly_dependent() const
{
return this->determinant() == 0;
}
bool Matrix::is_linearly_independent() const
{
return ! this->is_linearly_dependent();
}
bool Matrix::is_lowerTriangular() const
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = i + 1; j < cols_num; ++j)
if( at(i,j) )
return false;
return true;
}
bool Matrix::is_upperTriangular() const
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < i; ++j)
if( at(i,j) )
return false;
return true;
}
bool Matrix::is_consistent( ) const
{
Matrix mx1 = gaussJordanElimination();
bool square = is_square();
int num_non_zero_numbers = 0;
for(int i = 0; i < rows_num; ++i)
{
if (square)
for(int j = 0; j < cols_num; ++j)
{
if(mx1(i, j) != 0)
++num_non_zero_numbers;
}
else
for(int j = 0; j < cols_num - 1; ++j)
{
if(mx1(i, j) != 0)
++num_non_zero_numbers;
}
if( ! square && num_non_zero_numbers == 0 && mx1(i, cols_num - 1) != 0)
return false;
if(num_non_zero_numbers > 1)
return false;
num_non_zero_numbers = 0;
}
return true;
}
Matrix Matrix::transpose() const
{
Matrix trans(cols_num, rows_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
trans.at(j, i) = at(i, j);
return trans;
}
Fraction Matrix::trace() const
{
assert(is_square());
Fraction tr;
for(int i = 0; i < rows_num; ++i)
tr += at(i,i);
return tr;
}
size_t Matrix::rank() const
{
Matrix mx = this->gaussJordanElimination();
int rank = 0;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(mx(i, j) != 0)
{
++rank;
break;
}
return rank;
}
Fraction Matrix::determinant() const
{
assert(is_square());
if(is_zero())
return {0};
if(has_one_row_zero())
return {0};
if(rows_num == 1)
return at(0,0);
if(is_identity())
return {1};
if(is_constant())
return {0};
if(cols_num == 2)
return at(0,0) * at(1,1) - at(0,1) * at(1,0);
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
Matrix mx(*this);
vector<Fraction> row_mults;
int sign = 1;
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = mx.pivotEqualTo_one_Found ( pivot_row, pivot_col, row_with_alternative_pivot);
pivot_not_zero_found = mx.pivotNot_zero_Found(pivot_row, pivot_col, row_with_pivot_not_zero);
if (mx.at(pivot_row, pivot_col) != 1 && alternative_pivot_1_found )
{
mx.swapRows(pivot_row, row_with_alternative_pivot);
sign *= (-1);
}
else if (mx.at(pivot_row, pivot_col) == 0 && pivot_not_zero_found )
{
mx.swapRows(pivot_row, row_with_pivot_not_zero);
sign *= (-1);
}
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if (mx.at(pivot_row, col_dif_zero) != 1)
{
row_mults.push_back(mx.at(pivot_row, col_dif_zero));
mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
}
}
for (int i = pivot_row + 1; i < rows_num; ++i)
mx.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
++pivot_row;
++pivot_col;
}
Fraction det(sign);
for(int i = 0; i < rows_num; ++i)
det *= mx.at(i,i);
return accumulate(row_mults.begin(), row_mults.end(), det, multiplies());
}
Matrix Matrix::inverse() const
{
assert(is_square());
if( ! is_invertible())
throw runtime_error("\aNOT INVERTIBLE\n");
Matrix mx = *this;
Matrix inverse = Matrix::Identity(rows_num);
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
//Gauss Elimination
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = mx.pivotEqualTo_one_Found (pivot_row, pivot_col, row_with_alternative_pivot);
pivot_not_zero_found = mx.pivotNot_zero_Found(pivot_row, pivot_col, row_with_pivot_not_zero);
if (mx.at(pivot_row, pivot_col) != 1 && alternative_pivot_1_found )
{
inverse.swapRows(pivot_row, row_with_alternative_pivot);
mx.swapRows(pivot_row, row_with_alternative_pivot);
}
else if (mx.at(pivot_row, pivot_col) == 0 && pivot_not_zero_found )
{
inverse.swapRows(pivot_row, row_with_pivot_not_zero);
mx.swapRows(pivot_row, row_with_pivot_not_zero );
}
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if ( mx.at(pivot_row, col_dif_zero) != 1)
{
inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
}
}
if(number_not_zero_found)
{
for (int i = pivot_row + 1; i < cols_num; ++i)
{
inverse.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
mx.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
}
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if ( mx.at(pivot_row, col_dif_zero) != 1)
{
inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
}
}
if(number_not_zero_found)
{
for (int i = pivot_row - 1; i >= 0; --i)
{
inverse.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
mx.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
}
}
--pivot_row;
}
return inverse;
}
Matrix Matrix::adjoint() const
{
assert(is_square());
assert(cols_num > 1);
if(is_zero())
return Matrix(rows_num, cols_num);
if(is_constant())
return Matrix(rows_num, cols_num);
if(is_identity())
return *this;
Matrix cofact(rows_num, cols_num);
int r = 0, c = 0;
Matrix temp(rows_num - 1, cols_num - 1);
for(int i = 0; i < rows_num; ++i)
{
for(int j = 0; j < cols_num; ++j)
{
for(int k = 0; k < rows_num; ++k)
{
for(int h = 0; h < cols_num; ++h)
{
if (k != i && h != j)
{
temp(r, c++) = at(k, h);
if(c == cols_num - 1)
{
c = 0;
++r;
}
}
}
}
c = 0;
r = 0;
int sign;
sign = ( ( i + j ) % 2 == 0 ) ? 1 : -1;
cofact.at(i, j) = sign * temp.determinant();
}
}
return cofact.transpose();
}
Matrix Matrix::gaussJordanElimination() const
{
Matrix mx = *this;
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
///Gauss Elimination
while (pivot_row < (rows_num - 1) && pivot_row < (cols_num))
{
alternative_pivot_1_found = mx.pivotEqualTo_one_Found ( pivot_row, pivot_col,
row_with_alternative_pivot);
pivot_not_zero_found = mx.pivotNot_zero_Found(
pivot_row, pivot_col, row_with_pivot_not_zero);
if (mx.at( pivot_row, pivot_col) != 1 && alternative_pivot_1_found )
{
mx.swapRows(pivot_row, row_with_alternative_pivot);
}
else if (mx.at( pivot_row, pivot_col) == 0 && pivot_not_zero_found )
{
mx.swapRows( pivot_row, row_with_pivot_not_zero );
}
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.at(pivot_row, col_dif_zero) ) != 1)
{
mx.changePivotTo_one(pivot_row,
mx.at(pivot_row, col_dif_zero) );
}
}
if(number_not_zero_found)
{
for(int i = pivot_row + 1; i < rows_num; ++i)
{
mx.zeroOutTheColumn( i, pivot_row, mx.at(i, col_dif_zero));
}
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
if ( mx.at(pivot_row, col_dif_zero) != 1)
{
mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
}
if(number_not_zero_found)
for (int i = pivot_row - 1; i >= 0; --i)
mx.zeroOutTheColumn(i, pivot_row, mx.at(i, col_dif_zero));
--pivot_row;
}
return mx;
}
Matrix Matrix::gaussElimination() const
{
Matrix mx = *this;
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
///Gauss Elimination
while (pivot_row < (rows_num - 1) && pivot_row < (cols_num) )
{
alternative_pivot_1_found = mx.pivotEqualTo_one_Found ( pivot_row, pivot_col,
row_with_alternative_pivot);
pivot_not_zero_found = mx.pivotNot_zero_Found(
pivot_row, pivot_col, row_with_pivot_not_zero);
if (mx.at( pivot_row, pivot_col) != 1 && alternative_pivot_1_found )
{
mx.swapRows(pivot_row, row_with_alternative_pivot);
}
else if (mx.at( pivot_row, pivot_col) == 0 && pivot_not_zero_found )
{
mx.swapRows( pivot_row, row_with_pivot_not_zero );
}
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.at(pivot_row, col_dif_zero) ) != 1)
{
mx.changePivotTo_one(pivot_row,
mx.at(pivot_row, col_dif_zero) );
}
}
if(number_not_zero_found)
{
for(int i = pivot_row + 1; i < rows_num; ++i)
{
mx.zeroOutTheColumn( i, pivot_row, mx.at(i, col_dif_zero));
}
}
++pivot_row;
++pivot_col;
}
int col_dif_zero;
number_not_zero_found = mx.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
if ( mx.at(pivot_row, col_dif_zero) != 1)
{
mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));
}
return mx;
}
vector<Fraction> Matrix::main_diagonal()
{
assert(is_square());
vector<Fraction> diag;
for(int i = 0; i < rows_num; ++i)
diag.push_back(at(i,i));
return diag;
}
vector<Fraction> Matrix::secondary_diagonal()
{
assert(is_square());
vector<Fraction> diag;
for(int i = 0, j = rows_num - 1; i < rows_num; ++i, --j)
diag.push_back(at(i,j));
return diag;
}
void Matrix::swapRows( int row1, int row2)
{
for (int i = 0; i < cols_num; i++ )
std::swap( at(row1,i ), at(row2, i) );
}
bool Matrix::pivotEqualTo_one_Found( int pivot_row, int pivot_col, int& alternative_pivot_row )
{
for (int i = pivot_row + 1; i < rows_num; ++i)
{
if(at(i, pivot_col) == 1)
{
alternative_pivot_row = i;
return true;
}
}
return false;
}
bool Matrix::pivotNot_zero_Found(int pivot_row, int pivot_col,int& col_dif_zero )
{
for (int i = pivot_row + 1; i < rows_num; ++i)
if(at(i, pivot_col) != 0)
{
col_dif_zero = i;
return true;
}
return false;
}
bool Matrix::firstNumberNot_zero(int row_num, int& num_coluna_num_dif_zero)
{
for (int i = 0; i < cols_num; ++i)
if (at(row_num, i) != 0)
{
num_coluna_num_dif_zero = i;
return true;
}
return false;
}
void Matrix::changePivotTo_one( int row_num, Fraction constant)
{
for(int i = 0; i < cols_num; ++i)
if (at(row_num, i).num != 0)
at(row_num, i) = (at(row_num, i) / constant);
}
void Matrix::zeroOutTheColumn( int row_num, int num_pivot_row, Fraction constant)
{
for(int i = 0; i < cols_num; ++i)
at(row_num, i) = at(row_num, i) - (constant * at(num_pivot_row, i));
}
}// L_Algebra namespace
</code></pre>
<p>LA_Vector.h</p>
<pre><code>#ifndef LA_VECTOR_H
#define LA_VECTOR_H
#include "Fraction.h"
#include "Matrix.h"
#include <initializer_list>
#include <deque>
#include <ostream>
namespace L_Algebra
{
class Vector
{
std::deque<Fraction> data;
Fraction& at(std::size_t i)
{
return data.at(i);
}
const Fraction& at(std::size_t i) const
{
return data.at(i);
}
void push_back(Fraction n)
{
data.push_back(n);
}
friend std::vector<Vector> null_space(Matrix mx);
friend std::vector<Vector> null_space_(Matrix mx);
public:
Vector() = default;
Vector(std::vector<int> d)
{
assert(d.size() > 0);
for(auto const &e: d)
data.push_back(e);
}
Vector(std::deque<int> d)
{
assert(d.size() > 0);
for(auto const &e: d)
data.push_back(e);
}
Vector(std::vector<Fraction> d)
{
assert(d.size() > 0);
for(auto const &e: d)
data.push_back(e);
}
Vector(std::deque<Fraction> d) : data(d)
{
assert(data.size() > 0);
}
Vector(int d) : data(d, 0)
{
assert(data.size() > 0);
}
Vector(int d, long long int n) : data(d, n)
{
assert(data.size() > 0);
}
Vector(std::initializer_list<Fraction> values) : data(values)
{
assert(data.size() > 0);
}
friend std::ostream& operator<< (std::ostream& os, const Vector& lav);
explicit operator bool() const
{
return dimension() != 0;
}
bool operator==(const Vector& lav) const
{
return data == lav.data;
}
bool operator!=(const Vector& lav) const
{
return data != lav.data;
}
Fraction& operator[](size_t i)
{
return data.at(i);
}
const Fraction& operator[](size_t i) const
{
return data.at(i);
}
Vector operator+(const Vector& lav) const;
Vector operator-(const Vector& lav) const;
Vector operator->*(const Vector& lav) const; // vectorial product
Fraction operator*(const Vector& lav) const; // dot product
Vector& operator+=(const Vector& lav);
Vector& operator-=(const Vector& lav);
friend Vector operator*(const Vector& mx, Fraction n);
friend Vector operator*(Fraction n, const Vector& mx);
std::size_t dimension() const
{
return data.size();
}
Fraction norm_Power2() const;
double norm() const;
};
Vector proj(Vector u, Vector a);
Vector proj_orthogonal(Vector u, Vector a);
bool is_orthogonal(std::initializer_list<Vector> vec_set);
bool is_linearly_dependent(std::initializer_list<Vector> vec_set);
bool is_linearly_dependent(std::initializer_list<Matrix> matrices_set);
bool is_linearly_independent(std::initializer_list<Vector> vec_set);
bool is_linearly_independent(std::initializer_list<Matrix> matrices_set);
bool is_linear_combination(std::initializer_list<Vector> vec_set, Vector vec);
bool is_linear_combination(std::initializer_list<Matrix> matrices_set, Matrix mx);
bool spans_space(std::initializer_list<Vector> vec_set);
bool spans_space(std::initializer_list<Matrix> matrix_set);
bool is_in_span(Vector vec, std::initializer_list<Vector> span);
bool is_basis(std::initializer_list<Vector> vec_set);
bool is_basis(std::initializer_list<Matrix> matrices_set);
Vector change_basis(Vector vec, std::initializer_list<Vector> basis_from, std::initializer_list<Vector> basis_to);
Vector change_basis(Vector vec_in_standard_basis, std::initializer_list<Vector> destination_basis);
std::vector<Vector> row_space_basis(Matrix mx);
std::vector<Vector> column_space_basis(Matrix mx);
std::vector<Vector> null_space(Matrix mx);
std::size_t row_space_dim(Matrix mx);
std::size_t column_space_dim(Matrix mx);
std::size_t nullity(Matrix mx);
Vector coordinate_vector_relative_to_basis(std::initializer_list<Vector> basis, Vector vec);
Vector vector_with_coordinate_relative_to_basis(std::initializer_list<Vector> basis, Vector coordinate_vec);
Matrix vectorsToMatrix(std::vector<Vector>vec_set);
Matrix turnMatricesIntoLinearCombination(std::vector<Matrix>matrix_set);
/*
Vector rowOfMatrixToVector(Matrix mx, int row);
Vector columnOfMatrixToVector(Matrix mx, int column);
*/
} // L_Algebra namespace
#endif // LA_VECTOR_H
</code></pre>
<p>LA_Vector.cpp</p>
<pre><code>#include "LA_Vector.h"
#include <iostream>
#include <math.h>
#include <assert.h>
#include <set>
#include <deque>
#include <algorithm>
using namespace std;
namespace L_Algebra
{
Matrix transitionMatrix(Matrix from, Matrix to)
{
assert(from.size() == to.size());
int rows_num = to.rows();
int cols_num = to.cols();
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
//Gauss Elimination
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = to.pivotEqualTo_one_Found (pivot_row, pivot_col, row_with_alternative_pivot);
pivot_not_zero_found = to.pivotNot_zero_Found(pivot_row, pivot_col, row_with_pivot_not_zero);
if (to.at(pivot_row, pivot_col) != 1 && alternative_pivot_1_found )
{
from.swapRows(pivot_row, row_with_alternative_pivot);
to.swapRows(pivot_row, row_with_alternative_pivot);
}
else if (to.at(pivot_row, pivot_col) == 0 && pivot_not_zero_found )
{
from.swapRows(pivot_row, row_with_pivot_not_zero);
to.swapRows(pivot_row, row_with_pivot_not_zero );
}
int col_dif_zero;
number_not_zero_found = to.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if ( to.at(pivot_row, col_dif_zero) != 1)
{
from.changePivotTo_one(pivot_row, to.at(pivot_row, col_dif_zero));
to.changePivotTo_one(pivot_row, to.at(pivot_row, col_dif_zero));
}
}
if(number_not_zero_found)
{
for (int i = pivot_row + 1; i < cols_num; ++i)
{
from.zeroOutTheColumn(i, pivot_row, to.at(i, col_dif_zero));
to.zeroOutTheColumn(i, pivot_row, to.at(i, col_dif_zero));
}
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
number_not_zero_found = to.firstNumberNot_zero(pivot_row, col_dif_zero);
if(number_not_zero_found)
{
if ( to.at(pivot_row, col_dif_zero) != 1)
{
from.changePivotTo_one(pivot_row, to.at(pivot_row, col_dif_zero));
to.changePivotTo_one(pivot_row, to.at(pivot_row, col_dif_zero));
}
}
if(number_not_zero_found)
{
for (int i = pivot_row - 1; i >= 0; --i)
{
from.zeroOutTheColumn(i, pivot_row, to.at(i, col_dif_zero));
to.zeroOutTheColumn(i, pivot_row, to.at(i, col_dif_zero));
}
}
--pivot_row;
}
return from;
}
bool is_consistent(const Matrix& mx)
{
int rows_num = mx.rows();
int cols_num = mx.cols();
Matrix mx1 = mx.gaussJordanElimination();
bool square = mx.is_square();
int num_non_zero_numbers = 0;
for(int i = 0; i < rows_num; ++i)
{
if (square)
for(int j = 0; j < cols_num; ++j)
{
if(mx1(i, j) != 0)
++num_non_zero_numbers;
}
else
for(int j = 0; j < cols_num - 1; ++j)
{
if(mx1(i, j) != 0)
++num_non_zero_numbers;
}
if(num_non_zero_numbers > 1)
return false;
if( ! square && num_non_zero_numbers == 0 && mx1(i, cols_num - 1) != 0)
return false;
num_non_zero_numbers = 0;
}
return true;
}
Matrix vectorsToMatrix(std::vector<Vector>vec_set)
{
assert(vec_set.size() > 0);
int len = vec_set.size();
for(int i = 0; i < len; ++i)
assert(vec_set[i].dimension() == vec_set[0].dimension());
int rows_num = vec_set[0].dimension();
int cols_num = len;
Matrix mx(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
{
mx(i, j) = vec_set.at(j)[i];
}
return mx;
}
Matrix turnMatricesIntoLinearCombination(std::vector<Matrix>matrix_set)
{
assert(matrix_set.size() > 0);
int len = matrix_set.size();
for(int i = 0; i < len; ++i)
assert(matrix_set[i].size() == matrix_set[0].size());
/*
int rows_num = matrix_set[0].size();
int cols_num = len;
int r = matrix_set[0].rows();
int c = matrix_set[0].cols();
Matrix m(rows_num, cols_num);
Vector lav(r * c);
size_t vec_lav_size = cols_num;
vector<Vector> vec_lav(vec_lav_size, r * c);
// pass the values from the set of matrices to a set of la_vectors
int ind = 0;
for(size_t h = 0; h < vec_lav_size; ++h)
{
for(int i = 0; i < r; ++i)
for(int j = 0; j < c; ++j)
vec_lav.at(h)[ind++] = matrix_set.at(h)(i, j);
ind = 0;
}
transform the values from the set of the matrices into a new matrix;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
m(i, j) = vec_lav.at(j)[i];
*/
int rows_num = matrix_set[0].size();
int cols_num = len;
int r = matrix_set[0].rows();
int c = matrix_set[0].cols();
Matrix m(rows_num, cols_num);
for(int i = 0; i < cols_num; ++i)
{
int id = 0;
for(int x = 0; x < r; ++x)
{
for(int y = 0; y < c; ++y)
{
m(id++, i) = matrix_set[ i ](x, y);
}
}
}
return m;
}
Vector rowOfMatrixToVector(const Matrix& mx, int row)
{
assert(row <= mx.rows());
int cols_num = mx.cols();
Vector v(cols_num);
for(int i = 0; i < cols_num; ++i)
v[ i ] = mx(row, i);
return v;
}
Vector columnOfMatrixToVector(const Matrix& mx, int column)
{
assert(column <= mx.cols());
int rows_num = mx.rows();
Vector v(rows_num);
for(int i = 0; i < rows_num; ++i)
v[ i ] = mx(i, column);
return v;
}
ostream& operator<< (ostream& os, const Vector& lav)
{
os << "(";
for(auto el : lav.data)
os << el << ", ";
if(lav.data.empty())
os << " )";
else
os << "\b\b \b" << ")";
return os;
}
Vector Vector::operator+(const Vector& lav) const
{
size_t len = data.size();
assert(len == lav.data.size());
Vector addition;
addition.data.resize(len, 0);
for(size_t i = 0; i < len; ++i)
addition[i] = at(i) + lav[i];
return addition;
}
Vector& Vector::operator+=(const Vector& lav)
{
return *this = *this + lav;
}
Vector Vector::operator-(const Vector& lav) const
{
size_t len = data.size();
assert(len == lav.data.size());
Vector subtraction;
subtraction.data.resize(data.size(), 0);
for(size_t i = 0; i < len; ++i)
subtraction[i] = at(i) - lav[i];
return subtraction;
}
Vector& Vector::operator-=(const Vector& lav)
{
return *this = *this - lav;
}
Fraction Vector::operator*(const Vector& lav) const // dot product
{
size_t len = data.size();
assert(len == lav.data.size());
Fraction dot_prod;
for(size_t i = 0; i < len; ++i)
dot_prod += at(i) * lav[i];
return dot_prod;
}
// vectorial product
Vector Vector::operator->*(const Vector& lav) const
{
size_t len = data.size();
assert( (len == lav.data.size()) && len == 3);
return {at(1) * lav.at(2) - at(2) * lav.at(1),
- (at(2) * lav.at(0) - at(0) * lav.at(2)),
at(0) * lav.at(1) - at(1) * lav.at(0) };
}
Vector operator*(const Vector& lav, Fraction n)
{
Vector mult;
mult.data.resize(lav.data.size(), 0);
int i = 0;
for( auto el : lav.data)
mult.at(i++) = el * n;
return mult;
}
Vector operator*(Fraction n, const Vector& lav)
{
Vector mult;
mult.data.resize(lav.data.size(), 0);
int i = 0;
for( auto el : lav.data)
mult.at(i++) = el * n;
return mult;
}
double Vector::norm() const
{
Fraction n;
size_t len = dimension();
for(size_t i = 0; i < len; ++i)
n += pow_fract(at(i), 2);
return sqrt(n.to_double());
}
Fraction Vector::norm_Power2() const
{
Fraction n;
size_t len = dimension();
for(size_t i = 0; i < len; ++i)
n += pow_fract(at(i), 2);
return n;
}
bool is_orthogonal(std::initializer_list<Vector> vec_set)
{
assert(vec_set.size() > 1);
std::vector<Vector> vec(vec_set);
size_t len = vec.size();
for(size_t i = 0; i < len; ++i )
assert(vec.at(i).dimension() == vec.at(0).dimension());
for( size_t i = 0; i < len - 1; ++i)
for( size_t j = i + 1; j < len; ++j)
if (vec.at(i) * vec.at(j) == 0)
return true;
return false;
}
Vector proj(Vector u, Vector a)
{
return Fraction(u*a, a.norm_Power2()) * a;
}
Vector proj_orthogonal(Vector u, Vector a)
{
return u - proj(u, a);
}
bool is_linearly_dependent(std::initializer_list<Vector> vec_set)
{
Matrix mx = vectorsToMatrix(vec_set).gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
int num_non_zero_numbers = 0;
for(int i = 0; i < rows_num; ++i)
{
for(int j = 0; j < cols_num; ++j)
{
if(mx(i, j) != 0)
++num_non_zero_numbers;
}
if(num_non_zero_numbers > 1)
return true;
num_non_zero_numbers = 0;
}
return false;
}
bool is_linearly_dependent(initializer_list<Matrix> matrices_set)
{
assert(matrices_set.size() > 0);
vector<Matrix> vecs(matrices_set);
int len = vecs.size();
for(int i = 0; i < len; ++i)
assert(vecs[i].size() == vecs[0].size() && vecs[i].size() > 0);
int r = vecs[0].rows();
int c = vecs[0].cols();
Matrix mx(r, c);
vecs.push_back(mx);
Matrix m = turnMatricesIntoLinearCombination(vecs);
if( is_consistent(m))
return false;
else
return true;
}
bool is_linearly_independent(std::initializer_list<Vector>vec_set)
{
return ! is_linearly_dependent(vec_set);
}
bool is_linearly_independent(initializer_list<Matrix> matrices_set)
{
return ! is_linearly_dependent(matrices_set);
}
bool is_linear_combination(std::initializer_list<Vector> vec_set, Vector vec)
{
vector<Vector> vecs(vec_set);
vecs.push_back(vec);
Matrix mx = vectorsToMatrix(vecs);
if( ! is_consistent(mx))
return false;
mx = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
Vector results = columnOfMatrixToVector(mx, cols_num - 1);
Vector combination(rows_num);
for(int i = 0; i < rows_num; ++i)
{
for(int j = 0; j < cols_num - 1; ++j)
combination[i] += results[j] * vecs.at(j)[i];
}
if(vec == combination)
return true;
else
return false;
}
bool is_linear_combination(std::initializer_list<Matrix> matrices_set, Matrix mx)
{
assert(matrices_set.size() > 0);
vector<Matrix> vecs(matrices_set);
vecs.push_back(mx);
Matrix m = turnMatricesIntoLinearCombination(vecs);
int cols_num = m.cols();
vector<Vector> vec_lav(cols_num);
for(int i = 0; i < cols_num; ++i)
vec_lav[i] = columnOfMatrixToVector(m, i);
if( ! is_consistent(m))
return false;
m = m.gaussJordanElimination();
Vector results = columnOfMatrixToVector(m, cols_num - 1);
Vector combination(m.rows());
for(int i = 0; i < cols_num - 1; ++i)
combination += results[i] * vec_lav.at(i);
Vector lav = vec_lav[vec_lav.size() - 1];
if(lav == combination)
return true;
else
return false;
}
bool is_basis(std::initializer_list<Vector> vec_set)
{
assert(vec_set.size() > 0);
vector<Vector> vec(vec_set);
int len = vec.size();
for(int i = 0; i < len; ++i)
assert(vec[i].dimension() == vec[0].dimension());
if(vec.size() != vec[0].dimension())
return false;
return ! is_linearly_dependent(vec_set);
}
bool is_basis(std::initializer_list<Matrix> matrices_set)
{
return ! is_linearly_dependent(matrices_set);
}
Vector change_basis(Vector vec, std::initializer_list<Vector> basis_from,
std::initializer_list<Vector> basis_to)
{
assert(basis_to.size() == basis_from.size());
assert(vec.dimension() == basis_from.size());
Matrix from = vectorsToMatrix(basis_from);
Matrix to = vectorsToMatrix(basis_to);
Matrix transition_matrix = transitionMatrix(from, to);
int vec_dimension = vec.dimension();
Matrix vec_matrix(vec_dimension, 1);
for(int i = 0; i < vec_dimension; ++i)
vec_matrix(i,0) = vec[i];
Matrix new_basis_vec_matrix = transition_matrix * vec_matrix;
Vector vec_in_new_basis(vec_dimension);
for(int i = 0; i < vec_dimension; ++i)
vec_in_new_basis[i] = new_basis_vec_matrix(i,0);
return vec_in_new_basis;
}
Vector change_basis(Vector vec_in_standard_basis, std::initializer_list<Vector> destination_basis)
{
return coordinate_vector_relative_to_basis(destination_basis, vec_in_standard_basis);
}
bool spans_space(std::initializer_list<Vector> vec_set)
{
return ! is_linearly_dependent(vec_set);
}
bool spans_space(std::initializer_list<Matrix> matrix_set)
{
return ! is_linearly_dependent(matrix_set);
}
bool is_in_span(Vector vec, std::initializer_list<Vector> span)
{
return is_linear_combination(span, vec);
}
Vector coordinate_vector_relative_to_basis(std::initializer_list<Vector> basis,
Vector vec)
{
assert(basis.size() == vec.dimension());
vector<Vector> vecs(basis);
vecs.push_back(vec);
Matrix mx = vectorsToMatrix(vecs);
mx = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
if(! is_consistent(mx))
throw runtime_error("the basis is linearly dependent");
Vector coordinate_vector(rows_num);
for(int i = 0; i < rows_num; ++i)
coordinate_vector[i] = mx(i, cols_num - 1);
return coordinate_vector;
}
Vector vector_with_coordinate_relative_to_basis(initializer_list<Vector> basis,
Vector coordinate_vec)
{
assert(basis.size() > 0);
assert(coordinate_vec.dimension() == basis.size());
vector<Vector> vecs(basis);
int len = vecs.size();
for(int i = 0; i < len; ++i)
assert(vecs[i].dimension() == vecs[0].dimension());
assert(coordinate_vec.dimension() == vecs[0].dimension());
size_t basis_size = basis.size();
size_t vec_size = vecs[0].dimension();
Vector vec(vec_size);
for(size_t i = 0; i < basis_size; ++i)
for(size_t j = 0; j < vec_size; ++j)
vec[i] += coordinate_vec[j] * vecs.at(j)[i];
return vec;
}
std::vector<Vector> row_space_basis(Matrix mx)
{
mx = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
vector<Vector> space_basis;
Vector lav(cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(mx(i, j) != 0)
{
for(int j = 0; j < cols_num; ++j)
lav[j] = mx(i, j);
space_basis.push_back(lav);
break;
}
return space_basis;
}
vector<Vector> column_space_basis(Matrix mx)
{
Matrix m = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
vector<Vector> space_basis;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
{
Vector temp(rows_num);
if(m(i, j) != 0)
{
for(int k = 0; k < rows_num; ++k)
temp[ k ] = mx(k, j);
space_basis.push_back(temp);
break;
}
}
return space_basis;
}
vector<Vector> null_space(Matrix mx)
{
Matrix m = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
vector<int> pivot_cols;
vector<Vector> free_variables(cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(m(i, j) != 0)
{
// keeps all cols numbers so it is guaranteed that the column that contains a pivot won't
// be used for the null space
pivot_cols.push_back(j);
break;
}
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
{
if(m(i,j) != 0)
{
for(int k = 0; k < cols_num; ++k)
{
// the j'th column is the one with pivot so it can not be used for the null space
// meaning that it has to be above or below
// if it is below it means that the k'th column might be one with free variable,
// it will be checked, if it is free it will be added zero because to get to the
// j'th column it had to get past only zeroes
if( k < j )
{
// starting from the second row, before immediately adding 0(zero), it will be checked
// whether the column is one that contains a pivot, in case it does the 0 won't be added
if(i > 0)
{
if(find(pivot_cols.cbegin(), pivot_cols.cend(), k) == pivot_cols.cend())
free_variables[j].push_back(0);
}
else
free_variables[j].push_back(0);
}
else if(k > j && find(pivot_cols.cbegin(), pivot_cols.cend(), k) == pivot_cols.cend())
{
free_variables[j].push_back( -m(i, k) );
}
}
break;
}
}
int num_vectors = free_variables.size();
int dimension;
// get the dimension of the vector that will be of the null space
for(int i = 0; i < num_vectors; ++i)
if (free_variables[i].dimension() != 0)
{
dimension = free_variables[i].dimension();
break;
}
// add the Identity Matrix to the rows in the new matrix which correspond to the 'free' columns
// in the original matrix, making sure the number of rows equals the number of columns in the
// original matrix (otherwise, we couldn't multiply the original matrix against our new matrix)
int ind = 0;
for(int i = 0; i < num_vectors; ++i)
{
if(free_variables[i].dimension() == 0)
{
for(int j = 0; j < dimension; ++j)
if(j == ind)
free_variables[i].push_back(1);
else
free_variables[i].push_back(0);
++ind;
}
}
vector<Vector> space_basis(dimension, num_vectors);
for(int i = 0; i < dimension; ++i)
for(int j = 0; j < num_vectors; ++j)
space_basis.at(i)[ j ] = free_variables.at(j)[i];
return space_basis;
}
std::size_t column_space_dim(Matrix mx)
{
mx = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
int dimension = 0;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(mx(i, j) != 0)
{
++dimension;
break;
}
return dimension;
}
std::size_t row_space_dim(Matrix mx)
{
mx = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
int dimension = 0;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(mx(i, j) != 0)
{
++dimension;
break;
}
return dimension;
}
std::size_t nullity(Matrix mx)
{
Matrix m = mx.gaussJordanElimination();
int rows_num = mx.rows();
int cols_num = mx.cols();
vector<int> pivot_cols;
vector<Vector> free_variables(cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(m(i, j) != 0)
{
pivot_cols.push_back(j);
break;
}
int dimension = 0;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(m(i,j) != 0)
{
for(int k = 0; k < cols_num; ++k)
{
if(k < j )
{
if(i > 0)
{
if(find(pivot_cols.cbegin(), pivot_cols.cend(), k) == pivot_cols.cend())
++dimension;
}
else
++dimension;
}
else if(k > j && find(pivot_cols.cbegin(), pivot_cols.cend(), k) == pivot_cols.cend())
++dimension;
}
return dimension;
}
return 0;
}
}// L_Algebra namespace
</code></pre>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <math.h>
//#include <boost/timer/timer.hpp>
#include "Matrix.h"
#include "LA_Vector.h"
#include <vector>
#include <boost/format.hpp>
using namespace L_Algebra;
using namespace std;
int main()
{
vector<int> vec;
vec.push_back(76);
vec.push_back(76);
vec.push_back(76);
vec.push_back(76);
vec.push_back(76);
Vector vv(vec);
int sd = 87, ds = 56;
Fraction ffr = 10;
Matrix b(3,4,3);
Matrix c{5,5,3};
Matrix a = {{-5, 5, -6, 1, 0}, {0, -5, 10, -3, 3}, {1, 11, 6, 1, 7}, {4, 5, -9, 9, -7}, {-5, 10, 0, -4, 4}};
Matrix s = {{5, 5, -6, 1, 0}, {3, 4, 5, 7, 8}, {1, 11, 6, 1, 7}, {4, 5, -9, 9, -7}, {5, 10, 0, -4, 4}};
Matrix s1 = {{5, 5, -6, 1, 0}, {3, 4, 5, 7, 8}, {1, 11, 6, 1, 7}, {4, 5, -9, 9, -7}, {5, 10, 0, -4, 4}};
cout << a * 23;
Matrix sw = {{-5}};
Matrix d = {{1, 0, 2}, {2, 3, 7}};//, {-2, 2, 1, 7}, {-2, 3, 4, 1} };
Matrix e = {{1, 1}, {0, 0} };
Matrix g = {{0, 1}, {1, 0} };
Matrix h = {{1, 0}, {0, 1} };
Matrix i = {{1, 1}, {0, 1 } };
// cout << turnMatricesIntoLinearCombination({e, g, h, i});
try
{
// cout << boost::format("%1% %3%") % 36 % 77 % 34;
}
catch (exception& e)
{
cout << e.what();
}
Matrix f = { {4, 0, 7, 6}, {1, 0, 7, 7}, {8, 0, 8, 8}};//, {-1, -4, -5, 0} };
Matrix ff = { {4, 2, 7, 6, 5, 6}, {1, 7, 7, 7, 8, 0}, {8, 2, 8, 8, 9, 1}, {-1, -4, -5, 0, 1, 5} };
Matrix mx1 = { {4, 1, 3, 1}, {3, 1, 3, 0}, {5, 1, 4, 1} };
Matrix mx11 = { {1, 4, 8, 2}, {1, 4, 4, 9}, {1, 4, 4, 3}, {1, 4, 5, 5} };
// cout << f << endl << endl;
// vector<Vector> test = null_space(mx11);
//cout << f.gaussJordanElimination();
// for(auto e : test)
// cout << e << endl;
//
// cout << endl << nullity(f);
b(0,2) = 4;
b(1,2) = 5;
b(1,3) = 2;
b(2,0) = -8;
b(2,3) = 9;
b(0,0) = 1;
b(0,1) = 2;
//cout << mx11 << endl << endl;
//vector<Vector> test3 = null_space(mx11);
// for(auto e : test3)
// cout << e << endl;
// cout << mx11.determinant();
/*
Vector lav1 = {1, 2, 1};
Vector lav2 = {2, 9, 0};
Vector lav = {3, 3, 4};
Vector lav1 = {1, 5, 3};
Vector lav2 = {-2, 6, 2};
Vector lav = {3, -1, 1};
Vector lav1 = {1, 2, -1};
Vector lav2 = {6, 4, 2};
Vector lav3 = {9, 2, 7};
Vector lav1 = {3, 6, -9, -3};
Vector lav2 = {6, -2, 5, 1};
Vector lav3 = {-1, -2, 3, 1};
Vector lav4 = {2, 3, 0, -2, 0};
Vector lav3 = {3, 2, 1};
*/
// cout << p.gaussJordanElimination();
Matrix mx({ {3, 1, 1, 1}, {5, 2, 3, -2}});//,{-1, -2, 3, 1}});
// cout << mx.gaussJordanElimination();
initializer_list<initializer_list<Fraction>> A = { {1, 3}, {1, -2} };
initializer_list<Vector> B = { {3, 5}, {1, 2} };
initializer_list<Vector> C = {{1, 0, 0, 0, }, {-2, 1, 0, 0, }, {5, 3, 0, 0}, {0, 0, 1, 0}, {3, 0, 0, 0} };
// Vector vec = {3, 2};
Matrix gt(A);
Matrix wz = { {0, 0, 0, 2, 9, 6}, {0, 0, 0, 4, 5, 8} };
Matrix wzf = { {3, 2, 9, 2, 9, 6}, {6, 4, 5, 4, 5, 8} };
Matrix z = { {1, 3, -2, 0, 2, 0}, {2, 6, -5, -2, 4, -3}, {0, 0, 5, 10, 0, 15}, {2, 6, 0, 8, 4, 18} };
// cout << gt;
Matrix dz = { {4, 1, 5, 1, 7, 8, 2}, {6, 3, 3, 5, 2, 3, 1}};//, {0, 0, 5, 10, 0, 15}, {2, 6, 0, 8, 4, 18} };
Matrix fz = { {1, 3, 4, 4}, {2, 3, 5, 4}, {9, 1, 7, 2}};// {-1, -4, -5, 0} };
Matrix tfz = { {1, 3, 4, 4, 1}, {2, 3, 5, 4, 5}, {9, 1, 7, 2, 3}};// {-1, -4, -5, 0} };
Matrix khan = { {1, 1, 2, 3, 2}, {1, 1, 3, 1, 4} };
Matrix kha = { {2, 0, 2}, {-1, 0, -1}, {-1, 0, -1} };
// boost::timer::cpu_timer timer;
// wz.gaussJordanElimination();
// timer.stop();
// cout << timer.format();
Vector lav1 = {0, -2, 2};
Vector lav2 = {1, 3, -1};
Vector lav3 = {9, 0, 0};
Vector lav4 = {4, 0, 2};
Vector v = { 0, 0, 0};
Matrix p = { {4, 0}, {-2, -2} };
Matrix ph = { {1, -1}, {2, 3} };
Matrix ph1 = { {0, 2}, {1, 4} };
Matrix ph2 = { {-1, 5}, {7, 1} };
Matrix ph21 = { {6, -8}, {-1, -8} };
Matrix ph3 = { {6, 0}, {3, 8} };
Matrix ph0 = { {0, 0}, {0, 0} };
Fraction fr1(27, 17);
Fraction fr2(43, 34);
Fraction fr3(-29, 306);
Matrix mcf(3, 3, {2, 3, 5, 6, 4, 5, 5, 8, 9});
double db = 10.0 / 3;
Fraction frt;
// cout << frt;
// cout << s << endl;
try
{
// cout << s.main_diagonal() << endl;
// cout << s.secondary_diagonal() << endl;
//cout << coordinate_vector_relative_to_basis({ {0,1,0}, { {-4,5}, 0, {3,5}, }, { {3,5}, 0, {4,5} } }, {1,1,1});
//cout << change_basis(vec, A, B);
//cout << kha.gaussJordanElimination() << endl;
//vector<Vector> v = null_space(kha);
// cout << coordinate_vector_relative_to_basis({ lav1, lav2,lav3}, lav4);
// for(auto e : v)
// cout << e << endl;
// cout << endl << khan.rank();
}
catch(exception& e)
{
cout << e.what();
}
//cout << lav2 * (lav ->* lav1);
}
</code></pre>
<p>What I am looking for is reviews on every possible aspect: C++ best practices (taking into account C++20), algorithms used, code simplicity/readability/organization, potential bugs, tips, tricks, warnings etc etc.</p>
<p>Worthy to note that I have tested every functionality as best as I could which I am quite sure it is not good enough.</p>
|
[] |
[
{
"body": "<p>I think I would change the <code>Fraction::simplify</code>, personally. I would maybe let it be a static class method that took a <code>Fraction</code> object and returned it's reduced representation without modifying the original object.</p>\n<p>There are times when it might be useful to calculate a proportion without clobbering the original object, such as when calculating the <a href=\"http://mirror.centos.org/centos/7/os/x86_64/\" rel=\"nofollow noreferrer\">Binomial proportion confidence interval</a>, for example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T01:55:11.490",
"Id": "250732",
"ParentId": "250730",
"Score": "1"
}
},
{
"body": "<p>Some things to consider:</p>\n<ol>\n<li><p>Fundamental types do not have move constructors, so <code>num(std::move(_num))</code> is just the equivalent of <code>num(_num)</code></p>\n</li>\n<li><p>If you're not doing template code, move definitions out of header files. This can cause naming conflicts if multiple files include Fraction.h</p>\n</li>\n<li><p>Having a <code>++</code> and <code>--</code> operator for a Fraction doesn't make sense. What does it mean to increment a fraction. It seems that you've chosen to do frac + 1 but that if I wanted (num+1)/den</p>\n</li>\n<li><p>You can write <code>num = num / n;</code> as <code>num /= n;</code> which behaves like <code>+=</code> or <code>-=</code></p>\n</li>\n<li><p>For <code>-</code> operator, you call your intermediate variable sub, but in <code>+</code> and <code>*</code> operator you call them addition and multiplication. Keep it consistent. Also in <code>/</code> operator, you call the result sub when I think you meant division.</p>\n</li>\n<li><p>Your Matrix only takes a <code>std::initializer_list<></code>. What is somebody wants to pass a <code>std::vector<></code>? It seems that they would be out of luck</p>\n</li>\n<li><p>Use a for each loop instead of iterators in your Matrix constructor:</p>\n<pre><code>for (const auto& row: values)\n{\n assert(row.length() != 0);\n}\n</code></pre>\n</li>\n</ol>\n<p>There's probably some other things, but that was what I was able to find</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:54:03.673",
"Id": "493533",
"Score": "0",
"body": "In 2, do you mean I should not define any method inside the class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-19T22:01:53.273",
"Id": "493627",
"Score": "0",
"body": "@HBatalha, you declare them in your class, you should define them in your cpp files. There's a weird mixing that is happening right now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:20:07.840",
"Id": "250760",
"ParentId": "250730",
"Score": "5"
}
},
{
"body": "<h1>How long is a <code>long long</code>?</h1>\n<p>It depends on the CPU architecture and the operating system how long a <code>long long</code> really is. It might help to be more specific, and specify that a <code>Fraction</code> is a fraction of 64-bit integers, and then use <code>int64_t</code>. Also, instead of writing <code>long long</code>, consider creating a type alias:</p>\n<pre><code>using Integer = long long;\n</code></pre>\n<p>And use that everywhere. That makes changing the type of the integers used very easy.</p>\n<h1>Unnecessary calls to <code>std::move</code></h1>\n<p>There is no need to use <code>std::move</code> when copying an integer into another integer, it just clutters the code. Just write:</p>\n<pre><code>Fraction(Integer _num = 0, Integer _den = 1) : num{_num}, den{_den}\n</code></pre>\n<h1>Avoid names starting with an underscore</h1>\n<p>There are certain <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">rules for using underscores in identifiers</a>. While the above use is actually OK, I recommend you don't start any name with an underscore, as that is an easier rule to remember. You also don't need the underscores in the above function definition, you can write:</p>\n<pre><code>Fraction(Integer num = 0, Integer den = 1) : num{num}, den{den}\n</code></pre>\n<h1>Handling zero denominators</h1>\n<p>Your code <code>assert()</code>s that the denominator is not zero. Be aware that in release builds, <code>assert()</code> macros might be disabled. If you want to ensure you always report an error if the denominator is zero, consider throwing a <a href=\"https://en.cppreference.com/w/cpp/error/domain_error\" rel=\"nofollow noreferrer\"><code>std::domain_error</code></a>.</p>\n<p>However, consider that the following is perfectly fine code when dealing with floating point numbers:</p>\n<pre><code>float foo = 1.0 / 0.0;\n</code></pre>\n<p>The value of <code>foo</code> is well-defined in this case: it is positive infinity. You might want to support the denominator being zero. Just be aware of this inside <code>simplify()</code>, and just don't do anything if <code>den == 0</code>.</p>\n<h1>Reduce the amount of overloads you need to write</h1>\n<p>You have a lot of code duplication that can be reduced. Take for example <code>Fraction</code>'s <code>operator+</code>: you have three variants:</p>\n<pre><code>Fraction operator+(const Fraction& fr) const;\nfriend Fraction operator+(const Fraction& fr, long long n);\nfriend Fraction operator+(long long n, const Fraction& fr);\n</code></pre>\n<p>You only need to write one variant:</p>\n<pre><code>friend Fraction operator+(const Fraction& lhs, const Fraction& rhs);\n</code></pre>\n<p>Since a <code>Fraction</code> can be implicitly constructed from a single <code>long long</code>, the above statement will handle any combination of <code>long long</code> and <code>Fraction</code> arguments.</p>\n<h1>Cast to the right type</h1>\n<p>The function <code>to_double()</code> lies and returns a <code>long double</code> instead. Note that <code>double</code> is not the same as <code>long double</code>, on x86 and x86_64 a <code>long double</code> is 80 bits instead of 64 bits, and there are even architectures where <code>long double</code> is 128 bits.</p>\n<p>The implementation of the function <code>to_float()</code> casts numerator to <code>double</code>. Why not cast it to <code>float</code> instead?</p>\n<h1>Remove unused code</h1>\n<p>There's a lot of unused code. Some of it is commented out, but for example in <code>Fraction::operator-(const Fraction &)</code>, there are two variables <code>nu</code> and <code>de</code> that are not used at all (and if they would have been they would have the wrong type).</p>\n<h1>Avoid unnecessary parentheses:</h1>\n<pre><code>return (Fraction(n) + fr);\n</code></pre>\n<p>Can be written as:</p>\n<pre><code>return Fraction(n) + fr;\n</code></pre>\n<h1>Optimize <code>pow_fract()</code></h1>\n<p>There are more optimal ways to implement integer power functions, see <a href=\"https://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int\">this StackOverflow question</a>.</p>\n<h1>Consider allowing zero size vectors and matrices</h1>\n<p>The constructors of <code>Matrix</code> and <code>Vector</code> all <code>assert()</code> that the constructor object has a non-zero size. But is it really necessary to limit that case? Most functions work perfectly well with zero-sized vectors and matrices, and you avoid the overhead of the check every time you construct an object. You only need this check in the rare cases where a function would cause a crash or undefined behaviour if the size is zero.</p>\n<h1>Use range-<code>for</code> and STL algorithms where applicable</h1>\n<p>I see a lot of old-style <code>for</code>-loops where you could have used a range-<code>for</code> or even an STL algorithm. For example, <code>Matrix::Matrix()</code> can be rewritten as:</p>\n<pre><code>Matrix::Matrix(std::initializer_list<std::initializer_list<Fraction>> values )\n{\n rows_num = values.size();\n cols_num = 0;\n\n for(auto &row: values) {\n cols_num = row.size();\n break;\n }\n\n data.reserve(rows_num * cols_num);\n\n for(auto &row: values)\n {\n assert(row.size() == cols_num);\n std::copy(row.begin(), row.end(), std::back_inserter(data));\n }\n}\n</code></pre>\n<p>As another example, <code>Matrix::operator+(const Matrix &)</code> can be written as:</p>\n<pre><code>Matrix Matrix::operator+(const Matrix& mx) const\n{\n assert(rows_num == mx.rows_num && cols_num == mx.cols_num);\n\n Matrix result(rows_num, cols_num);\n\n std::transform(data.begin(), data.end(), mx.data.begin(), result.data.begin(), std::plus);\n\n return result;\n}\n</code></pre>\n<p>Note that the result matrix is initialized unnecessarily; consider adding a (possibly private) constructor that allows creating a <code>Matrix</code> of a given size with <code>data</code> not being initialized.</p>\n<h1>Use a <code>std::vector</code> in <code>Vector</code></h1>\n<p>Why does the <code>Vector</code> class store its data in a <code>std::deque</code>? You don't need the functionality of a deque (like <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> insertion and removal at both ends), but now you pay the price in performance and storage overhead.</p>\n<h1>Reduce the number of constructors of <code>Vector</code></h1>\n<p>You have overloaded the constructor of <code>Vector</code> to handle <code>std::vector</code>s and <code>std::deque</code>s of <code>int</code>s and <code>Fraction</code>s as input. But what if I want to pass it a <code>std::array<unsigned int></code>? Surely you can see that you cannot support everything this way unless you write hundreds of overloads, and even then you will miss some cases. If you really want to handle arbitrary contains being passed to the constructor, do what the STL does in its container classes, and write a template that takes a pair of iterators, like so:</p>\n<pre><code>template<class InputIt>\nVector(InputIt first, InputIt last): data(first, last) {}\n</code></pre>\n<p>That's all there is to it. Now you can do something like:</p>\n<pre><code>std::list<unsigned long> foo{1, 2, 3, 4, 5};\nVector vec(foo.begin(), foo.end());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-18T21:50:00.583",
"Id": "493532",
"Score": "0",
"body": "Thanks for the great review, wish you got deeper into the implementations files."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T19:54:56.137",
"Id": "250763",
"ParentId": "250730",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-15T23:24:04.837",
"Id": "250730",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"library"
],
"Title": "Linear Algebra Library in C++;"
}
|
250730
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.