body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
Python 2 is the predecessor of Python 3 and its last version, Python 2.7 was formally released on July 3, 2010. Use this tag along with the main python tag to denote programs that are meant to be run on a Python 2 interpreter only. Do not mix this tag with the python-3.x tag. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T14:50:52.310",
"Id": "200590",
"Score": "0",
"Tags": null,
"Title": null
} | 200590 |
<p>What can be simplified, altered, or implemented differently? I would like to know if there's a way to further improve this code.</p>
<pre><code>#ifndef _DEQUE_H_
#define _DEQUE_H_
//-------------------------------------------------------------------------
template <typename Type>
class Deque
{
private:
struct Node
{
Type element = {};
Node* prev = nullptr;
Node* next = nullptr;
};
size_t count;
Node* head;
Node* tail;
public:
//Member functions
Deque();
Deque(const Deque & deq);
Deque(Deque && deq);
Deque & operator = (const Deque & deq);
Deque & operator = (Deque && deq);
~Deque();
//Element access
//const Type & at(Deque pos) const; Not implemented
//template <typename Type>
//const Type & operator[](size_type pos) const; Not implemented
const Type & front() const;
const Type & back() const;
//Iterators
//TODO: Implement in the near future
//Capacity
bool empty() const;
size_t size() const;
//size_t max_size() const noexcept; Not implemented
//Modifiers
void push_front(const Type & tp);
void push_back(const Type & tp);
//void emplace_front(); Not implemented
//void emplace_back(); Not implemented
void pop_front();
void pop_back();
void clear() noexcept;
void swap(Deque & deq) noexcept;
};
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type>::Deque() : count(0), head(nullptr), tail(nullptr)
{
//Body of the constructor class
}
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type>::Deque(const Deque & deq) : count(deq.count), head(nullptr), tail(nullptr)
{
for (const Node* n_ptr = deq.head; n_ptr != nullptr; n_ptr = n_ptr->next)
{
Node* n_ptr_new = new Node;
n_ptr_new->element = n_ptr->element;
if (head == nullptr && tail == nullptr)
{
head = n_ptr_new;
tail = head;
}
else
{
tail->next = n_ptr_new;
n_ptr_new->prev = tail;
n_ptr_new->next = nullptr;
tail = n_ptr_new;
}
}
}
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type>::Deque(Deque && deq) : count(deq.count), head(deq.head), tail(deq.tail)
{
deq.count = 0;
deq.head = nullptr;
deq.tail = nullptr;
}
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type> & Deque<Type>::operator = (const Deque & deq)
{
if (this == &deq)
{
return *this;
}
Deque tmp(deq);
std::swap(count, tmp.count);
std::swap(head, tmp.head);
std::swap(tail, tmp.tail);
return *this;
}
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type> & Deque<Type>::operator = (Deque && deq)
{
if (this == &deq)
{
return *this;
}
std::swap(count, deq.count);
std::swap(head, deq.head);
std::swap(tail, deq.tail);
return *this;
}
//--------------------------------------------------------------------------
template <typename Type>
Deque<Type>::~Deque()
{
while (head)
{
Node* n_ptr_del = head;
head = head->next;
delete n_ptr_del;
}
count = 0;
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::push_front(const Type & tp)
{
Node* n_ptr_new = new Node;
n_ptr_new->element = tp;
if (head == nullptr && tail == nullptr)
{
head = n_ptr_new;
tail = head;
}
else
{
n_ptr_new->next = head;
n_ptr_new->prev = nullptr;
head->prev = n_ptr_new;
head = n_ptr_new;
}
++count;
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::push_back(const Type & tp)
{
Node* n_ptr_new = new Node;
n_ptr_new->element = tp;
if (head == nullptr && tail == nullptr)
{
head = n_ptr_new;
tail = head;
}
else
{
tail->next = n_ptr_new;
n_ptr_new->prev = tail;
n_ptr_new->next = nullptr;
tail = n_ptr_new;
}
++count;
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::pop_front()
{
if (empty())
{
throw std::out_of_range("Can't pop from empty list");
}
if (head == tail)
{
delete head;
--count;
head = nullptr;
tail = nullptr;
return;
}
Node* n_ptr_del = head;
head = head->next;
head->prev = nullptr;
--count;
delete n_ptr_del;
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::pop_back()
{
if (empty())
{
throw std::out_of_range("Can't pop from empty list");
}
if (head == tail)
{
delete head;
--count;
head = nullptr;
tail = nullptr;
return;
}
Node* n_ptr_del = tail;
tail = tail->prev;
tail->next = nullptr;
--count;
delete n_ptr_del;
}
//--------------------------------------------------------------------------
template <typename Type>
bool Deque<Type>::empty() const
{
return head == nullptr;
}
//--------------------------------------------------------------------------
template <typename Type>
const Type & Deque<Type>::front() const
{
if (empty())
{
throw std::out_of_range("List<Type>::top: empty stack");
}
return head->element;
}
//-------------------------------------------------------------------------------------------------
template <typename Type>
const Type & Deque<Type>::back() const
{
if (empty())
{
throw std::out_of_range("List<Type>::top: empty stack");
}
return tail->element;
}
//--------------------------------------------------------------------------
template <typename Type>
size_t Deque<Type>::size() const
{
return count;
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::clear() noexcept
{
while (count)
{
pop_back();
}
}
//--------------------------------------------------------------------------
template <typename Type>
void Deque<Type>::swap(Deque & deq) noexcept
{
Deque temp(deq);
deq = std::move(*this);
*this = std::move(temp);
}
//--------------------------------------------------------------------------
#endif // _DEQUE_H_
</code></pre>
| [] | [
{
"body": "<ul>\n<li><blockquote>\n <p><code>Node</code> wants a constructor</p>\n</blockquote>\n\n<pre><code>Node(const Type& tp, Node * prev = nullptr, Node * next = nullptr)\n : element(tp)\n , prev(prev)\n , next(next)\n{}\n</code></pre></li>\n<li><blockquote>\n <p>What can be simplified</p>\n</... | {
"AcceptedAnswerId": "200684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T16:14:40.067",
"Id": "200597",
"Score": "5",
"Tags": [
"c++",
"c++11",
"queue"
],
"Title": "Implementation of deque"
} | 200597 |
<p>I’m writing a small HTTP server (just for fun and education). One important part is the response dispatcher. Responses for each socket should be sent in the order the requests were received. The idea is:</p>
<ul>
<li>There’s an asynchronous connection manager that registers the request (and get id) and sends it to some request handler</li>
<li>The request handler is a multithreading black box (at least for now) that creates the response and puts it to the response dispatcher. </li>
<li>The response dispatcher having request sequences for each socket and ready responses fills the queue that stores the responses that should be sent now.</li>
</ul>
<p>Now, when <code>ResponseDispatcher</code> class works (functionally, it works as supposed to) I'd appreciate any ideas to improve my code.</p>
<p><a href="https://www.dropbox.com/s/be81qyvcamjmnrh/TestDispatcher.zip?dl=0" rel="nofollow noreferrer">Here you can find the whole project</a>.</p>
<p><strong>ResponseDispatcher.h</strong></p>
<pre><code>#pragma once
#include <map>
#include <list>
#include "BlockingQueue.h"
#include "winsock2.h"
#include "DataTypes.h"
class ResponseDispatcher
{
public:
ResponseDispatcher();
~ResponseDispatcher();
void registerRequest( RequestIdType, SOCKET );
void registerResponse( ResponsePtr );
ResponseData * pullResponse();
void removeResponse(RequestIdType);
void Dump();
void putTopResponseToQueue(SOCKET);
SOCKET getSocket(RequestIdType) const;
private:
std::map< RequestIdType, SOCKET > m_id2SocketMap;
std::map< RequestIdType, ResponsePtr > m_storedResponses;
std::map< SOCKET, std::list<RequestIdType> > m_topQueue;
BlockingQueue<RequestIdType> m_topResponces;
std::mutex m_Mtx;
};
</code></pre>
<p><strong>ResponseDispatcher.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include "ResponseDispatcher.h"
#include<sstream>
ResponseDispatcher::ResponseDispatcher()
{
}
ResponseDispatcher::~ResponseDispatcher()
{
}
void ResponseDispatcher::registerRequest( RequestIdType id, SOCKET sock )
{
static char pNof[] = __FUNCTION__ ": ";
if (m_id2SocketMap.find(id) != m_id2SocketMap.end())
{
std::stringstream error;
error << pNof << "Request id duplication #" << id;
throw std::runtime_error( error.str() );
}
std::unique_lock<std::mutex> lck;
m_id2SocketMap[id] = sock;
std::list<RequestIdType> & list = m_topQueue[sock];
auto itFirstSmaller = std::lower_bound( list.begin(), list.end(), id );
list.insert(itFirstSmaller, id);
}
void ResponseDispatcher::registerResponse( ResponsePtr response )
{
static char pNof[] = __FUNCTION__ ": ";
RequestIdType id = response->id;
std::unique_lock<std::mutex> lck;
if (m_storedResponses.find(id) != m_storedResponses.end())
{
std::stringstream error;
error << pNof << "Duplicating response id #" << id;
throw std::runtime_error(error.str());
}
auto itID = m_id2SocketMap.find(id);
if ( itID == m_id2SocketMap.end() )
{
std::stringstream error;
error << pNof << "Can't find socket for the response id #" << id;
throw std::runtime_error( error.str() );
}
SOCKET sock = itID->second;
m_storedResponses[id] = std::move(response);
putTopResponseToQueue(sock);
}
SOCKET ResponseDispatcher::getSocket(RequestIdType id) const
{
static char pNof[] = __FUNCTION__ ": ";
auto it = m_id2SocketMap.find(id);
if ( it == m_id2SocketMap.end() )
{
std::stringstream error;
error << pNof << "Can't find socket for the response id #" << id;
throw std::runtime_error(error.str());
}
return it->second;
}
void ResponseDispatcher::putTopResponseToQueue(SOCKET sock)
{
static char pNof[] = __FUNCTION__ ": ";
std::unique_lock<std::mutex> lck;
auto itSock = m_topQueue.find(sock);
if (itSock == m_topQueue.end() )
{
std::stringstream error;
error << pNof << "Can't find socket #" << sock;
throw std::runtime_error(error.str());
}
RequestIdType topId = itSock->second.front();
if ( !m_topResponces.contains(topId) )
{
m_topResponces.push(topId);
}
}
ResponseData * ResponseDispatcher::pullResponse()
{
RequestIdType id = m_topResponces.pull();
return m_storedResponses[id].get();
}
void ResponseDispatcher::removeResponse( RequestIdType id )
{
static char pNof[] = __FUNCTION__ ": ";
std::unique_lock<std::mutex> lck;
auto itID = m_id2SocketMap.find(id);
if (itID == m_id2SocketMap.end() )
{
std::stringstream error;
error << pNof << "Can't find socket for the response id #" << id;
throw std::runtime_error(error.str());
}
SOCKET sock = itID->second;
auto itSock = m_topQueue.find(sock);
if ( itSock == m_topQueue.end() )
{
std::stringstream error;
error << pNof << "Can't find socket #" << sock;
throw std::runtime_error(error.str());
}
itSock->second.remove(id);
m_storedResponses.erase( m_storedResponses.find(id) );
m_id2SocketMap.erase( m_id2SocketMap.find(id) );
putTopResponseToQueue( sock );
}
#include <iostream>
void ResponseDispatcher::Dump()
{
auto printList = [&](const std::pair<SOCKET, std::list<RequestIdType>> & item)
{
std::cout << item.first << ": ";
std::for_each(item.second.begin(), item.second.end(), [&](const RequestIdType & i) {std::cout << i << " "; });
std::cout << std::endl;
};
std::for_each(m_topQueue.begin(), m_topQueue.end(), printList);
std::cout << std::endl;
std::cout << "id vs sockets: ";
std::for_each(m_id2SocketMap.begin(),
m_id2SocketMap.end(),
[&](const auto & t) {std::cout << "[" << t.first << ":" << t.second << "] "; });
std::cout << std::endl;
std::cout << "Stored responses: ";
std::for_each(m_storedResponses.begin(),
m_storedResponses.end(),
[&](const auto & t) {std::cout << t.first << " "; });
std::cout << std::endl;
std::cout << "Top responses: " << m_topResponces.Dump() << std::endl << std::endl;
std::cout << " ======================== " << std::endl << std::endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T19:08:24.513",
"Id": "386275",
"Score": "0",
"body": "I edited your post to fix some grammar mistakes, but I have no clue what to make of the last bullet point. Would you mind rewording it please?"
},
{
"ContentLicense": "CC... | [
{
"body": "<h1>DRY (Don't repeat yourself)</h1>\n\n<p>There are lots of snippets that are repeated the same or very similar across many functions:</p>\n\n<ul>\n<li><p>Error handling: All cases of error handling have the following form:</p>\n\n<pre><code>std::stringstream error;\nerror << pNof << som... | {
"AcceptedAnswerId": "200625",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T16:19:11.907",
"Id": "200598",
"Score": "6",
"Tags": [
"c++",
"c++14",
"queue",
"socket"
],
"Title": "Response dispatcher for HTTP server"
} | 200598 |
<p>The <code>tweepy.models.Status</code> class creates a 'tweet' object, it has attribute <code>.created_at</code> which is the posting time of the tweet in the form of Python <code>datetime</code> object. </p>
<p>Here is the case, I have a function <code>time_distribution(tweets, **kwargs)</code> which calculates the distribution of the tweets by time. The function is at the end of this post.</p>
<p>Here is an example implementation, we may use the samples from <a href="https://github.com/anbarief/statistweepy/tree/master/samples" rel="nofollow noreferrer">statistweepy</a> which is about 3000 tweets of @CocaCola_ID twitter account, stored in a <code>.npy</code> file. Each 'tweet' is a <code>tweepy.models.Status</code> object. </p>
<p>Example:</p>
<pre><code>import numpy
import matplotlib.pyplot as plt
data = list(numpy.load('CocaCola_ID_3093samples_hour_min_21_50_date_24_6_2018.npy'))
dist_only = time_distribution(data, unit = 'hour')
print(dist_only)
fig, ax = plt.subplots(1, 1)
dist_and_plot = time_distribution(data, cont_hist = (ax, 20), unit = 'hour')
plt.show()
</code></pre>
<p>With argument <code>cont_hist = (ax, n)</code>, the function also returns a histogram with <code>n</code> number of bins to be plotted on top of <code>ax</code>.</p>
<p>My question : </p>
<ul>
<li>How to write it better? (sustainable, convenience, readable, compact) </li>
<li>How to optimize the performance?</li>
</ul>
<hr>
<pre><code>import operator
import itertools
def time_distribution(tweets, unit = 'hour', output = 'frequency', cont_hist = False):
if not any([unit == 'year', unit == 'month', unit == 'day', unit == 'hour']):
raise AssertionError(' The argument unit must be one of \'year\', \'month\', \'day\', or \'hour\'. ')
unicity_key = operator.attrgetter('created_at.'+unit)
tweets = sorted(tweets, key=unicity_key)
distribution = {}
for time, time_tweets in itertools.groupby(tweets, key=unicity_key):
time_tweets = list(time_tweets)
if output == 'frequency':
distribution[time] = len(time_tweets)
fy = lambda x: x
elif output == 'tweets':
distribution[time] = time_tweets
fy = lambda x: len(x)
else:
raise AssertionError(' The argument output must be either \'frequency\', or \'tweets\'. ')
if cont_hist:
axes = cont_hist[0]
if unit == 'year':
xt = [tweet.created_at.year + (tweet.created_at.month + (tweet.created_at.day + tweet.created_at.hour/24)/30)/12 for tweet in tweets]
elif unit == 'month':
xt = [(tweet.created_at.month + (tweet.created_at.day + tweet.created_at.hour/24)/30) for tweet in tweets]
elif unit == 'day':
xt = [(tweet.created_at.day + tweet.created_at.hour/24) for tweet in tweets]
elif unit == 'hour':
xt = [tweet.created_at.hour + (tweet.created_at.minute + tweet.created_at.second/60)/60 for tweet in tweets]
a = int(min(xt)) + 1
b = int(max(xt)) + 1
ticks = range(a-1, b+2)
histogram = axes.hist(xt, bins = cont_hist[1])
axes.set_xticks(ticks)
axes.set_xticklabels([str(i) for i in ticks])
axes.set_xlabel(unit)
axes.set_ylabel('frequency')
return distribution, histogram
return distribution
</code></pre>
<hr>
<p>Plot result :</p>
<p><a href="https://i.stack.imgur.com/5rjlC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5rjlC.png" alt="enter image description here"></a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T16:31:11.193",
"Id": "200599",
"Score": "3",
"Tags": [
"python",
"functional-programming",
"matplotlib",
"twitter"
],
"Title": "Time distribution of Twitter data"
} | 200599 |
<p>This is a question from the book "<a href="https://www.amazon.in/gp/product/0984782850/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=0106d-21&creative=24630&linkCode=as2&creativeASIN=0984782850&linkId=a87fccd12fcac59a008e6fff0ccbd8ba" rel="nofollow noreferrer">Cracking the Coding Interview</a>".</p>
<blockquote>
<p>Write code to reverse a C-Style String (C-String means that “abcd” is
represented as five characters, including the null character )</p>
</blockquote>
<p>Please review this code.</p>
<pre><code>#include <iostream>
void inPlaceReverseString(char str[], int size)
{
int j = size - 2;
int i;
for (i = 0; i < (size-1)/2; ++i)
{
std::swap(str[i], str[j]);
j--;
}
str[size - 1] = '\0';
}
int main()
{
char str[255];
std::cout << "Enter String\n";
std::cin.getline(str, 255);
std::cout << "String: " << str << '\n';
int size = 0;
while (str[size] != '\0')
{
size++;
}
size++;
inPlaceReverseString(str, size);
std::cout << "Reversed String: " << str << '\n';
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T01:59:05.483",
"Id": "386305",
"Score": "3",
"body": "`std::reverse(str, std::strchr(str, '\\0'));`"
}
] | [
{
"body": "<p>You should look at using the <code>strlen()</code> function. Use sizeof(str) so you don't have constants in two places.</p>\n\n<pre><code>int main()\n{\n char str[255];\n std::cout << \"Enter String\\n\";\n std::cin.getline(str, sizeof(str));\n std::cout << \"String: \" &l... | {
"AcceptedAnswerId": "200630",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T16:34:29.077",
"Id": "200600",
"Score": "5",
"Tags": [
"c++",
"strings",
"programming-challenge",
"interview-questions"
],
"Title": "In-place reverse of C-style string"
} | 200600 |
An easy-to-use Python library for accessing the Twitter API. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T16:39:40.947",
"Id": "200602",
"Score": "0",
"Tags": null,
"Title": null
} | 200602 |
<p>I started self-learning Bash scripting yesterday, and I finished my first successful "advance" script.</p>
<h1>Goal</h1>
<p>To create an interactive step-by-step script to that allowed customizing various parts of the process of creating permanent swapfiles. I based my idea off of <strong>Ask Ubuntu</strong> Answer's <a href="https://askubuntu.com/a/1039179/782513">#1</a> and <a href="https://askubuntu.com/a/1049496/782513">#2</a>.</p>
<h1>Background</h1>
<p>While creating it, I extended ideas such as allowing exiting from the script at any time and formatting the output.</p>
<p>You will see that I use different styles throughout the code (i.e. case vs if-elif-else, etc...). That deals with me learning as I coded, and having issues trying to get the syntax right while learning. I want to consolidate my different styles - probably into cases.</p>
<h1>Additional Concerns I have</h1>
<p>I know that all of you will suggest any issues that you see, and I will be happy about that; however, I am curious about a few things.</p>
<ol>
<li>Is this code portable? [Edit] Mostly anyone with a Linux Distro should be able to use this script.</li>
<li>I put a lot of effort into formatting the output and making it look easy to read. I tried to separate the output of my code vs the output of other commands (i.e. adding <code>>></code> and<code>>>>></code>). Is it good enough? Would you suggest anything else? etc?</li>
</ol>
<h1>Possible Extensions</h1>
<p>The code works as intended; however, I do plan on extending it in the future. These could affect possible responses - some response might make these harder or easier to implement, or they might have no effect at all. Anyways, if I extend the code later on to accommodate more use-cases, these are what I believe I could do in the future:</p>
<ol>
<li>Allow a non-interactive script mode that uses arguments for customizations</li>
<li>Allow single/batch removal of swapfiles.</li>
<li>Allow easier testing of each pathway of the interactive script</li>
<li>Allow color and bold support.</li>
</ol>
<hr>
<h1>Code</h1>
<blockquote>
<p><strong>GitHub Repo</strong> at <a href="https://github.com/ciscorucinski/Swapfile-Utils/" rel="nofollow noreferrer">ciscorucinski/Swapfile-Utils</a></p>
<p><strong>For <em>unmodified code</em>, check out the Protected Branch at <a href="https://github.com/ciscorucinski/Swapfile-Utils/tree/1_200606_StackExchange-CodeReview" rel="nofollow noreferrer"><code>1_200606_StackExchange-CodeReview</code></a></strong></p>
<p><em>Note: Only the variable declaration of <code>help_text</code> on the GitHub link is different due to a mistake on my side. No escaped tabs and newlines in GitHub</em></p>
<p><strong>For <em>updated code</em>, check out the Development Branch at <a href="https://github.com/ciscorucinski/Swapfile-Utils/tree/develop" rel="nofollow noreferrer"><code>develop</code></a></strong></p>
</blockquote>
<pre><code>#!/bin/bash
help_text="/n>> Documentation:\n\n\t
Usage: $(basename "$0") [-h]\n\t
Creates a new permanent swapfile\n\n\t
where:\n\t\t
-h displays help text"
ask_for_size_allocation="
>>>> Amount to allocate for new swapfile? (default: 4G) : "
ask_for_swapfile_name="
>>>> Filename for new swapfile? (default: '/swapfile') : "
line="# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #"
shopt -s extglob
case $1 in
?(-)@(-h|-help) )
echo -e help_text
;;
esac
retry=true
while $retry; do
echo -e -n ">>>> Are you sure you want to create a new swapfile? (Y / N):"
read yes_no
case $yes_no in
[Yy]|[Yy][Ee][Ss] )
echo -e "\n$line"
echo -e "Current Swapfiles:\n"
sudo swapon -s
echo -e "$line"
retry=false
;;
[Nn]|[Nn][Oo]|[Qq][Uu][Ii][Tt] )
echo -e ">> Exiting..."
exit 0
;;
* )
echo -e ">> Error: invalid response\n"
retry=true
esac
done
echo -e ""
echo -e ">> Step 1: Size Allocation"
echo -e -n $ask_for_size_allocation
read swap_size
if [ -z "${swap_size}" ]; then
swap_size="4G"
elif [[ $swap_size =~ [1-9][0-9]*[mMgG] ]]; then
:
elif [[ $swap_size =~ [Qq][Uu][Ii][Tt] ]]; then
echo -e ">> Exiting..."
exit 0
else
echo -e ">> Invalid Size: ${swap_size^^}. Exiting..."
exit 1
fi
echo -e ""
echo -e ">> Step 2: File Name"
echo -e -n $ask_for_swapfile_name
read swap_name
if [ -z "${swap_name}" ]; then
swap_name="/swapfile"
elif [[ $swap_size =~ [Qq][Uu][Ii][Tt] ]]; then
echo -e ">> Exiting..."
exit 0
elif [[ $swap_name =~ [/]+([0-9a-zA-Z]|[_-]) ]]; then
:
elif [[ $swap_name =~ [+([0-9a-zA-Z]|[_-])] ]]; then
swap_name="/$swap_name"
else
echo -e ">> Invalid Pattern: $swap_name. Exiting..."
exit 1
fi
echo -e ""
echo -e -n ">>>> Continue? '$swap_name' (${swap_size^^}) will be created. (Y / N):"
read yes_no
case $yes_no in
[Yy]|[Yy][Ee][Ss] )
echo -e""
echo -e ">> 1. Creating swapfile..."
echo -e ""
echo -e "$line"
sudo fallocate -l $swap_size $swap_name
sudo chmod 600 $swap_name
sudo mkswap $swap_name
echo -e "$line"
echo -e ""
echo -e ">> 2. Enabling swapfile..."
sudo swapon $swap_name
echo -e ">> 3. Swapfile added."
echo -e ""
echo -e "$line"
echo -e "Current Swapfiles:"
echo -e ""
sudo swapon -s
echo -e "$line"
echo -e ""
;;
[Qq][Uu][Ii][Tt]|[Nn]|[Nn][Oo]|[*])
echo -e ">> Exiting..."
exit 0
;;
esac
echo -e -n ">>>> Make swapfile permanent? (Y / N):"
read yes_no
case $yes_no in
[Yy]|[Yy][Ee][Ss] )
echo -e "$swap_name none swap sw 0 0" | sudo tee -a /etc/fstab > /dev/null
echo -e ""
echo -e ">> 4. Created permanent swapfile. Modified '/etc/fstab'"
echo -e -n ">>>> Do you want to view '/etc/fstab?' (Y / N):"
read yes_no
case $yes_no in
[Yy]|[Yy][Ee][Ss] )
lenght=${#swap_name}
echo -e ""
echo -e "$line"
cat /etc/fstab
echo -e "$line"
;;
*)
echo -e ">> Exiting..."
exit 0
;;
esac
;;
[Qq][Uu][Ii][Tt] )
echo -e ">> Exiting..."
exit 0
;;
*)
echo -e ">> 4. Created temp swapfile."
echo -e ">> Exiting..."
exit 0
;;
esac
shopt -u extglob
</code></pre>
<h1>Output</h1>
<pre><code>$ bash new_swapfile.sh
>>>> Are you sure you want to create a new swapfile? (Y / N):y
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Current Swapfiles:
[sudo] password for ciscorucinski:
Filename Type Size Used Priority
/swapfile_ext3 file 262140 238384 -5
/swapfile_ext7 file 131068 106376 -3
/swapfile file 8388604 476148 -6
/swapfile_ext6 file 131068 68840 -4
/swapfile_ext5 file 131068 115304 -2
/dev/dm-1 partition 1003516 0 -7
/swapfile_ext8 file 131068 0 -8
/swapfile_ext9 file 131068 0 -9
/swapfile_ext10 file 131068 0 -10
/swapfile_ext11 file 131068 0 -11
/swapfile_ext12 file 131068 0 -12
/swapfile_ext13 file 131068 0 -13
/swapfile_ext file 524284 0 -14
/swapfile_ext14 file 131068 0 -15
/swapfile_ext15 file 131068 0 -16
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
>> Step 1: Size Allocation
>>>> Amount to allocate for new swapfile? (default: 4G) :128m
>> Step 2: File Name
>>>> Filename for new swapfile? (default: '/swapfile') :/swapfile_ext16
>>>> Continue? '/swapfile_ext16' (128M) will be created. (Y / N):y
>> 1. Creating swapfile...
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Setting up swapspace version 1, size = 128 MiB (134213632 bytes)
no label, UUID=94e452f1-b252-4ea2-8d5f-e23634e34081
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
>> 2. Enabling swapfile...
>> 3. Swapfile added.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Current Swapfiles:
Filename Type Size Used Priority
/swapfile_ext3 file 262140 238384 -5
/swapfile_ext7 file 131068 106376 -3
/swapfile file 8388604 476148 -6
/swapfile_ext6 file 131068 68840 -4
/swapfile_ext5 file 131068 115304 -2
/dev/dm-1 partition 1003516 0 -7
/swapfile_ext8 file 131068 0 -8
/swapfile_ext9 file 131068 0 -9
/swapfile_ext10 file 131068 0 -10
/swapfile_ext11 file 131068 0 -11
/swapfile_ext12 file 131068 0 -12
/swapfile_ext13 file 131068 0 -13
/swapfile_ext file 524284 0 -14
/swapfile_ext14 file 131068 0 -15
/swapfile_ext15 file 131068 0 -16
/swapfile_ext16 file 131068 0 -17
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
>>>> Make swapfile permanent? (Y / N):y
>> 4. Created permanent swapfile. Modified '/etc/fstab'
>>>> Do you want to view '/etc/fstab?' (Y / N):y
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
/dev/mapper/ubuntu--vg-root / ext4 errors=remount-ro 0 1
# /boot/efi was on /dev/nvme0n1p1 during installation
UUID=D6C3-F1E1 /boot/efi vfat umask=0077 0 1
/dev/mapper/ubuntu--vg-swap_1 none swap sw 0 0
/swapfile none swap sw 0 0
/swapfile_ext3 none swap sw 0 0
/swapfile_ext5 none swap sw 0 0
/swapfile_ext6 none swap sw 0 0
/swapfile_ext7 none swap sw 0 0
/swapfile_ext8 none swap sw 0 0
/swapfile_ext9 none swap sw 0 0
/swapfile_ext10 none swap sw 0 0
/swapfile_ext11 none swap sw 0 0
/swapfile_ext13 none swap sw 0 0
/swapfile_ext14 none swap sw 0 0
/swapfile_ext15 none swap sw 0 0
/swapfile_ext16 none swap sw 0 0
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
</code></pre>
| [] | [
{
"body": "<h3>Portability</h3>\n\n<p>You mentioned portability as one of your top concerns.\nThe commands used by the script limit it to certain systems:</p>\n\n<ul>\n<li><code>swapon</code>, <code>mkswap</code>: these are common in Linux systems</li>\n<li><code>fallocate</code>: available in Linux, supporting... | {
"AcceptedAnswerId": "200711",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:14:19.337",
"Id": "200606",
"Score": "6",
"Tags": [
"bash",
"linux"
],
"Title": "Interactive bash script to create new permanent swapfiles"
} | 200606 |
<p>This is my first algorithm in C++ ever to check if two strings are permutations of each other. Please provide guidance on correctness of algorithm + ways to improve + thoughts on my use of the language itself.</p>
<p>The idea is two create two dictionaries which count the number of occurrences of each character using two for loops, and then we use a final for loop to check if the counts are equal.</p>
<pre><code>void checkPermut(std::string &sentence1, std::string &sentence2)
{
std::map<char, int> dict1;
std::map<char, int> dict2;
for (char & c : sentence1)
{
if (dict1.find(c) == dict1.end())
{
dict1.insert(std::pair<char, int>(c, 1));
}
else
{
dict1[c] == dict1[c] + 1;
}
}
for (char & c : sentence2)
{
if (dict2.find(c) == dict2.end())
{
dict2.insert(std::pair<char, int>(c, 1));
}
else
{
dict2[c] == dict2[c] + 1;
}
}
bool arePermut = true;
for (char & c : sentence2)
{
if (dict1.find(c) == dict1.end())
{
arePermut = false;
std::cout << "Not permutations." << std::endl;
break;
}
else if (dict1[c] != dict2[c])
{
arePermut = false;
std::cout << "Not permutations." << std::endl;
break;
}
}
if (arePermut)
{
std::cout << "Are permutations" << std::endl;
}
}
int main()
{
std::string somestring1;
std::string somestring2;
std::cin >> somestring1 >> somestring2;
checkPermut(somestring1, somestring2);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:33:53.170",
"Id": "386263",
"Score": "5",
"body": "Do you mean that it checks whether two strings are anagrams?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:36:34.183",
"Id": "386264",
... | [
{
"body": "<h2>Basic Review</h2>\n\n<p>Look below for algorithm ideas:</p>\n\n<p>You are not modifying the input strings. So they should be passed by const reference to prevent accidents:</p>\n\n<pre><code>void checkPermut(std::string const& sentence1, std::string const& sentence2)\n ... | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:21:57.993",
"Id": "200607",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"strings"
],
"Title": "Attempt at checking whether two words are permutations"
} | 200607 |
<p>I am going in a circle over and over trying to write a "supermarket" application using OOP.</p>
<p>The app should be useful for the employees of a supermarket. The app reads data from a CSV file which looks like this:</p>
<pre><code>name,amount
soap,4
rice,5
bread,10
</code></pre>
<p>The supermarket has cashiers and managers. Cashiers should only be able to view the amount for a product. Managers can view but also change an amount. </p>
<p>Here's the code I came up with:</p>
<pre><code>import pandas
class Data:
"""Creates a pandas dataframe out of a text file"""
def __init__(self, datafile = "products.txt"):
self.datafile = datafile
def get_dataframe(self):
df = pandas.read_csv("products.txt", index_col = "name")
return df
def save_to_csv(self):
df = pandas.read_csv("products.txt", index_col = "name")
df.to_csv(self.datafile)
print(df)
class Product:
"""Represent a product from the dataframe table"""
def __init__(self, name, dataframe = Data().get_dataframe()):
self.name = name
self.dataframe = dataframe
def get_amount(self):
"""Return the available amount of the product object taken from the dataframe"""
return self.dataframe.loc[self.name, "amount"]
def add_amount(self, amount, password):
"""Changes the dataframe by adding an amount to the existing amount"""
if password == 1234:
self.dataframe.loc[self.name, "amount"] += amount
data = Data()
data.save_to_csv()
print("Saved")
else:
return "You're not a manager"
def remove_component(self, person):
"""Changes the dataframe by removing an amount from the existing amount"""
if password == 1234:
self.dataframe.loc[self.name, amount] -= 1
else:
return "You're not a manager"
def __del__(self):
"""Delete the dataframe from memory when Product is destroyed"""
del self.dataframe
Data().save_to_csv()
</code></pre>
<p>I think the authentication layer is very poorly implemented here. I simply added a conditional in the add and remove methods. Is there any better way to do the authentication part?</p>
<p>Should I also create Manager and Cashier classes in case I expand the program later. For example, adding info about salaries for managers and cashiers. That would require to have Manager and Cashier objects I guess.</p>
<p>Will the code load many Data objects? Should I use a singleton for the Data object? </p>
<p>What other design pattern could I have used for this app? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:55:56.170",
"Id": "386268",
"Score": "0",
"body": "Can the downvoter expain the techical reason of the downvote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T19:19:22.663",
"Id": "386276",
... | [
{
"body": "<p>From an OOP design perspective, you've duplicated the sales items. Data is the products, and Products are the products too (hope that makes sense?).</p>\n\n<p>Think back for a second regarding what entities are at work here, and their specific functions. We have:</p>\n\n<ul>\n<li>a manager, </li>... | {
"AcceptedAnswerId": "200657",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T17:25:13.973",
"Id": "200608",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Supermarket app using OOP"
} | 200608 |
<p>I am preparing for an interview, and here's a popular problem on the dynamic programming. And I want to see if there's any feedback or code review for my solution at dynamic programming question.</p>
<blockquote>
<pre><code># Problem: Coin Sum
#
# Given an array of coins and a target total, return how many
# unique ways there are to use the coins to make up that total.
#
# Input: coins {Integer Array}, total {Integer}
# Output: {Integer}
#
#
# Example:
# Input: [1,2,3], 4
# Output: 4
#
# 1+1+1+1
# 1+3
# 1+1+2
# 2+2
#
#
# Input: [2,5,3,6], 10
# Output: 5
#
# 2+3+5
# 5+5
# 2+3+2+3
# 2+2+6
# 2+2+3+3
#
# Note: You have an unlimited number of each coin type. All coins in the
# coin array will be unique
# Order does not matter. Ex: One penny and one nickel to create six
# cents is equivalent to one nickel and one penny
#
#
</code></pre>
</blockquote>
<pre><code>def coin_sum(coins, total):
# tabulation way
arr = [1] + [0] * total
for coin in coins:
for i in range(coin, total + 1):
arr[i] += arr[i - coin]
return 0 if total == 0 else arr[total]
# Time Complexity: O(N*M), let the number of coins be m.
# We iterate from arr[coin] -> arr[n], or ~ n operations on each coin, hence n*m.
# Auxiliary Space Complexity: O(N)
</code></pre>
<p>It passes all of the following 5 tests for my Coin sum tests:</p>
<pre><code>def expect(count, name, test):
if (count == None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
errMsg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
errMsg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if errMsg != None:
print(' ' + errMsg + '\n')
def lists_equal(lst1, lst2):
if len(lst1) != len(lst2):
return False
for i in range(0, len(lst1)):
if lst1[i] != lst2[i]:
return False
return True
print("\nCoin Sum Tests")
test_count = [0, 0]
def test():
example = coin_sum([1, 2, 3], 4)
return example == 4
expect(test_count, 'should work for first example case', test)
def test():
example = coin_sum([2, 5, 3, 6], 10)
return example == 5
expect(test_count, 'should work for second example case', test)
def test():
example = coin_sum([2], 10)
return example == 1
expect(test_count, 'should work for a single coin', test)
def test():
example = coin_sum([7, 15], 20)
return example == 0
expect(test_count, 'should work when there is no solution', test)
def test():
example = coin_sum(
[78, 10, 4, 22, 44, 31, 60, 62, 95, 37, 28, 11, 17, 67, 33, 3, 65, 9, 26, 52, 25, 69, 41, 57, 93, 70, 96, 5,
97, 48, 50, 27, 6, 77, 1, 55, 45, 14, 72, 87, 8, 71, 15, 59], 100)
return example == 3850949
expect(test_count, 'should work for variety of coins and large total', test)
print(('\nPASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1])))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T18:17:54.367",
"Id": "386270",
"Score": "0",
"body": "python 3.? Please mention the version you might be using"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T18:20:30.593",
"Id": "386273",
"S... | [
{
"body": "<p>Some tips:</p>\n\n<ul>\n<li>Know your PEP8, format your code appropriately.</li>\n<li>Learn string formatting - and know the differences between 3.6 and earlier.</li>\n<li>Your <code>errMsg</code> and Exception process seem like you expect an error but what error are you expecting? Might want to s... | {
"AcceptedAnswerId": "200646",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T18:11:57.570",
"Id": "200611",
"Score": "3",
"Tags": [
"python",
"dynamic-programming"
],
"Title": "Coin sum dynamic programming in Python"
} | 200611 |
<p>I find this <a href="https://leetcode.com/problems/minimum-window-substring/description/" rel="nofollow noreferrer">Substring Leetcode challenge online</a>. Given a string <code>S</code> and a string <code>T</code>, find the minimum window in <code>S</code> which will contain all the characters in <code>T</code> in complexity \$O(n^2)\$ or \$O(n)\$ (optimized).</p>
<p>Input: S = "ADOBECODEBANC", T = "ABC"</p>
<p>Output: "BANC"</p>
<p>I did the following approach. Moving Window problems. I also test my code on <a href="https://repl.it/@Jeffchiucp/AromaticSwiftMaintenance" rel="nofollow noreferrer">repl.it</a>.</p>
<pre><code>function minimumWindowSubstring(S, T) {
let result = [0, Infinity]
let counts = {};
let missingCharacters = T.length;
// Create the counts hash table
for(let i = 0; i < T.length; i++) {
counts[T[i]] = 0;
}
let slow = 0;
for(let fast = 0; fast < S.length; fast++) {
// Check if character at fast index is incounts hash
if(S[fast] in counts) {
// If you haven't seen that character before
if(counts[S[fast]] === 0) {
// Decrement number of missing characters
missingCharacters -= 1;
}
// And add one to its counts value
counts[S[fast]] += 1
}
// Shrink window until you have an incomplete set
while(missingCharacters === 0) {
// Updates result range if smaller than previous range
if((fast - slow) < (result[1] - result[0])) {
result[0] = slow
result[1] = fast
}
if(S[slow] in counts) {
counts[S[slow]] -= 1
if(counts[S[slow]] === 0) {
missingCharacters += 1
}
}
slow += 1;
}
}
return result[1] === Infinity ? "" : S.slice(result[0], result[1] + 1);
}
console.log(minimumWindowSubstring("ADOBECODEBANC", "ABC")) // "BANC"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T20:49:10.457",
"Id": "386294",
"Score": "2",
"body": "What is `n` in the _complexity O(n)_? Length of `S`? length of `T`? size of an alphabet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T21:20:33.... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T20:19:25.463",
"Id": "200616",
"Score": "0",
"Tags": [
"javascript",
"strings"
],
"Title": "Minimum Window Substring in JavaScript"
} | 200616 |
<p>Problem: Write a function that takes a positive integer and returns the next smaller positive integer containing the same digits.</p>
<p>My solution:</p>
<pre><code>def next_smaller(n):
import itertools
x = list(str(n)) #list of digits
#permutates and joins digits
x = [int(''.join(i)) for i in list(itertools.permutations(x))]
x.sort() #sorts numerically
#picks number previous to original in list
r = [x[i-1] for i in range(0,len(x)) if x[i] == n][0]
if r > n: return -1 #returns -1 if no solution
else: return r #returns solution
</code></pre>
<p>My code works, however it is terribly inefficient with very large numbers. Any way to make this code more efficient and cut down the execution time?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T20:37:27.040",
"Id": "386293",
"Score": "0",
"body": "check https://stackoverflow.com/questions/28872566/find-the-largest-number-small-than-having-the-same-digits-as-of-n?noredirect=1#comment46008958_28872566"
}
] | [
{
"body": "<p>Following the input from Joop Eggen, I believe the below algorithm works and it is much faster than the original solution in the question. Making a list of all permutations will have an enormously large number of entries for large numbers (like 125658452143250) and will probably stall your compute... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T20:28:59.733",
"Id": "200617",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Python function to find the next smaller number with same set of digits"
} | 200617 |
<p>My directory <code>folderMarket</code> has lots of files with the same name but are tagged with a date string at the end. The date tag can be formatted differently, e.g. "2018-07-25" or "25Jul18". My helper function is tasked with extracting a path list matching each found file name against <code>filename_list</code>. is there a better way to build a filename_list instead of brute force used below?</p>
<pre><code>from datetime import datetime
strToday = "2018-07-25"
files_market = ['apples_DATE.xml', 'peaches_DATE.xml', 'cucumbers_DATE.xml', 'potatos_DATE.xml', 'tomates.DATE.csv']
def get_path_list(directory, base_filename_list, savedAsOf):
strDate1 = savedAsOf
filename_list1 = [n.replace('DATE', strDate1) for n in base_filename_list]
strDate2 = datetime.strptime(savedAsOf, '%Y-%m-%d').strftime('%d%b%y')
filename_list2 = [n.replace('DATE', strDate2) for n in base_filename_list]
filename_list = filename_list1 + filename_list2
path_list = []
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename in filename_list:
path_list.append(os.path.join(directory, filename))
continue
return path_list
print (len(get_path_list(folderMarket, files_market, strToday)))
</code></pre>
| [] | [
{
"body": "<p>Firstly some tips:</p>\n\n<ul>\n<li>Your code uses a mixture of snake_case and camelCase, you should stick to a specific style. If you're going to write python, PEP8 states snake_case should be used as the expected style.</li>\n<li>Your code lacks a <code>if __name__ == \"__main__\":</code> starti... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T21:09:17.253",
"Id": "200620",
"Score": "2",
"Tags": [
"python",
"datetime",
"file-system"
],
"Title": "Listing files whose names match a pattern with a date"
} | 200620 |
<p>I made a function that makes font sizes in <code><div></code>s as big as possible without overflowing. It takes a long time to run. How do I optimize this?</p>
<pre><code>$(document).ready(() => {
$('.text-fit').each((index, element) => {
let currentElement = $(element);
let fontSize = 999;
currentElement.wrapInner("<div class='wrapper'></div>");
while (currentElement.find('.wrapper').innerHeight() > currentElement.innerHeight()) {
fontSize -= 1;
currentElement.css('font-size', fontSize + 'px');
}
});
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T23:22:32.157",
"Id": "386299",
"Score": "2",
"body": "Well... It executes a piece of JQuery around 900 times... I think that would do it. This is also not what JQuery is for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Crea... | [
{
"body": "<p>No particular comment on the style, but FWIW, I had to implement <a href=\"https://github.com/Quuxplusone/CppConTimer/blob/master/index.html#L104-L124\" rel=\"nofollow noreferrer\">the same thing</a> recently — also in jQuery — and this is how I did it. Assume we have an outer <code><div></c... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-30T23:20:43.153",
"Id": "200623",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"ecmascript-6",
"layout"
],
"Title": "Making the font as big as possible without overflowing each div"
} | 200623 |
<p>I'm trying to set up an algorithm in python for getting all sets from a set (DataSet1) less any instances of data in a second set (DataSet2).</p>
<p>Objective:</p>
<pre><code>DataSet1: DataSet2:
A B C A B C D
1 6 5 1 1 4 4 3 1
2 4 4 3 2 4 4 3 1
3 4 4 3 3 6 5 3 1
4 4 4 3 4 5 3 1 1
5 3 2 3 5 3 2 3 1
DataSet1 - DataSet2 = ResultSet
ResultSet:
A B C
1 6 5 1
2 4 4 3
</code></pre>
<p>Notice that the data has many repeat rows and when the difference operation is applied, the number of duplicate instances in DataSet1 are subtracted from the duplicate instances in DataSet2.</p>
<p>The parameters of this exercise are such:</p>
<blockquote>
<ol>
<li>Extra columns in the subtrahend (DataSet2) must be ignored. </li>
<li>Instances of a record in DataSet1 that also exists in Dataset two
must be be removed from DataSet1 until either there are no
instances of the duplicate left in DataSet1 or there are no
instances left in DataSet2. </li>
<li>In line with the above is a certian
record is duplicated 3 times in DataSet1 and once in DataSet2 then
two of those duplicates should remain in duplicate 1. Else if it's
the other way around 1-3 = -2 so all duplicates of that record are
removed from the returned DataSet. </li>
<li>We must assume that the name
and number of columns, rows, index positions, are all unknown.</li>
</ol>
</blockquote>
<p>My Algorithm So Far:</p>
<pre><code>import pandas as pd
import numpy as np
import copy
def __sub__(self, arg):
"""docstring"""
#Create a variable that holds the column names of self. We
# will use this filter and thus ignore any extra columns in arg
lstOutputColumns = self.columns.tolist()
#Group data into normalized sets we can use to break the data
# apart. These groups are returned usint pd.Dataframe.size() which
# also gives me the the count of times a record orccured in the
# origional data set (self & arg).
dfGroupArg = arg.groupby(arg.columns.tolist(),as_index=False).size().reset_index()
dfGroupSelf = self.groupby(lstOutputColumns,as_index=False).size().reset_index()
#Merge the normalized data so as to get all the data that in the
# subtrahend set (DataSet2) that matches a record in Dataset# and
# we can forget about the rest.
dfMergedArg = dfGroupArg.merge(dfGroupSelf, how="inner", on=lstOutputColumns)
#Add a calculated column to the merged subtrahend set to get the
# difference between column counts that our groupby.size() appened
# to each row two steps ago. This all done using iloc so as to
# avoid naming columns since I can't guarantee any particular column
# name isn't already in use.
dfMergedArg = pd.concat([dfMergedArg, pd.Series(dfMergedArg.iloc[:,-1] - dfMergedArg.iloc[:,-2])], axis=1)
#The result of the last three steps is a DataFrame with only
# rows that exist in both sets, with the count of the time each
# particular row exists on the far left of the table along with the
# difference between those counts. It should end up so that the
# last three columns of the DataFrame are
# (DataSet2ct),(DataSet1ct),(DataSet1ct-DataSet2ct)
# Now we iterate through rows and construct a new data set based on
# the difference in the last column.
lstRows = []
for index, row in dfMergedArg.iterrows():
if row.iloc[-1] > 0:
dictRow = {}
dictRow.update(row)
lstRows += [dictRow] * row[-1]
#Create a new dataframe with the rows we created in the the
#lst Variable.
dfLessArg = pd.DataFrame(lstRows, columns=lstOutputColumns)
#This next part is a simple left anti-join to get the rest of
# data out of DataSet1 that is unaffected by DataSet2.
dfMergedSelf = self.DataFrameIns.merge(dfGroupArg, how="left", on=lstOutputColumns)
dfMergedSelf = dfMergedSelf[dfMergedSelf[0] == np.nan]
#Now we put both datasets back together in a single DataFrame
dfCombined = dfMergedSelf.append(dfLessArgs).reset_index()
#Return the result
return dfCombined[lstOutputColumns]
</code></pre>
<p>This works, the reason i've posted it here is because it's not very efficient. The creation of the multiple DataFrames during a run cause it to be a memory hog. Also, the use of iterrows() I feel is like a last resort that inevitably results in slow execution. I think the problem is interesting though because its about dealing with really un-ideal data situations that (lets face it) occur all the time. </p>
<p>Alright StackExchange - please rip me apart now!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T13:10:36.067",
"Id": "386390",
"Score": "0",
"body": "Any reason for naming it `__sub__`? or is it a method inside some class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T16:20:58.287",
"Id": ... | [
{
"body": "<p>You can remove the concatenation and the manual iteration over <code>iterrows</code> using <a href=\"http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.repeat.html#pandas.Index.repeat\" rel=\"nofollow noreferrer\"><code>pandas.Index.repeat</code></a>; which uses <a href=\"https://d... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T00:04:02.983",
"Id": "200626",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Non normalized set difference algorithm"
} | 200626 |
<p>I'm trying to beat the native <code>Double.TryParse</code> for performance in parsing large multi-million row (simple) CSV files as much as possible. I do not have to support exponential notation, thousand separators, Inf, -Inf, NaN, or anything exotic. Just millions of "<code>0.##</code>" format doubles.</p>
<p>Here's my best attempt, which is ~350% faster by my tests (64 bit release mode)</p>
<p><strong>My Implementation</strong></p>
<p>This is the setup of the function (mostly for context).</p>
<pre><code>private static readonly char CharNegative = CurrentCulture.NumberFormat.NegativeSign[0];
private static readonly char CharDecimalSeparator =
CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
/// <summary>High performance double parser with rudimentary flexibility.
/// <returns>Returns true only if we can be certain we parsed the string correctly.
/// <remarks>Does not support exponential notation, thousand separators or whitespace.
/// Does not support Infinity, Negative Infinity, NaN, or detect over/underflows.
/// Supports only leading negative signs, no positive signs or trailing signs.</remarks>
public static bool FastTryParseDouble(string input, out double result)
{
result = 0d;
int length = input.Length;
if (length == 0) return false;
double sign = 1d;
int currentIndex = 0;
char nextChar = input[0];
// Handle a possible negative sign at the beginning of the string.
if (nextChar == CharNegative)
{
sign = -1d;
++currentIndex;
}
</code></pre>
<p>As you can see, I try to remain culture aware and support negative numbers.
This is the remainder of the method, which I think needs to be optimized for performance:</p>
<pre><code> unchecked
{
while (true)
{
// Return now if we have reached the end of the string
if (currentIndex >= length)
{
result *= sign;
return true;
}
nextChar = input[currentIndex++];
// Break if the result wasn't a digit between 0 and 9
if (nextChar < '0' || nextChar > '9') break;
// Multiply by 10 and add the next digit.
result = result * 10 + (nextChar - '0');
}
// The next character should be a decimal character, or else it's invalid.
if (nextChar != CharDecimalSeparator) return false;
double fractionalPart = 0d;
int fractionLengh = length - currentIndex;
while (currentIndex < length)
{
nextChar = input[currentIndex++];
// If we encounter a non-digit now, it's an error
if (nextChar < '0' || nextChar > '9') return false;
fractionalPart = fractionalPart * 10 + (nextChar - '0');
}
// Add the fractional part to the result, apply sign, and return
if (fractionLengh < NegPow10.Length)
result = (result + fractionalPart * NegPow10[fractionLengh]) * sign;
else
result = (result + fractionalPart * Math.Pow(10, -fractionLengh)) * sign;
}
return true;
}
</code></pre>
<p><code>NegPow10</code> at the end there is just the following array, which has a quick lookup value to cover the first 20 or so values of <code>10^-n</code> for quick reference. Anything bigger just falls back to <code>Math.Pow()</code></p>
<pre><code>/// <summary>A cache of negative powers of 10 for quick magnitude adjustment of parsed
/// decimals up to the maximum number of possible decimal places that might be consumed
/// from a string representation of a double.</summary>
private static readonly double[] NegPow10 = new double[]
{
1d,
0.1,
0.01,
///... you get the idea
0.0000000000000001
};
</code></pre>
<hr />
<p><strong>Test Cases</strong></p>
<p>The following test cases are all passing:</p>
<pre><code>TestSuccess("0", 0d);
TestSuccess("1", 1d);
TestSuccess("-1", -1d);
TestSuccess("123.45", 123.45);
TestSuccess("-123.45", -123.45);
TestSuccess("12345678901234", 12345678901234d);
TestSuccess("-12345678901234", -12345678901234d);
TestSuccess("0.12", 0.12);
TestSuccess("-0.12", -0.12);
TestSuccess("0.00", 0.00);
TestSuccess("-0.00", -0.00);
TestSuccess("1234567890123.01", 1234567890123.01);
TestSuccess("-1234567890123.01", -1234567890123.01);
TestSuccess("123456789000000000000000", 123456789000000000000000d);
TestSuccess("-123456789000000000000000", -123456789000000000000000d);
</code></pre>
<p>I also have the unsupported (failure) cases laid out if anyone's interested, but it's basically the limitations mentioned in the remarks above.</p>
<hr />
<p><strong>Benchmarks</strong></p>
<p>I benchmarked my implementation against native <code>Double.TryParse</code> to guage the performance difference.</p>
<p>I tested parsing an array of <strong>10 million different strings</strong> using:</p>
<pre><code>Double.TryParse(value, NumberStyles.Float, cachedCulture, out _)
</code></pre>
<p>Note that I cache the culture instance and pass in explicit NumberStyles to get the native method as fast as possible before comparing it to my own. My method was of course running 10 million strings through:</p>
<pre><code>Parsers.FastTryParseDouble(value, out _)
</code></pre>
<p><strong>Results</strong></p>
<blockquote>
<p>Native Double.TryParse took ~4500 ms.</p>
<p>Custom Parsers.FastTryParseDouble took ~950 ms.</p>
<p>Performance gain was ~370%</p>
</blockquote>
<hr />
<p><strong>Next Steps</strong></p>
<p>See any other ways I can squeeze out more performance?</p>
<p>Any awful flaws that might cause incorrect results to be returned? Note that I'm always happy to return "false" for unsupported cases if that's what's fastest, but I'm not okay to return <code>true</code> and a bad result.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T01:34:06.037",
"Id": "386302",
"Score": "0",
"body": "You missed 3 cases, `∞`, `-∞` and `NaN`. These should parse out as `Double.PositiveInfinity`, `Double.NegativeInfinity` and `Double.NaN`. Actually there is one more, your tests s... | [
{
"body": "<p>Here is a much longer implementation that handles scientific notation, NaN, Infinity, Negative Infinity, and leading positive signs. I also added a lot of comments to help visually break it into chunks.</p>\n<p>It manages to be almost as fast as the previous method - most of the logic takes place ... | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T00:25:22.053",
"Id": "200627",
"Score": "6",
"Tags": [
"c#",
"performance",
"parsing",
"floating-point"
],
"Title": "Custom double parser optimized for performance"
} | 200627 |
<blockquote>
<p>Have the function VowelSquare(strArr) take the strArr parameter being
passed which will be a 2D matrix of some arbitrary size filled with
letters from the alphabet, and determine if a 2x2 square composed
entirely of vowels exists in the matrix. For example: strArr is
{{"a","b","c","d"},{"e","i","k","r"}, {"o","u","f","j"}} then this matrix looks like the following: </p>
<p>$$\begin{array}{cccc}
a & b & c & d \\
\color{red}e & \color{red}i & k & r \\
\color{red}o & \color{red}u & f & j \\
\end{array}$$</p>
<p>Within this matrix there is a 2x2 square of vowels starting in the
second row and first column, namely, ei, ou. If a 2x2 square of vowels
is found your program should return the top-left position (row-column)
of the square, so for this example your program should return 1-0. If
no 2x2 square of vowels exists, then return the string not found. If
there are multiple squares of vowels, return the one that is at the
most top-left position in the whole matrix. The input matrix will at
least be of size 2x2.</p>
</blockquote>
<p>Are there any improvements I can make in terms of readability?</p>
<pre><code>bool must_be_2x2(std::vector<std::vector<std::string>>& letters)
{
constexpr int MIN_SIZE = 2;
if (letters.at(0).size() > MIN_SIZE && letters.at(1).size() > MIN_SIZE)
{
return true;
}
return false;
}
std::string matrix_vector_to_string(std::vector<std::vector<std::string>>& matrix)
{
std::string str;
for (int row = 0; row < matrix.size(); ++row)
{
for (int col = 0; col < matrix.at(row).size(); ++col)
{
str += matrix.at(row).at(col);
}
}
return str;
}
bool alphabet_only(std::vector<std::vector<std::string>>& letters)
{
std::string str = matrix_vector_to_string(letters);
for (std::size_t pos = 0; pos < str.length(); ++pos)
{
if (!std::isalpha(str.at(pos)))
{
return false;
}
}
return true;
}
bool equal_length(std::vector<std::vector<std::string>>& letters)
{
const size_t SIZE = letters.at(0).size();
for (std::size_t row = 1; row < letters.size(); ++row)
{
if (letters.at(row).size() != SIZE)
{
return false;
}
}
return true;
}
bool is_vowel(std::string element) noexcept
{
static const auto vowels = std::array<std::string,5> { "a","e","i","o","u" };
return std::find(vowels.begin(), vowels.end(), element) != vowels.end();
}
std::string find_vowel_square(std::vector<std::vector<std::string>>& letters)
{
for (std::size_t row = 0; row < letters.size()-1; ++row)
{
for (std::size_t col = 0; col < letters.at(row).size()-1; ++col)
{
if (is_vowel(letters.at(row).at(col)) && is_vowel(letters.at(row).at(col + 1)) && is_vowel(letters.at(row + 1).at(col)) && is_vowel(letters.at(row).at(col + 1)))
{
return std::to_string(row) + "-" + std::to_string(col);
}
}
}
return "not found";
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T05:30:05.197",
"Id": "386328",
"Score": "1",
"body": "Does this work? Looking at `find_vowel_square()`, the `if` statement repeats `.at(row).at(col+1)` where it should have `at(row+1).at(col+1)`. (That is the last condition is a rep... | [
{
"body": "<p>The #1 improvement you can make for code readability is adding comments. Plain code, even the most expressive plain code, rarely makes any sense on its own. In addition to comments, a use case showing the code in action is <em>very</em> helpful. Tests, too.</p>\n\n<p>As for the code itself:</p>\n\... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T00:30:33.200",
"Id": "200629",
"Score": "3",
"Tags": [
"c++",
"matrix"
],
"Title": "Demonstration of Find Vowel Square"
} | 200629 |
<p>I wrote a simple sitemap.xml checker using asyncio and aiohttp. I followed the <a href="http://asyncio.readthedocs.io/en/latest/producer_consumer.html" rel="nofollow noreferrer">documentation</a> demonstrating the producer/consumer pattern. However, I noticed that as the URLs scale larger, it seems to get slower in performance. Is there something I'm doing wrong? Can I improve request speed?</p>
<p><strong>Use case</strong>:</p>
<p>When <code>check()</code> is given the URL <a href="https://www.google.com/flights/sitemap.xml" rel="nofollow noreferrer">https://www.google.com/flights/sitemap.xml</a> with ~310 links, it takes approximately 00:03:24 minutes to complete. Github <a href="https://github.com/1-hit/sitemapcheck" rel="nofollow noreferrer">source</a> code is available if needed.</p>
<pre><code># -*- coding: utf-8 -*-
from timeit import default_timer as timer
from sys import exit as abort
import time
import sys
import logging
import asyncio
import aiohttp
import defusedxml.ElementTree
class Logger(object):
FMT = '%(name)s: %(levelname)s: %(message)s'
def __init__(self):
self._logger = logging.getLogger(__name__)
self._logger.setLevel(level=logging.INFO)
stdout = logging.StreamHandler(stream=sys.stdout)
stderr = logging.StreamHandler(stream=sys.stderr)
stdout.setLevel(level=logging.INFO)
stderr.setLevel(level=logging.WARNING)
stdout.addFilter(lambda record: record.levelno == logging.INFO)
stdout.setFormatter(
logging.Formatter(
fmt=self.FMT,
datefmt=None,
style='%'))
stderr.setFormatter(
logging.Formatter(
fmt=self.FMT,
datefmt=None,
style='%'))
self._logger.addHandler(hdlr=stdout)
self._logger.addHandler(hdlr=stderr)
def __del__(self):
if not self._logger.hasHandlers():
return
for handler in self._logger.handlers:
if isinstance(handler, logging.StreamHandler):
handler.flush()
handler.close()
self._logger.removeHandler(handler)
class Config(object):
"""Base Config."""
LIMIT = 100
TIMEOUT = None
USER_AGENT = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
MAXSIZE = 0
class ProdConfig(Config):
"""Prod Config."""
TIMEOUT = 8
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
MAXSIZE = 500
class Checker(object):
"""Sitemap Checker."""
def __init__(self):
self._logger = Logger()
self._loop = asyncio.get_event_loop()
self._queue = asyncio.Queue(
maxsize=ProdConfig.MAXSIZE, loop=self._loop)
def check(self, url):
"""Main() entry-point."""
start = timer()
self._loop.run_until_complete(self._fetch_links(url))
elapsed = time.strftime(
'%H:%M:%S', time.gmtime(timer() - start))
self._logger._logger.info('time elapsed {}'.format(elapsed))
async def _fetch_doc(self, client, url):
"""Fetch a sitemap.xml document."""
self._logger._logger.info('fetching sitemap @ {}'.format(url))
try:
async with client.get(
url=url,
allow_redirects=True,
timeout=ProdConfig.TIMEOUT,
verify_ssl=True
if url.startswith('https') else False) as response:
response.raise_for_status()
return await response.text()
except aiohttp.ClientResponseError as error:
self._logger._logger.error(
'sitemap yielded <{}>'.format(
error.status))
except aiohttp.ClientError as error:
self._logger._logger.error(str(error))
abort(1)
async def _producer(self, doc):
"""Parse sitemap.xml and queue discovered links."""
try:
root = defusedxml.ElementTree.fromstring(doc)
except defusedxml.ElementTree.ParseError:
self._logger._logger.error('failed to parse *.xml document')
abort(1)
self._logger._logger.info(
'*.xml document contains ({}) links'.format(
len(root)))
for link in root:
if link:
await self._queue.put(''.join(link[0].text.split()))
async def _consumer(self, client):
"""Process queued links with HEAD requests."""
while True:
url = await self._queue.get()
async with client.head(
url=url,
allow_redirects=True,
timeout=ProdConfig.TIMEOUT,
verify_ssl=True if url.startswith('https') else False) as http:
self._logger._logger.info(
'<{}> {} - {}'.format(http.status, http.reason, url))
self._queue.task_done()
async def _fetch_links(self, url):
"""Fetch sitemap.xml links."""
headers = {'User-Agent': ProdConfig.USER_AGENT}
connector = aiohttp.TCPConnector(
limit=ProdConfig.LIMIT, loop=self._loop)
async with aiohttp.ClientSession(
connector=connector, loop=self._loop, headers=headers) as client:
doc = await self._fetch_doc(client, url)
consumer = asyncio.ensure_future(self._consumer(client))
await self._producer(doc)
await self._queue.join()
consumer.cancel()
def __del__(self):
if self._loop:
if not self._loop.is_running:
self._loop.close()
if __name__ == '__main__':
Checker().check(sys.argv[1])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T03:41:06.590",
"Id": "386866",
"Score": "1",
"body": "Unfortunately I cannot get your code to run. It imports custom libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T10:54:10.857",
"Id":... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T01:15:40.007",
"Id": "200631",
"Score": "6",
"Tags": [
"python",
"performance",
"python-3.x",
"asynchronous"
],
"Title": "Asyncio HTTP Request Queue"
} | 200631 |
<p>I'm fairly new to d3 and am wanting to create a visualization that will allow a user to check whether or not a device will be in range of a bluetooth speaker. </p>
<p>I was able to hack together most of what I want, but am not sure if I'm following d3 best practices. This will be eventually integrated with React. Any feedback on style/efficiency is appreciated.</p>
<p>(Note: you'll want to view in the full page)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = 8,
unitRadius = 64;
var points = d3.range(10).map(function() {
return {
x: Math.round(Math.random() * (width - radius * 2) + radius),
y: Math.round(Math.random() * (height - radius * 2) + radius)
};
});
var circle = d3.range(1).map(function() {
return {
x: width / 2,
y: height / 2
};
});
var points = svg
.selectAll("circle.point")
.data(points)
.enter()
.append("circle")
.attr("class", "point")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", radius)
.style("fill", "red");
var circle = svg
.selectAll("circle.unit")
.data(circle)
.enter()
.append("circle")
.attr("class", "overlay")
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.attr("r", unitRadius)
.style("fill", "blue")
.call(
d3
.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);
function dragstarted(d) {
d3.select(this)
.raise()
.classed("active", true);
}
function dragged(d, i) {
d3.select(this)
.attr("cx", (d.x = d3.event.x))
.attr("cy", (d.y = d3.event.y));
var inside = d3.selectAll("circle.point").style("fill", function(p) {
var x = d.x - p.x;
var y = d.y - p.y;
var dis = Math.sqrt(x * x + y * y);
if (dis <= Math.abs(unitRadius - radius)) {
return "green";
} else {
return "red";
}
});
}
function dragended(d) {
d3.select(this).classed("active", false);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
fill-opacity: 0.1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<svg width="960" height="500"></svg></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Overall you have a pretty nice code for someone who is <em>\"fairly new to D3\"</em>, good on you.</p>\n\n<p>The proposed changes here are few:</p>\n\n<p><strong>The big circle</strong></p>\n\n<p>You have just one big circle (the blue one). Therefore, you don't need that mix of <code>d3.range</cod... | {
"AcceptedAnswerId": "200643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T01:42:46.020",
"Id": "200633",
"Score": "4",
"Tags": [
"javascript",
"d3.js"
],
"Title": "Visualization showing overlays of points"
} | 200633 |
<p>I am a novice programmer and am currently learning Python programming by myself through a book. I stumbled upon a question in a chapter and it took me 2 days to figure out a solution for it. Although, it may not be an efficient code for the problem, I would be grateful if you guys could review it. Just to let everyone know of my Knowledge level on programming, I just have basic knowledge of functions, sequences and decision structure.</p>
<blockquote>
<p>Write a program to check if a date is valid or not? The date should be
in the mm/dd/yyyy format.</p>
<p>Pseudocode:</p>
<ul>
<li>Define 3 functions to check the validity of month,day and year, if valid return True for each function.</li>
<li>input a string date separated by a "/" and assign it to a date variable.</li>
<li>split the date variable to 3 separate variables.</li>
<li>check if the 3 variables are True or not.</li>
<li>Print if the date is valid or not.</li>
</ul>
</blockquote>
<p>I didn't take into account leap years where February has 29 days and also assumed the year to start at 1 A.D. to current years.</p>
<pre><code>def monthcheck(month):
if month > 0 and month <= 12: ## If month is between 1 and 12, return True.
return True
else:
return False
def daycheck(month,day):
monthlist1 = [1,3,5,7,8,10,12] ## monthlist for months with 31 days.
monthlist2 = [4,6,9,11] ## monthlist for months with 30 days.
monthlist3 = 2 ## month with month with 28 days.
for mon in monthlist1: ## iterate through monthlist1.
if month == mon: ## Check if the parameter month equals to any month with 31 days.
if day >=1 and day <= 31: ## If the parameter day is between 1 and 31, return True.
return True
else:
return False
for mon in monthlist2: ## iterate through the monthlist with 30 days.
if month == mon: ## check if the parameter month equals to any month with 30 days.
if day >= 1 and day <= 30: ## if the parameter day is between 1 and 30,return True.
return True
else:
return False
if month == monthlist3: ## check if parameter month equals month with 28 days.
if day >=1 and day <= 28: ## if the parameter day is between 1 and 28,return True.
return True
else:
return False
def yearcheck(year):
if len(year) >= 1 and len(year) <= 4: ## Check if year has between 1 to 4 numbers and return True.
return True
else:
return False
def main():
date = str(input("Enter the date in mm/dd/yyyy format: ")) ## Input date in the given format.
month,day,year = date.split("/") ## split the date into 3 separate variables.
monthvalidity = monthcheck(int(month))
dayvalidity = daycheck(int(month),int(day))
yearvalidity = yearcheck(year)
if monthvalidity == True and dayvalidity == True and yearvalidity == True: ## check if all 3 variables are valid or True
print("The date {0} is valid.".format(date))
else:
print("The date {0} is invalid.".format(date))
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T09:28:03.683",
"Id": "386370",
"Score": "17",
"body": "Welcome to hell. Validating a date is one of the hardest (programming) problems ever. For example you are not checking if the year is n the range of dates when the gregorian cal... | [
{
"body": "<p>For the most part, looks pretty good to me!</p>\n\n<h2>Format</h2>\n\n<p>You didn't use underscores to separate the words in a lot of variable names, which kinda bothered me. Snake_case is recommended by PEP8, so I changed that.</p>\n\n<p>You also added extra indentation in your first function (wh... | {
"AcceptedAnswerId": "200639",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T02:23:51.933",
"Id": "200634",
"Score": "21",
"Tags": [
"python",
"beginner",
"python-3.x",
"datetime",
"validation"
],
"Title": "Program to check if a date is valid or not"
} | 200634 |
<p>I have a need to update thousands of database records at a time. I am using a loop to generate the necessary <code>PreparedStatement</code> updates, but am hoping for a more efficient method.</p>
<p>Normally, I would try to use a batch operation, but since the number of fields I need to update for each record differs, I need a new <code>PreparedStatement</code> for each update.</p>
<p>As it is, updates around 2,000 records takes 3-4 minutes.</p>
<pre><code> for (AgentUpdate update : updateList) {
Agent thisAgent = update.getAgent();
// Prefix for updating each agent
StringBuilder sql = new StringBuilder(
"UPDATE REP_ASSIST.AGENTS SET\n"
);
// Create a map of all changes
Map<String, String> updateMap = new HashMap<>();
for (AgentDiffs diff : update.getChanges()) {
updateMap.put(diff.getAgentField().toString(), diff.getNewValue());
}
// Iterate through the map and build the SQL statement,
// including all fields to be updated
Iterator iterator = updateMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry) iterator.next();
sql.append(pair.getKey()).append("=?");
if (iterator.hasNext()) {
sql.append(",\n");
}
}
sql.append("\nWHERE AGENT_CODE=? AND UPN=?;");
Utility.printTempMsg(sql.toString());
// Create the PreparedStatement and fill each ? with the
// appropriate new value.
ps = connection.prepareStatement(sql.toString());
int paramNum = 1;
for (String fieldName : updateMap.keySet()) {
String newValue = updateMap.get(fieldName);
ps.setString(paramNum, newValue);
// Increase the parameter count
paramNum++;
}
// We are now to our last two parameters, fill them
ps.setString(paramNum++, thisAgent.getAgentCode());
ps.setInt(paramNum, thisAgent.getAgentUpn());
ps.executeUpdate();
count++;
Utility.printTempMsg(sql.toString());
// Update the progress based on total count so far
updateProgress(count, totalOperations);
}
</code></pre>
<p>So how does one handle large dynamic updates of this sort?</p>
| [] | [
{
"body": "<p>You don't even need to create a <code>HashMap</code> because you already have an object <code>AgentDiffs</code> to hold the values for you. Creating a <code>HashMap</code> is just an unnecessary step here.</p>\n\n<p>To create the <code>UPDATE</code> statement, you may directly use <code>Stream</co... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T02:28:36.597",
"Id": "200635",
"Score": "2",
"Tags": [
"java",
"sql-server",
"jdbc"
],
"Title": "Slow SQL Server performance with multiple PreparedStatement loop"
} | 200635 |
<p>I'm currently working on an approval system right now using <strong>PHP (Codeigniter)</strong> and I have this method of getting all the requests according to your department group and position depth.</p>
<p>The checking of the requests is based upon the user's position depth. 6 being the lowest and 1 being the highest. So basically there will be a maximum of 5 people to check the request. For example my depth is 6, line1 will be 5, line2 will be 4 and so on. The system will find someone with position depths like that and same department group. Lines 3 and 2 will decide to send it to ceo (1) or not so the default is only until 2.</p>
<p><strong>Some of my database columns</strong>
<a href="https://i.stack.imgur.com/DzNlA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DzNlA.jpg" alt="Some database columns"></a></p>
<p>It is designed that people above the line can check the request even if the lower lines havent checked it yet like for example maybe line1 havent checked it yet because he/she is on vacation and line3 cannot wait already so he/she decides to process the request because it is important. <strong>Now if the above line processes it already, lower lines cannot process it anymore so they will only be allowed to view it.</strong></p>
<p>Now here comes my code of nested <code>for</code> loops in checking out all these things that I said. People say nested <code>for</code> loops, especially as many as mine is not a good practice. <strong>Is my <code>for</code> loop gonna have problems when it comes to large data? If so how do I alter my code without altering my database for this?</strong></p>
<p><strong>This is my Model</strong></p>
<pre><code>public function getRequestsToProcess($i,$depth,$departmentGroup)
{
$this->db->select('*, ns_request_info.idx as request_idx, ns_staff_info.idx as staff_idx');
$this->db->from('ns_request_info');
$this->db->join('ns_staff_info', 'ns_request_info.requested_by_idx = ns_staff_info.member_idx');
$this->db->where('line'.$i.'', $depth);
$this->db->where('line'.$i.'_action', 'PENDING');
if($departmentGroup!='HIGHER TIER'){ $this->db->where('ns_staff_info.department_group', $departmentGroup); }
$this->db->where('status', 'PENDING');
$this->db->or_where('status', 'ONGOING');
$this->db->where('line'.$i.'', $depth);
$this->db->where('line'.$i.'_action', 'PENDING');
if($departmentGroup!='HIGHER TIER'){ $this->db->where('ns_staff_info.department_group', $departmentGroup); }
$query = $this->db->get();
return $query->result_array();
}
</code></pre>
<p><strong>This is my method with nested <code>for</code> loops</strong></p>
<pre><code>public function process()
{
$data = new stdClass;
$data->param_menu = 'request';
$staffInfo = $this->staffinfo_model->selectItem(array('member_idx'=>$this->session->userdata('member_index')));
for ( $i=1 ; $i<=5 ; $i++) {
/*get lines with user depth and if same department group*/
${"line" . $i} = $this->staffrequisition_model->getRequestsToProcess($i,$staffInfo->position_depth,$staffInfo->department_group);
for ($x = 0 ; $x < count(${"line" . $i}) ; $x++) {
$counter = 0;
for ($y = $i + 1 ; $y <=5 ; $y++) {
if (${"line" . $i}[$x]['line'.$y.'_action']!=='PENDING' && ${"line" . $i}[$x]['line'.$y.'_action']!=='') {
$counter++;
break;
}
}
if ($counter > 0) {
${"line" . $i}[$x]['is_checked'] = 1;
} else {
${"line" . $i}[$x]['is_checked'] = 0;
}
}
}
$data->param_requests = array_merge($line1, $line2, $line3, $line4, $line5);
$this->load->view('dashboard/staff/process_view', $data);
}
</code></pre>
<p>Now <code>is_checked</code> being the marker if the request is already checked in upper lines. I hope you guys can give me any tips on how to optimize my code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T07:46:05.237",
"Id": "386349",
"Score": "2",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished ... | [
{
"body": "<p>I am able to remove one <code>for</code> loop in my code with the following:</p>\n\n<p>I changed my method in the Controller</p>\n\n<pre><code>public function process()\n{\n $data = new stdClass;\n $data->param_menu = 'request';\n\n $staffInfo = $this->staffinfo_model->selectItem... | {
"AcceptedAnswerId": "200872",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T04:47:49.410",
"Id": "200642",
"Score": "2",
"Tags": [
"performance",
"php",
"codeigniter"
],
"Title": "CodeIgniter method to get requests for superiors to approve"
} | 200642 |
<p>I have made some code in c#. I am currently developing a Gameserver so I have a function to update fields in the database. I also have a function to update the player-cash, but its like almost the same code. So my question is, do you guys have an idea to put this into one function?</p>
<pre><code> /// <summary>
/// This function helps to update something in the dabase by an objectid
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
/// <param name="userid"></param>
public static void UpdateUserColByObjectId<T>(string key, T value, ObjectId objectid)
{
var filter = Builders<User>.Filter.Eq("_id", objectid);
var update = Builders<User>.Update.Set(key, value);
Usercol.UpdateOne(filter, update);
}
/// <summary>
/// Changes the cash in the database
/// </summary>
/// <param name="player">The player</param>
/// <param name="money">The new money he has</param>
public static void ChangeDatabaseCash(Client player, int money)
{
//Create filters
var filter = Builders<User>.Filter.Eq("_id", player.GetData("objectid"));
var update = Builders<User>.Update.Set("cash", money);
//Update it
Usercol.UpdateOne(filter, update);
//Create a log
LogSystem.CreateLog("money", "Datbase cash changed to " + money + " player: " + player.GetData("objectid"));
//change it in the client
Utils.ChangeCashClient(player, money);
}
</code></pre>
| [] | [
{
"body": "<p>The functions are almost identical for the first 3 lines of code. Applying DRY (don't repeat yourself) principles you would call the first function in your second function instead of rewriting the filter / update / updateone part:</p>\n\n<pre><code>public static void ChangeDatabaseCash(Client play... | {
"AcceptedAnswerId": "200671",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T12:44:58.167",
"Id": "200661",
"Score": "-2",
"Tags": [
"c#",
"mongodb"
],
"Title": "How can I get this two functions into one"
} | 200661 |
<p><strong>Aim:</strong> To improve the speed of the following code. Current timing is about 80~ hours :0 </p>
<p><strong>Purpose:</strong> The code imports a dataset which contains 1.9 million rows and two columns. One of these columns contain text posts of var length. I then loop through each of these <em>rows</em> and query the post against an imported function that returns a specific counter of <em>variable length</em>. The counter tells me about the presence of certain words in the text. On average the func takes less than 1 ms to return this counter. (Timer for the "Func" inserted at the end to prove this)</p>
<p><strong>Overheads:</strong> The code i'm looking to improve is the loop. I accept a certain level of overhead with the "func" which can't be improved at this minute. I have considered looking at Spark or Dask to parallelize the loop and speed up the process. Suggestions are welcome</p>
<pre><code>#Import data
import pandas as pd
from func import func
data = pd.read_csv('Dataset.csv')
print(len(data))
>> 1900000
print(data.columns)
>> Index(['type', 'body'], dtype='object')
#Create new DF
data2 = pd.Dataframe()
for post in data['post']:
post = str(post)
scores = func.countWords(posts)
data2 = data2.append(scores,ignore_index=True)
print(scores)
>> Counter({0: 306,
1: 185,
2: 61,
45: 31,
87: 23,
92: 5,
94: 3,
102: 30,})
import time
start = time.time()
score = func.countWords("Slow down Sir, you're going to give yourself skin faliure!")
end = time.time()
print(end - start)
>> 0.0019948482513427734
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T16:56:11.323",
"Id": "386416",
"Score": "4",
"body": "Any appreciable speedup here will come from optimizing countWords - I\"d advise that you post that function for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creat... | [
{
"body": "<p>Several errors:</p>\n\n<blockquote>\n <p>I then loop through each of these loops</p>\n</blockquote>\n\n<p>I take it you mean \"I then loop through each of these columns\".</p>\n\n<blockquote>\n <p>for post in data['post]:</p>\n</blockquote>\n\n<p>missing end quote mark</p>\n\n<blockquote>\n <p>... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T13:08:18.460",
"Id": "200662",
"Score": "1",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Importing text into PANDAS and counting certain words"
} | 200662 |
<p>I have a real-world problem involving finding the best known term from a string containing sets of terms. We have <code>Term</code> objects that are comparable in that they have a method <code>a_term.is_better_than(other_term)</code>. This method is Boolean -- if it returns <code>False</code>, then <code>a_term</code> may be as good as <code>other_term</code>, but isn't better.</p>
<p>Using this method, I need to pare down a set of terms to the best ones. The best way I've been able to think about this is to compare pairs of terms and eliminate any terms when one isn't as good as the other, something like this:</p>
<pre><code>def get_best_terms(terms: Set[Term]): Set[Term]
best_terms = set()
m_terms = list(terms)
while m_terms:
term = m_terms.pop()
for i in reversed(range(len(m_terms))):
if term.is_better_than(m_terms[i]):
del m_terms[i]
if m_terms[i].is_better_than(term):
break
else: # We never encountered the `break` statement
best_terms.add(term)
break
best_terms |= {a_term for a_term in m_terms
if not (term.is_better_than(a_term) or
a_term.is_better_than(term))}
return best_terms
</code></pre>
<p>This approach is functional, but pretty gross in my opinion. For one thing, there's a lot of mutation going on here. For another, once I've identified a single best term, finding all the terms that are equally good is messy. The whole thing is hard to read.</p>
<p>What do you suggest?</p>
<h2>Examples</h2>
<p>A Term is a string with some metadata attached. For example,</p>
<pre><code>a = AutoTerm(term='honda', term_span=1, term_range=(1, 2),
original_term='CAR HONDA ACC...')
b = AutoTerm(term='2015 honda accord', term_span=2, term_range=(1, 3),
original_term='2015 HONDA ACC...')
c = AutoTerm(term='2015 accord', ...)
</code></pre>
<p>Sometimes a term is a better choice because it's more specific, but there are other nuances, such as a match in a database. Let's say, arbitrarily, that b and c are equally good, but <code>a</code> is not as good. Then</p>
<pre><code>assert get_best_terms({a, b, c}) == {b, c}
</code></pre>
<p>should pass.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T13:57:47.250",
"Id": "386396",
"Score": "0",
"body": "Can you provide an example of `Term` and some example IO?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T20:01:23.787",
"Id": "386448",
"... | [
{
"body": "<ol>\n<li>You have a bug, if you remove an item in your <code>for</code> loop without breaking you get an <code>IndexError</code>.\nInstead use a <code>worse</code> set so that you know what to skip.</li>\n<li>What you seem to be doing is performing a sort, and so if you make a <code>cmp</code> funct... | {
"AcceptedAnswerId": "200667",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T13:17:57.733",
"Id": "200663",
"Score": "5",
"Tags": [
"python",
"algorithm"
],
"Title": "Finding the best terms to use"
} | 200663 |
<p>I have a JS running in Google App Script, but for me, it's like an overall example/problem I ran into more often.
The script fetches via JDBC the results of a MySQL query. The result has about 60.000 rows. Fetching that goes quite fast. After that I take the result and use this JS code to write it into a 2D array:</p>
<pre><code>var rangeArray = [];
var row = 1;
while (rs.next()) {
var tempArray = [];
for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
tempArray.push(rs.getString(col + 1));
}
rangeArray.push(tempArray);
row++;
}
</code></pre>
<p>So it's this loop, which costs most time.
Fetching the query result itself executes in about 12 seconds - which is pretty much the execution time of the MySQL server itself.</p>
<p>However, fetching the query results AND write them to the array takes 10 minutes.
I am not surprised that it takes that long but is there a principal way to avoid such loops and create the array more effectively.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T21:44:46.267",
"Id": "386462",
"Score": "1",
"body": "Probably only a minor improvement and not a complete answer, but assuming `rs.getMetaData().getColumnCount()` doesn't change from one call to the next, you could pull that out in... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T14:33:58.587",
"Id": "200666",
"Score": "1",
"Tags": [
"javascript",
"performance",
"jdbc",
"google-apps-script"
],
"Title": "JavaScript loop to copy JDBC query results to a 2D array"
} | 200666 |
<p>Please critique this very, very basic routine which returns the length of a given char buffer or "string."</p>
<pre><code>strlen: ; NOTE: RDI IS THE DEFAULT SRC FOR SCASB
push rdi
push rcx
xor rcx, rcx
mov rcx, -1
xor al, al
cld
repne scasb
neg rcx
sub rcx, 1
mov rax, rcx
pop rcx
pop rdi
ret
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:41:10.040",
"Id": "386426",
"Score": "2",
"body": "I would be helpful to indicate whether you're coding to the [Sys V ABI](https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf) or the [Microsoft ABI](... | [
{
"body": "<p>Saving <code>rcx</code> is usually not necessary, it is not callee-save in common calling conventions. On Linux (and similar) <code>rdi</code> also does not need to be saved, I guess you're using that since the Win64 calling convention does not pass an argument in <code>rdi</code>. You can save th... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T14:51:15.097",
"Id": "200669",
"Score": "11",
"Tags": [
"strings",
"assembly",
"x86"
],
"Title": "string length in x64 assembly (fasm)"
} | 200669 |
<p>The idiomatic way of reading lines from a file doesn't work for my purposes because the files I'm dealing with might have lines that are escaped. I came up with the below (which seems to meet my needs) and am wondering if anyone has ideas on how I can improve things:</p>
<pre><code>import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public final class LineReader implements AutoCloseable, Iterable<String> {
private final char[] m_buffer;
private final char m_escapeChar;
private final Object m_lock;
private final InputStreamReader m_reader;
private int m_bufferOffset = 0;
private int m_bufferPosition = 0;
private String m_lineValue = "";
private int m_numCharsRead = 0;
public String getCurrent() { return m_lineValue; }
public LineReader (final InputStreamReader reader, final char escapeChar, final int bufferLength) {
m_buffer = new char[bufferLength];
m_escapeChar = escapeChar;
m_lock = this;
m_reader = reader;
}
public LineReader(final InputStreamReader reader) {
this(reader, '"', 1024);
}
public LineReader(final String filePath, final String encodingName) throws FileNotFoundException, UnsupportedEncodingException {
this (new InputStreamReader(new FileInputStream(filePath), encodingName));
}
public void close() throws IOException {
m_reader.close();
}
public Iterator<String> iterator() {
return new Iterator<String>() {
@Override
public boolean hasNext() {
try {
return read();
}
catch (final IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public String next() {
return getCurrent();
}
};
}
public boolean read() throws IOException {
final char[] buffer = m_buffer;
final char escapeChar = m_escapeChar;
final Object lock = m_lock;
boolean isEscaping = false;
synchronized(lock) {
m_lineValue = "";
do {
while (m_bufferPosition < m_numCharsRead) {
final char currentChar = buffer[m_bufferPosition++];
if (currentChar == escapeChar) {
if (!nextCharEquals(escapeChar)) {
isEscaping = !isEscaping;
}
else {
m_bufferPosition++;
}
}
if (!isEscaping && ((currentChar == '\r') || (currentChar == '\n'))) {
if (m_bufferOffset < m_bufferPosition) {
m_lineValue += new String(buffer, m_bufferOffset, (m_bufferPosition - m_bufferOffset - 1));
}
if ((currentChar == '\r') && nextCharEquals('\n')) {
m_bufferPosition++;
}
m_bufferOffset = m_bufferPosition;
return true;
}
}
} while (fillBuffer());
return (m_lineValue.equals("") ? false : true);
}
}
public Stream<String> stream() {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), (Spliterator.NONNULL | Spliterator.ORDERED)), false);
}
private boolean fillBuffer() throws IOException {
final char[] buffer = m_buffer;
final int offset = m_bufferOffset;
final int position = m_bufferPosition;
final InputStreamReader reader = m_reader;
if (offset < position) {
m_lineValue += new String(buffer, offset, (position - offset));
}
m_bufferOffset = 0;
m_bufferPosition = 0;
m_numCharsRead = reader.read(buffer);
return (0 < m_numCharsRead);
}
private boolean nextCharEquals(final char value) throws IOException {
return (((m_bufferPosition < m_numCharsRead) || fillBuffer()) && (m_buffer[m_bufferPosition] == value));
}
}
</code></pre>
| [] | [
{
"body": "<p>I noticed that you return a ternary statement for a boolean value, this is not necessary.</p>\n\n<blockquote>\n<pre><code>return (m_lineValue.equals(\"\") ? false : true);\n</code></pre>\n</blockquote>\n\n<p>you should simply return:</p>\n\n<pre><code>return !m_lineValue.equals(\"\");\n</code></pr... | {
"AcceptedAnswerId": "200688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T14:56:09.027",
"Id": "200670",
"Score": "4",
"Tags": [
"java",
"file",
"escaping"
],
"Title": "Escaped line reader"
} | 200670 |
<p>I've made a simple dirbuster. (I wanted to play with threading.)</p>
<p>The program makes requests to <a href="https://en.wikipedia.org/wiki/Fuzzing" rel="nofollow noreferrer">fuzz</a> for files and/or directories on a site.</p>
<p><strong>Featuring</strong></p>
<ul>
<li>fuzzing for response codes</li>
<li>fuzzing for files</li>
<li>threading</li>
</ul>
<p>You can critique any and all.</p>
<p><strong>Troubling points</strong></p>
<ul>
<li>The way it handles threading</li>
<li>I think I'm over engineering the arguments handler</li>
</ul>
<h1>Code</h1>
<pre><code>import threading
from queue import Queue
from textwrap import dedent
from urllib.parse import urljoin
import os
import sys
import re
import argparse
import requests
NUMBER_OF_THREADS = 5
QUEUE = Queue()
def create_workers(response_codes):
"""creates some threads of workers"""
for _ in range(NUMBER_OF_THREADS):
thread = threading.Thread(target=work, args=(response_codes,))
thread.daemon = True
thread.start()
def work(response_codes):
"""gets the url from the queue and call print_response_code"""
while True:
url = QUEUE.get()
print_response_code(url, response_codes)
QUEUE.task_done()
def dir_buster(url, wordlist, file_extensions):
"""puts the urls to fuzz in a queue"""
for word in read_wordlist(wordlist):
QUEUE.put(urljoin(url, word))
if not file_extensions is None:
for ext in file_extensions:
QUEUE.put(urljoin(url, f"{word}.{ext}"))
QUEUE.join()
def read_wordlist(wordlist):
"""yields a word from a \n delimited wordlist"""
with open(wordlist) as f:
for line in f:
yield line.rstrip()
def print_response_code(url, response_codes):
"""gets response code from url and prints if matches a condition"""
code = requests.head(url).status_code
if response_codes is None or code in response_codes:
print(f"[{code}]\t{url}")
def parse_arguments():
"""arguments parser"""
parser = argparse.ArgumentParser(usage='%(prog)s [options] <url>',
description='Dirbuster by @Ludisposed',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=dedent('''Examples:
python dirbust.py -c "200, 301, 401" -w wordlist.txt -t 10 -e "html, php ,py" https://mylocalweb:1234'''))
parser.add_argument('-c', '--code', type=str, help='HTTP response codes to filter on')
parser.add_argument('-e', '--extension', type=str, help='Filename extensions you want to fuzz')
parser.add_argument('-t', '--threads', type=int, help='Number of threads')
parser.add_argument('-w', '--wordlist', type=str, help='Wordlist you want to fuzz with')
parser.add_argument('url', type=str, help='Url you want to fuzz')
args = parser.parse_args()
try:
requests.head(args.url).status_code
except Exception as e:
print("[!] Url is not responding")
sys.exit(1)
if args.wordlist is None or not os.path.isfile(args.wordlist):
print("[!] Wordlist is not valid")
sys.exit(1)
if not args.code is None and re.match(r"^(\s*\d{1,3}\s*)(,\s*\d{1,3}\s*)*$", args.code) is None:
print("[!] Response codes are not valid, logging all response codes")
args.code = None
if not args.code is None:
args.code = list(map(int, re.sub(r"\s+", "", args.code).split(",")))
if not args.extension is None and re.match(r"^(\s*[a-z]+\s*)(,\s*[a-z]+\s*)*$", args.extension.lower()) is None:
print("[!] Extensions are not valid, only searching for directories")
args.extension = None
if not args.extension is None:
args.extension = re.sub(r"\s+", "", args.extension).split(",")
if not args.threads is None:
global NUMBER_OF_THREADS
NUMBER_OF_THREADS = args.threads
return args.url, args.code, args.wordlist, args.extension
def main(url, response_codes, wordlist, file_extensions):
"""main method that will create workers and adds url to the Queue"""
create_workers(response_codes)
dir_buster(url, wordlist, file_extensions)
if __name__ == '__main__':
main(*parse_arguments())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T16:45:56.260",
"Id": "386415",
"Score": "1",
"body": "What is a dirbuster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:07:53.187",
"Id": "386417",
"Score": "0",
"body": "'@MathiasEt... | [
{
"body": "<p>I do have some points in regards to scope. Having code like:</p>\n\n<pre><code>if not args.threads is None:\n global NUMBER_OF_THREADS\n NUMBER_OF_THREADS = args.threads\n</code></pre>\n\n<p>means you'll encounter weird issues when values change and you need to track them down. Obviously I'm... | {
"AcceptedAnswerId": "200713",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T15:05:45.313",
"Id": "200672",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"multithreading"
],
"Title": "Simple dirbuster with threading"
} | 200672 |
<p>I have an assignment to create a GUI with a keyboard and text area. Conceptually, the user would type on the physical keyboard and the respective key would change background on screen to reflect that key press. Pressing the onscreen keys yields no behaviour so I don't need to implement <code>keyTyped(...)</code> (I think).</p>
<p>For brevity and as per SO's axiomatic policies, here's some relevant code (let me know if there's something to add)</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
Object current = press.getSource();
for (int i = 0; i < 14; i++) {
if (current.toString() == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
repaint();
}
}
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
for (int i = 0; i < 14; i++) {
if (current.toString() == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
repaint();
}
}
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
</code></pre>
<p>How do I map the physicals key pressed with the on screen keyboard with KeyEvent?</p>
<hr>
<p>Edit:</p>
<p>Full code</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ButtonInPane extends JFrame implements KeyListener {
// input
String input;
//context
JLabel context1, context2;
// default color
Color defaultColor = new JButton().getBackground();
// main rows of keys
public String rowOne[] = {
"~",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"+",
"h"
};
public String rowTwo[] = {
"Tab",
"Q",
"W",
"E",
"R",
"T",
"Y",
"U",
"I",
"O",
"P",
"[",
"]",
"\\"
};
public String rowThree[] = {
"Caps",
"A",
"S",
"D",
"F",
"G",
"H",
"J",
"K",
"L",
":",
"'",
"Enter"
};
public String rowFour[] = {
"Shift",
"Z",
"X",
"C",
"V",
"B",
"N",
"M",
",",
".",
"?",
" ^"
};
public String rowFive[] = {
" ",
"<",
"v",
">"
};
/**
* Account for chars with no shift: Program toggles Shift key, meaning if a
* user clicks on it, all keys will be toggled to their respective shift
* value. The user can tap the shift key again to change back to regular
* value
*/
public String shiftless[] = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"0",
"-",
"=",
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
};
// Account for special chars
public String specialChars[] = {
"~",
"-",
"+",
"[",
"]",
"\\",
";",
".",
"?"
};
// declare rows of buttons
public JButton buttons_rowOne[], buttons_rowTwo[], buttons_rowThree[], buttons_rowFour[], buttons_rowFive[];
private JTextArea body;
private JPanel top;
private JPanel middle;
private JPanel bottom;
private JPanel contextBox;
// ctor
public ButtonInPane() {
super("Typing Tutor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setPreferredSize(new Dimension(1000, 600));
this.setLocation(50, 50);
this.setVisible(true);
__init__();
}
public void __init__layout(JPanel top, JPanel middle, JPanel bottom, JPanel contextBox) {
setLayout(new BorderLayout());
add(top, BorderLayout.NORTH);
add(contextBox);
add(middle, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
}
public void __init__body() {
body = new JTextArea();
body.setPreferredSize(new Dimension(1000, 150));
body.addKeyListener(this);
}
public void __init__panels() {
context1 = new JLabel("Type some text using your keyboard. " +
"The keys you press will be highlighed and the text will be displayed.");
context2 = new JLabel("\nNote: Clicking the buttons with your mouse will not perform any action.");
context1.setFont(new Font("Verdana", Font.BOLD, 14));
context2.setFont(new Font("Verdana", Font.BOLD, 14));
top = new JPanel();
top.setSize(new Dimension(500, 500));
middle = new JPanel();
bottom = new JPanel();
contextBox = new JPanel();
__init__layout(top, middle, bottom, contextBox);
top.setLayout(new BorderLayout());
bottom.setLayout(new GridLayout(5, 5));
top.add(context1);
top.add(context2);
middle.setLayout(new BorderLayout());
middle.add(body, BorderLayout.WEST);
middle.add(body, BorderLayout.CENTER);
}
public void __init__() {
// text area
__init__body();
// panels for layout
__init__panels();
pack();
// get length of row strings
int length_rowOne = rowOne.length;
int length_rowTwo = rowTwo.length;
int length_rowThree = rowThree.length;
int length_rowFour = rowFour.length;
int length_rowFive = rowFive.length;
// create array for each row of buttons
buttons_rowOne = new JButton[length_rowOne];
buttons_rowTwo = new JButton[length_rowTwo];
buttons_rowThree = new JButton[length_rowThree];
buttons_rowFour = new JButton[length_rowFour];
buttons_rowFive = new JButton[length_rowFive];
// create panel for each row of buttons
JPanel r1 = new JPanel(new GridLayout(1, length_rowOne));
JPanel r2 = new JPanel(new GridLayout(1, length_rowTwo));
JPanel r3 = new JPanel(new GridLayout(1, length_rowThree));
JPanel r4 = new JPanel(new GridLayout(1, length_rowFour));
JPanel r5 = new JPanel(new GridLayout(1, length_rowFive));
// draw out the rows of buttons
draw(r1, length_rowOne, r2, length_rowTwo, r3, length_rowThree, r4, length_rowFour, r5, length_rowFive);
}
// draw rows of buttons
public void draw(JPanel r1, int s1, JPanel r2, int s2, JPanel r3, int s3, JPanel r4, int s4, JPanel r5, int s5) {
for (int i = 0; i < s1; i++) {
JButton currentButton = new JButton(rowOne[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowOne[i] = currentButton;
r1.add(buttons_rowOne[i]);
}
for (int i = 0; i < s2; i++) {
JButton currentButton = new JButton(rowTwo[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowTwo[i] = currentButton;
r2.add(buttons_rowTwo[i]);
}
for (int i = 0; i < s3; i++) {
JButton currentButton = new JButton(rowThree[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowThree[i] = currentButton;
r3.add(buttons_rowThree[i]);
}
for (int i = 0; i < s4; i++) {
JButton currentButton = new JButton(rowFour[i]);
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFour[i] = currentButton;
r4.add(buttons_rowFour[i]);
}
for (int i = 0; i < s5; i++) {
JButton currentButton = new JButton(rowFive[i]);
// account for space bar
if (i == 1) {
currentButton = new JButton(rowFive[i]);
currentButton.setPreferredSize(new Dimension(400, 10));
currentButton.setBounds(10, 10, 600, 100);
buttons_rowFive[i] = currentButton;
} else {
currentButton.setPreferredSize(new Dimension(100, 50));
buttons_rowFive[i] = currentButton;
}
r5.add(buttons_rowFive[i]);
}
bottom.add(r1);
bottom.add(r2);
bottom.add(r3);
bottom.add(r4);
bottom.add(r5);
} // !draw(...)
// called when a button is pressed
@Override
public void keyPressed(KeyEvent press) {
Object current = press.getSource();
for (int i = 0; i < 14; i++) {
if (current.toString() == rowOne[i]) {
buttons_rowOne[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowTwo[i]) {
buttons_rowTwo[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowThree[i]) {
buttons_rowThree[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowFour[i]) {
buttons_rowFour[i].setBackground(Color.BLACK);
repaint();
} else if (current.toString() == rowFive[i]) {
buttons_rowFive[i].setBackground(Color.BLACK);
repaint();
}
}
} // !keyPressed(...)
// called when a button is released
@Override
public void keyReleased(KeyEvent release) {
Object current = release.getSource();
for (int i = 0; i < 14; i++) {
if (current.toString() == rowOne[i]) {
buttons_rowOne[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowTwo[i]) {
buttons_rowTwo[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowThree[i]) {
buttons_rowThree[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowFour[i]) {
buttons_rowFour[i].setBackground(defaultColor);
repaint();
} else if (current.toString() == rowFive[i]) {
buttons_rowFive[i].setBackground(defaultColor);
repaint();
}
}
} // !keyReleased(...)
@Override
public void keyTyped(KeyEvent typed) {
// Object current = typed.getSource().toString();
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 14; i++) {
// if (current == rowOne[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowTwo[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowThree[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFour[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// } else if (current == rowFive[i]) {
// sb.append(typed.getKeyCode());
// body.append(sb.toString());
// }
// }
}
// main method
public static void main(String[] args) {
new ButtonInPane();
} // !main method
private static final long serialVersionUID = 999;
} // !main class
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:29:34.617",
"Id": "386422",
"Score": "0",
"body": "\"How do I map the physicals key pressed with the on screen keyboard with KeyEvent?\" This would make it off topic. Is your code currently working as intended?"
},
{
"Con... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:13:23.300",
"Id": "200679",
"Score": "1",
"Tags": [
"java",
"swing",
"javafx",
"awt"
],
"Title": "KeyEvent listener: mapping physical keyboard to onscreen keyboard"
} | 200679 |
<p>I wonder if it's possible to optimize this code in CUDA. Could I get any hints how to? Equivalent algorithm runs faster in Matlab for me, but there I'm doing matrix operations.</p>
<h1>Compution</h1>
<p>I'm not asking how to change computation or optimize math operations. But nonetheless I will describe goal of this kernel.</p>
<p>Basically I need to do \$1e5\$ of <code>for</code> loops. Each of these <code>for</code> loops is computing weight matrix <code>W += Wi</code> where <code>Wi</code> is weight of pattern <code>Pi</code>. There are, for example, 400 patterns <code>P</code>. After getting <code>W</code> we pick random index <code>k</code> of some pattern from <code>P</code>, then compute <code>S = W*P[k]</code> and check hamming distance between feed <code>P[k]</code> and <code>S</code>.</p>
<p>I implemented all this algorithm in single kernel. All patterns are generated before hand (here as dummy 1). Each pattern is supposed to be different so together there are \$1e5 \cdot 400\$ patterns.</p>
<p>Each pattern is of size <code>N = 100</code>. Total memory of patterns is:</p>
<p>\$1e5 \cdot 400 \cdot 100 \cdot sizeof(int) = 15.3GB\$.</p>
<p>I have only 6GB of GPU memory so I had put this patterns to chunks. </p>
<h1>Kernel structure</h1>
<p>My kernel is organized like that:</p>
<ul>
<li>each block computes for one time step for no of steps: \$1e5\$/<code>nChunks</code></li>
<li>each thread computes weights for one pattern from nP patterns</li>
<li>some lucky thread is picked randomly and:
<ul>
<li>computes state of network after feeding some pattern</li>
<li>then computes error between feed and state</li>
</ul></li>
</ul>
<h1>What are ways to optimize this kernel?</h1>
<p>My ideas:</p>
<ul>
<li>Should I replace for loops inside kernel with some high performance functions? </li>
<li>Make simpler kernel and run it in async with \$1e5\$ calls?</li>
</ul>
<p>I'm asking for this to better understand how to use CUDA properly in some algorithm rather than in some general cases like mat mul, etc.</p>
<h2>Kernel</h2>
<p>#define N_N 100</p>
<pre><code>__global__ void mykernel(cuint nSteps, cuint nP, cuint nN, cuint caseIdx, const int *P, float *errorB) {
cuint stepIdx = blockIdx.x;
cuint stepSize = blockDim.x * blockIdx.x;
cuint patternIdx = threadIdx.x;
if (patternIdx < nP && stepIdx < nSteps) {
__shared__ volatile float s_W[N_N * N_N]; //weights updated from all patterns
//extern __shared__ volatile int s_P[]; //each thread has his own pattern
__shared__ volatile int s_F[N_N]; //we share same feed pattern
__shared__ volatile float s_S[N_N];
float Wij = 0;
float _N = 1.f / nN;
cuint idx = stepSize + patternIdx * nN;
//compute W matrix from weights of all patterns
#pragma unroll
for (int i = 0; i < nN; ++i) {
#pragma unroll
for (int j = 0; j < nN; ++j) {
s_W[i * nN + j] += P[idx + i] * P[idx + j] * _N;
}
}
int feedIdx = 0; //random index from range [0, nP)
if (patternIdx == feedIdx) {
#pragma unroll
for (int i = 0; i < nN; ++i) {
s_F[i] = P[idx + i];
}
}
__syncthreads();
//compute state for given feed index, only once
if (patternIdx == 0) {
float Si;
#pragma unroll
for (int i = 0; i < nN; ++i) {
Si = 0;
#pragma unroll
for (int j = 0; j < nN; ++j) {
Si += s_W[i * nN + j] * s_F[i];
}
s_S[i] = Si;
}
#pragma unroll
for (int i = 0; i < nN; ++i) {
errorB[caseIdx] += s_S[i] != s_F[i];
}
}
}
}
</code></pre>
<p>Complete code:</p>
<pre><code># To run this code with profiling do:
# nvprof ./hello --system-profiling on --print-gpu-trace on --profile-from-start off
//#include "cuda_reduce_benchmark.cuh"
//#include "hopfield_deterministic.cuh"
#ifdef USE_CUDA_DUMMY
#include "cuda_dummy.h"
//#include "std_utils.h"
#else
#include <cuda.h>
#include <cuda_runtime.h>
#include <cstdio>
#include <cuda_profiler_api.h>
#ifdef USE_CUBLAS
#include <cublas_v2.h>
#endif
#ifdef USE_CURAND
#include <curand.h>
#endif
// Utilities and system includes
#include <helper_cuda.h>
#include <helper_functions.h>
#define __CUDA_INTERNAL_COMPILATION__
#include <math_functions.h>
#include <device_functions.h>
#include <device_launch_parameters.h>
#undef __CUDA_INTERNAL_COMPILATION__
#endif
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/sequence.h>
#define BTOMB(x) (x)/1024/1024
#define MBTOB(x) (x)*1024*1024
#ifdef USE_CUDA_DUMMY
#define cuint const unsigned int
#define uint unsigned int
#else
typedef const unsigned int cuint;
typedef unsigned int uint;
#endif
#define fori(s, n) for(int i=s; i<n; ++i)
#define forj(s, n) for(int j=s; j<n; ++j)
#define fork(s, n) for(int k=s; k<n; ++k)
#define forl(s, n) for(int l=s; l<n; ++l)
#define forh(s, n) for(int h=s; h<n; ++h)
#define forauto(vec) for(auto & i : vec)
template<typename T>
T nextpow2(T x) {
T n = x;
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
#define CUDA_ECHO_ERROR(e, strs) { \
char a[255]; \
if (e != cudaSuccess) { \
strncpy(a, strs, 255); \
fprintf(stderr, \
"CUDA Failed to run %s at file %s line %d :: errorCode : %s\n", \
a, __FILE__, __LINE__, cudaGetErrorString(e) ); \
exit(EXIT_FAILURE); \
} \
}
#define CUDA_KERNEL_DYN(kernel, bpg, tpb, shd, ...){ \
kernel<<<bpg,tpb,shd>>>( __VA_ARGS__ ); \
cudaError_t err= cudaGetLastError(); \
CUDA_ECHO_ERROR(err, #kernel); \
}
#define CUDA_KERNEL(kernel, bpg, tpb, ...){ \
kernel<<<bpg,tpb>>>( __VA_ARGS__ ); \
cudaError_t err= cudaGetLastError(); \
CUDA_ECHO_ERROR(err, #kernel); \
}
#define CUDA_MEMSET(darr, v, T, n){ \
cudaError_t err = cudaMemset(darr, v, n * sizeof(T)); \
CUDA_ECHO_ERROR( err, "cudaMemset in " #darr ); \
}
#define CUDA_FREEDEV(darr){ \
cudaError_t err = cudaFree(darr ); \
CUDA_ECHO_ERROR( err, "cudaFree the " #darr ); \
}
#define CUDA_FREEHST(harr){ \
cudaError_t err = cudaFreeHost(harr ); \
CUDA_ECHO_ERROR( err, "cudaFreeHost the " #harr ); \
}
#define CUDA_MALDEV(darr, T, n){ \
cudaError_t err = cudaMalloc( ( void** ) &darr, n* sizeof( T ) ); \
CUDA_ECHO_ERROR( err, "cudaMalloc the " #darr ); \
}
#define CUDA_MALHST(harr, T, n){ \
cudaError_t err = cudaMallocHost( ( void** ) &harr, n* sizeof( T ) ); \
CUDA_ECHO_ERROR( err, "cudaMallocHost the " #harr ); \
}
#define CUDA_CP2HST(darr, harr, T, n){ \
cudaError_t err = cudaMemcpy(harr, darr, n*sizeof( T ), cudaMemcpyDeviceToHost); \
CUDA_ECHO_ERROR( err, "cudaMemcpy from " #darr " to " #harr ); \
}
inline void cuda_get_device_prop(cudaDeviceProp &prop, int device) {
cudaGetDeviceProperties(&prop, device);
printf("...Device Number: %d\n", device);
printf(" Device name: %s\n", prop.name);
printf(" Memory Clock Rate (KHz): %d\n",
prop.memoryClockRate);
printf(" Memory Bus Width (bits): %d\n",
prop.memoryBusWidth);
printf(" Peak Memory Bandwidth (GB/s): %f\n\n",
2.0 * prop.memoryClockRate * (prop.memoryBusWidth / 8) / 1.0e6);
}
inline cuint cuda_count_devices() {
int nDevices;
cudaGetDeviceCount(&nDevices);
printf("CUDA nDevices : %d\n", nDevices);
return (cuint) (nDevices);
}
inline cuint init_cuda_gpu(cuint device) {
// Init GPU Device
cuint nGpu = cuda_count_devices();
if (!nGpu) {
fprintf(stderr, "CUDA no devices ERROR, cant init device : %d\n", device);
return 1;
}
printf("CUDA init device : %d\n", device);
CUdevice dev;
CUcontext context;
cuInit(device);
cuDeviceGet(&dev, device);
cuCtxCreate(&context, device, dev);
cudaError_t err = cudaSetDevice(device);
CUDA_ECHO_ERROR(err, "init_cuda_gpu");
return nGpu;
}
/*
EACH BLOCK IN GRID: contains one time step to compute error by
W = P * P
F = P[randIdx]
S = W * F
error = S != F
EACH THREAD IN BLOCK: handles one pattern to compute weights Wp
this weights are summed up for all patterns to one W matrix
W += Wp
*/
#define N_N 100
__global__ void mykernel(cuint nSteps, cuint nP, cuint nN, cuint caseIdx, const int *P, float *errorB) {
cuint stepIdx = blockIdx.x;
cuint stepSize = blockDim.x * blockIdx.x;
cuint patternIdx = threadIdx.x;
if (patternIdx < nP && stepIdx < nSteps) {
__shared__ volatile float s_W[N_N * N_N]; //weights updated from all patterns
//extern __shared__ volatile int s_P[]; //each thread has his own pattern
__shared__ volatile int s_F[N_N]; //we share same feed pattern
__shared__ volatile float s_S[N_N];
float Wij = 0;
float _N = 1.f / nN;
cuint idx = stepSize + patternIdx * nN;
//compute W matrix from weights of all patterns
#pragma unroll
for (int i = 0; i < nN; ++i) {
#pragma unroll
for (int j = 0; j < nN; ++j) {
s_W[i * nN + j] += P[idx + i] * P[idx + j] * _N;
}
}
int feedIdx = 0; //random index from range [0, nP)
if (patternIdx == feedIdx) {
#pragma unroll
for (int i = 0; i < nN; ++i) {
s_F[i] = P[idx + i];
}
}
__syncthreads();
//compute state for given feed index, only once
if (patternIdx == 0) {
float Si;
#pragma unroll
for (int i = 0; i < nN; ++i) {
Si = 0;
#pragma unroll
for (int j = 0; j < nN; ++j) {
Si += s_W[i * nN + j] * s_F[i];
}
s_S[i] = Si;
}
#pragma unroll
for (int i = 0; i < nN; ++i) {
errorB[caseIdx] += s_S[i] != s_F[i];
}
}
}
}
#define thr thrust
int main() {
#ifdef USE_CUDA_DUMMY
cudaError_t err;
#endif
uint deviceIdx = 0;
cudaDeviceProp prop;
cuint nGpu = init_cuda_gpu(deviceIdx);
cudaProfilerStart();
cuda_get_device_prop(prop, deviceIdx);
int nN = N_N;
int nP = 400;
size_t maxGlobMem = BTOMB(prop.totalGlobalMem);
size_t maxGlobMem_1p6 = nextpow2<size_t>(maxGlobMem * 1 / 6);
size_t maxGlobMem_2p6 = 2 * maxGlobMem_1p6;
size_t maxGlobMem_3p6 = 3 * maxGlobMem_1p6;
size_t maxGlobMem_4p6 = 4 * maxGlobMem_1p6;
size_t maxGlobMem_5p6 = 5 * maxGlobMem_1p6;
uint maxThrPerBlc = (uint) prop.maxThreadsPerBlock;
uint maxShm = (uint) prop.sharedMemPerBlock;
int maxGridx = prop.maxGridSize[0];
printf("globMem: %zu maxThrPerBlc: %d, shm: %d, gridsize: %d\n",
maxGlobMem, maxThrPerBlc, maxShm, maxGridx);
size_t maxGlobFloat = maxGlobMem / sizeof(float);
size_t maxGlobFloat_4p6 = maxGlobMem_4p6 / sizeof(float);
size_t maxGlobFloat_3p6 = maxGlobMem_3p6 / sizeof(float);
size_t maxGlobFloat_2p6 = maxGlobMem_2p6 / sizeof(float);
size_t maxGlobFloat_1p6 = maxGlobMem_1p6 / sizeof(float);
size_t maxGlobInt_1p6 = maxGlobMem_1p6 / sizeof(int);
printf("maxGlobFloat_4p6: %zu, maxGlobFloat_3p6: %zu, maxGlobFloat_2p6: %zu, maxGlobFloat_1p6: %zu, maxGrid: %d\n",
maxGlobFloat_4p6, maxGlobFloat_3p6, maxGlobFloat_2p6, maxGlobFloat_1p6, maxGridx);
size_t nSteps = (size_t) 1e5;
size_t nPatternsPerTime = nSteps * nN;
size_t nTotPatterns = nP * nPatternsPerTime;
size_t nChunksP = BTOMB(nTotPatterns) / (size_t) (maxGlobFloat) + 1;
size_t nChunksP_4p6 = BTOMB(nTotPatterns) / (size_t) (maxGlobFloat_4p6) + 1;
size_t nChunksP_3p6 = BTOMB(nTotPatterns) / (size_t) (maxGlobFloat_3p6) + 1;
size_t nChunksP_2p6 = BTOMB(nTotPatterns) / (size_t) (maxGlobFloat_2p6) + 1;
size_t nChunksP_1p6 = BTOMB(nTotPatterns) / (size_t) (maxGlobFloat_1p6) + 1;
printf("np2(1e5): %zu, nChunksP: %zu/%zu = %zu\n", nP * nSteps, BTOMB(nTotPatterns), maxGlobFloat, nChunksP);
printf("np2(1e5): %zu, nChunksP_4p6: %zu/%zu = %zu\n", nP * nSteps, BTOMB(nTotPatterns), maxGlobFloat_4p6, nChunksP_4p6);
printf("np2(1e5): %zu, nChunksP_3p6: %zu/%zu = %zu\n", nP * nSteps, BTOMB(nTotPatterns), maxGlobFloat_3p6, nChunksP_3p6);
printf("np2(1e5): %zu, nChunksP_2p6: %zu/%zu = %zu\n", nP * nSteps, BTOMB(nTotPatterns), maxGlobFloat_2p6, nChunksP_2p6);
printf("np2(1e5): %zu, nChunksP_1p6: %zu/%zu = %zu\n", nP * nSteps, BTOMB(nTotPatterns), maxGlobFloat_1p6, nChunksP_1p6);
size_t nStepsChunk = nSteps / nChunksP_4p6;
size_t sChunk = nStepsChunk * nP * nN;
printf("nStepsChunk: %zu, sizePatSteps=%zu\n", nStepsChunk, sChunk);
float *dev_ErrorB;
float *hst_ErrorB;
int *dev_P;
CUDA_MALHST(hst_ErrorB, float, 100);
CUDA_MALDEV(dev_ErrorB, float, 100);
CUDA_MALDEV(dev_P, int, sChunk);
dim3 blcPerGrd(nStepsChunk);
dim3 thrPerBlc(nP);
printf("sizeof(int)=%zu, sizeof(float)=%zu\n", sizeof(int), sizeof(float));
printf("CALL KERNEL: blckPerGrd: %zu, thrPerBlc: %d, SHM: %zu/%zu\n",
nSteps, maxThrPerBlc, maxShm / sizeof(int), maxShm / sizeof(float));
fori(0,nChunksP_4p6){
CUDA_KERNEL(mykernel,
blcPerGrd, thrPerBlc,
nStepsChunk, nP, nN, 0, dev_P, dev_ErrorB);
}
cudaDeviceSynchronize();
CUDA_CP2HST(dev_ErrorB, hst_ErrorB, float, 100);
cudaProfilerStop();
CUDA_FREEDEV(dev_P);
CUDA_FREEDEV(dev_ErrorB);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T15:27:21.837",
"Id": "386975",
"Score": "0",
"body": "actually it seems that kernel dont work properly, will have time for it after exams in august, so until this time put this question on hiatus"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:22:43.900",
"Id": "200681",
"Score": "2",
"Tags": [
"performance",
"c",
"matrix",
"cuda",
"kernel"
],
"Title": "CUDA kernel to compare matrix entries, weighted with a pattern"
} | 200681 |
<p>This is a question from the book "<a href="https://www.amazon.in/gp/product/0984782850/ref=as_li_tl?ie=UTF8&tag=0106d-21&camp=3638&creative=24630&linkCode=as2&creativeASIN=0984782850&linkId=6bf430d6374ca7ffb9f2cac081fc2d31" rel="nofollow noreferrer">Cracking the Coding Interview</a>".</p>
<blockquote>
<p>Design an algorithm and write code to remove the duplicate characters
in a string without using any additional buffer NOTE: One or two
additional variables are fine An extra copy of the array is not</p>
</blockquote>
<p>This is not the efficient code, but I want to preserve the order of characters after deleting duplicate characters.</p>
<pre><code>#include <iostream>
#include <string>
#include <cctype> //std::toupper, std::tolower
void removeDuplicates(std::string& str)
{
int flag = 0;
int len = str.length();
for (int i = 0; i < len - 1; ++i)
{
for (int j = i + 1; j < len - 1; ++j)
{
if (str[i] == std::toupper(str[j])
|| str[i] == std::tolower(str[j]))
{
str.erase(str.begin() + j);
flag = 1;
}
}
}
if (flag == 0)
{
std::cout << "There are no duplicate characters\n";
}
else
{
std::cout << "There are duplicate characters\n";
}
}
int main()
{
std::string str;
std::cout << "Enter String\n";
std::getline(std::cin, str);
removeDuplicates(str);
std::cout << "New String\n";
std::cout << str << '\n';
}
</code></pre>
<p>Help me optimize this code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:46:34.970",
"Id": "386428",
"Score": "0",
"body": "It would only have a significant effect if a number of characters are repeated 3+ times, but instead of doing string.erase for each character (potentially O(n^3)), you could manu... | [
{
"body": "<h1>Clarify the requirement</h1>\n\n<p>You state 'remove duplicate characters' but then your code checks for upper and lower case matches - is the requirement to check for distinct letters, or distinct characters? </p>\n\n<h1>Sort out the bugs</h1>\n\n<p>I sense premature optimisation here, and it is... | {
"AcceptedAnswerId": "200695",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T17:29:10.220",
"Id": "200682",
"Score": "4",
"Tags": [
"c++",
"programming-challenge",
"interview-questions"
],
"Title": "Remove duplicate characters in a string"
} | 200682 |
<p>Any and all comments are welcome in this review.</p>
<h2>Problem</h2>
<p>I've been doing a lot with numerical integration methods recently and have mostly been programming in Python. But...speedups! And FPGAs are cool! Thusly, I'm attempting to implement the trapezoidal integration method in Verilog. (I have never programmed in Verilog before and know almost nothing about it, hence this code review on a very short program that is probably also very crappy.)</p>
<p>The trapezoidal method is at its heart very simple. Take two points on your function and call them y<sub>1</sub> and y<sub>2</sub>. Then define a trapezoid with the two "bases" defined by the height from the x-axis to y<sub>1</sub> and y<sub>2</sub> and a height of the interval between the two corresponding x coordinates (i.e., x<sub>2</sub> - x<sub>1</sub>; we'll call this value x for simplicity). Then plug this into the formula for the area of a trapezoid and you get $$A = \frac{x(y_1+y_2)}{2}$$ sum this for a bunch of points with a very small value of x and you've got the integral.</p>
<p>The other little quirk in what I'm doing is that I'm doing it cumulatively, i.e., I'm taking in a signal (which I call <code>SIGNAL</code> in my code) and find A at that point and send it to the output (<code>OUT</code>). Then on the board I'll wire <code>OUT</code> to <code>SUM</code> and effectively add the past <code>OUT</code> to my new <code>OUT</code> to get the total area up to that point.</p>
<h2>Code Description</h2>
<p>I take in several inputs - a clock signal <code>CLK</code>, the function-signal <code>SIGNAL</code> (i.e., what I'm integrating) the distance between clock ticks <code>x</code>, and the past <code>SUM</code> (again, what <code>OUT</code> is mapped to). I have one output, <code>OUT</code>, which is the solution up to that point.</p>
<p>I begin by defining three 64 bit registers. The first two are for the two values y<sub>1</sub> and y<sub>2</sub>, and the third is for the <code>SUM</code> (I handle it oddly). Then I start an <code>always</code> loop - whenever <code>CLK</code> is high, I set <code>yregtwo</code> equal to whatever is in <code>yregone</code> and <code>yregone</code> equal to the <code>SIGNAL</code> (effectively shifting the y values) and then check if <code>yregtwo</code> actually has something in it - i.e., that it's not step one. If this is true, then I perform the actual calculation detailed in the formula I gave above and add <code>SUM</code> to it (not <code>sum</code>). Finally, I set <code>sum</code> equal to that calculation and set <code>OUT</code> equal to <code>sum</code>. </p>
<h2>Full Code</h2>
<pre><code>module trapverilog(
input CLK,
input signed [7:0] SIGNAL,
input signed [7:0] x,
input signed [7:0] SUM, // OUT pins are mapped to SUM pins on board
output reg OUTP,
output reg OUT1,
output reg OUT2,
output reg OUT3,
output reg OUT4,
output reg OUT5,
output reg OUT6,
output reg OUT7
);
reg[7:0] yregone;
reg[7:0] yregtwo;
reg[7:0] innerSumOutput;
reg[7:0] innerSum;
function [7:0] multiply;
input [7:0] a;
input [7:0] b;
reg [15:0] a1, a2, a3, a4, a5, a6, a7, a8;
begin
a1 = (b[0]==1'b1) ? {8'b00000000, a} : 16'b0000000000000000;
a2 = (b[1]==1'b1) ? {7'b0000000, a, 1'b0} : 16'b0000000000000000;
a3 = (b[2]==1'b1) ? {6'b000000, a, 2'b00} : 16'b0000000000000000;
a4 = (b[3]==1'b1) ? {5'b00000, a, 3'b000} : 16'b0000000000000000;
a5 = (b[4]==1'b1) ? {4'b0000, a, 4'b0000} : 16'b0000000000000000;
a6 = (b[5]==1'b1) ? {3'b000, a, 5'b00000} : 16'b0000000000000000;
a7 = (b[6]==1'b1) ? {2'b00, a, 6'b000000} : 16'b0000000000000000;
a8 = (b[7]==1'b1) ? {1'b0, a, 7'b0000000} : 16'b0000000000000000;
multiply = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8;
end
endfunction
always @(posedge CLK)
begin
yregtwo <= yregone;
yregone <= SIGNAL;
if (yregone != 0)
begin
innerSum <= multiply((yregone + yregtwo), x); //treats x as plain h, change if treated as h/2 // multiply defined by function shift-adds
innerSumOutput <= (innerSum <<< 1) + SUM; // <<< is signed one bit shift which = /2
if (innerSumOutput[0] == 1)
begin
OUTP <= 1;
end
OUT1 <= innerSumOutput[1];
OUT2 <= innerSumOutput[2];
OUT3 <= innerSumOutput[3];
OUT4 <= innerSumOutput[4];
OUT5 <= innerSumOutput[5];
OUT6 <= innerSumOutput[6];
OUT7 <= innerSumOutput[7];
end
end
endmodule
</code></pre>
<h2>User Config File</h2>
<pre><code>NET "CLK" LOC = P126;
NET "SIGNAL[0]" LOC = P35 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[1]" LOC = P34 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[2]" LOC = P33 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[3]" LOC = P32 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[4]" LOC = P30 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[5]" LOC = P29 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[6]" LOC = P27 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SIGNAL[7]" LOC = P26 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[0]" LOC = P24 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[1]" LOC = P23 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[2]" LOC = P22 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[3]" LOC = P21 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[4]" LOC = P17 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[5]" LOC = P16 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[6]" LOC = P15 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "x[7]" LOC = P14 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[0]" LOC = P12 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[1]" LOC = P11 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[2]" LOC = P10 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[3]" LOC = P9 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[4]" LOC = P8 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[5]" LOC = P7 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[6]" LOC = P6 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
NET "SUM[7]" LOC = P5 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = FAST;
</code></pre>
<p>I'm using the Mimas Spartan 6 board.</p>
| [] | [
{
"body": "<p>Why are the inputs <code>signed</code>, are you working with negative dimensions?</p>\n\n<p>Most FPGAs have dedicated logic for multiplication so you usually can simply write <code>x*y</code> without having any issues. For better or worse, manually writing it out like you did could impact optimiza... | {
"AcceptedAnswerId": "224838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T18:20:01.180",
"Id": "200686",
"Score": "5",
"Tags": [
"numerical-methods",
"verilog",
"fpga"
],
"Title": "Verilog implementation of trapezoidal integration method"
} | 200686 |
<p><strong>Problem Statement</strong></p>
<blockquote>
<p>A Chakravyuha is a wheel-like formation. Pictorially it is depicted as
below</p>
<p><a href="https://i.stack.imgur.com/VGgIz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VGgIz.png" alt="enter image description here"></a> </p>
<p>A Chakravyuha has a very well-defined co-ordinate system. Each point
on the co-ordinate system is manned by a certain unit of the army. The
Commander-In-Chief is always located at the center of the army to
better co-ordinate his forces. The only way to crack the Chakravyuha
is to defeat the units in sequential order.</p>
<p>A Sequential order of units differs structurally based on the radius
of the Chakra. The radius can be thought of as length or breadth of
the matrix depicted above. The structure i.e. placement of units in
sequential order is as shown below</p>
<p><a href="https://i.stack.imgur.com/mJHkY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJHkY.png" alt="enter image description here"></a> </p>
<p>The entry point of the Chakravyuha is always at the (0,0) co-ordinate
of the matrix above. This is where the 1st army unit guards. From
(0,0) i.e. 1st unit Abhimanyu has to march towards the center at (2,2)
where the 25th i.e. the last of the enemy army unit guards. Remember
that he has to proceed by destroying the units in sequential fashion.
After destroying the first unit, Abhimanyu gets a power point.
Thereafter, he gets one after destroying army units which are
multiples of 11. You should also be a in a position to tell Yudhisthir
Maharaj the location at which Abhimanyu collected his power points.</p>
<p><strong>Input Format:</strong> </p>
<p>First line of input will be length as well as breadth of the army units, say N</p>
<p><strong>Output Format:</strong> </p>
<ul>
<li>Print NxN matrix depicting the placement of army units, with unit numbers delimited by (\t) Tab character</li>
<li>Print Total power points collected</li>
<li>Print coordinates of power points collected in sequential fashion (one per line)</li>
<li>Print coordinates of power points collected in sequential fashion (one per line)</li>
</ul>
<p><strong>Constraints:</strong></p>
<p>0 < N <=100</p>
<p><strong>The Logic:</strong></p>
<p><a href="https://i.stack.imgur.com/VPggo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VPggo.jpg" alt="enter image description here"></a></p>
</blockquote>
<pre><code>#include<stdio.h>
int isDiv(int);
int main(){
int n;
scanf("%d",&n);
//check contraint
if(n<=0 || n>100){
return 0;
}
int a[100][100]; // main matrix
int counter=1; // keeps track of number
int i,j; //keeps track of position
int w; // w - window
int size=n-1; // size - size of segment of window
for( w = 0 ; w < n / 2 ; w++){
i = w;
j = w;
//go right
for( j = j ; j < size + w ; j++){
a[ i ][ j ] = counter;
counter++;
}
//go down
for( i = i ; i < size + w ; i++){
a[ i ][ j ] = counter;
counter++;
}
//go left
for( j = j ; j > w ; j--){
a[ i ][ j ] = counter;
counter++;
}
//go up
for( i = i ; i > w ; i--){
a[ i ][ j ] = counter;
counter++;
}
size = size-2;
}
if( n % 2 != 0){
a[ w ][ w ] = counter;
}
//print matrix
for( i = 0 ; i < n ; i++){
for( j = 0 ; j < n ; j++){
printf("%d\t", a[ i ][ j ]);
}
printf("\n");
}
int no_div = (n*n)/11 + 1 ; // no of divisibles
printf("Total Power points : %d\n",no_div);
printf("(0,0)\n");
size=n-1;
//print positions
for( w = 0 ; w < n / 2 ; w++){
i = w;
j = w;
//go right
for( j = j ; j < size + w ; j++){
if(isDiv( a[ i ][ j ] )){
printf("(%d,%d)\n", i, j);
}
}
//go down
for( i = i ; i < size + w ; i++){
if(isDiv( a[ i ][ j ] )){
printf("(%d,%d)\n", i, j);
}
}
//go left
for( j = j ; j > w ; j--){
if(isDiv( a[ i ][ j ] )){
printf("(%d,%d)\n", i, j);
}
}
//go up
for( i = i ; i > w ; i--){
if(isDiv( a[ i ][ j ] )){
printf("(%d,%d)\n", i, j);
}
}
size = size-2;
}
if( n % 2 != 0){
if(isDiv( a[ i ][ j ] )){
printf("(%d,%d)\n", i, j);
}
}
return 0;
}
int isDiv(int x){
if( x % 11 == 0 ){
return 1;
}
else{
return 0;
}
}
</code></pre>
<p>The code is working fine as can be checked on <a href="https://ideone.com/4jX2sc" rel="nofollow noreferrer">Ideone</a>.</p>
| [] | [
{
"body": "<p>You should try to keep your <code>main</code> function small and focused. (Well, you should try to keep <em>every</em> function you write small and focused!) For example, you might do something like this:</p>\n\n<pre><code>struct Coord {\n int row, col;\n};\nstruct CoordList {\n int size;\n ... | {
"AcceptedAnswerId": "200705",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T19:35:48.580",
"Id": "200690",
"Score": "5",
"Tags": [
"performance",
"algorithm",
"c",
"programming-challenge"
],
"Title": "Code Vita: Chakravyuha"
} | 200690 |
<p>I have a list of values which are parsed in other place and are populated in the <code>List<string>compareValues</code> list.</p>
<p>There is also a <code>value</code> with which I need to compare a list of <code>compareValues</code> which can be <code>decimal</code> (2.50), <code>int</code> (10), <code>Date</code> (31/07/2018 or 7-31-2018 etc) or a string.</p>
<p>For the comparison operators, I have an enum which looks like:</p>
<pre><code>public enum CompareOperation
{
[Description("=")]
Equal,
[Description("<>")]
NotEqual,
[Description(">")]
Greater,
[Description(">=")]
GreaterOrEqual,
[Description("<")]
Less,
[Description("<=")]
LessOrEqual
}
</code></pre>
<p>The value of the comparison operation is also parsed in other place.</p>
<p>I need to write a method which will perform the operation of the corresponding comparison and return <code>true</code> or <code>false</code>.</p>
<p>In my method a lot of copy-paste and the question is, how it's better to implement this task more "correctly" to avoid copy-paste?</p>
<pre><code>private bool CompareCondition(List<string> compareValues, string value, CompareOperation operation)
{
int intVal;
decimal decimalVal;
DateTime datetimeVal;
switch (operation)
{
case CompareOperation.Equal:
{
if (Int32.TryParse(value, out intVal))
{
return compareValues.Any(x => intVal == Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValues.Any(x => decimalVal == Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValues.Any(x => datetimeVal == DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return compareValues.Any(x => x == value);
}
}
case CompareOperation.NotEqual:
{
if (Int32.TryParse(value, out intVal))
{
return compareValues.Any(x => intVal != Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValues.Any(x => decimalVal != Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValues.Any(x => datetimeVal != DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return false;
}
}
case CompareOperation.Greater:
{
if (Int32.TryParse(value, out intVal))
{
return compareValue.Any(x => intVal > Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValue.Any(x => decimalVal > Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValue.Any(x => datetimeVal > DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return false;
}
}
case CompareOperation.GreaterOrEqual:
{
if (Int32.TryParse(value, out intVal))
{
return compareValue.Any(x => intVal >= Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValue.Any(x => decimalVal >= Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValue.Any(x => datetimeVal >= DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return false;
}
}
case CompareOperation.Less:
{
if (Int32.TryParse(value, out intVal))
{
return compareValue.Any(x => intVal < Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValue.Any(x => decimalVal < Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValue.Any(x => datetimeVal < DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return false;
}
}
case CompareOperation.LessOrEqual:
{
if (Int32.TryParse(value, out intVal))
{
return compareValue.Any(x => intVal <= Int32.Parse(x));
}
else if (Decimal.TryParse(value, out decimalVal))
{
return compareValue.Any(x => decimalVal <= Decimal.Parse(x));
}
else if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out datetimeVal))
{
return compareValue.Any(x => datetimeVal <= DateTime.Parse(x, CultureInfo.InvariantCulture, DateTimeStyles.None));
}
else
{
return false;
}
}
default:
return false;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T23:26:53.557",
"Id": "386473",
"Score": "1",
"body": "Is there any reason that the `compareValues` are assumed to be parsable in the type that `value` can be parsed to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDa... | [
{
"body": "<p>I’ve flatten the outter <code>switch</code>-block and the inner <code>if-else</code> block, since the nested block is almost identical in all the cases, except the fallback string comparison when the operation is “equal”. \nAnd, I’ve also moved the <code>compareValues</code> parameter to the last ... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T21:31:38.757",
"Id": "200696",
"Score": "3",
"Tags": [
"c#",
"algorithm"
],
"Title": "Dynamically convert to a type and perform an operation comparing the converted values"
} | 200696 |
<p>I'm asking myself if there's any better/shorter way of getting a module entry by its name from an external process.</p>
<p>This is the code I have so far:</p>
<pre><code>MODULEENTRY32 GetModule(const char* ModuleName) {
HANDLE Module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
MODULEENTRY32 Entry;
Entry.dwSize = sizeof(Entry);
WCHAR *ModuleNameChar;
int Chars = MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, NULL, 0);
ModuleNameChar = new WCHAR[Chars];
MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, (LPWSTR)ModuleNameChar, Chars);
while (Module32Next(Module, &Entry)) {
if (!wcscmp((wchar_t*)Entry.szModule, ModuleNameChar)) {
CloseHandle(Module);
return Entry;
}
}
/*
Return the module base 0x0 if we don't find any module
*/
CloseHandle(Module);
Entry.modBaseAddr = 0x0;
return Entry;
}
</code></pre>
<p>It should work but it's quite complicated. Is there any useful function or method I can make use of to simplify this whole thing?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T17:55:48.377",
"Id": "386640",
"Score": "0",
"body": "I'd say this is pretty concise for WinAPI code. When I wrote a similar function once it turned out longer."
}
] | [
{
"body": "<p>Unfortunately, I'm not sure of any way of being more concise.</p>\n\n<p>There are a few changes you could make, but they're mostly optional.</p>\n\n<ol>\n<li><p>Check the return value of <code>CreateToolhelp32Snapshot()</code>. The documentation says the following:</p>\n\n<blockquote>\n <p>Includ... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T23:03:53.220",
"Id": "200698",
"Score": "4",
"Tags": [
"c++",
"winapi"
],
"Title": "Get module entry by name from external program via WinAPI"
} | 200698 |
<p>I was asked to perform the following tasks at one of the technical interviews. I did the BST implementation in python. I think the solution passed all of the solution. I broke down the tasks in the following bulletin:</p>
<pre><code># 1) initilize the binary Search tree
# 2) Implement the "put" and "contains" methods with helper function
# 3) Test the "inOrderTraversal" method.
# 4) Add additional relevant tests
import unittest
class BST(object):
def __init__(self):
self.root = Node()
def put(self, value):
self._put(value, self.root)
def _put(self, value, node):
if node.value is None:
node.value = value
else:
if value < node.value:
if node.left is None:
node.left = Node()
self._put(value, node.left)
else:
if node.right is None:
node.right = Node()
self._put(value, node.right)
def contains(self, value):
return self._contains(value, self.root)
def _contains(self, value, node):
if node is None or node.value is None:
return False
else:
if value == node.value:
return True
elif value < node.value:
return self._contains(value, node.left)
else:
return self._contains(value, node.right)
def in_order_traversal(self):
acc = list()
self._in_order_traversal(self.root, acc)
return acc
def _in_order_traversal(self, node, acc):
if node is None or node.value is None:
return
self._in_order_traversal(node.left, acc)
acc.append(node.value)
self._in_order_traversal(node.right, acc)
class Node(object):
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TestBST(unittest.TestCase):
def setUp(self):
self.search_tree = BST()
def test_bst(self):
self.search_tree.put(3)
self.search_tree.put(1)
self.search_tree.put(2)
self.search_tree.put(5)
self.assertFalse(self.search_tree.contains(0))
self.assertTrue(self.search_tree.contains(1))
self.assertTrue(self.search_tree.contains(2))
self.assertTrue(self.search_tree.contains(3))
self.assertFalse(self.search_tree.contains(4))
self.assertTrue(self.search_tree.contains(5))
self.assertFalse(self.search_tree.contains(6))
self.assertEqual(self.search_tree.in_order_traversal(), [1,2,3,5])
def test_empty(self):
self.assertEqual(self.search_tree.in_order_traversal(), [])
def test_negative(self):
self.search_tree.put(-1)
self.search_tree.put(11)
self.search_tree.put(-10)
self.search_tree.put(50)
self.assertTrue(self.search_tree.contains(-1))
self.assertTrue(self.search_tree.contains(11))
self.assertTrue(self.search_tree.contains(-10))
self.assertTrue(self.search_tree.contains(50))
self.assertEqual(self.search_tree.in_order_traversal(), [-10,-1,11,50])
def test_dupes(self):
self.search_tree.put(1)
self.search_tree.put(2)
self.search_tree.put(1)
self.search_tree.put(2)
self.assertTrue(self.search_tree.contains(1))
self.assertTrue(self.search_tree.contains(2))
self.assertEqual(self.search_tree.in_order_traversal(), [1,1,2,2])
def test_none(self):
self.search_tree.put(None)
self.assertFalse(self.search_tree.contains(None))
self.assertEqual(self.search_tree.in_order_traversal(), [])
if __name__ == '__main__':
unittest.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T05:09:38.183",
"Id": "386683",
"Score": "0",
"body": "there are actually a few ways to accomplish this structure, I'd recommend searching around the internet and looking at all the other different implementations. I personally would... | [
{
"body": "<p><strong>class Node</strong>:</p>\n\n<p>It is \"strange\" to have a <code>Node</code> with no value. Consider removing the default <code>value=None</code>.</p>\n\n<p>You never create a <code>Node</code> with an explicit \"left\" or \"right\" branch. Consider removing these extra parameters from t... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T23:22:05.903",
"Id": "200699",
"Score": "1",
"Tags": [
"python",
"tree"
],
"Title": "BST implementation in Python"
} | 200699 |
<p>I was asked to solve a problem for \$\binom{n}{k}\$. I did the following implementation and am wondering if there's any feedback.</p>
<p><strong>Input:</strong></p>
<p><code>n</code> = Integer</p>
<p><code>k</code> = Integer</p>
<p><strong>Output:</strong></p>
<p><code>result</code> = Array of arrays of integers</p>
<p><strong>Constraints:</strong></p>
<p>Time: \$O(\binom{n}{k})\$</p>
<p>Space: \$O(\binom{n}{k})\$</p>
<p>The order of the output array DOES NOT MATTER.</p>
<p><code>n</code> and <code>k</code> are both positive.</p>
<p>Resources:</p>
<p><a href="https://en.wikipedia.org/wiki/Binomial_coefficient" rel="nofollow noreferrer">N Choose K</a></p>
<p><a href="https://betterexplained.com/articles/easy-permutations-and-combinations/" rel="nofollow noreferrer">Combinations</a></p>
<pre><code>function combinations(n, k) {
let result= [];
function recurse(start, combos) {
if(combos.length === k) {
return result.push(combos.slice());
}
// Check if you can actually create a combo of valid length
// given current start number
// For example: 5 choose 4 can't begin with [3] since it would never have 4 numbers
if(combos.length + (n - start + 1) < k){
return;
}
recurse(start + 1, combos);
combos.push(start);
recurse(start + 1, combos);
combos.pop();
}
recurse(1, []);
return result;
}
</code></pre>
<p>I was wondering if there's a reason why the time gets optimized using a backtracking solution.</p>
<pre><code>// function combinations(n, k) {
// let result = []
// function combine(combo, currentNumber){
// if(combo.length === k) {
// result.push(combo);
// return;
// }
// if(currentNumber > n) {
// return;
// }
// let newCombo1 = combo.slice();
// let newCombo2 = combo.slice();
// newCombo2.push(currentNumber);
// combine(newCombo2, currentNumber + 1);
// combine(newCombo1, currentNumber + 1);
// }
// combine([], 1);
// return result;
// }
// speed: 1120.756 ms
//backtracking method
function combinations(n, k) {
let result = []
let stack = []
function combine(currentNumber){
if(stack.length === k) {
let newCombo = stack.slice()
result.push(newCombo);
return;
}
if(currentNumber > n) {
return;
}
stack.push(currentNumber)
combine(currentNumber + 1);
stack.pop();
combine(currentNumber + 1);
}
combine(1);
return result;
}
console.time("Naive Combinations")
console.log(combinations(20, 10))
console.timeEnd("Naive Combinations")
// speed: 320.756 ms
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T11:06:55.890",
"Id": "386560",
"Score": "2",
"body": "The constraints are impossible using simple arrays: the size of the output is \\$k\\binom{n}{k}\\$ which is not \\$O\\left(\\binom{n}{k}\\right)\\$"
},
{
"ContentLicense"... | [
{
"body": "<h1>Performance testing.</h1>\n\n<p>Please note this answer is about performance not complexity.</p>\n\n<h2>Why the strange performance result?</h2>\n\n<p>The reason for the different results is down to poor testing.</p>\n\n<p>JavaScript unlike most languages is never fully compiled. In the backgroun... | {
"AcceptedAnswerId": "201016",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T23:31:43.617",
"Id": "200700",
"Score": "3",
"Tags": [
"javascript",
"performance",
"comparative-review",
"combinatorics"
],
"Title": "n choose k combination in JavaScript"
} | 200700 |
<blockquote>
<p>Given an integer, sort the digits in ascending order and return the
new integer.</p>
<ul>
<li>Ignore leading zeros.</li>
</ul>
<p>Parameters:</p>
<ul>
<li>Input: num {Integer}</li>
<li>Output: {Integer}</li>
</ul>
<p>Constraints:</p>
<ul>
<li>Do not convert the integer into a string or other data type.</li>
<li>Time: O(N) where N is the number of digits.</li>
<li>Space: O(1)</li>
</ul>
<p>Examples:</p>
<ul>
<li>8970 --> 789</li>
<li>32445 --> 23445</li>
<li>10101 --> 111</li>
</ul>
</blockquote>
<p>My code (as follows) works similar to the counting sort:</p>
<pre><code>def sort_digits(n):
digit_counts = {}
result = 0
while n > 0:
digit = n % 10
digit_counts[digit] = digit_counts.get(digit, 0) + 1
n /= 10
power = 0
for i in range(10, -1, -1):
if i in digit_counts:
while digit_counts[i] >= 1:
result += i * (10 ** (power))
power += 1
digit_counts[i] -= 1
return result
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T00:09:35.483",
"Id": "386477",
"Score": "1",
"body": "Without qualification, the constraint `Do not convert the integer into a string or other data type.` doesn't make much sense. For example, in your solution, you indirectly encode... | [
{
"body": "<h3>1) Use collections.Counter</h3>\n\n<p><code>from collections import Counter</code>. Counter is a subclass of <code>dict</code> that helps keep tallies. This way, you don't need <code>.get(digit, 0)</code> or <code>if i in digit_counts</code>, making your code look a bit cleaner.</p>\n\n<h3>2) Ite... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T23:36:45.683",
"Id": "200702",
"Score": "3",
"Tags": [
"python",
"sorting"
],
"Title": "Sort digits in Python"
} | 200702 |
<p>So after getting a very thorough review and feedback from <em>indi</em> in my previous attempt, <a href="https://codereview.stackexchange.com/questions/200150/sdl-c-high-low-guessing-game">SDL/C++ High-Low Guessing Game</a>, I decided to go through the game and fix as many mistakes as I could. But going through the feedback also just opened up even more questions.</p>
<p>Things I was unable to do</p>
<ul>
<li><p>Get rid of all global variables. I was able to remove or move most of the global variables, but I had an issue with the <code>SDL_Window*</code>, <code>SDL_Renderer</code>, and <code>TTF_Font</code>. It was suggested that I used a <code>std::unique_ptr</code>, so I made the window a <code>std::unique_ptr</code>, but I was unable to use that window as a parameter for creating the renderer because there was no suitable conversion from a <code>std::unique_ptr</code> to a <code>SDL_Window*</code>. Thus I just kept them in global until I can figure out how to make it work.</p></li>
<li><p>Use the struct "tags" for my <code>LTexture</code> class. It was suggested to use <code>struct from_surface_tag {} from_surface;</code> and <code>struct from_text_tag {} from_text;</code> to indicate which version of the constructor I was using. The compiler just kept saying that <code>from_text</code> or <code>from_surface</code> were undefined. I realize that there mainly for the reader of the code, so I just made an <code>enum</code> to use as the tags.</p></li>
<li><p>Used the state machine that was suggested. I make the engine that was suggested, but I failed miserably. Instead I created a very basic state machine that hopefully works and gets rid of the <code>playAgain -> mainMenu -> playAgain</code> loop. Hopefully I'll be able to understand how to other one once I get more experience.</p></li>
<li><p>Lastly, I did not make not make the <code>LTexture</code> class it's own file, mainly because I struggled getting the SDL one's to work.</p></li>
</ul>
<p>Here is my code:</p>
<p><strong>SDLInit.h</strong></p>
<pre><code>#pragma once
class sdl
{
public:
sdl();
sdl(sdl&& other) noexcept;
~sdl();
auto operator=(sdl&& other) noexcept->sdl&;
// Non-copyable
sdl(sdl const&) = delete;
auto operator=(sdl const&)->sdl& = delete;
friend void _swap(sdl& a, sdl& b) noexcept;
private:
bool _own = false;
};
class sdl_img
{
public:
sdl_img();
sdl_img(sdl_img&& other) noexcept;
~sdl_img();
auto operator=(sdl_img&& other) noexcept->sdl_img&;
// Non-copyable
sdl_img(sdl_img const&) = delete;
auto operator=(sdl_img const&)->sdl_img& = delete;
friend void _swap(sdl_img& a, sdl_img& b) noexcept;
private:
bool _own = false;
};
class sdl_ttf
{
public:
sdl_ttf();
sdl_ttf(sdl_ttf&& other) noexcept;
~sdl_ttf();
auto operator=(sdl_ttf&& other) noexcept->sdl_ttf&;
// Non-copyable
sdl_ttf(sdl_ttf const&) = delete;
auto operator=(sdl_ttf const&)->sdl_ttf& = delete;
friend void _swap(sdl_ttf& a, sdl_ttf& b) noexcept;
private:
bool _own = false;
};
</code></pre>
<p><strong>SDLInit.cpp</strong></p>
<pre><code>#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include "SDLInit.h"
//Initialize SDL
sdl::sdl()
{
auto const result = SDL_Init(SDL_INIT_VIDEO);
if (result != 0)
std::cout << "SDL could not initialize";
}
sdl::sdl(sdl&& other) noexcept
{
_swap(*this, other);
}
sdl::~sdl()
{
if (_own)
SDL_Quit();
}
auto sdl::operator=(sdl&& other) noexcept -> sdl&
{
_swap(*this, other);
return *this;
}
void _swap(sdl& a, sdl& b) noexcept
{
using std::swap;
swap(a._own, b._own);
}
//Initialize SDL Image
sdl_img::sdl_img()
{
auto const result = IMG_Init(IMG_INIT_PNG);
if (result == 0)
std::cout << "SDL Image could not initialize";
}
sdl_img::sdl_img(sdl_img&& other) noexcept
{
_swap(*this, other);
}
sdl_img::~sdl_img()
{
if (_own)
IMG_Quit();
}
auto sdl_img::operator=(sdl_img&& other) noexcept -> sdl_img&
{
_swap(*this, other);
return *this;
}
void _swap(sdl_img& a, sdl_img& b) noexcept
{
using std::swap;
swap(a._own, b._own);
}
//Initialize SDL True Type Fonts
sdl_ttf::sdl_ttf()
{
auto const result = TTF_Init();
if (result != 0)
std::cout << "SDL TTF could not initialize";
}
sdl_ttf::sdl_ttf(sdl_ttf&& other) noexcept
{
_swap(*this, other);
}
sdl_ttf::~sdl_ttf()
{
if (_own)
TTF_Quit();
}
auto sdl_ttf::operator=(sdl_ttf&& other) noexcept -> sdl_ttf&
{
_swap(*this, other);
return *this;
}
void _swap(sdl_ttf& a, sdl_ttf& b) noexcept
{
using std::swap;
swap(a._own, b._own);
}
</code></pre>
<p><strong>Main.cpp</strong></p>
<pre><code>#include <iostream>
#include <random>
#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include "SDLInit.h"
constexpr int SCREEN_WIDTH = 640;
constexpr int SCREEN_HEIGHT = 480;
SDL_Window* gWindow = nullptr;
SDL_Renderer* gRenderer = nullptr;
TTF_Font* gFont = nullptr;
enum class GameStates
{
MAIN_MENU,
MAIN_LOOP,
PLAY_AGAIN,
EXIT,
};
struct Game
{
int numberofGuesses = 0;
const int min = 1;
int max = 0;
int randomNumber = 0;
bool game_was_won = false;
};
std::mt19937& random_engine()
{
static std::mt19937 mersenne(std::random_device{}());
return mersenne;
}
int getRandomNumber(int x, int y)
{
std::uniform_int_distribution<> dist{ x,y };
return dist(random_engine());
}
//used to tag how the texture was rendered
enum TextureType { from_surface, from_text };
class LTexture
{
public:
LTexture(TextureType type, SDL_Renderer* renderer, std::string const& path);
LTexture(TextureType type, SDL_Renderer* renderer, std::string const& text, SDL_Color color, int width);
LTexture(LTexture&& other) noexcept
{
swap(*this, other);
}
~LTexture();
void render(SDL_Renderer* renderer, int x, int y);
LTexture& operator=(LTexture&& other) noexcept
{
swap(*this, other);
return *this;
}
SDL_Texture* mTexture = nullptr;
int mWidth = 0;
int mHeight = 0;
SDL_Rect mButton = {};
LTexture(LTexture const&) = delete;
LTexture& operator=(LTexture const&) = delete;
friend void swap(LTexture& a, LTexture& b) noexcept;
};
LTexture::LTexture(TextureType type, SDL_Renderer* renderer, std::string const& path)
{
SDL_Surface *surface = IMG_Load(path.c_str());
if (!surface)
std::cout << "Failed to create surface";
mTexture = SDL_CreateTextureFromSurface(gRenderer, surface);
if (!mTexture)
std::cout << "Failed to create texture";
mWidth = surface->w;
mHeight = surface->h;
}
LTexture::LTexture(TextureType type, SDL_Renderer* renderer, std::string const& text, SDL_Color color, int width)
{
SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(gFont, text.c_str(), color, width);
if (!textSurface)
std::cout << "Failed to create surface";
mTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
if (!mTexture)
std::cout << "Failed to created texture";
mWidth = textSurface->w;
mHeight = textSurface->h;
SDL_FreeSurface(textSurface);
}
void LTexture::render(SDL_Renderer* renderer, int x, int y)
{
SDL_Rect destRect = { x, y, mWidth, mHeight };
SDL_RenderCopy(renderer, mTexture, nullptr, &destRect);
//create a rectangle that coincides with texture to check for button presses
mButton = { x, y, mWidth, mHeight };
}
void swap(LTexture& a, LTexture& b) noexcept
{
using std::swap;
swap(a.mTexture, b.mTexture);
swap(a.mWidth, b.mWidth);
swap(a.mHeight, b.mHeight);
swap(a.mButton, b.mButton);
}
LTexture::~LTexture()
{
if (mTexture)
SDL_DestroyTexture(mTexture);
}
bool button_is_pressed(SDL_Event const& event, SDL_Rect const& button_rect)
{
if (event.type == SDL_MOUSEBUTTONDOWN)
{
auto const& mouse_button_event = event.button;
auto const mouse_position = SDL_Point{ mouse_button_event.x, mouse_button_event.y };
return (mouse_button_event.button == SDL_BUTTON_LEFT) && SDL_PointInRect(&mouse_position, &button_rect);
}
return false;
}
// compare random number to guess player provided
int compare(int randomNumber, int guess)
{
if (randomNumber < guess)
{
return -1;
}
if (randomNumber > guess)
{
return 1;
}
return 0;
}
bool playAgain_input(GameStates& gameState, LTexture const& yesButton, LTexture const& noButton)
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT || button_is_pressed(e, noButton.mButton))
{
gameState = GameStates::EXIT;
return false;
}
if (button_is_pressed(e, yesButton.mButton))
{
gameState = GameStates::MAIN_MENU;
return false;
}
}
return true;
}
bool playAgain_update()
{
return true;
}
bool playAgain_render(LTexture& highLowTexture, LTexture& winlose, LTexture& playAgain, LTexture& yesButton, LTexture& noButton)
{
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
highLowTexture.render(gRenderer, 0, 0);
winlose.render(gRenderer, 335, 70);
playAgain.render(gRenderer, 325, 300);
yesButton.render(gRenderer, 300, 350);
noButton.render(gRenderer, 300 + yesButton.mWidth + 10, 350);
SDL_RenderPresent(gRenderer);
return true;
}
void playAgain(GameStates& gameState, Game game)
{
SDL_Color const textColor = { 0,0,0 };
auto const textWidth = 250;
auto highLowTexture = LTexture(from_surface, gRenderer, "Resources/HiLo.png");
auto playAgain = LTexture(from_text, gRenderer, "Play Again?", textColor, textWidth);
auto yesButton = LTexture{ from_surface, gRenderer, "Resources/HiLoYes.png" };
auto noButton = LTexture{ from_surface, gRenderer, "Resources/HiLoNo.png" };
std::string dialogue;
//change dialogue based on if player won or not
if (game.game_was_won)
{
dialogue = "YOU WON!!! The correct answer was " + std::to_string(game.randomNumber) + ".";
}
else
{
dialogue = "You lose. The correct answer was " + std::to_string(game.randomNumber) + ".";
}
auto winlose = LTexture{ from_text, gRenderer, dialogue, textColor, textWidth };
while (playAgain_input(gameState, yesButton, noButton) && playAgain_update() && playAgain_render(highLowTexture, winlose, playAgain, yesButton, noButton))
{}
}
bool gameLoop_input(GameStates& gameState, std::string& guessInput, int& guess, int& guessCount)
{
SDL_Event e;
SDL_StartTextInput();
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
gameState = GameStates::EXIT;
return false;
}
if (e.type == SDL_TEXTINPUT)
{
//if input is a numeric value, add to string.
if (e.text.text[0] == '0' || e.text.text[0] == '1' || e.text.text[0] == '2' || e.text.text[0] == '3' || e.text.text[0] == '4' ||
e.text.text[0] == '5' || e.text.text[0] == '6' || e.text.text[0] == '7' || e.text.text[0] == '8' || e.text.text[0] == '9')
{
guessInput += e.text.text;
}
}
if (e.type == SDL_KEYDOWN)
{
if (e.key.keysym.sym == SDLK_RETURN || e.key.keysym.sym == SDLK_KP_ENTER)
{
//if input is not empty
if (guessInput != " ")
{
//convert guess to int
guess = stoi(guessInput);
//reset string
guessInput = " ";
++guessCount;
}
}
else if (e.key.keysym.sym == SDLK_BACKSPACE && guessInput.length() > 0)
{
guessInput.pop_back();
}
}
}
SDL_StopTextInput();
return true;
}
bool gameLoop_update(GameStates& gameState, std::string& dialogue, int guess, int guessCount, Game& game)
{
if (guessCount == 0)
{
dialogue = "I'm thinking of a number between " + std::to_string(game.min) + " and " + std::to_string(game.max) + ". You have " + std::to_string(game.numberofGuesses) + " guesses.";
}
// if player ran out of moves
else if (guessCount == game.numberofGuesses)
{
game.game_was_won = false;
gameState = GameStates::PLAY_AGAIN;
return false;
}
else
{
int cmp = compare(game.randomNumber, guess);
//change dialogue based on comparison
if (cmp > 0)
{
dialogue = "Your guess was too low.";
}
else if (cmp < 0)
{
dialogue = "Your guess was too high.";
}
else
{
game.game_was_won = true;
gameState = GameStates::PLAY_AGAIN;
return false;
}
}
return true;
}
bool gameLoop_render(LTexture& highLowTexture, LTexture& guessPrompt, std::string guessInput, std::string dialogue, SDL_Color textColor, int textWidth, int guessCount, Game game)
{
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
highLowTexture.render(gRenderer, 0, 0);
guessPrompt.render(gRenderer, 350, 250);
auto bubbleText = LTexture(from_text, gRenderer, dialogue, textColor, textWidth);
bubbleText.render(gRenderer, 335, 70);
auto guessCounter = LTexture(from_text, gRenderer, "Guesses remaining: " + std::to_string(game.numberofGuesses - guessCount), textColor, textWidth);
guessCounter.render(gRenderer, 350, 200);
auto inputTexture = LTexture(from_text, gRenderer, guessInput, textColor, textWidth);
if (guessInput == "")
{
inputTexture = LTexture(from_text, gRenderer, " ", textColor, textWidth);
}
inputTexture.render(gRenderer, 350 + guessPrompt.mWidth, textWidth);
SDL_RenderPresent(gRenderer);
return true;
}
void gameLoop(GameStates& gameState, Game& game)
{
std::string guessInput = " ";
std::string dialogue = " ";
SDL_Color const textColor = { 0,0,0 };
auto const textWidth = 250;
auto highLowTexture = LTexture(from_surface, gRenderer, "Resources/HiLo.png");
auto guessPrompt = LTexture(from_text, gRenderer, "Enter a number:", textColor, textWidth);
int guessCount = 0;
int guess = 0;
while (gameLoop_input(gameState, guessInput, guess, guessCount) &&
gameLoop_update(gameState, dialogue, guess, guessCount, game) &&
gameLoop_render(highLowTexture, guessPrompt, guessInput, dialogue, textColor, textWidth, guessCount, game))
{}
}
bool mainMenu_input(GameStates& gameState, Game& game, LTexture& tenButton, LTexture& hundredButton, LTexture& thousandButton)
{
SDL_Event e;
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_QUIT)
{
gameState = GameStates::EXIT;
return false;
}
//change game settings based on button
if (button_is_pressed(e, tenButton.mButton))
{
game.numberofGuesses = 5;
game.max = 10;
game.randomNumber = getRandomNumber(game.min, game.max);
gameState = GameStates::MAIN_LOOP;
//used to make sure game works properly
std::cout << game.randomNumber;
return false;
}
else if (button_is_pressed(e, hundredButton.mButton))
{
game.numberofGuesses = 7;
game.max = 100;
game.randomNumber = getRandomNumber(game.min, game.max);
gameState = GameStates::MAIN_LOOP;
std::cout << game.randomNumber;
return false;
}
else if (button_is_pressed(e, thousandButton.mButton))
{
game.numberofGuesses = 9;
game.max = 1000;
game.randomNumber = getRandomNumber(game.min, game.max);
gameState = GameStates::MAIN_LOOP;
std::cout << game.randomNumber;
return false;
}
}
return true;
}
bool mainMenu_update()
{
return true;
}
bool mainMenu_render(LTexture& menuTexture, LTexture& tenButton, LTexture& hundredButton, LTexture& thousandButton)
{
SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(gRenderer);
menuTexture.render(gRenderer, 0, 0);
tenButton.render(gRenderer, (SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 175);
hundredButton.render(gRenderer, (SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 225);
thousandButton.render(gRenderer, (SCREEN_WIDTH / 2) - (tenButton.mWidth / 2), 275);
SDL_RenderPresent(gRenderer);
return true;
}
void mainMenu(GameStates& gameState, Game& game)
{
auto menuTexture = LTexture(from_surface, gRenderer, "Resources/HiLoMenu.png");
auto tenButton = LTexture(from_surface, gRenderer, "Resources/HiLo10.png");
auto hundredButton = LTexture(from_surface, gRenderer, "Resources/HiLo100.png");
auto thousandButton = LTexture(from_surface, gRenderer, "Resources/HiLo1000.png");
while (mainMenu_input(gameState, game, tenButton, hundredButton, thousandButton) &&
mainMenu_update() &&
mainMenu_render(menuTexture, tenButton, hundredButton, thousandButton))
{}
}
void init()
{
auto sdlinit = sdl{};
auto img = sdl_img{};
auto ttf = sdl_ttf{};
gWindow = SDL_CreateWindow("HiLo", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (gWindow == nullptr)
{
std::cout << "Failed to create window";
}
gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (gRenderer == nullptr)
{
std::cout << "Failed to create renderer";
}
gFont = TTF_OpenFont("Resources/opensans.ttf", 20);
if (gFont == nullptr)
{
std::cout << "Failed to open font";
}
}
void close()
{
if (gFont)
{
TTF_CloseFont(gFont);
}
if (gWindow)
{
SDL_DestroyWindow(gWindow);
}
if (gRenderer)
{
SDL_DestroyRenderer(gRenderer);
}
}
int main(int argc, char* args[])
{
init();
GameStates gameState = GameStates::MAIN_MENU;
Game game;
while (gameState != GameStates::EXIT)
{
switch (gameState)
{
case GameStates::MAIN_MENU:
mainMenu(gameState, game);
break;
case GameStates::MAIN_LOOP:
gameLoop(gameState, game);
break;
case GameStates::PLAY_AGAIN:
playAgain(gameState, game);
break;
}
}
close();
return 0;
}
</code></pre>
<p>I know I still have a lot to learn, but any additional feedback would be greatly appreciated.</p>
<p>I also have a few more questions:</p>
<ul>
<li><p>I was previously told that my code looks very "C-ish". If it still is, what makes it "C-ish"? I probably just don't know enough about the difference between the two to really tell.</p></li>
<li><p>What is the difference between doing something like <code>sdl sdlinit;</code> and <code>auto sdlinit = sdl{}</code>? Additionally, how do you determine when to use auto and when to specify?</p></li>
</ul>
<p>Thanks again for your time.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T04:02:15.833",
"Id": "386498",
"Score": "0",
"body": "You should flag a moderator and request your accounts be merged"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T06:17:16.443",
"Id": "386507",... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T00:18:24.143",
"Id": "200703",
"Score": "3",
"Tags": [
"c++",
"sdl"
],
"Title": "SDL/C++ High-Low Guessing Game (Version 2)"
} | 200703 |
<p>If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.</p>
<p>Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.</p>
<p>Example two:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.</p>
<p>My solution: </p>
<p>walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const perfectPrice = (prices, peak = {
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable: {}
}) => {
const week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
prices.forEach((price, day, all) => {
if (peak['buy'] === null) {
peak['buy_day'] = day
peak['buy'] = price
} else if (price < peak['buy']) {
peak['buy'] = price
peak['buy_day'] = day
}
if (peak['profit'] < (price - peak['buy'])) {
peak.profitable = {
buy: week[peak.buy_day],
buy_at: peak['buy'],
sell: week[day],
sell_at: price,
profit: price - peak['buy']
}
peak['profit'] = price - peak['buy']
}
});
return ((peak || {}).profitable || {}).profit ? peak.profitable : 'not profitable to sell';
}
console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
max-height: 100% !important;
top: 0;
}</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T02:37:14.363",
"Id": "386489",
"Score": "1",
"body": "Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate":... | [
{
"body": "<h2>Readability</h2>\n\n<ul>\n<li>The way you've named your variables makes the code more difficult to read for example <code>peak</code> just doesn't make sense to me. Another consideration would be to rename <code>buy_day</code> to <code>cheapest_day</code></li>\n<li>Don't overcomplicate things: I ... | {
"AcceptedAnswerId": "201115",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T01:44:16.733",
"Id": "200706",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"hash-map"
],
"Title": "Buy and Sell a Stock for maximum profit (given a day and a price)"
} | 200706 |
<p>I've just finished the first iteration of my new project. It's the first time I publish Python code and I would like to know what you think about the structure of the project, the API, testing, the documentation and obviously the implementation.</p>
<p>The goal of this library is to offer a flexible tool to perform generative-testing/property-based testing for software that accepts CSV files as an input.</p>
<p>It does so by leveraging hypothesis default strategies. The idea is to generate data tuples that are then converted to CSV files in different dialects. At the same time I follow the same approach of hypothesis giving complex customization options to generate specific subsets of CSV files.</p>
<p>You can find the whole project here: <a href="https://github.com/chobeat/hypothesis-csv" rel="nofollow noreferrer">https://github.com/chobeat/hypothesis-csv</a></p>
<p>Feel free to comment on any of these aspects.</p>
<p>It's the first time I post here and I'm not sure if this is the right approach (big reviews are usually bad reviews) so I will also submit some chunks of code for a more direct and focused review.</p>
<p>These are the two main files:</p>
<p>_data_rows.py</p>
<pre><code>import functools
import string
from hypothesis.errors import InvalidArgument
from hypothesis.strategies import composite, integers, sampled_from, floats, text
from multimethod import overload
from hypothesis_csv.type_utils import *
valid_column_types = [integers, floats,
functools.partial(text, min_size=1, max_size=10,
alphabet=string.ascii_lowercase + string.ascii_uppercase + string.digits)]
@overload
def get_columns(draw, columns):
raise InvalidArgument("Columns parameter must either be an integer or a list of strategies")
@overload
def get_columns(draw, columns: isa(collections.Iterable)):
return columns
@overload
def get_columns(draw, columns: isa(int)):
columns = [draw(sampled_from(valid_column_types))() for _ in range(columns)]
return columns
@overload
def get_columns(draw, columns: is_none):
return get_columns(draw, draw(integers(min_value=1, max_value=10)))
@overload
def get_lines_num(draw, lines_param):
raise InvalidArgument("Lines param must be an integer or None")
@overload
def get_lines_num(draw, lines_param: is_none):
return draw(integers(min_value=1, max_value=100))
@overload
def get_lines_num(draw, lines_param: isa(int)):
return lines_param
@composite
def data_rows(draw, lines=None, columns=None):
"""
Strategy to produce a list of data tuples
:param draw:
:param lines: number of data tuples to be produced. If not specified, it will be drawn randomly
in a range between 1 and 100
:param columns: int or List. If an int is provided, it will define the size of the data tuple.
Its data types will be drawn randomly.
If a List of strategies is provided, the elements for each tuple will be drawn from these strategies. They will
be returned in the same order of the list here provided.
:return: a list of data tuples
"""
lines_num = get_lines_num(draw, lines)
columns = get_columns(draw, columns)
rows = [tuple(draw(column) for column in columns) for _ in range(lines_num)]
return rows
</code></pre>
<p>_csv.py</p>
<pre><code>from hypothesis.strategies import lists
from meza.convert import records2csv
from hypothesis_csv._data_rows import *
from hypothesis_csv.type_utils import *
def draw_header(draw, header_len):
return draw(lists(text(min_size=1,
alphabet=string.ascii_lowercase + string.ascii_uppercase + string.digits),
min_size=header_len, max_size=header_len, unique=True))
@overload
def _get_header_and_column_types(draw, header, columns):
raise InvalidArgument("Header or column are of invalid type")
@overload
def _get_header_and_column_types(draw, header: is_seq, columns: is_seq):
if len(header) == len(columns):
return header, columns
else:
raise InvalidArgument("Header and columns must be of the same size")
@overload
def _get_header_and_column_types(draw, header: is_seq,
columns: is_none):
return header, len(header)
@overload
def _get_header_and_column_types(draw, header: is_none, columns: is_none):
columns = draw(integers(min_value=1, max_value=10))
return None, columns
@overload
def _get_header_and_column_types(draw, header: isa(int), columns: isa(int)):
if header == columns:
header_fields = draw_header(draw, header)
return header_fields, len(header_fields)
else:
raise InvalidArgument("Header and columns must be of the same size")
@overload
def _get_header_and_column_types(draw, header: is_none, columns: isa(int)):
return None, columns
@overload
def _get_header_and_column_types(draw, header: isa(int), columns: is_none):
return _get_header_and_column_types(draw, header, header)
@overload
def _get_header_and_column_types(draw, header: is_none, columns: is_seq):
return None, columns
@composite
def csv(draw, header=None, columns=None, lines=None):
"""
Strategy to produce a CSV string. Uses `data_rows` strategy to generate the values. Refer to the `data_rows`
strategy for more details about the `columns` and `lines` parameter.
:param draw:
:param header: if a list of strings, these will be used as the header for each column, according to their position.
If an int, this parameter will define the number of columns to be used. If None, the produced CSV will have no
header
:param columns: If a list of strategies, these will be used to draw the values for each column.
If an int, this parameter will define the number of columns to be used. If not provided the number of columns will
be drawn randomly or the `header` param will be used.
:param lines: number of rows in the CSV.
:return: a string in CSV format
"""
header_param, columns = _get_header_and_column_types(draw, header, columns)
rows = list(draw(data_rows(lines=lines, columns=columns)))
header = header_param or ["col_{}".format(i) for i in range(len(rows[0]))] # placeholder header for meza records
data = [dict(zip(header, d)) for d in rows]
return records2csv(data, skip_header=header_param is None).getvalue()
</code></pre>
<p>My main concern is on the way I've handled parameter overloading: I wanted to accept both int and list for two optional parameters and instead of going through the usual jungle of if else that you see in many projects (sklearn, pandas and so on), I've tried to decompose the problem using multimethod library. I've never seen an example of this approach so I'm not sure I'm handling it the right way but I'm satisfied by the end result since it's very readable. A bit verbose if you ask me but still better than handling it with if-else.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T03:21:33.950",
"Id": "386679",
"Score": "0",
"body": "Your code looks extremely rigid. If you had to change your code to also accept a dictionary, how many lines would you have to change? Hint: adding more overloaded signatures is n... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T08:02:13.607",
"Id": "200722",
"Score": "2",
"Tags": [
"python",
"library"
],
"Title": "Generative testing for CSV using Hypothesis - project, API, implementation"
} | 200722 |
<p>I have this item (an item is an object linked to a xml view), to build it I need 2 things, get labels from codes, and get text from the strings.xml android file.</p>
<p>please ignore the long to int and int to long convertion, for some reason the database value where randomly set to long and int but they could all be int,
I will refactor this later.</p>
<p><code>refManager</code> is calling a <code>DAO</code>to fetch data from the database.</p>
<p>I have a for loop, building several <code>OperationInstallItem</code></p>
<pre><code>//constructor
public OperationInstallItem(final Resources resources, final RefManager refManager,
final ModuleCategoryEnum category, final ModeleOperationEntity modeleOperationEntity,
boolean isMandatory) {
//basic init
this.category = category
this.isMandatory = isMandatory;
this.refTypeOperation = modeleOperationEntity.getRefTypeOperation();
this.refTypeInstallation = Long.valueOf(modeleOperationEntity.getRefTypeInstallation());
//label init
this.operationLabel = refManager.getOperationLabel(Ints.checkedCast(refTypeOperation));
this.installationShortLabel = parametrageManager.getInstallationShortLabelt(refTypeInstallation);
this.installationLongLabel = parametrageManager.getInstallationLongLabel(refTypeInstallation);
this.title = resources.getString(R.string.operation_intallation_title)
//icons specific to this class
CodeTypeOperation codeTypeOperation =
CodeTypeOperation.getEnumByCode(Ints.checkedCast(refTypeOperation));
addModuleAdapterIconId = codeTypeOperation.getIcon();
moduleAdapterIconId = codeTypeOperation.getIcon();
moduleAdapterIconselectedId = codeTypeOperation.getIconSelected();
moduleFragmentClass = TDBAddModuleFragment.class;
}
</code></pre>
<p>Most of my collueages are uneasy with passing a manager as a constructor arguments but noone of
them can explain me why. "it's just not done this way"</p>
<p>same thing with <code>Resources resources</code> that allow you to get String values from the strings.xml file doing this <code>resources.getString(R.string.operation_intallation_title)</code>,
according to them, it is bad to pass it in the constructor.</p>
<p>I don't get it, I need those labels/title, if I do this before the instanciation and pass it as parameters it's the exact
same thing. no performance gain, nothing is different. </p>
<p>Or is there something I'm missing?</p>
| [] | [
{
"body": "<p>First of all, it violates the \"tell don't ask\" principle: if your OptionInstallItem is not inherently coupled to the database and its actions (and as you do not even record the reference to the refmanager, it obviously isn't) it should not go about scavenging in your whole application to get its... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T09:09:51.267",
"Id": "200725",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"database",
"constructor"
],
"Title": "Fetching data from your database in a constructor"
} | 200725 |
<blockquote>
<p>In a party everyone is in couple except one. People who are in couple
have same numbers. Find out the person who is not in couple.</p>
<p><strong>Input:</strong> </p>
<p>The first line contains an integer \$T\$ denoting the total
number of test cases. In each test cases, the first line contains an
integer \$N\$ denoting the size of array. The second line contains \$N\$
space-separated integers \$A_1, A_2, \ldots, A_N\$ denoting the elements of the
array. (\$N\$ is always odd)</p>
<p><strong>Output:</strong> </p>
<p>In each seperate line print number of the person not in
couple.</p>
<p><strong>Constraints:</strong> </p>
<p>\$ 1 \leq T \leq 30\$</p>
<p>\$ 1 \leq N \leq 500\$</p>
<p>\$ 1 \leq A[i] \leq 500\$</p>
<p>\$ N \% 2 = 1\$</p>
<p>Example: </p>
<p><strong>Input:</strong> </p>
<pre><code>1
5
1 2 3 2 1
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3
</code></pre>
</blockquote>
<p>My approach:</p>
<pre><code>/*package whatever //do not write package name here */
import java.util.Scanner;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
class GFG {
private static int getAloneNum (int[] arr) {
List<Integer> alone = new ArrayList<>();
for (Integer elem : arr) {
if (!(alone.contains(elem))) {
alone.add(elem);
}
else {
alone.remove(alone.indexOf(elem));
}
}
return alone.get(0);
}
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int numTests = sc.nextInt();
for (int i = 0; i < numTests; i++) {
int size = sc.nextInt();
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = sc.nextInt();
}
System.out.println(getAloneNum(arr));
}
}
}
</code></pre>
<p>I have the following questions with regards to the above code:</p>
<ol>
<li><p>How can I further improve my approach?</p></li>
<li><p>Is there a better way to solve this question?</p></li>
<li><p>Are there any grave code violations that I have committed?</p></li>
<li><p>Can space and time complexity be further improved?</p></li>
<li><p>Is my code very redundant?</p></li>
</ol>
<p><a href="https://practice.geeksforgeeks.org/problems/alone-in-couple/0/?track=Placement" rel="nofollow noreferrer">Reference</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T09:34:02.967",
"Id": "386543",
"Score": "0",
"body": "`LinkedList` should be faster than `ArrayList` for adding and removing items"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T09:40:23.657",
"I... | [
{
"body": "<p>You are using a pretty nice idea here. You store things you've seen once and remove them when you've seen them a second time. To do so you're using a <code>List</code>. </p>\n\n<p>Instead of a <code>List</code> you should be using a <code>Set</code> though. Lists are not optimized for <code>contai... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T09:14:42.847",
"Id": "200726",
"Score": "2",
"Tags": [
"java",
"beginner",
"interview-questions",
"complexity"
],
"Title": "Alone in a Couple implementation in Java"
} | 200726 |
<p>I am building an application that is becoming some kind of social media platform. I need to work a lot with the entities ID's in the HTML and Javascript for the purpose of AJAX calls. However, for security reasons I don't want the original ID's exposed.</p>
<p>Instead of encrypting an ID every time it is displayed or being sent to the client, I figured it would be better to encrypt the ID of every entity once. When they are loaded. I tried to encrypt the <code>$id</code> field of entities on <code>postLoad</code> and decrypt them again at <code>preUpdate</code>. That works fine, until relations come around. Doctrine simply finds no relations because the ID of the current entity is ecrypted (duh).</p>
<p>I decided to not touch the <code>$id</code> field of the entities and create an additional field. The field will only be used when the entity is loaded and will not be persisted. Instead of adding the field and get/set methods to each entity, I decided to create an <code>interface</code> and <code>abstract class</code>. The interface is to use for checking the object later on. The abstract class is to implement the methods.</p>
<p>This is the interface defining the methods that are needed. I also defined <code>getId()</code> here. This is so I can be sure that <code>getId()</code> is available by checking the objects against this interface.</p>
<pre><code>namespace App\Entity;
interface EncryptableEntity
{
/**
* @return int|null
*/
public function getId(): ?int;
/**
* @return null|string
*/
public function getEncryptedId(): ?string;
/**
* @param string $encryptedId
*
* @return EncryptableEntity
*/
public function setEncryptedId( string $encryptedId ): EncryptableEntity;
}
</code></pre>
<p>This is the <code>abstract class</code>, implementing the field and the methods. Except the <code>getId()</code> method, because it is already implemented in the entity itself.</p>
<pre><code>namespace App\Entity;
abstract class AbstractEncryptableEntity implements EncryptableEntity
{
/**
* @var null|string
*/
private $encryptedId;
/**
* {@inheritdoc}
*/
public function getEncryptedId(): ?string
{
return $this->encryptedId;
}
/**
* {@inheritdoc}
*/
public function setEncryptedId( string $encryptedId ): EncryptableEntity
{
$this->encryptedId = $encryptedId;
return $this;
}
}
</code></pre>
<p>This is an example entity extending the <code>AbstractEncryptableEntity</code> class.</p>
<pre><code>namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\PostRepository")
*/
class Post extends AbstractEncryptableEntity
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $content;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="posts")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}
</code></pre>
<p>The Doctrine listener class encrypts the ID of the entity and sets the field when the entity is loaded. <a href="https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#entity-listeners" rel="nofollow noreferrer">Read more about Doctrine event listeners.</a> I use <code>NzoUrlEncryptor</code> because I also use it for routing purposes. It could however be any encryption tool.</p>
<pre><code>namespace App\EventListener;
use App\Entity\EncryptableEntity;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Nzo\UrlEncryptorBundle\UrlEncryptor\UrlEncryptor;
class EntityEncryptorListener
{
private $encryptor;
public function __construct( UrlEncryptor $encryptor )
{
$this->encryptor = $encryptor;
}
public function postLoad( LifecycleEventArgs $args )
{
$entity = $args->getEntity();
if ( $entity instanceof EncryptableEntity ) {
$entity->setEncryptedId(
$this->encryptor->encrypt( $entity->getId() )
);
}
}
}
</code></pre>
<p>This is the <code>services.yml</code> file entry.</p>
<pre><code>services:
App\EventListener\EntityEncryptorListener:
tags:
- { name: doctrine.event_listener, event: postLoad }
</code></pre>
<p>I am quite happy with my solution. However I would have liked it even more if I didn't need the extra field. Does one of you guys have an idea about how I can omit this?</p>
<p>It would be best if I could somehow override Doctrine behavior so I wouldn't have to touch the entity classes at all.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T09:27:00.480",
"Id": "200727",
"Score": "3",
"Tags": [
"php",
"symfony3"
],
"Title": "Symfony: Encrypt ID's on postLoad event"
} | 200727 |
<p>An attempt with regular expression to do a foolproof validation of an IV4 or Hostname:port Number.</p>
<p>Example texts that can be validated for any of the following:
</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>www.google.com:8080
127.0.0.1:8000
localhost:65535
codereview.stackexchange.com:9000
www.n-plus-t.com:4000
30my_domain.test-ng.com:754
</code></pre>
</blockquote>
<pre class="lang-java prettyprint-override"><code>((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d]) | ([\\p{Alnum}+ && [.{1}-_*[\p{Alnum}+]]]){1,253}:(6553[0-5]|655[0-2][0-9]\d|65[0-4](\d){2}|6[0-4](\d){3}|[1-5](\d){4}|[1-9](\d){0,3})
</code></pre>
<p>The IPv4 address validations are mainly to ensure that the tuples are between the range 0 to 255. Also the hostname is validated against the valid names which can be alphanumeric, starting with number, subdomains separated by a single . and - and _ allowed in between, though not at end. Port range is validated from 0 to 65535</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T10:22:28.107",
"Id": "386547",
"Score": "0",
"body": "Which regex implementation are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T10:23:11.677",
"Id": "386548",
"Score": "0",
... | [
{
"body": "<p>While this appears to work, there are a few things about it that are not very clear.</p>\n\n<h2>Reconsider the use of regex</h2>\n\n<p>Rather than using a regex, for the numeric ranges in particular, it may make more sense to capture those values and check them with Java statements. It would cert... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T10:18:36.473",
"Id": "200731",
"Score": "3",
"Tags": [
"java",
"regex",
"ip-address"
],
"Title": "Regular Expression for text that validates IPV4 or Hostname followed by a port number eg: 127.0.0.1:8080 or localhost:8080"
} | 200731 |
<p>First time posting in Code Review! I have started learning front-end development to complement my UI design skillset and am starting with CSS Grid and bootstrap.</p>
<p>Have a look at the snippets. I think the 2 work quite well, using CSS Grid for layout and the Bootstrap library for things like buttons, forms and navs etc.</p>
<p>Can you let me know if there is anything I can do to make my code more scalable and more toward production standard?</p>
<p>Thanks!</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>body{
margin: 0%;
padding: 0%;
background-image: url('../img/background.jpg');
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
background-color: #464646;
overflow: hidden;
}
.logo{
height: 30px;
margin: 50px;
}
.container-fluid{
height: 100vh;
padding: 0;
margin: 0;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-areas:
"L R"
}
.left-side{
grid-area: L;
height: 100vh;
margin: 0;
padding: 0;
}
.right-side{
grid-area: R;
background: linear-gradient(-135deg, rgb(255, 0, 0,0.8), rgba(167,0,0,0.8));
height: 100vh;
margin-right: 0;
text-align: center;
}
.right-inner{
margin: 40% auto;
max-width: 500px;
min-width: 200px;
height: 100vh;
}
.welcome{
color: #fff;
text-align: left;
font-family: "UniversNext", sans-serif;
font-size: 36px;
margin-top: 0;
padding-top: 0;
margin-bottom: 30px;
}
.cust-name{
color: #fff;
font-family: "UniversNext", sans-serif;
}
.log-in{
background-color: transparent;
border: 1px solid #fff;
color: #fff;
padding: 9px;
height: 38px;
width: 100px;
font-size: 14px;
font-family: sans-serif;
float: left;
}
.log-in:hover{
background-color: #fff;
border: 1px solid #fff;
color: #253038;
}
.log-in:active{
background-color: rgb(221, 221, 221);
border: 1px solid #fff;
color: #253038;
}
.log-in:focus{
background-color: rgb(221, 221, 221);
border: 1px solid #fff;
color: #253038;
}
.password{
margin-bottom: 20px;
}
.form-control{
min-height: 38px;
}
.col-form-label-sm{
color: #fff;
text-align: center;
font-family: sans-serif;
}
p{
text-align: left;
padding-top: 10px;
color: #fff;
font-family: sans-serif;
letter-spacing: 0.4px;
}
a{
text-align: left;
padding-top: 10px;
color: #fff;
font-family: sans-serif;
letter-spacing: 0.4px;
}
a:hover{
text-align: left;
padding-top: 10px;
color: #fff;
font-family: sans-serif;
letter-spacing: 0.4px;
text-decoration: underline;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="./css/style.css">
<link rel="icon" href="./img/favicon.png" type="image/png">
<title>site</title>
</head>
<body>
<div class="container-fluid">
<div class="left-side">
<img src="./img/logo.png" alt="Logo" class="logo">
</div>
<!-- Right hand side -->
<div class="right-side">
<div class="right-inner">
<h3 class="welcome">Welcome back <span class="cust-name">Alan!</span></h3>
<form>
<div class="form-group row">
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input type="password" class="form-control password" id="inputPassword3" placeholder="Password">
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<input class="btn btn-primary log-in" id="log-in" type="submit" value="Log in">
<p>Forgot your password?</p>
</div>
</div>
</form>
<p>Don't have an account? <a href="#">Register</a></p>
</div>
</div>
<!-- right hand side End -->
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h1>Semantics and UX</h1>\n\n<p>You can adjust a few things that will improve the overall UX of your login-page:</p>\n\n<h2>Document outline / structure</h2>\n\n<p>To improve the overall structure of your document use sectioning elements like <code>header</code>, <code>main</code>, <code>section</cod... | {
"AcceptedAnswerId": "200746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T10:28:12.917",
"Id": "200734",
"Score": "3",
"Tags": [
"html",
"css",
"twitter-bootstrap"
],
"Title": "CSS Grid and Bootstrap 4"
} | 200734 |
<p>Kindly provide your review comments:</p>
<pre><code>//SmartPtr.h
class RefCount {
public:
void AddRef() {
++(this->_count);
}
int Release() {
return --(this->_count);
}
private:
int _count;
};
template <class T>
class SmartPtr {
public:
// constructor
SmartPtr();
SmartPtr(T* iObject);
// copy constructor
SmartPtr(const SmartPtr<T>& iSPtr);
// destructor
~SmartPtr();
// operators
SmartPtr<T>& operator=(const SmartPtr<T>& iSPtr);
T& operator*();
T* operator->();
private:
T* _ptr;
RefCount* _refCount;
void _release();
void _copySmartPtr(const SmartPtr<T>& iSPtr);
};
//SmartPtr.cpp
#include "SmartPtr.h"
// constructor
template <class T>
SmartPtr<T>::SmartPtr():
_refCount(nullptr),
_ptr(nullptr)
{
}
template <class T>
SmartPtr<T>::SmartPtr(T* iObject):
_refCount(new RefCount()),
_ptr(iObject)
{
this->_refCount->AddRef();
}
// copy constructor
template <class T>
SmartPtr<T>::SmartPtr(const SmartPtr<T>& iSPtr)
{
this->_copySmartPtr(iSPtr);
}
// destructor
template <class T>
SmartPtr<T>::~SmartPtr() {
this->_release();
}
// operators
template <class T>
SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& iSPtr) {
if (iSPtr._ptr && (this != &iSPtr)) {
this->_release();
this->_copySmartPtr(iSPtr);
}
return *this;
}
template <class T>
T& SmartPtr<T>::operator*() {
return *(this->_ptr);
}
template <class T>
T* SmartPtr<T>::operator->() {
return this->_ptr;
}
template <class T>
void SmartPtr<T>::_release() {
if (this->_refCount && this->_refCount->Release() == 0) {
delete this->_ptr;
delete this->_refCount;
}
}
template <class T>
void SmartPtr<T>::_copySmartPtr(const SmartPtr<T>& iSPtr) {
this->_ptr = iSPtr._ptr;
this->_refCount = iSPtr._refCount;
this->_refCount->AddRef();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T11:19:42.583",
"Id": "386565",
"Score": "5",
"body": "What C++ version did you use? Is there a reason you wrote this instead of using `std::unique_ptr` or `std::shared_ptr`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Creat... | [
{
"body": "<ul>\n<li><p>As @bipll mentioned, <code>template</code>s must be fully available everywhere they are used. Maybe move the implementation to the header, or at least add a note that the .cpp file is intended to be included instead of the header, as this is unusual.</p></li>\n<li><p>Some operators (<cod... | {
"AcceptedAnswerId": "200764",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T10:54:13.777",
"Id": "200737",
"Score": "8",
"Tags": [
"c++",
"pointers",
"c++98"
],
"Title": "custom smart pointer class template"
} | 200737 |
<p>In my ASP.NET MVC application there are occasions where I need to generate an absolute URI, such as when sending an email confirmation link to a user. The most straightforward approach is to use <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.urlhelperextensions.action?view=aspnetcore-2.1#Microsoft_AspNetCore_Mvc_UrlHelperExtensions_Action_Microsoft_AspNetCore_Mvc_IUrlHelper_System_String_System_String_System_Object_System_String_" rel="nofollow noreferrer"><code>UrlHelper.Action()</code> with the <code>protocol</code> parameter</a>, and this has worked well for me.</p>
<p>However, now my server is behind a reverse proxy, so the absolute URIs that I'm generating are pointing to <code>backendserver.myorg.local</code> instead of <code>publicsite.example.com</code>, and that's not good for business.</p>
<p>So, I wrote this method to inspect the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin" rel="nofollow noreferrer">Origin header</a>. Do you see any security problems or other reasons this might not be a good solution?</p>
<pre><code>static class UrlHelperExtensions
{
private const string OriginHeader = "Origin";
/// <summary>
/// Generates a full absolute URI, with HTTP(S), host name, and everything. Is reverse-proxy-aware,
/// so will generate public URIs in the event that our server is behind a reverse proxy.
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="actionName"></param>
/// <param name="controllerName"></param>
/// <param name="routeValues"></param>
/// <returns></returns>
public static string AbsoluteAction(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues = null)
{
if (urlHelper == null)
throw new ArgumentNullException(nameof(urlHelper), $"{nameof(urlHelper)} is null.");
var protocol = urlHelper.RequestContext.HttpContext.Request.Url.Scheme; // Should be "http" or "https"
var localUriString = urlHelper.Action(actionName, controllerName, routeValues, protocol);
var originValues = urlHelper.RequestContext.HttpContext.Request.Headers.GetValues(OriginHeader)
.Where(x => !String.IsNullOrWhiteSpace(x))
.ToList();
if (!originValues.Any())
return localUriString; // We are NOT behind a reverse proxy. Easy peasy, return local URI.
var originUriString = originValues.First(); // There should only be only 1 Origin header, but theoretically it's possible to have more than 1.
var originUri = parseOriginUri(originUriString);
var uriBuilder = new UriBuilder(localUriString);
uriBuilder.Scheme = originUri.Scheme; // AKA "protocol" (http or https)
uriBuilder.Host = originUri.Host;
uriBuilder.Port = originUri.Port;
return uriBuilder.ToString();
}
private static Uri parseOriginUri(string originText)
{
try
{
return new Uri(originText);
}
catch (UriFormatException ex)
{
throw new UriFormatException($"{OriginHeader} header URI is in an invalid format: \"{originText}\"", ex);
}
}
}
</code></pre>
<p>Note: Right now I don't have any requirements to actually manipulate the URL path.</p>
| [] | [
{
"body": "<p>This is based on a misunderstanding of the <code>Origin</code> header. <a href=\"https://stackoverflow.com/a/15514049/138757\">Chrome and Safari add this header to their web requests</a>, but other browsers don't necessarily. You only have to test this from a browser like Internet Explorer or Fire... | {
"AcceptedAnswerId": "200759",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T12:10:40.550",
"Id": "200742",
"Score": "4",
"Tags": [
"c#",
"security",
"http",
"asp.net-mvc",
"url-routing"
],
"Title": "Generating absolute URIs behind a reverse proxy"
} | 200742 |
<p>I have a <code>Calculation</code> class. It is persisted in the DB and users can modify it.</p>
<p>The aim of the <code>CompareWith</code> function is to display to the users which parameters have been changed.</p>
<p>A good part of the function is just the same code duplicated. I have been thinking about a way to abstract it out in a function, but have not been able to figure it out.</p>
<p><strong>How can I improve this function?</strong></p>
<pre><code>Public Class Calculation
Public Property ValueCalculation As String
Public Property LowLowLowLimitCalculation As String
Public Property LowLowLimitCalculation As String
Public Property LowLimitCalculation As String
Public Property TargetCalculation As String
Public Property HighLimitCalculation As String
Public Property HighHighLimitCalculation As String
Public Property HighHighHighLimitCalculation As String
Public Function CompareWith(comparedCalculation As Calculation) As CalculationError
Dim resultStatus As New CalculationError
If comparedCalculation Is Nothing Then
Return CalculationError.NotCreated
End If
If Not (ValueCalculation = comparedCalculation.ValueCalculation) Then
resultStatus = resultStatus Or CalculationError.Value
End If
If Not (LowLowLowLimitCalculation = comparedCalculation.LowLowLowLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.LowLowLowLimit
End If
If Not (LowLowLowLimitCalculation = comparedCalculation.LowLowLowLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.LowLowLimit
End If
If Not (LowLimitCalculation = comparedCalculation.LowLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.LowLimit
End If
If Not (TargetCalculation = comparedCalculation.TargetCalculation) Then
resultStatus = resultStatus Or CalculationError.Target
End If
If Not (HighHighHighLimitCalculation = comparedCalculation.HighHighHighLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.HighHighHighLimit
End If
If Not (HighHighLimitCalculation = comparedCalculation.HighHighLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.HighHighLimit
End If
If Not (HighLimitCalculation = comparedCalculation.HighLimitCalculation) Then
resultStatus = resultStatus Or CalculationError.HighLimit
End If
Return resultStatus
End Function
End Class
<Flags>
Public Enum CalculationError
NotCreated = 1
Value = 2
LowLowLowLimit = 4
LowLowLimit = 8
LowLimit = 16
HighLimit = 32
HighHighLimit = 64
HighHighHighLimit = 128
Target = 256
End Enum
</code></pre>
<p>Example of use:</p>
<pre><code>Public Sub Main()
Dim foo As New Calculation() With {.ValueCalculation = "1+1"}
Dim bar As new Calculation() With {.ValueCalculation = "2+2"}
Console.WriteLine(foo.CompareWith(bar).ToString())
'Output: Value
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T13:31:24.970",
"Id": "386585",
"Score": "0",
"body": "would you please provide the entire class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T13:38:09.360",
"Id": "386586",
"Score": "1",
... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T12:34:10.230",
"Id": "200744",
"Score": "4",
"Tags": [
".net",
"vb.net"
],
"Title": "Comparing two instances of a class"
} | 200744 |
<p>I have a big file, which contains column names in the first row. The data is about 20GB and consists of 10s of millions of rows. Every other row contains data which I would like to append to other files depending on the distinct entries in a particular column (depending on index). When the program encounters a new distinct entry it creates the file other wise it should append the data. The following piece of code is my basic attempt to achieve this (I am Python newbie):</p>
<pre><code>import re
import os
input_path_file1 = 'C:\InputData.txt'
output_path = r'C:\Output\Data'
unique_values = {}
# read in first line containing column names
with open(input_path_file1, 'r') as file:
first_line = file.readline()
rows = 0
# 7 line_number
# 35 range
index = 35
with open(input_path_file1, mode='r') as file:
# skip first row
next(file)
for line in file:
splitted_data = re.split(r'\t+', line.rstrip('\t'))
cell_data = splitted_data[index].replace('/', '')
target = os.path.join(output_path, cell_data + '.txt')
if cell_data in unique_values:
unique_values[cell_data] += 1
else:
unique_values[cell_data] = 1
with open(target, 'w') as outfile:
outfile.write(first_line)
with open(target, 'a') as outfile:
outfile.write(line)
rows += 1
</code></pre>
<p>Could this be made more efficient?</p>
| [] | [
{
"body": "<p>It would be more efficient to open each file only once,\ninstead of reopening every time you need it.\nTwo obvious approaches come to mind:</p>\n\n<ul>\n<li><p>Accumulate all the lines you want to write to files into a dictionary of lists, and then write to the files one by one. Given that your co... | {
"AcceptedAnswerId": "200762",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T13:20:27.680",
"Id": "200747",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"csv"
],
"Title": "Split big file into separate files depending on column's distinct values"
} | 200747 |
<p>I'm new to programming and this is one of my first programs. I had no idea what I was doing so most of this program was made from bad bug-fixing that barely managed to fix the bugs. I'm sure that there are many things that I did wrong or very inefficiently. Please tell me what I did wrong and how I can improve this program:</p>
<pre><code>stock={'banana':6,
'apple':0,
'orange':32,
'pear':15,}
prices={'banana': 4,
'apple':2,
'orange':1.5,
'pear':3}
def uppercase(x):
return x[0].upper()+x[1:]
name=input('''What is your name?
''')
print('Hi, %s, welcome to my fruit store. Here is the menu:'%(name))
print()
def menu():
for fruit in prices:
print(uppercase(fruit))
print('Price: $%s'%(prices[fruit]))
print('Stock: %s'%(stock[fruit]))
print()
print('You have: $%s'%(money))
print()
def ask_fruit(money):
fruit=input('''What fruit do you want?
''')
print()
if fruit in stock:
if stock[fruit]>0:
ask_amount(fruit,money)
else:
print('''Sorry, %ss are out of stock
'''%(fruit))
ask_fruit(money)
else:
print('''Sorry, we don\'t have that, look at the menu.
''')
ask_fruit(money)
def ask_amount(fruit,money):
amount=int(input('''How many %ss do you want?
'''%(fruit)))
print()
if amount<=0:
print('''At least buy one.
''')
ask_amount(fruit,money)
elif stock[fruit]>=amount:
sell(fruit,amount,money)
else:
print('''Sorry, we don\'t have that many %ss.
'''%(fruit))
ask_amount(fruit,money)
def sell(fruit,amount,money):
cost=prices[fruit]*amount
confirmation=input('''Are you sure? That will be $%s.
-Yes
-No
'''%(cost)).lower()
print()
if confirmation=='yes':
money-=cost
print('''Thank you for the business!
''')
stock[fruit]=stock[fruit]-amount
ask_again()
elif confirmation=='no':
ask_fruit()
else:
print('''Answer me.
''')
sell(fruit,amount,money)
def ask_again():
answer=input('''Do you want anything else?
-Yes
-No
''').lower()
print()
if answer=='yes':
menu()
ask_fruit(money)
elif answer=='no':
print('Okay, bye.')
else:
print('Answer me.')
ask_again()
money=117
menu()
ask_fruit(money)
</code></pre>
| [] | [
{
"body": "<p>First of all well done, this is not bad for a first program :D</p>\n\n<h1>Good</h1>\n\n<ul>\n<li>Usage of functions</li>\n<li>Using correct datatypes (dictionary for example)</li>\n</ul>\n\n<h1>Some Improvements in random order</h1>\n\n<ul>\n<li><p>Read <a href=\"https://www.python.org/dev/peps/pe... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T13:44:37.643",
"Id": "200751",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Simple Shop Program"
} | 200751 |
<h1>Task</h1>
<p>control how much coroutines are running simultaneously with ability to stop the process from inside.</p>
<h3>Use case</h3>
<p>when scraping websites you want to control how much memory program consumes and how much load on target it produces.</p>
<h3>Usage</h3>
<ol>
<li>create an instance</li>
<li>call <code>attach_coroutines_generator</code> to attach some generator which will create new coroutines from queue which is accessible from these coroutines (for example, every coroutine downloads html and queues new downloads for extracted links)</li>
<li>call <code>run</code> method</li>
</ol>
<h3>More description</h3>
<p><code>_sleep</code> method, <code>_do_stop</code> and <code>stop_gracefully</code> all exists to allow code inside <code>_runner</code> method stop <code>run</code> method call (because we can't cancel future from its child).</p>
<p>When runner catches <code>StopIterationError</code> it is put on sleep for <code>delay</code> seconds.</p>
<p>When some "runner" realizes that every other runner is put on sleep, it updates <code>_do_stop</code> attribute so all runners will break their while-loops.</p>
<h3>Questions</h3>
<ul>
<li>I'm not sure about appropriate naming and typing.</li>
<li>Security issues?</li>
<li>Is there other/better ways to do the same?</li>
</ul>
<h2>Code</h2>
<pre><code>import asyncio
class RunnersPool:
def __init__(self, pool_size: int, delay: float =1., enable_auto_stop=True):
self._pool_size = pool_size
self._delay = delay
self._auto_stop_enabled = enable_auto_stop
self._do_stop = False
self._active_counter = 0
self._delayed_counter = 0
self._coroutines_generator = None
self._runners = None
# ----------------
# runner methods
async def _runner(self) -> None:
self._active_counter += 1
while True:
try:
coroutine = next(self._coroutines_generator)
except StopIteration:
await self._sleep()
if not self.is_running and self._auto_stop_enabled:
break
else:
try:
await coroutine
except Exception as exc:
self.handle_exception(exc, coroutine)
self._active_counter -= 1
async def _sleep(self) -> None:
if self._delayed_counter + 1 == self._pool_size:
self.stop_gracefully()
return
self._delayed_counter += 1
await asyncio.sleep(self._delay)
self._delayed_counter -= 1
# end
# ----------------
async def run(self):
if not self._coroutines_generator:
raise RuntimeError('coroutines_generator not attached yet')
self._runners = asyncio.gather(*[
self._runner() for _ in range(self._pool_size)
])
await self._runners
def handle_exception(self, exception: Exception, coroutine: Coroutine):
raise exception
def cancel(self):
self._runners.cancel()
def stop_gracefully(self):
self._do_stop = True
def attach_coroutines_generator(self, coroutines_generator: Iterable[Coroutine]):
self._coroutines_generator = coroutines_generator
@property
def pool_size(self) -> int:
return self._pool_size
@property
def delay(self) -> float:
return self._delay
@property
def is_running(self) -> bool:
return not self._do_stop
@property
def auto_stop_enabled(self) -> bool:
return self._auto_stop_enabled
@property
def delayed_runners(self) -> int:
return self._delayed_counter
@property
def active_runners(self) -> int:
return self._active_counter
</code></pre>
<h3>Example usage</h3>
<pre><code>class SmartQueue:
def __init__(self):
self.queue = collections.deque()
def put(self, x):
self.queue.append(x)
def get(self):
return self.queue.popleft()
def __next__(self):
if self.queue:
return self.get()
else:
raise StopIteration
async def main():
sq = SmartQueue()
async def cor(num):
await asyncio.sleep(1)
print(num)
if num > 0:
sq.put(cor(num - 1))
for i in range(1, 10+1):
sq.put(cor(i))
r = RunnersPool(5)
r.attach_coroutines_generator(sq)
await r.run()
if __name__ == '__main__':
loop = asyncio.new_event_loop()
loop.run_until_complete(main())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T02:39:50.937",
"Id": "386676",
"Score": "1",
"body": "From experience, coroutines are not built to act like this; they're event-based processors (they process something when the next event fires off). You're adding all the functiona... | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T14:27:12.783",
"Id": "200754",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"async-await"
],
"Title": "pool of python coroutines"
} | 200754 |
<p>I have written an Angular Directive that disables a button after it has been clicked, to prevent double posting / saving of data. This works fine in most of our use cases. However, in some situation we want to re-enable the button. For example: the button-click triggers a form submit, but the server-side validation fails. We want to allow the user to submit again, so we need to re-enable the button.</p>
<p>My solution uses an <code>EventEmitter</code> that is owned by the 'host' Component. This <code>EventEmitter</code> is passed on to the button's Directive. This Directive then subscribes to it. Whenever the host wants to instruct the button to re-enable, is emits an event. The Directive will take care of enabling the button.</p>
<p>As an alternative, one could use the <code>disabled</code> property of the button to control its state. However, I would like to reserve that property for other logic that is part of the host Component (e.g. are all required fields correctly filled, etc.). I would like to keep the code for the double posting safeguard contained to the Directive as much as possible.</p>
<p>I'd like to learn if there might be a cleaner way to accomplish what I'm after. Here's what I do now:</p>
<h2>The button as used in the host Component template</h2>
<pre class="lang-html prettyprint-override"><code><button [appDisableAfterClick]="reenableButton"
(click)="doStuff()">My button</button>
</code></pre>
<h2>Inside the host Component</h2>
<pre><code>private reenableButton = new EventEmitter<boolean>();
doStuff() {
// Make some external call.
// In case of an error, re-enable the button:
this.reenableButton.emit();
}
</code></pre>
<h2>The <code>DisableAfterClick</code> Directive</h2>
<p><em>Several null checks and unsubscribe calls omitted for brevity.</em></p>
<pre><code>@Directive({
selector: '[appDisableAfterClick]'
})
export class DisableAfterClickDirective implements OnChanges, OnDestroy {
@Input('appDisableAfterClick') reenableButton: EventEmitter<boolean>;
ngOnChanges(changes: SimpleChanges) {
this.reenableButton = changes.reenableButton.currentValue;
this.reenableButton.subscribe(_ => {
(<HTMLButtonElement>this.el.nativeElement).disabled = false;
});
}
@HostListener('click')
onClick() {
(<HTMLButtonElement>this.el.nativeElement).disabled = true;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-27T13:23:50.673",
"Id": "390366",
"Score": "0",
"body": "Why exactly are you using a directive though? Is this a directive that will be used in several parts of your application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"Cre... | [
{
"body": "<p>One of the main ways in which you can improve this is by using <a href=\"https://angular.io/api/core/Renderer2\" rel=\"noreferrer\">Renderer2</a> in the directive instead of directly accessing <code>this.el.nativeElement</code> and making changes to it. This might work in most of the cases. But re... | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T14:51:29.337",
"Id": "200757",
"Score": "9",
"Tags": [
"event-handling",
"typescript",
"angular-2+"
],
"Title": "Angular directive to disable a button when clicked, allowing re-enabling as needed"
} | 200757 |
<p>This is legacy, so I'm not really looking for improvements on architectural approach.</p>
<p>Here's what the method does:</p>
<ol>
<li>Extracts filename from a string containing full file path (passed in as parameter)</li>
<li>Checks to see if the filename extracted is not null or empty or just white spaces</li>
<li><p>If check in step 2 passes, then it uses naming conventions in the filename, to determine the logical "Type" for the file as follows:</p>
<ol>
<li>If filename contains <code>__Import__</code>, then set<code>Type</code> to <code>Source Data</code></li>
<li>If filename contains <code>__Export__</code>, then set<code>Type</code> to <code>Destination Data</code></li>
<li>If filename contains <code>__Transform__</code>, then set<code>Type</code> to <code>Transformational Data</code></li>
<li>If none of the conditions from 3.1 through 3.3 are met, then default the "Type" to <code>General</code>.</li>
</ol></li>
</ol>
<p>Is there a way to make the <code>if...else if... else if...</code> block more concise, and elegant without loss of functionality?</p>
<pre><code>private static string GetFileDataType(string fullFileNameWithPath)
{
// extract filename only
var fileName = Path.GetFileNameWithoutExtension(fullFileNameWithPath);
var fileDataType = string.Empty;
// if filename is not empty
if (!string.IsNullOrWhiteSpace(fileName))
{
// if... else... to determine type of file contents based on file name convention
// legacy code, so not looking for architectural improvements etc... :)
if (fileName.Contains("__Import__"))
{
fileDataType = "Source Data";
}
else if (fileName.Contains("__Export__"))
{
fileDataType = "Destination Data";
}
else if (fileName.Contains("__Transform__"))
{
fileDataType = "Transformational Data";
}
else
{
fileDataType = "General";
}
}
return fileDataType;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T17:24:20.827",
"Id": "386629",
"Score": "1",
"body": "You need to explain what your code is doing first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T17:38:00.840",
"Id": "386631",
"Score":... | [
{
"body": "<p>You're searching through the file name for each type until you find one. If you use the <code>__</code> as delimiters and find the indexes of the string between them, you will only search the whole string once.</p>\n\n<p>By extracting the substring with the type, now you can use a <code>switch</c... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T17:09:04.743",
"Id": "200766",
"Score": "4",
"Tags": [
"c#",
"strings"
],
"Title": "Use filename to determine file type"
} | 200766 |
<p>I was doing a recursion problem called power set, and would like to get code review. Here's the problem. </p>
<blockquote>
<pre><code># Power Set: Given a set S, return the powerset P(S), which is
# a set of all subsets of S.
#
# Input: A String
# Output: An Array of String representing the power set of the input
#
# Example: S = "abc", P(S) = ['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
#
# Note: The input string will not contain duplicate characters
# The letters in the subset string must be in the same order
# as the original input.
</code></pre>
</blockquote>
<p>I also draw out an example of recursive tree in the following example:</p>
<pre><code># input: "abc"
# output: ["", "a", "b", "c", "ab", "ac", bc", "abc"]
2 * 2 * 2 = 8 total
_ _ _
# index
# a b c
# "",i=0
# / \
# "a",i=1 "", i= 1
# / \ / \
# "ab",i=2 "a",i=2 "b", i=2 "" i=2
# / \ / \ / \ / \
# "abc", i=3 "ab", i=3 "ac",i=3 "a", i=3 "bc", i=3 "b", i=3 "c", i=3 "", i = 3
# ret ret ret ret ret ret ret ret
# result = ["abc", "ab", "ac", "a", "bc", "b", "c", ""]
</code></pre>
<p>python solution</p>
<pre><code>def powerset(input):
results = []
def recurse(build, depth):
if (depth == len(input)):
results.append(build)
return
recurse(build, depth + 1)
recurse(build + input[depth], depth + 1)
recurse('', 0)
return results
</code></pre>
<p>The solution passes all of the tests.</p>
<pre><code># ###########################################################
# ############## DO NOT TOUCH TEST BELOW!!! ###############
# ###########################################################
from cStringIO import StringIO
import sys
# custom expect function to handle tests
# List count : keeps track out how many tests pass and how many total
# in the form of a two item array i.e., [0, 0]
# String name : describes the test
# Function test : performs a set of operations and returns a boolean
# indicating if test passed
def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
errMsg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception, err:
errMsg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if errMsg is not None:
print(' ' + errMsg + '\n')
# code for checking if lists contain the same elements
def lists_matching(lst1, lst2):
if len(lst1) != len(lst2):
return False
cache = {}
for i in xrange(0, len(lst1)):
if lst1[i] in cache:
cache[lst1[i]] += 1
else:
cache[lst1[i]] = 1
for j in xrange(0, len(lst2)):
if lst2[j] not in cache or cache[lst2[j]] == 0:
return False
cache[lst2[j]] -= 1
return True
print('Powerset Tests')
test_count = [0, 0]
def test():
example = powerset('abc')
return (example is not None and lists_matching(example,
['', 'a', 'b', 'c', 'ab', 'bc', 'ac', 'abc']))
expect(test_count, 'should work on example input abc', test)
def test():
example = powerset('')
return example is not None and lists_matching(example, [''])
expect(test_count, 'should work on empty input', test)
def test():
example = powerset('ab')
return (example is not None and
lists_matching(example, ['', 'a', 'b', 'ab']))
expect(test_count, 'should work on two-letter input', test)
def test():
example = powerset('abcdefg')
solution = ['', 'g', 'f', 'fg', 'e', 'eg', 'ef', 'efg', 'd', 'dg', 'df',
'dfg', 'de', 'deg', 'def', 'defg', 'c', 'cg', 'cf', 'cfg',
'ce', 'ceg', 'cef', 'cefg', 'cd', 'cdg', 'cdf', 'cdfg', 'cde',
'cdeg', 'cdef', 'cdefg', 'b', 'bg', 'bf', 'bfg', 'be', 'beg',
'bef', 'befg', 'bd', 'bdg', 'bdf', 'bdfg', 'bde', 'bdeg',
'bdef', 'bdefg', 'bc', 'bcg', 'bcf', 'bcfg', 'bce', 'bceg',
'bcef', 'bcefg', 'bcd', 'bcdg', 'bcdf', 'bcdfg', 'bcde',
'bcdeg', 'bcdef', 'bcdefg', 'a', 'ag', 'af', 'afg', 'ae',
'aeg', 'aef', 'aefg', 'ad', 'adg', 'adf', 'adfg', 'ade',
'adeg', 'adef', 'adefg', 'ac', 'acg', 'acf', 'acfg', 'ace',
'aceg', 'acef', 'acefg', 'acd', 'acdg', 'acdf', 'acdfg',
'acde', 'acdeg', 'acdef', 'acdefg', 'ab', 'abg', 'abf', 'abfg',
'abe', 'abeg', 'abef', 'abefg', 'abd', 'abdg', 'abdf', 'abdfg',
'abde', 'abdeg', 'abdef', 'abdefg', 'abc', 'abcg', 'abcf',
'abcfg', 'abce', 'abceg', 'abcef', 'abcefg', 'abcd', 'abcdg',
'abcdf', 'abcdfg', 'abcde', 'abcdeg', 'abcdef', 'abcdefg']
return example is not None and lists_matching(example, solution)
expect(test_count, 'should work on longer input', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
| [] | [
{
"body": "<ul>\n<li><code>input</code> is a library function. Use a different variable name.</li>\n<li>Python comes with the methods <a href=\"https://devdocs.io/python~2.7/library/itertools#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations</code></a>, which can generate all com... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T18:27:49.450",
"Id": "200769",
"Score": "4",
"Tags": [
"python",
"recursion",
"combinatorics"
],
"Title": "Recursive implementation of power set in Python"
} | 200769 |
<p>I have been working with some matrix functions and need the determinant. I have looked at several examples, but they all seem to use a hard coded size for the matrix, or calculate for a matrix of int, etc.</p>
<p>My data is stored in a <code>vector<vector<double>></code> and can be of any size. This is a typical square matrix of a matrix and its transpose MT*M.</p>
<p>This is my current code and is based in part on <a href="http://www.cplusplus.com/forum/general/183464/" rel="noreferrer">this post</a>.</p>
<pre><code>#include <vector>
#include <iostream>
#include <cstdlib>
// add namespace
using namespace std;
// declare, dynamically size, and return a 2D array of double as pointer to pointer
double** matrix_allocate_size(const unsigned int rows, const unsigned int columns) {
// declare a pointer to a 2 dimensiona array of double
// and allocate the number of rows
double **matrix = (double **) calloc( rows, sizeof(double) );
// allocate space for each column of each row
// using calloc here initalizes array elements to 0
for(unsigned int i=0; i<columns; i++) {
matrix[i] = (double *) calloc(columns, sizeof(double));
}
return matrix;
};
// calculate the determinant of a square matrix
// this function is called recursively
double matrix_determinant(unsigned int size, double **matrix) {
// 2D array version of cofactor matrix
// declare pointer to pointer and size by function call
double **matrix_copy = matrix_allocate_size(size, size);
// return value
double determinant = 0.0;
// sign for each product
double sign = 1.0;
// loop iterator
unsigned int position = 0;
// current location in array_matrix
unsigned int matrix_row = 0, matrix_column = 0;
// current location in matrix copy
unsigned int copy_row = 0, copy_column = 0;
// for matrix with one element
if(size == 1) { return (matrix[0][0]); }
// for a matrix with 4 elements, use the formula
// this is essentially length*width = area
else if(size == 2) { return ( (matrix[0][0]*matrix[1][1])-(matrix[1][0]*matrix[0][1]) ); }
// for a matrix with 9 or more elements
else {
// reinitialize local determinant value
determinant = 0.0;
// loop on size of current array_matrix
for(position=0; position<size; position++) {
// zero out current matrix position
copy_row = 0; copy_column = 0;
// create determinant products by skipping each row and column in sequence
// iterate through array_matrix up to size,size
// size decrements on each recursive call
for(matrix_row=0; matrix_row<size; matrix_row++) {
for(matrix_column=0; matrix_column<size; matrix_column++) {
// skip current row and column when making copy
if(matrix_row != 0 && matrix_column != position) {
// copy matrix elements not part of current row and column
matrix_copy[copy_row][copy_column] = matrix[matrix_row][matrix_column];
// increment column location in matrix copy up to size-2
if( copy_column<(size-2) ) { copy_column++; }
// move to next row in matrix copy, reset column number to 0
else { copy_column=0; copy_row++; }
}
}
}
// calculate current element of determinant and add to sum
// pass matrix copy in all subsequent recursive calls
determinant += sign * ( matrix[0][position] * matrix_determinant(size-1, matrix_copy) );
// reverse sign for next iteration
sign = -1 * sign;
} // for(position=0; position<size; position++) endbrace
} // else endbrace
return (determinant);
};
// re-cast data from vector<vector<double>> to 2D array
// creates a matrix as a 2D array ot pointer to pointer
// populates the matrix, and passed it to a function to calculate the determinant
// returns the calculated determinant
double matrix_determinant_caller(const vector< vector<double> >& M1) {
// return value
double M1_determinant = 0.0;
// store size of passed vector<vector<double>> matrix
unsigned int M1_dimension = M1.size();
// call function to size array version of matrix[rows][columns]
// this is a square matrix, so use the same dimension for rows and columns
double **array_matrix = matrix_allocate_size(M1_dimension, M1_dimension);
// copy M1 to a_matrix
for(unsigned int i=0; i<M1_dimension; i++) {
for(unsigned int j=0; j<M1[0].size(); j++) { array_matrix[i][j] = M1[i][j]; }
}
// call function to get determinant
M1_determinant = matrix_determinant(M1_dimension, array_matrix);
return M1_determinant;
};
// program entry point
int main() {
// vector version of matrix
vector< vector<double> > matrix_vector_version;
// number of matrix rows and matrix columns
unsigned int num_rows = 4, num_columns = 4;
// temp matrix row for insert
vector<double> temp_row;
// size temp row vector
temp_row.resize(num_columns);
// add rows and columns to matrix
for(unsigned int i=0; i<num_rows; i++) { matrix_vector_version.push_back(temp_row); }
// add test data to matrix row 0
matrix_vector_version[0][0] = 1248.14;
matrix_vector_version[0][1] = 1408.68;
matrix_vector_version[0][2] = -828.282;
matrix_vector_version[0][3] = -53.0927;
// add test data to matrix row 1
matrix_vector_version[1][0] = 1408.68 ;
matrix_vector_version[1][1] = 1623.81;
matrix_vector_version[1][2] = -952.41;
matrix_vector_version[1][3] = -67.2946 ;
// add test data to matrix row 2
matrix_vector_version[2][0] = -828.282;
matrix_vector_version[2][1] = -952.41;
matrix_vector_version[2][2] = 559.421;
matrix_vector_version[2][3] = 38.0384;
// add test data to matrix row 3
matrix_vector_version[3][0] = -53.0927;
matrix_vector_version[3][1] = -67.2946;
matrix_vector_version[3][2] = 38.0384;
matrix_vector_version[3][3] = 5.46328;
// call function to calculate determinant
double determinant = matrix_determinant_caller(matrix_vector_version);
// print determinant
// should be 44.1164 for this data
cout << "determinant: " << determinant << endl;
cout << endl;
return 0;
} // main EOF brace
</code></pre>
<p>This code compiles and runs and gives the correct value for the determinant of 44.1164 which is confirmed by an online calculator.</p>
<p>It would be nice to have some input on ways to improve the code. In particular, I think there is no exception handling to speak of and I am sure that performance and stability can be improved. The test matrix here is a 4x4 but I will need to use this on matrices that are at least 50x50. I guess in that case I might want to use a long double for the return value.</p>
<p>Current run time for this data is,</p>
<pre><code>real 0m0.000s
user 0m0.030s
sys 0m0.000s
</code></pre>
<p>I can post a more realistic version of the data, or a version that reads an input file if that would be helpful.</p>
<p>This is more or less written in c++98. I don't object to more recent versions, but at times I work on c and c++ that is married to very old F77 code and I can't always get the newer gfortran compiler versions to be happy with my very old fortran code. I generally have good luck if I stick with c++98 standards and older c++ compilers.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T05:40:54.733",
"Id": "386688",
"Score": "0",
"body": "Shouldn't your first `calloc()` call in `matrix_allocate_size()` use `sizeof (double*)` rather than `sizeof(double)`? They may be the same on your platform, so it may work, but i... | [
{
"body": "<h1>Are you sure you need to do this?</h1>\n\n<p>Be aware that determinants for any reasonable sized matrix are very expensive to calculate, so if you're actually doing something else (linear solve, eigen-solve etc) there is probably a better way without calculating the determinant. And there are man... | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T19:28:43.747",
"Id": "200774",
"Score": "5",
"Tags": [
"c++",
"matrix",
"c++98"
],
"Title": "Determinant of a matrix of doubles"
} | 200774 |
<p>I had to do a CLI script that does something, I also had to add a validation that checks if it runs inside the Docker. After some research I found a solution that people check some processes via <code>cat /proc/self/cgroup</code> and then <code>grep</code> to search for a <code>docker</code> phrase within.</p>
<p>So I ended-up with this method. It works pretty well. Inside docker it returns <code>true</code>, while on my local mac it returns <code>false</code>.</p>
<p>It's not rocket science however I would like people to take a look and tell me if this is a sufficient method or a completely different approach is better.</p>
<pre><code>private function isDocker(): bool
{
$processStack = explode(PHP_EOL, shell_exec('cat /proc/self/cgroup'));
$processStack = array_filter($processStack); // remove empty item made by EOL
foreach ($processStack as $process) {
if (strpos($process, 'docker') === false) {
return false;
}
}
return true;
}
</code></pre>
<p>Later call to this script looks like:</p>
<pre><code>if ($this->isDocker() === false) {
throw new \Exception('This helper script can be called only inside Docker container.' . "\n");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:28:08.320",
"Id": "415527",
"Score": "0",
"body": "Hey Matt- would you be willing to let me know if my answer is useful? this question is technically still [unanswered](https://stackoverflow.blog/2008/09/30/ok-now-define-answered... | [
{
"body": "<p>For this simple method, I have a couple thoughts below. Your method seems sufficient; I don't think a completely different approach is necessary, although I question how often this method is called. If it is called more than once per page load/script run, it may be worth memoizing the value once o... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T22:31:17.097",
"Id": "200779",
"Score": "3",
"Tags": [
"php",
"strings",
"docker"
],
"Title": "Bool function in PHP to check if you run the script inside docker"
} | 200779 |
<p>I'm new to Python but I've coded in other languages mainly for hardware. I made Pong in Python using turtle but it's a little glitchy. I was wondering if any of you guys could check it out and give advice. If you have any advice on how to improve collision detection let me know please.</p>
<pre><code>import os
import math
import random
import time
import turtle
#set up screen
screen = turtle.Screen()
screen.bgcolor("green")
screen.title("Pong")
# set up border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
#set score to 0
score = 0
#set time to zero
time = 0
seconds = 0
#Draw score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 310)
scorestring = "Score %s" %score
score_pen.write(scorestring, False, align="left", font= ("Arial", 14, "normal"))
score_pen.hideturtle()
#Draw timer
time_pen = turtle.Turtle()
time_pen.speed(0)
time_pen.color("white")
time_pen.penup()
time_pen.setposition(260, 310)
timestring = "Time %s" %time
time_pen.write(timestring, False, align="left", font= ("Arial", 14, "normal"))
time_pen.hideturtle()
#create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("square")
player.shapesize(0.5, 4)
player.penup()
player.speed(0)
player.setposition(-280,-250)#(x,y)
player.setheading(90)
playerspeed = 15
#create the AIplayer turtle
AIplayer = turtle.Turtle()
AIplayer.color("black")
AIplayer.shape("square")
AIplayer.shapesize(0.5, 4)
AIplayer.penup()
AIplayer.speed(0)
AIplayer.setposition(280,250)#(x,y)
AIplayer.setheading(90)
AIplayerspeed = 15
#create the pong
pong = turtle.Turtle()
pong.color("red")
pong.shape("circle")
pong.shapesize(0.5, 0.5)
pong.penup()
pong.speed(10)
pong.setposition(0,0)#(x,y)
pongspeed = 15
pong.goto(0, 265)
pong.dy = -5
pong.dx = 5
#Move player up and down
def move_up():
y = player.ycor()
y += playerspeed
if y > 265:
y = 260
player.sety(y)
def move_down():
y = player.ycor()
y -= playerspeed
if y < -265:
y = -260
player.sety(y)
#keyboard bindings
turtle.listen()
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
#turtle.onkey(fire_bullet, "space")
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()- t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 20:
return True
else:
return False
#main game loop
while True:
#move pong ball
pong.sety(pong.ycor() +pong.dy)
pong.setx(pong.xcor() +pong.dx)
#check for bounce and redirect it
if pong.ycor() < -300:
pong.dy *= -1
if pong.ycor() > 300:
pong.dy *= -1
if pong.xcor() < -300:
pong.dx *= -1
print("Game Over")
exit()
if pong.xcor() > 300:
pong.dx *= -1
#move AI paddle (might speed up pong movement)
y = pong.ycor()
y += AIplayerspeed
AIplayer.sety(y)
if AIplayer.ycor() > 265:
AIplayerspeed *= -1
if AIplayer.ycor() < -250:
AIplayerspeed *= -1
#collision pong and player
if isCollision(pong, player):
pong.dy *= -1
pong.dx *= -1
#Update the score
score += 10
scorestring = "Score: %s" %score
score_pen.clear()
score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
#collision pong and AIplayer
if isCollision(pong, AIplayer):
pong.dy *= -1
pong.dx *= -1
#updates timer and increases ball speed
if seconds > 29:
pong.dy *= -2
pong.dx *= -2
if seconds > 59:
pong.dy *= -3
pong.dx *= -3
#displays timer but makes game laggy
# seconds += 0.1
# time = seconds
# timestring = "Time: %s" %time
# time_pen.clear()
# time_pen.write(timestring, False, align="Left", font=("Arial", 14, "normal"))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T02:33:43.167",
"Id": "386675",
"Score": "0",
"body": "As-is, your code doesn't execute (Python 3.7). Could you try again and update the code? Are you missing a class or an import?"
},
{
"ContentLicense": "CC BY-SA 4.0",
... | [
{
"body": "<p>Okay, thanks for fixing up the code. Now, to make it more pythonic, we need to move all the statements (not functions) into the entry point, which is a </p>\n\n<pre><code>if __name__ == \"__main__\":\n # set up screen\n screen = turtle.Screen()\n screen.bgcolor(\"green\")\n screen.titl... | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-01T23:25:10.337",
"Id": "200782",
"Score": "4",
"Tags": [
"python",
"beginner",
"game",
"collision",
"turtle-graphics"
],
"Title": "Python Turtle based Pong game"
} | 200782 |
<p>I completed <a href="https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace/" rel="nofollow noreferrer">this challenge <em>Search and Replace</em></a> and passed the tests:</p>
<blockquote>
<p>Perform a search and replace on the sentence using the arguments provided and return the new sentence.</p>
<p>First argument is the sentence to perform the search and replace on.</p>
<p>Second argument is the word that you will be replacing (before).</p>
<p>Third argument is what you will be replacing the second argument with (after).</p>
<h3>Note</h3>
<p>Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".</p>
<h3>Example</h3>
<p><code>myReplace("Let us go to the store", "store", "mall")</code> should return <code>"Let us go to the mall"</code>.</p>
</blockquote>
<p>I was hoping to simplify my code. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myReplace(str, before, after) {
let newStr = str.split(' ');
for (var a=0; a < str.length; a++) {
if(before === newStr[a]) {
str = str.replace(before, after);
}
if (before[0] === before[0].toUpperCase()) {
var swap = after[0].toUpperCase() + after.slice(1);
str = str.replace(before, swap)
}
}
return str;
}
console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-01T00:56:08.333",
"Id": "403375",
"Score": "1",
"body": "How is \"cleaner\" defined and \"faster\" measured?"
}
] | [
{
"body": "<p>This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...</p>\n\n<p>Pass a function as second argument of <code>string.replace()</code> and it will call that function for... | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T04:08:38.920",
"Id": "200787",
"Score": "7",
"Tags": [
"javascript",
"performance",
"programming-challenge",
"strings",
"iteration"
],
"Title": "Search and Replace (FreeCodeCamp intermediate algorithm scripting)"
} | 200787 |
<p>I've been roughing out a proof of concept enabling admin staff to flag submitted applications with issues as needed. We have many forms some of which are nested. So we end up with these big hashes to validate. Primarily we have issues with uploaded images (too blurry, too dark etc) but it could be any field.</p>
<p>So admin may see a field <code>verified_documents -> drivers_licence -> front_image</code>. If an issue is raised we end up with a hash to store.</p>
<pre><code>{
verified_documents: {
drivers_licence: {
front_image: ['Image is too blurry', 'Image is too dark']
}
}
}
</code></pre>
<p>The code works but is very smelly. The function in question is <code>updateIssue</code>. Which accepts a string representation of the path <code>"verified_documents.drivers_licence.front_image"</code> and an array of selected options from a dropdown.</p>
<p><strong>The function's intentions:</strong></p>
<ol>
<li>Take a copy of current issues, an attempt to be pure and return a new object.</li>
<li>Split the string into an array.</li>
<li>Iterate over each value in the path array.</li>
<li>If path length is the last set its value to the array of issues.</li>
<li>If the value is an empty array set the value to undefined (only happens if an issue is removed).</li>
<li>If the key can't be found, create the next level as a child hash.</li>
<li>Returning the next level of nested object if no other condition is met.</li>
</ol>
<p>I'm happy I was able to get it all working, but now it's not readable. Readability over performance is my objective, as this code is likely to change. </p>
<pre><code>import { merge, isEmpty } from "lodash";
let Issues = undefined;
const getNestedValue = (nestedObj, pathArr) => {
return pathArr.reduce(
(obj, key) => (obj && obj[key] !== "undefined" ? obj[key] : undefined),
nestedObj
);
};
export class IssuesData {
static updateIssue = (path, value) => {
const valueObj = merge({}, Issues);
const pathArr = path.split(".");
pathArr.reduce((obj, key, i) => {
if (pathArr.length - 1 === i) {
if (isEmpty(value)) {
return (obj[key] = undefined);
}
return (obj[key] = value);
}
if (obj[key] === undefined) {
return (obj[key] = {});
}
return obj[key];
}, valueObj);
Issues = valueObj;
};
static getIssueByKey = path => {
return getNestedValue(Issues, path.split("."));
};
static getIssues() {
return Issues;
}
static setIssues(issues) {
if (!Issues) {
Issues = issues;
}
}
}
</code></pre>
<hr>
<h3>UPDATE:</h3>
<p>After sleeping on it I managed to clean it up a little. This is more readable but there are still multiple return. If anyone has advice on cleaning it up further it'll be welcomed. I think I'll turn my attention to converting the static methods to instance methods now. </p>
<pre><code> static updateIssue = (path, value) => {
const valueObj = merge({}, Issues);
const pathArray = path.split(".");
pathArray.reduce((obj, key, i) => {
if (isLast(pathArray, i)) {
if (isEmpty(value)) {
return delete obj[key];
}
return (obj[key] = value);
}
return obj[key];
}, valueObj);
Issues = valueObj;
};
</code></pre>
| [] | [
{
"body": "<p>Since you are already using lodash, don't reinvent the wheel! Nearly all of your code can be replaced by a single <code>_.set</code> call.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class... | {
"AcceptedAnswerId": "203519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T07:01:55.373",
"Id": "200791",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "JavaScript reducer that updates a deep value in a hash"
} | 200791 |
<p>I'm clearing all the controls on a windows form with the following</p>
<pre><code>form.Controls.Cast<dynamic>().ToList().ForEach(c =>
{
switch (c)
{
case CheckBox t when c is CheckBox:
c.Checked = false;
break;
case System.Windows.Forms.ComboBox t when c is System.Windows.Forms.ComboBox:
c.Items.Clear();
break;
case CheckEdit t when c is CheckEdit:
c.Checked = false;
break;
default:
c.Text = "";
break;
}
});
</code></pre>
<p>I have to use <code>dynamic</code> because if I dont, I wont get the options for <code>Checked</code> and I also wont be able to clear any <code>items</code> in a combobox or list for that matter.<br><br> Is there a neater way of achieving this? I'm using c# 7.3 which allows me to use the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch" rel="noreferrer">when</a> keyword, I wasn't able to find how to do this with anything under 7.0, If there is something for under 7.0, what would it be?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T10:33:08.163",
"Id": "386716",
"Score": "0",
"body": "Why are you seeking a way how to do it in C# 7.0 if you can use the latest 7.3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T10:34:01.880",
... | [
{
"body": "<p>I think you're rather over-complicated this for yourself! A much better solution is to use the pattern matched results (which you are already creating (<code>t</code>)) (this requires C# 7.0 still, I believe).</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (Control c in form.... | {
"AcceptedAnswerId": "200794",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T07:59:16.567",
"Id": "200793",
"Score": "11",
"Tags": [
"c#",
"winforms"
],
"Title": "Clearing all controls"
} | 200793 |
<p>I have this regex:</p>
<pre><code>(\d?)[A-Za-z](?=(\d?)(.*))(?=(.* ){5})
</code></pre>
<p>It would be used by me for Chess <a href="https://de.wikipedia.org/wiki/Forsyth-Edwards-Notation" rel="nofollow noreferrer">FEN</a> strings.</p>
<p>I wonder if regex <code>[A-Za-z]</code> is faster than <code>[RNBQKrnbqk]</code>? I only need to check the given letters (but no other letters will appear).</p>
<p>My thoughts are:</p>
<ol>
<li><p><code>[A-Za-z]</code> - the regex engine can match if a char is <code>65 <= c <= 90</code> or <code>97 <= c <= 122</code>. Worst case is 4 comparisons.</p></li>
<li><p><code>[RNBQKrnbqk]</code> - the engine checks if the inspected char equals every given character in the group. Worst case is 10 comparisons.</p></li>
</ol>
<p>Am I understanding regex correctly?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T09:25:36.373",
"Id": "386711",
"Score": "5",
"body": "It's impossible to say, because It would depend on the implementation details of the regex engine. In any case, it's unlikely that this is something you would need to worry about... | [
{
"body": "<p>No. The matching for <code>a-zA-Z</code> would be slower than the exact character-set you supply: <code>RNBQKrnbqk</code>.</p>\n\n<p>You can observe this behaviour by checking the backtrace it generates. I compared 3 different patterns, two being your own, and the third I found on <a href=\"https:... | {
"AcceptedAnswerId": "200798",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T09:11:25.493",
"Id": "200796",
"Score": "2",
"Tags": [
"java",
"performance",
"regex"
],
"Title": "Java Regex for Chess notations"
} | 200796 |
<p>I wrote a library and two related scripts to wrap <code>notify-send</code> from <code>libnotify</code>.
I need this script, since I am remotely administering workstations and wanted to automate desktop messages.
Since <code>notify-send</code> needs a DBUS session address configured in the environment variables and to be run within the context of the user the notification is sent to, I chose an implementation in python 3.6, since a previous shellscript became too complex and unstable.</p>
<p>So <a href="https://gitlab.com/coNQP/notify-users" rel="nofollow noreferrer">here</a> is what I came up with:</p>
<pre><code># usernotify - Wrapper library for notify-send.
# Copyright (C) 2018 Richard Neumann
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""A notify-send wrapping library."""
from configparser import Error, ConfigParser
from logging import basicConfig, getLogger
from os import setuid, fork, wait, _exit, environ
from pathlib import Path
from pwd import getpwnam
from subprocess import call
__all__ = ['MIN_UID', 'MAX_UID', 'send', 'broadcast', 'Args']
_LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
basicConfig(format=_LOG_FORMAT)
_LOGGER = getLogger(__file__)
_DBUS_ENV_VAR = 'DBUS_SESSION_BUS_ADDRESS'
_DEFAULT_CONFIG = {
'MIN_UID': 1000,
'MAX_UID': 60000,
'NOTIFY_SEND': '/usr/bin/notify-send',
'RUN_USER': '/run/user'}
_SECTION_NAME = 'UserNotify'
# Load global configurations.
_CONFIG = ConfigParser()
_CONFIG.setdefault(_SECTION_NAME, _DEFAULT_CONFIG)
_CONFIG_PATH = Path('/etc/usernotify.conf')
try:
_CONFIG.read(_CONFIG_PATH)
except Error as error:
_LOGGER.warning(error)
# Load user-dependent configuration.
_USER_CONFIG = ConfigParser()
_USER_CONFIG_PATH = Path.home().joinpath('.usernotify.conf')
try:
_USER_CONFIG.read(_USER_CONFIG_PATH)
except Error as error:
_LOGGER.warning(error)
_CONFIG.update(_USER_CONFIG)
_SECTION = _CONFIG[_SECTION_NAME]
# Read configuration values.
MIN_UID = int(_SECTION['MIN_UID'])
MAX_UID = int(_SECTION['MAX_UID'])
_NOTIFY_SEND = _SECTION['NOTIFY_SEND']
_RUN_USER = Path(_SECTION['RUN_USER'])
_DBUS_BUS_DIR = '{}/bus'
_DBUS_PATH = _RUN_USER.joinpath(_DBUS_BUS_DIR)
_DBUS_BUS_GLOB = _DBUS_BUS_DIR.format('*')
_DBUS_ENV_PATH = f'unix:path={_DBUS_PATH}'
_UIDS = range(MIN_UID, MAX_UID + 1)
def _getuid(user):
"""Gets the UID for the respective user."""
try:
return int(user)
except ValueError:
return getpwnam(user).pw_uid
def send(user, args):
"""Sends a notification to the respective user."""
uid = _getuid(user)
env = {_DBUS_ENV_VAR: _DBUS_ENV_PATH.format(uid)}
command = (_NOTIFY_SEND,) + tuple(args)
if fork() == 0:
setuid(uid)
with _Env(env):
exit_code = call(command)
_exit(exit_code)
_, returncode = wait()
return returncode
def broadcast(args, uids=_UIDS):
"""Seds the respective message to all
users with an active DBUS session.
"""
returncode = 0
for path in _RUN_USER.glob(_DBUS_BUS_GLOB):
uid = int(path.parent.name)
if uid in uids:
returncode += send(uid, args)
return returncode
class _Env:
"""Context manager to temporarily substitute environment variables."""
__slots__ = ('env', 'substituted')
def __init__(self, env):
"""Sets the dict of evironment variables to substitute."""
self.env = env
self.substituted = {}
def __enter__(self):
"""Substitutes the evironment variables."""
for key in self.env:
self.substituted[key] = environ.get(key)
environ.update(self.env)
return self
def __exit__(self, *_):
"""Restores the substituted environment variables."""
for key, value in self.substituted.items():
if value is None:
del environ[key]
else:
environ[key] = value
self.substituted.clear()
class Args:
"""Arguments for nofiy-send."""
__slots__ = (
'summary', 'body', 'urgency', 'expire_time', 'app_name', 'icon',
'category', 'hint', 'version')
def __init__(self, summary, body=None, urgency=None, expire_time=None,
app_name=None, icon=None, category=None, hint=None,
version=None):
"""Initailizes the arguments."""
self.summary = summary
self.body = body
self.urgency = urgency
self.expire_time = expire_time
self.app_name = app_name
self.icon = icon
self.category = category
self.hint = hint
self.version = version
@classmethod
def from_options(cls, options):
"""Creates arguments from the respective docopt options."""
return cls(
options['<summary>'],
body=options['<body>'],
urgency=options['--urgency'],
expire_time=options['--expire-time'],
app_name=options['--app-name'],
icon=options['--icon'],
category=options['--category'],
hint=options['--hint'],
version=options['--version'])
def __iter__(self):
"""Yields the command line arguments for notify-send."""
if self.urgency is not None:
yield '--urgency'
yield self.urgency
if self.expire_time is not None:
yield '--expire-time'
yield self.expire_time
if self.app_name is not None:
yield '--app-name'
yield self.app_name
if self.icon is not None:
yield '--icon'
yield self.icon
if self.category is not None:
yield '--category'
yield self.category
if self.hint is not None:
yield '--hint'
yield self.hint
if self.version: # Bool.
yield '--version'
yield self.summary
if self.body is not None:
yield self.body
</code></pre>
<p>While the library is working perfectly fine, I'd prefer a more elegant way to <em>temporarily</em> substitute the user context instead of doing a fork (or worse using <code>su</code> in the subprocess).</p>
| [] | [
{
"body": "<p>Since you are using Python >= 3.5, you sould use <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"nofollow noreferrer\"><code>subprocess.run</code></a> that superseeds the <a href=\"https://docs.python.org/3/library/subprocess.html#call-function-trio\" rel=\"nofol... | {
"AcceptedAnswerId": "200808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T09:57:31.250",
"Id": "200800",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Library to wrap notify-send"
} | 200800 |
<p>Interrogating a web API using query-url's, for each query I can get either zero hits, one hit, or multiple hits. Each of those categories needs to go into a separate CSV file for manual review or processing later. (More on this project <a href="https://codereview.stackexchange.com/q/200209/39869">here</a> and <a href="https://codereview.stackexchange.com/q/200176/39869">here</a>). </p>
<p>The input data (from a 14K line csv, one line per artist) is full of holes. Only a name is always given, but may be misspelled or in a form that the API does not recognise. Birth dates, death dates may or may not be known, with a precision like for example 'not before may 1533, not after january 1534'. It may also have exact dates in ISO format. </p>
<p>Using those three different output csv's, the user may go back to their source, try to refine their data, and run the script again to get a better match. Exactly one hit is what we go for: a persistent identifier for this specific artist. </p>
<p>In the code below, <code>df</code> is a Pandas dataframe that has all the information in a form that is easiest to interrogate the API with. </p>
<p>First, I try to get an exact match <code>best_q</code> (exact match of name string + any of the available input fields elsewhere in the record), if that yields zero, I try a slightly more loose match <code>bracket_q</code> (any of the words in the literal name string + any of the available input fields elsewhere in the record). </p>
<p>I output the dataframe as a separate csv, and each list of zero hits, single hits, or multiple hits also in a separate csv. </p>
<p>I'm seeking advice on two specific things. </p>
<ol>
<li><p>Is there a more Pythonic way of handling the lists? Right now, I think the code is readable enough, but I have one line to generate the lists, another to put them in a list of lists, and another to put them in a list of listnames. </p></li>
<li><p>The second thing is the nested <code>if..elif</code> on zero hits for the first query. I know it ain't pretty, but it's still quite readable (to me), and I don't see how I could do that any other way. That is: I <em>have</em> to try <code>best q</code> first, and <em>only</em> if it yields zero, try again with <code>bracket_q</code>. </p></li>
</ol>
<p>I have omitted what goes before. It works, it's been reviewed, I'm happy with it. </p>
<p>A final note: I'm not very concerned about performance, because the API is the bottleneck. I <em>am</em> concerned about readability. Users may want to tweak the script, somewhere down the line. </p>
<pre><code>singles, multiples, zeroes = ([] for i in range(3))
for row in df.itertuples():
query = best_q(row)
hits, uri = ask_rkd(query)
if hits == 1:
singles.append([row.priref, row.name, hits, uri])
elif hits > 1:
multiples.append([row.priref, row.name, hits])
elif hits == 0:
query = bracket_q(row)
hits, uri = ask_rkd(query)
if hits == 1:
singles.append([row.priref, row.name, hits, uri])
elif hits > 1:
multiples.append([row.priref, row.name, hits])
elif hits == 0:
zeroes.append([row.priref, str(row.name)]) # PM: str!!
lists = singles, multiples, zeroes
listnames = ['singles','multiples','zeroes']
for s, l in zip(listnames, lists):
listfile = '{}_{}.csv'.format(input_fname, s)
writelist(list=l, fname=listfile)
outfile = fname + '_out' + ext
df.to_csv(outfile, sep='|', encoding='utf-8-sig')
</code></pre>
| [] | [
{
"body": "<p>As you already noticed you have repeated code. you have variable names for your lists and also string definitions for list names which most probably should match. while this is no big problem for just 3 lists it could get cumbersome on adding another list. A simple way to avoid such name-to-string... | {
"AcceptedAnswerId": "200804",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T10:31:08.247",
"Id": "200802",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"csv",
"pandas"
],
"Title": "Iterate over a list of list names as file names"
} | 200802 |
<p>I'm writing a C# extension-method that converts any object to a type. E.g. the method shall convert a string with value <code>"y"</code> to a <code>true</code>-boolean - so there will be some specific castings like bools, chars, DateTimes,...</p>
<p>Here are some examples of my target:</p>
<pre><code>int number = 3;
string stringNumber = number.To<string>();
</code></pre>
<p><code>stringNumber</code> now should be a string with value equals to "3". (Yeah, there's already the <code>ToString()</code>, it's just an example)
another one:</p>
<pre><code>string myDateString = "Mon, 27 Jun 2007 12:34:56 CET";
DateTime myDate = myDateString.To<DateTime>();
</code></pre>
<p><code>myDate</code> now should be a <code>DateTime</code>-object with value equals to a Date on 27th June of 2007 on time 12:34:56.</p>
<p>So, what I did is, I wrote following method:</p>
<pre><code>public static T To<T>(this object @this)
{
CastTo castedValue = null;
if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
{
DateTime? result = null;
if (@this is string actualStringValue)
result = _tryCastStringToDateTime(actualStringValue);
if (result != null)
castedValue = new CastTo<DateTime> {Value = result.Value};
}
else if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
{
bool? result = null;
if (@this is string actualStringValue)
result = _tryCastStringToBoolean(actualStringValue);
else if (@this is int actualIntegerValue)
result = _tryCastIntegerToBoolean(actualIntegerValue);
if (result != null)
castedValue = new CastTo<bool> {Value = result.Value};
}
if (castedValue == null || castedValue.IsInitial)
return (T) Convert.ChangeType(@this, typeof(T));
return ((CastTo<T>) castedValue).Value;
}
</code></pre>
<p>those <code>_tryCast....</code>-methods simply cast an object to the specific type.</p>
<p>Here are my classes <code>CastTo</code> and <code>CastTo<T></code>. </p>
<pre><code>internal abstract class CastTo
{
public abstract bool IsInitial { get; }
public object Value { get; set; }
}
internal class CastTo<T> : CastTo
{
private T _value;
public override bool IsInitial => EqualityComparer<T>.Default.Equals(Value, default(T));
public new T Value
{
get => _value;
set
{
if (!EqualityComparer<T>.Default.Equals(value, default(T)))
_value = value;
}
}
}
</code></pre>
<p>Are there any issues you'd suggest me to change? </p>
<ul>
<li>Code-Style?</li>
<li>Performance?</li>
<li>Bad Practice?</li>
<li>Someone said, this is a misuse of generics. Is it really?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T11:33:06.380",
"Id": "386725",
"Score": "0",
"body": "What is the use-case for this? It's possible that a better solution exists at a slightly higher level; this task as presented is inherently dodgy (but not a misuse of generics as... | [
{
"body": "<p>This design looks to me like a massive violation of <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">KISS</a>. For a start, I don't see the benefit of <code>CastTo</code> and <code>CastTo<T></code>. It seems to me that they could be eliminated by tweaking the wrapp... | {
"AcceptedAnswerId": "200818",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T11:05:07.657",
"Id": "200805",
"Score": "3",
"Tags": [
"c#",
"extension-methods",
"casting"
],
"Title": "Writing a generic casting extension-method"
} | 200805 |
<p>I have the following Data.json file and I would like to update some of the values. </p>
<pre><code>{
"A0_Water":"-306.3",
"A1_Water":"0.0",
"A2_Water":"0.0",
"A3_Water":"0.0",
"Barometer":"100.8",
"Bar_Offset":"0",
"Temp":"29.95",
"ip":"192.168.2.47",
"serial":"02:42:52:bf:82:27",
"A0_Sensor":"PS30A",
"A1_Sensor":"None",
"A2_Sensor":"None",
"A3_Sensor":"None",
"A0_Offset":"0",
"A1_Offset":"0",
"A2_Offset":"0",
"A3_Offset":"0"
}
</code></pre>
<p>I am new to coding so any help will be much appriciated.
This is the code that I have working: The var data object that I created contains the entries that I want to update in the Data.json file but I was not sure how to use it. The remainder of the code is what I was able to get working but I am sure there is a better way to update the entries in the Data.json file</p>
<pre><code>var data = {
'A0_Water': c_inh2o_A0,
'A1_Water': c_inh2o_A1,
'A2_Water': c_inh2o_A2,
'A3_Water': c_inh2o_A3,
'Barometer': b_mbar_corrected,
'Temp': b_temp
};
var fileName = '/home/admin/reactwatertracker/src/var/Data.json';
var file4 = require(fileName);
var file5 = file4;
var file6 = file4;
var file7 = file4;
var file8 = file4;
var file9 = file4;
file4['A0_Water'] = c_inh2o_A0;
file5['A1_Water'] = c_inh2o_A1;
file6['A2_Water'] = c_inh2o_A2;
file7['A3_Water'] = c_inh2o_A3;
file8['Temp'] = b_temp;
file9['Barometer'] = b_mbar_corrected;
console.log('Writing to' + fileName);
fs.writeFile(fileName, JSON.stringify(file4,file5,file6,file7,file8,file9, null, 2), function (err) {
if (err) return console.log(err);
console.log (JSON.stringify(file4));
});
</code></pre>
| [] | [
{
"body": "<pre><code>const fs = require('fs');\n// Read data from JSON file and parse it as a JSON object\nconst dataFromFile = JSON.parse(fs.readFileSync('./Data.json', 'utf8'));\n\nconst data = {\n 'A0_Water': 'c_inh2o_A0',\n 'A1_Water': 'c_inh2o_A1',\n 'A2_Water': 'c_inh2o_A2',\n 'A3_Water': 'c_inh2o_A3... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T12:10:41.200",
"Id": "200806",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"node.js",
"json"
],
"Title": "Updating entries in a JSON file"
} | 200806 |
<p>supposed I have an XML like</p>
<pre><code><root>
<topic>
<name>foo</name>
</topic>
<subject>
<name>foo</name>
</subject>
<subject>
<name>bar</name>
</subject>
</root>
</code></pre>
<p>I want to add attributes to all <code><name></code> tags if they are children of a <code><subject></code>, bot not if they are children of a <code><topic></code>.
My current approach is:</p>
<pre><code>// Select all names which are childs of a subject
val names: Seq[Node] = (xml \\ "subject" \\ "name").theSeq
private class AddAttributes(foo: Seq[Node]) extends RewriteRule {
override def transform(n: Node): Seq[Node] = {
n match {
case elem: Elem if foo.contains(elem) => elem.copy(attributes = new UnprefixedAttribute("role", "nrol:full", Null))
case other => other
}
}
}
new RuleTransformer(new AddAttributes(names))(prepXml)
</code></pre>
<p>While this works, I wonder if there is a more "scalatic" way of doing this?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T13:26:32.860",
"Id": "200812",
"Score": "1",
"Tags": [
"scala",
"xml"
],
"Title": "Add an attribute to specific XML Elements in Scala"
} | 200812 |
<p>I want to detect <code>$number</code> substring in <code>std::string</code> and then replace it with <code>$number + 1</code>.</p>
<p>For example, the string <code>Hello$9World$1</code> should become <code>Hello$10World$2</code>.</p>
<p>Here's my code:</p>
<pre><code>#include <iostream>
#include <string>
void modifyDollarNumber(std::string &str)
{
for (size_t i = str.length(); i --> 0 ;)
{
if (str[i] == '$')
{
size_t j = i + 1;
while (j < str.length() && isdigit(str[j]))
{
++j;
}
size_t len = j - (i + 1);
if (len)
{
std::string sub = str.substr(i + 1, len);
int num = std::stoi(sub) + 1;
str.erase(i + 1, len);
sub = std::to_string(num);
str.insert(i + 1, sub);
}
}
}
}
int main()
{
std::string str = "!$@#$34$1%^&$5*$1$!%$91$12@$3";
modifyDollarNumber(str);
std::cout << "Result : " << str << '\n';
}
</code></pre>
<p>And I can get the result I want which is</p>
<pre><code>Result : !$@#$35$2%^&$6*$2$!%$92$13@$4
Program ended with exit code: 0
</code></pre>
<p>But I want to improve my code so it can be as fast as possible.</p>
<p>How can I simplify <code>modifyDollarNumber()</code> function?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T14:02:13.443",
"Id": "386751",
"Score": "2",
"body": "'fast' is generally within a particular usage; does it need to be fast for lots of small strings like the example, or long strings with many numbers...?"
},
{
"ContentLic... | [
{
"body": "<p>String manipulation can be slow. Inserting and deleting characters requires shifting characters in memory, if modifying in place, or allocating and freeing temporaries. </p>\n\n<p>It could be faster to allocate one destination character buffer (<code>char[]</code> or <code>wchar_t[]</code>), and ... | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T13:47:48.873",
"Id": "200815",
"Score": "4",
"Tags": [
"c++",
"strings"
],
"Title": "Replace $number with $number+1 in std::string"
} | 200815 |
<p>I got this question from the interviewbit site test.</p>
<p>There are n horses and you are the kth person in the line to ride on the horse. All the persons in the queue will go with the lowest numbered horse available i.e if horse no.1 and horse no.2 are present , the person will choose horse no.1 .All the horses have their own riding time and after their riding time ends they are free for next round. If there are no horses available the person will wait for the horse to come and will go on with it. We have to find that on which horse number we will be riding.</p>
<p>Input:- T - no. of test cases, n - no. of horses, k - your number in queue,ride time(M) - n numbers which will denote the riding time of the horses</p>
<p>constraints:- 1 <= T <= 100, 1 <= N <= 1000, 1 <= K <= 10^9, 1 <= M(i) <= 100000</p>
<p>output :- you have to tell the horse number which you will get.</p>
<p>Ex. 1</p>
<p>3 8</p>
<p>4 2 1</p>
<p>output:-
1</p>
<p>Here there are 3 horses with running time 4, 2, 1 and i am 8th in the queue.
so first three persons will go with horse#1 , horse#2 and horse#3. After this
there will be no horse so the fourth person will have to wait. horse#3 will
come first so he will go with it. fifth will go with horse#2 and sixth with
horse#3, seventh will go with horse#3 and eight will go with horse #1. so the
output is 1.<br>
Below is my code :-</p>
<p>Its time complexity is O(N*K). Is there a better way to solve it. </p>
<pre><code>#include<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,k;
cin>>n>>k;
int hrs[n], ans;
for(int i = 0;i < n;i++)
cin>>hrs[i];
if(n >= k){
cout<<k<<endl;
}else{
int tt = 0,p = n;
int B[n];
for(int j = 0;j < n;j++)
B[j] = hrs[j];
while(p != k){
tt++;
for(int m = 0;m < n;m++){
if(tt == hrs[m]){
p++;
hrs[m] += B[m];
if(p == k){
ans = m;
break;
}
}
}
}
cout<<ans+1<<endl;
}
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<h1>Use portable constructs</h1>\n\n<p>Variable-length arrays are not standard C++. Using such non-standard extensions hampers your code because you can't easily use different compilers (this can possibly even exclude entire target platforms).</p>\n\n<h1>Avoid importing all of <code>std</code> into ... | {
"AcceptedAnswerId": "200831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T14:01:17.883",
"Id": "200817",
"Score": "1",
"Tags": [
"c++",
"complexity"
],
"Title": "Finding the horse number you will get"
} | 200817 |
<p>Our business intelligence suite outputs data as an indented hierarchy, as below:</p>
<pre><code>Level 1 1000
Level 2a 600
Level 3a 500
Level 3b 100
Level 2b 400
Level 3c 400
</code></pre>
<p>I've written a macro that converts this into a 'database' format, where only rows with the base (most granular) level are preserved, and the parents are listed to the left as below (this way the # column is summable):</p>
<pre><code> 1 2 3 #
Level 1 Level 2a Level 3a 500
Level 1 Level 2a Level 3b 100
Level 1 Level 2b Level 3c 400
</code></pre>
<p>The problem I've been running into is that it takes 5-10 minutes to process a file with ~8000 rows. Although my code works, I'm convinced there's a faster way. See below for my code:</p>
<pre><code>Sub Database()
Application.ScreenUpdating = False
Dim WS As Worksheet
Dim SR As Range
Dim Rows As Integer
Dim Indent As Integer
Dim TR As Integer
Dim BR As Integer
Set WS = ActiveWorkbook.ActiveSheet
'StartCell is a function that returns the address of the first cell in the hierarchy
Set SR = WS.Range(StartCell())
Rows = SR.End(xlDown).Row - SR.Row
BR = SR.End(xlDown).Row
TR = SR.Row
'Insert 4 columns & add headers (Level 1, Level 2, etc.)
For x = 0 To 3
SR.EntireColumn.Insert
SR.Offset(-1, -1) = "Level " & x + 3
Next x
x = 0
q = 0
'The main code
Do While x < Rows + 1
'Identifies a row with base-level indentation & sets indent value to this level
If Left(SR.Offset(x, 0), 5) = "P_PC7" Then
Indent = SR.Offset(x, 0).IndentLevel
End If
i = 0
'Loop while the indentation level is greater than one
Do While Indent > 1
'Move upwards and check whether indentation of new cell is one less than initial cell
If SR.Offset(x - i, 0).IndentLevel = Indent - 1 Then
'If so, this cell is the parent of the initial cell - copy it into the appropriate spot to the left of the base level cell
SR.Offset(x - i, 0).Copy SR.Offset(x, -1 * (6 - Indent))
'Set new indent level - the next loop will now look for the parent of the new cell
Indent = SR.Offset(x - i, 0).IndentLevel
'If indent level is not one less than initial cell, continue moving upward
Else: i = i + 1
End If
Loop
x = x + 1
Loop
'Remove all rows that are not base-level
For q = BR To TR Step -1
If WS.Cells(q, 6).IndentLevel <> 5 Then
WS.Cells(q, 6).EntireRow.Delete
End If
Next q
WS.UsedRange.IndentLevel = 0
Application.ScreenUpdating = True
End Sub
</code></pre>
| [] | [
{
"body": "<p>In reviewing your code first, there are several things you can do to make your code more consistent.</p>\n\n<ol>\n<li>Always use <code>Option Explicit</code>. Please.</li>\n<li>When you're looking at performance, you can do more than just disable <code>ScreenUpdating</code>. See <a href=\"https://... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T15:16:23.253",
"Id": "200827",
"Score": "4",
"Tags": [
"performance",
"vba",
"excel",
"tree"
],
"Title": "Macro to convert an indented hierarchy to a database format"
} | 200827 |
<p>I have an application that needs to contact a remote API many times to request information about various products. It was taking around a minute with synchronous programming. I adjusted all my methods to be async and I still do not see a performance enhancement. I suspect it's because I'm awaiting each result from the API instead of running them all in parallel.</p>
<p>The code works but it just does not work well. I'm really looking to learn and understand how to develop async methods the correct way.</p>
<p>Here is my API wrapper (if you guys have any suggestions for this too I'd love to hear it):</p>
<pre><code>public class InventoryAPI
{
private RestClient _client;
private RestRequest request;
public InventoryAPI(RestClient client)
{
this._client = client;
}
public async Task<RootLotsObject> GetInventory(string company, string buyer, string vendCode, string lotNum, string prodNum, string status)
{
request = new RestRequest("ppro/services", Method.POST);
var cancelTokenSource = new CancellationTokenSource();
request.AddParameter("appId", "APIINV");
request.AddParameter("command", "getInventory");
request.AddParameter("username", "jraynor");
if (company != null) { request.AddParameter("company", company); }
if (buyer != null) { request.AddParameter("buyer", buyer); }
if (vendCode != null) { request.AddParameter("vendor", vendCode); }
if (lotNum != null) { request.AddParameter("lotNum", lotNum); }
if (prodNum != null) { request.AddParameter("prodNum", prodNum); }
if (status != null) { request.AddParameter("status", status); }
IRestResponse<RootLotsObject> response = await client.ExecuteTaskAsync<RootLotsObject>(request, cancelTokenSource.Token);
request = null;
return response.Data;
}
}
</code></pre>
<p>Here I call the API wrapper:</p>
<pre><code>public LoadSchedulingRepository(RestClient client)
{
db = new LoadEntities();
invAPI = new InventoryAPI(client);
}
public async Task<IEnumerable<InventoryProdAndSubsVM>> GetInventoryForOrdersAPIAsync(string prodNum, DateTime? userDate)
{
var invResults = await invAPI.GetInventory("0009", null, null, null, prodNum, "O");
if (invResults != null)
{
var results = invResults.responseData.lots.Where(x => x.ExcludeFIFOAlloc == "N").GroupBy(l => l.productNum).Select(x => new InventoryProdAndSubsVM
{
ProdDesc = x.Max(y => y.productDesc),
ProdCode = x.Max(y=>y.product),
ProdNum = x.Key,
Committed = invResults.responseData.lots.Where(w => w.ReceiveDate != null).Sum(z => Convert.ToDecimal(z.commitQty)),
DueIn = invResults.responseData.lots.Where(w => w.ExpectedDate == userDate).Sum(z => Convert.ToDecimal(z.orderedQty)),
OnHand = x.Sum(y => y.OnHand),
Condition = x.Max(y => y.condition),
Commodity = x.Max(y => y.commodity)
});
return results;
}
return null;
}
</code></pre>
<p>Here is my bottle neck method I believe:</p>
<pre><code>private async Task<List<InventoryProdAndSubsVM>> GetProductInventoryAsync(IEnumerable<BackhaulTopVM> prodCodes, DateTime userDate)
{
//Only take unique ProdCodes
foreach (var product in prodCodes.GroupBy(x => x.ProdNum).Select(x => x.FirstOrDefault()))
{
//Get inventory for specific product code and append it to a list
//BOTTLE NECK HERE;
itemsToAdd = await loadSchedulingRepo.GetInventoryForOrdersAPIAsync(product.ProdNum, userDate);
foreach (var item in itemsToAdd)
{
//Create a new list item and add it to resultSet
var currentInventory = new InventoryProdAndSubsVM
{
Commodity = item.Commodity,
DueIn = item.DueIn,
OnHand = item.OnHand,
Committed = item.Committed,
ProdCode = item.ProdCode,
ProdNum = item.ProdNum,
ProdDesc = item.ProdDesc
};
//Append to initalized list
resultSet.Add(currentInventory);
}
}
return resultSet;
}
</code></pre>
<p>Here I'm awaiting <code>loadSchedulingRepo.GetInventoryForOrdersAPIAsync</code>
and I think it needs to complete a web request for every single <code>ProdCode</code> in <code>prodCodes</code>.</p>
<p>Is there a way to run every rest request in parallel or something?</p>
<p>I was toying around with this:</p>
<pre><code>var prodCodeTasks = prodCodes.Select(x => loadSchedulingRepo.GetInventoryForOrdersAPIAsync(x.ProdNum, userDate)).ToList();
await Task.WhenAll(prodCodeTasks);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T15:37:37.310",
"Id": "386779",
"Score": "0",
"body": "Is the other side of the connection synchronous or async? If all the request are going into one connection and that connection is synchronous it may not matter what you do on you... | [
{
"body": "<p>The idea about using <code>Task.WhenAll</code> is a good start as it could help with running then in parallel.</p>\n\n<p>Take a look at the following refactor</p>\n\n<pre><code>private async Task<List<InventoryProdAndSubsVM>> GetProductInventoryAsync(IEnumerable<BackhaulTopVM> pr... | {
"AcceptedAnswerId": "200865",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T15:22:15.113",
"Id": "200828",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"api"
],
"Title": "Async await multiple API calls"
} | 200828 |
<p>I've already made a version of this game which was supposed to be played on the console. I got it reviewed and applied almost all of the recommendations I received in that topic. Thus you can consider this topic a follow-up from <a href="https://codereview.stackexchange.com/questions/197675/macau-card-game">this one</a>. This would be the first time I got in touch with SFML. I must mention that all the user interactions are still going through the console.</p>
<p>Most of the files remained the same from the original question (with the recommendations applied), so I will post only the new files/parts that have changed as those concern me the most. However, I've got <a href="https://github.com/ISilviu/MacaoGame" rel="nofollow noreferrer">the project hosted on GitHub</a> if you're interested in other aspects.</p>
<p><strong>CardsTexturesHolder.hpp</strong></p>
<pre><code>#pragma once
#include <unordered_map>
#include <filesystem>
#include <SFML/Graphics/Texture.hpp>
#include "Exceptions.hpp"
#include "Card.hpp"
namespace std
{
template <>
struct hash<Card>
{
constexpr std::size_t operator()(Card const& card) const noexcept
{
return (static_cast<int>(card.rank()) + static_cast<int>(card.suit()));
}
};
}
class CardsTexturesHolder
{
public:
template <typename Container>
CardsTexturesHolder(Container const& cardIdentifiers, std::string_view path);
template <typename Iterator>
CardsTexturesHolder(Iterator first, Iterator last, std::string_view path);
const sf::Texture& operator[](Card const& card) const noexcept;
private:
std::unordered_map<Card, sf::Texture> _textures;
template <typename Container>
void load(Container const& cardIdentifiers, std::string_view path);
template <typename Iterator>
void load(Iterator first, Iterator last, std::string_view path);
};
template <typename Container>
CardsTexturesHolder::CardsTexturesHolder(Container const& cardIdentifiers, std::string_view path)
{
load(cardIdentifiers, path);
}
template <typename Iterator>
CardsTexturesHolder::CardsTexturesHolder(Iterator first, Iterator last, std::string_view path)
{
load(first, last, path);
}
template <typename Iterator>
void CardsTexturesHolder::load(Iterator first, Iterator last, std::string_view path)
{
sf::Texture texture;
auto constexpr iteratorAdvanceOffset{ 1 };
for (auto const& file : std::filesystem::directory_iterator(path))
{
if (texture.loadFromFile(file.path().string()))
{
_textures[*first] = texture;
std::advance(first, iteratorAdvanceOffset);
}
else
throw CouldNotLoadTextureException("A certain card texture could not be loaded. Consider checking the textures directory.");
}
}
template <typename Container>
void CardsTexturesHolder::load(Container const& cardIdentifiers, std::string_view path)
{
sf::Texture texture;
auto currentCardIterator = std::begin(cardIdentifiers);
auto constexpr iteratorAdvanceOffset{ 1 };
for (auto const& file : std::filesystem::directory_iterator(path))
{
if (texture.loadFromFile(file.path().string()))
{
_textures[*currentCardIterator] = texture;
std::advance(currentCardIterator, iteratorAdvanceOffset);
}
else
throw CouldNotLoadTextureException("A certain card texture could not be loaded. Consider checking the textures directory.");
}
}
</code></pre>
<p><strong>CardsTexturesHolder.cpp</strong></p>
<pre><code>#include "CardsTexturesHolder.hpp"
const sf::Texture& CardsTexturesHolder::operator[](Card const& card) const noexcept
{
auto const it = _textures.find(card);
return it->second;
}
</code></pre>
<p>There are 2 aspects of this class that I don't like.</p>
<ol>
<li>The Cards in the <code>cardIdentifiers</code> container must have a strict ordering that matches the one in the Textures folder (see it on GitHub). If one changes any card's place in that container, the textures won't be corresponding to the actual card anymore.</li>
<li>I had to name all the textures in such a way that the folder will be traversed in alphabetical order. If one changes the name of a texture file, everything will be messed up. </li>
</ol>
<p><strong>FontsHolder.hpp</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics/Font.hpp>
#include <unordered_map>
class FontsHolder
{
public:
explicit FontsHolder(std::string_view path);
const sf::Font& operator[](std::string const& fontName) const;
private:
const std::string extractFileName(std::string const& filePath) const noexcept;
void loadFonts(std::string_view path);
std::unordered_map<std::string, sf::Font> _fonts;
};
</code></pre>
<p><strong>FontsHolder.cpp</strong></p>
<pre><code>#include "FontsHolder.hpp"
#include "Exceptions.hpp"
#include <algorithm>
#include <filesystem>
FontsHolder::FontsHolder(std::string_view path)
{
loadFonts(path);
}
const sf::Font& FontsHolder::operator[](std::string const& fontName) const
{
auto const it = _fonts.find(fontName);
if (it != _fonts.cend())
return it->second;
else
throw FontNotFoundException("The requested font was not found.");
}
const std::string FontsHolder::extractFileName(std::string const& filePath) const noexcept
{
auto constexpr newDirectoryIdentifier = '\\';
auto constexpr fileIdentifier = '.';
auto const lastPositionOfDirectoryIdentifier = filePath.find_last_of(newDirectoryIdentifier);
auto const firstPositionOfFileIdentifier = filePath.find_first_of(fileIdentifier);
return std::string(std::next(filePath.cbegin(),lastPositionOfDirectoryIdentifier + 1), std::next(filePath.cbegin(), firstPositionOfFileIdentifier));
}
void FontsHolder::loadFonts(std::string_view path)
{
sf::Font font;
std::string filePath;
for (auto const& file : std::filesystem::directory_iterator(path))
{
filePath = file.path().string();
if (font.loadFromFile(filePath))
_fonts[extractFileName(filePath)] = font;
else
throw CouldNotLoadFontException("A certain font could not be loaded. Consider checking the textures directory.");
}
}
</code></pre>
<p><strong>Renderer.hpp</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include "FontsHolder.hpp"
#include "CardsTexturesHolder.hpp"
#include "Deck.hpp"
#include <vector>
class Renderer
{
public:
template <typename Container>
Renderer(Container const& cardsIdentifiers, std::string_view pathToTextures, std::string_view pathToFonts);
template <typename Iterator>
Renderer(Iterator first, Iterator last, std::string_view pathToTextures, std::string_view pathToFonts);
template <typename Container>
void drawPlayerCards(sf::RenderTarget& target, Container const& cards) const;
void drawPileTopCard(sf::RenderTarget& target, Card const& card) const;
void drawEscapeText(sf::RenderTarget& target, std::string const& style) const;
void drawPlayerName(sf::RenderTarget& target, std::string const& name, sf::Vector2f position, std::string const& style) const;
void drawWinner(sf::RenderTarget& target, std::string const& outputData, std::string const& style) const;
void drawInformationAboutSpecialCard(sf::RenderTarget& target, std::string const& information, sf::Vector2f position, std::string const& style) const;
private:
CardsTexturesHolder _textures;
FontsHolder _fonts;
};
template<typename Container>
inline Renderer::Renderer(Container const & cardsIdentifiers, std::string_view pathToTextures, std::string_view pathToFonts)
: _textures(cardsIdentifiers, pathToTextures),
_fonts(pathToFonts)
{}
template<typename Iterator>
inline Renderer::Renderer(Iterator first, Iterator last, std::string_view pathToTextures, std::string_view pathToFonts)
: _textures(first, last, pathToTextures),
_fonts(pathToFonts)
{}
template <typename Container>
void Renderer::drawPlayerCards(sf::RenderTarget & target, Container const & cards) const
{
auto const defaultScaleValues = sf::Vector2f(0.2f, 0.2f);
auto constexpr xDirectionOffset{ 135 };
auto constexpr yDirectionOffset{ 220 };
sf::Sprite cardSprite;
auto constexpr initialValueForX{ 0 };
auto constexpr initialValueForY{ 250 };
float x{ initialValueForX };
float y{ initialValueForY };
for (auto const& card : cards)
{
cardSprite.setTexture(_textures[card]);
cardSprite.setPosition(x, y);
cardSprite.setScale(defaultScaleValues);
target.draw(cardSprite);
x += xDirectionOffset;
if (x + cardSprite.getGlobalBounds().width > target.getSize().x)
{
x = initialValueForX;
y += yDirectionOffset;
}
}
}
</code></pre>
<p><strong>Renderer.cpp</strong></p>
<pre><code>#include "Renderer.hpp"
#include <SFML/Graphics/Text.hpp>
void Renderer::drawPileTopCard(sf::RenderTarget& target, Card const& card) const
{
sf::Vector2f const defaultScaleValues(0.2f, 0.2f);
sf::Sprite cardSprite{ _textures[card] };
cardSprite.setScale(defaultScaleValues);
auto constexpr yDirectionOffset{ 1 };
cardSprite.setPosition(sf::Vector2f(target.getSize().x / 2, yDirectionOffset));
target.draw(cardSprite);
}
void Renderer::drawPlayerName(sf::RenderTarget & target, std::string const& name, sf::Vector2f position, std::string const& style) const
{
sf::Text playerName;
playerName.setFont(_fonts[style]);
playerName.setString(name);
playerName.setPosition(position);
target.draw(playerName);
}
void Renderer::drawEscapeText(sf::RenderTarget & target, std::string const & style) const
{
static std::string const outputData{ "Press Enter to continue..." };
sf::Text output;
output.setFont(_fonts[style]);
output.setString(outputData);
static const auto targetSize = target.getSize();
static const auto point = sf::Vector2f(10, 10);
output.setPosition(point);
target.draw(output);
}
void Renderer::drawWinner(sf::RenderTarget & target, std::string const & outputData, std::string const & style) const
{
int constexpr characterSize{ 60 };
sf::Text output;
output.setFont(_fonts[style]);
output.setString(outputData);
output.setCharacterSize(characterSize);
static auto const targetSize = target.getSize();
static auto const middlePoint = sf::Vector2f(targetSize.x / 2, targetSize.y / 2);
output.setPosition(middlePoint);
target.draw(output);
}
void Renderer::drawInformationAboutSpecialCard(sf::RenderTarget& target, std::string const& information, sf::Vector2f position, std::string const& style) const
{
sf::Text specialCardInformation;
specialCardInformation.setFont(_fonts[style]);
specialCardInformation.setString(information);
specialCardInformation.setPosition(position);
target.draw(specialCardInformation);
}
</code></pre>
<p><strong>VisualGame.hpp</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics/RenderWindow.hpp>
#include "Player.hpp"
#include "FontsHolder.hpp"
#include "Renderer.hpp"
#include <vector>
std::string const defaultWindowName{ "MacaoGame" };
class VisualGame
{
public:
template <typename InputContainer>
VisualGame(InputContainer&& players, std::string_view pathToCardTextures
, std::string_view pathToFonts, std::size_t width, std::size_t height);
template <typename InputIterator>
VisualGame(InputIterator first, InputIterator last,
std::string_view pathToCardTextures, std::size_t width, std::size_t height);
void run();
private:
constexpr void validateNumberOfPlayers() const;
constexpr bool areCompatible(Card const& left, Card const& right) const noexcept;
void prepareGame() noexcept;
void dealInitialCardsToEachPlayer() noexcept;
void receiveCardsFromDeck(Player& player, std::size_t numberOfCards);
void putCardToPile(Player& player, std::size_t cardNumber) noexcept;
bool isSpecial(Card const& card) const noexcept;
void printInformationAboutThePlayerAndTheTopCardFromPile(Player const& player) noexcept;
void printInformationAboutThePlayerAndTheTopCardFromPile(Player const& player, Rank rank) noexcept;
void normalCardPlayerTurn(Player& player);
void specialCardPlayerTurn(Player& player);
std::unique_ptr<Player> findWinner() const noexcept;
auto receiveAndValidateInput() const noexcept->int;
auto checkBounds(Player const& player, int cardNumber) const noexcept->int;
void validatePlayerCardCompatibilityWithPileTopCard(Player const& player, int& cardNumber) const noexcept;
sf::RenderWindow _mainWindow;
Renderer _renderer;
std::vector<std::unique_ptr<Player>> _players;
Deck _deck;
Pile _pile;
bool _gameOver;
};
inline constexpr void VisualGame::validateNumberOfPlayers() const
{
static constexpr auto minimumNumberOfPlayers{ 2 };
static constexpr auto maximumNumberOfPlayers{ 9 };
auto const numberOfPlayers = std::distance(_players.cbegin(), _players.cend());
if (numberOfPlayers < minimumNumberOfPlayers || numberOfPlayers > maximumNumberOfPlayers)
throw InvalidNumberOfPlayersException("The minimum number of players is 2, while the maximum is 9.");
}
template<typename InputContainer>
inline VisualGame::VisualGame(InputContainer && players, std::string_view pathToCardTextures,
std::string_view pathToFonts, std::size_t width, std::size_t height)
: _players(std::move(players)),
_renderer(defaultDeck, pathToCardTextures, pathToFonts),
_mainWindow(sf::VideoMode(width, height), defaultWindowName),
_gameOver(false)
{
validateNumberOfPlayers();
}
template<typename InputIterator>
inline VisualGame::VisualGame(InputIterator first, InputIterator last,
std::string_view pathToCardTextures, std::size_t width, std::size_t height)
:_players(std::make_move_iterator(std::begin(players)), std::make_move_iterator(std::end(players))),
_renderer(vectorDefaultDeck, pathToCardTextures, pathToFonts),
_mainWindow(sf::VideoMode(width, height), defaultWindowName),
_gameOver(false)
{
validateNumberOfPlayers();
}
</code></pre>
<p><strong>VisualGame.cpp</strong></p>
<pre><code>#include <SFML/Graphics.hpp>
#include "VisualGame.hpp"
#include "Exceptions.hpp"
#include <iostream>
#include <cctype>
auto const defaultBackgroundColor = sf::Color::Color(51, 51, 255);
std::string const defaultFont{ "FredokaOne" };
namespace
{
constexpr auto specialCards = std::array
{
Card{ Rank::Two, Suit::Clubs },
Card{ Rank::Two, Suit::Diamonds },
Card{ Rank::Two, Suit::Spades },
Card{ Rank::Two, Suit::Hearts },
Card{ Rank::Three, Suit::Clubs },
Card{ Rank::Three, Suit::Diamonds },
Card{ Rank::Three, Suit::Spades },
Card{ Rank::Three, Suit::Hearts },
Card{ Rank::Ace, Suit::Diamonds },
Card{ Rank::Ace, Suit::Clubs },
Card{ Rank::Ace, Suit::Spades },
Card{ Rank::Ace, Suit::Hearts },
};
}
constexpr bool VisualGame::areCompatible(Card const& left, Card const& right) const noexcept
{
return left.rank() == right.rank() || left.suit() == right.suit();
}
void VisualGame::prepareGame() noexcept
{
_deck.shuffle();
dealInitialCardsToEachPlayer();
_pile.add(_deck.deal());
while (isSpecial(_pile.topCard()))
{
_deck.add(_pile.deal());
_deck.shuffle();
_pile.add(_deck.deal());
}
}
void VisualGame::dealInitialCardsToEachPlayer() noexcept
{
static constexpr auto numberOfCards{ 5 };
static std::vector<Card> playerCards;
for (auto const& player : _players)
{
playerCards = _deck.deal(numberOfCards);
player->_hand.add(playerCards.cbegin(), playerCards.cend());
}
}
void VisualGame::printInformationAboutThePlayerAndTheTopCardFromPile(const Player& player) noexcept
{
_mainWindow.clear(defaultBackgroundColor);
_renderer.drawPileTopCard(_mainWindow, _pile.topCard());
_renderer.drawPlayerName(_mainWindow, player.name(), sf::Vector2f(10, 10), defaultFont);
_renderer.drawPlayerCards(_mainWindow, player._hand.cards());
_mainWindow.display();
}
void VisualGame::printInformationAboutThePlayerAndTheTopCardFromPile(Player const & player, Rank rank) noexcept
{
static auto const cardInformationPosition = sf::Vector2f(500, 1);
static auto const playerNamePosition = sf::Vector2f(10, 10);
static auto const specialCardInformationPosition = sf::Vector2f(0, _mainWindow.getSize().x / 2);
switch (rank)
{
case Rank::Two:
{
_mainWindow.clear(defaultBackgroundColor);
_renderer.drawPileTopCard(_mainWindow, _pile.topCard());
_renderer.drawPlayerName(_mainWindow, player.name(), playerNamePosition, defaultFont);
static const std::string cardInformation{ "This is 2 card and you will need to receive 2 cards from the deck.\n"
"If you have a 4 card that has the same suit, then you can stop it.\n" };
_renderer.drawInformationAboutSpecialCard(_mainWindow, cardInformation, specialCardInformationPosition, defaultFont);
_renderer.drawPlayerCards(_mainWindow, player._hand.cards());
_mainWindow.display();
break;
}
case Rank::Three:
{
_mainWindow.clear(defaultBackgroundColor);
_renderer.drawPileTopCard(_mainWindow, _pile.topCard());
_renderer.drawPlayerName(_mainWindow, player.name(), playerNamePosition, defaultFont);
static const std::string cardInformation{ "This is 3 card and you will need to receive 3 cards from the deck.\n"
"If you have a 4 card that has the same suit, then you can stop it.\n" };
_renderer.drawInformationAboutSpecialCard(_mainWindow, cardInformation, specialCardInformationPosition, defaultFont);
_renderer.drawPlayerCards(_mainWindow, player._hand.cards());
_mainWindow.display();
break;
}
//case Rank::Seven:
//{
// _renderer.draw(_mainWindow, _pile.topCard());
// _renderer.draw(_mainWindow, player._hand.cards());
// std::cout << "\nTop card from pile: " << _pile.top() << "\nThis is a 7 card and you will need to put down a card that has the specified suit. If you have a Joker, then"
// << " you can put it. Enter 0 if you don't have such a compatible card.\n" << player << "\n";
// break;
//}
case Rank::Ace:
{
_mainWindow.clear(defaultBackgroundColor);
_renderer.drawPileTopCard(_mainWindow, _pile.topCard());
_renderer.drawPlayerName(_mainWindow, player.name(), sf::Vector2f(10, 10), "FredokaOne");
_renderer.drawPlayerCards(_mainWindow, player._hand.cards());
_mainWindow.display();
break;
}
}
}
void VisualGame::validatePlayerCardCompatibilityWithPileTopCard(Player const& player, int& cardNumber) const noexcept
{
while (!areCompatible(player._hand.get(cardNumber), _pile.topCard()))
{
std::cout << "This card is incompatible.\nEnter another card or enter 0 to skip your turn.\n";
cardNumber = receiveAndValidateInput();
if (!cardNumber)
break;
}
}
std::unique_ptr<Player> VisualGame::findWinner() const noexcept
{
auto const it = std::find_if(_players.cbegin(), _players.cend(),
[](auto const& player) { return !player->_hand.numberOfCards(); });
if (it == _players.cend())
return std::make_unique<Player>(nullptr);
return std::make_unique<Player>(**it);
}
auto VisualGame::checkBounds(Player const& player, int cardNumber) const noexcept->int
{
static constexpr auto lowerBound{ 0 };
while (cardNumber < lowerBound || cardNumber > player._hand.numberOfCards())
{
std::cout << "That card doesn't exist. You can enter 0 to skip your turn.\n";
std::cin >> cardNumber;
}
return cardNumber;
}
auto VisualGame::receiveAndValidateInput() const noexcept->int
{
std::string cardNumber{};
std::getline(std::cin, cardNumber);
while (!std::all_of(cardNumber.cbegin(), cardNumber.cend(), [](auto const character) {return std::isdigit(character); })
|| cardNumber.empty())
{
std::cout << "Empty input/Not an integer.\n";
std::getline(std::cin, cardNumber);
}
return std::stoi(cardNumber);
}
void VisualGame::specialCardPlayerTurn(Player& player)
{
static constexpr auto neededCardsToPickForTwo{ 2 };
static constexpr auto neededCardsToPickForThree{ 3 };
int cardNumber{ 0 };
switch (_pile.topCard().rank())
{
case Rank::Two:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Two);
int cardNumber = receiveAndValidateInput();
cardNumber = checkBounds(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForTwo);
else if (player._hand.get(cardNumber).rank() == Rank::Four && areCompatible(player._hand.get(cardNumber), _pile.topCard()))
putCardToPile(player, cardNumber);
else
{
receiveCardsFromDeck(player, neededCardsToPickForTwo);
/* validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
if (!cardNumber)
else
putCardToPile(player, cardNumber);*/
}
break;
}
case Rank::Three:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Three);
int cardNumber = receiveAndValidateInput();
cardNumber = checkBounds(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, neededCardsToPickForThree);
else if (player._hand.get(cardNumber).rank() == Rank::Four && areCompatible(player._hand.get(cardNumber), _pile.topCard()))
putCardToPile(player, cardNumber);
else
{
receiveCardsFromDeck(player, neededCardsToPickForThree);
/* validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
if (!cardNumber)
else
putCardToPile(player, cardNumber);*/
}
break;
}
case Rank::Ace:
{
printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Ace);
break;
}
}
if (!player._hand.numberOfCards())
_gameOver = true;
}
void VisualGame::normalCardPlayerTurn(Player& player)
{
static constexpr auto defaultNumberOfCardsToPick{ 1 };
printInformationAboutThePlayerAndTheTopCardFromPile(player);
int cardNumber = receiveAndValidateInput();
cardNumber = checkBounds(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, defaultNumberOfCardsToPick);
else
{
validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber);
cardNumber = checkBounds(player, cardNumber);
if (!cardNumber)
receiveCardsFromDeck(player, defaultNumberOfCardsToPick);
else
putCardToPile(player, cardNumber);
}
if (!player._hand.numberOfCards())
_gameOver = true;
}
void VisualGame::run()
{
prepareGame();
Card lastCard{ _pile.topCard() };
bool specialCardHadEffect{ false };
while (_mainWindow.isOpen())
{
sf::Event event;
while (_mainWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
_mainWindow.close();
}
for (auto& currentPlayer : _players)
{
if (!isSpecial(_pile.topCard()))
normalCardPlayerTurn(*currentPlayer);
else
{
if (isSpecial(_pile.topCard()) && !specialCardHadEffect)
{
specialCardPlayerTurn(*currentPlayer);
specialCardHadEffect = true;
}
else
normalCardPlayerTurn(*currentPlayer);
}
if (_pile.topCard() != lastCard)
{
specialCardHadEffect = false;
lastCard = _pile.topCard();
}
if (_gameOver)
break;
}
while (_gameOver)
{
_mainWindow.clear(defaultBackgroundColor);
_renderer.drawWinner(_mainWindow, findWinner()->name() + " wins!", defaultFont);
_renderer.drawEscapeText(_mainWindow, defaultFont);
_mainWindow.display();
sf::Event event;
if (_mainWindow.waitEvent(event))
{
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Enter))
_mainWindow.close();
}
}
}
}
</code></pre>
<p>And the driver code:</p>
<p><strong>SFML.cpp</strong></p>
<pre><code>#include "VisualGame.hpp"
#include <iostream>
using vectorOfPlayers = std::vector<std::unique_ptr<Player>>;
using paths = std::pair<std::string, std::string>;
vectorOfPlayers getPlayers() noexcept
{
vectorOfPlayers players;
std::cout << "Enter players.\n"
"\t* Enter an empty name when done adding players.\n";
for (auto name = std::string{}; std::getline(std::cin, name); )
{
if (name == "")
break;
players.push_back(std::make_unique<Player>(std::move(name)));
}
return players;
}
paths getPaths() noexcept
{
std::cout << "Enter the path to the textures folder.\n";
std::string texturesPath;
std::getline(std::cin, texturesPath);
std::cout << "Enter the path to the fonts folder.\n";
std::string fontsPath;
std::getline(std::cin, fontsPath);
return std::make_pair(texturesPath, fontsPath);
}
int main()
{
while (true)
{
try
{
int const monitorWidth = sf::VideoMode::getDesktopMode().width;
int const monitorHeight = sf::VideoMode::getDesktopMode().height;
vectorOfPlayers players = getPlayers();
paths resourcePaths = getPaths();
//constexpr std::string_view firstPath("G:/Visual Studio projects/MacaoGame/Debug/Textures");
//constexpr std::string_view secondPath("G:/Visual Studio projects/MacaoGame/Debug/Fonts");
VisualGame myVisualGame(players, resourcePaths.first, resourcePaths.second, monitorWidth, monitorHeight);
myVisualGame.run();
break;
}
catch (CouldNotLoadTextureException const& e)
{
std::cerr << e.what() << '\n';
return -1;
}
catch (CouldNotLoadFontException const& e)
{
std::cerr << e.what() << '\n';
return -1;
}
catch (InvalidNumberOfPlayersException const& e)
{
std::cerr << e.what() << '\n';
return -1;
}
}
return 0;
}
</code></pre>
<p>Also, what I don't like here is that I need to give absolute paths, otherwise <code>std::filesystem::directory_iterator</code> will throw an exception.</p>
| [] | [
{
"body": "<p>A few random, disconnected thoughts:</p>\n\n<h1>Reading Card Textures</h1>\n\n<p>You say:</p>\n\n<blockquote>\n <p>There are 2 aspects of this class that I don't like.</p>\n \n <ol>\n <li><p>The Cards in the cardIdentifiers container must have a strict ordering that matches the one in the Text... | {
"AcceptedAnswerId": "200868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T16:37:09.700",
"Id": "200833",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"game",
"playing-cards",
"sfml"
],
"Title": "Macau Card Game (with graphics)"
} | 200833 |
<p>This is a question from the book "<a href="https://www.amazon.in/gp/product/0984782850/ref=as_li_tl?ie=UTF8&tag=0106d-21&camp=3638&creative=24630&linkCode=as2&creativeASIN=0984782850&linkId=6bf430d6374ca7ffb9f2cac081fc2d31" rel="noreferrer">Cracking the Coding Interview</a>".</p>
<blockquote>
<p>Write a method to decide if two strings are anagrams or not</p>
</blockquote>
<p>I think interviewer will not be convinced with this solution because here it is no test of logic. Please help me to optimise this solution.</p>
<pre><code>#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
std::string toLower(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char ch) { return std::tolower(ch); });
return str;
}
bool areAnagrams(std::string& str1, std::string& str2)
{
str1 = toLower(str1);
str2 = toLower(str2);
std::sort(str1.begin(), str1.end());
std::sort(str2.begin(), str2.end());
if (str1.compare(str2) == 0)
{
return true;
}
else
{
return false;
}
}
int main()
{
std::string str1, str2;
std::cout << "Enter String 1: ";
std::getline(std::cin, str1);
std::cout << "Enter String 2: ";
std::getline(std::cin, str2);
bool res = areAnagrams(str1, str2);
if (res == 1)
{
std::cout << "Strings are anagram\n";
}
else
{
std::cout << "Strings are not anagram\n";
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I think interviewer will not be convinced with this solution because here it is no test of logic.</p>\n</blockquote>\n\n<p>I'm not sure what you mean by \"because here it is no test of logic,\" but if what you mean is \"because I found this puzzle too easy,\" then <em>good!</em> Th... | {
"AcceptedAnswerId": "200840",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T17:02:02.043",
"Id": "200835",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"interview-questions"
],
"Title": "Are strings anagram"
} | 200835 |
<p>I am making a game in which the player has a certain amount of available boost. To show this, I am using a blue bar inside a black frame. The bar can grow and shrink at different rates as available boost goes up and down. It works well and looks nice, but it almost halves my FPS. </p>
<p>The relevant snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var boostStyle = document.getElementById("available-boost").style;
var currBoost = 100;
var maxBoost = 100;
function setBoost(boostAmount) {
boostStyle.width = (boostAmount / maxBoost) * 100 + "%";
};
function demonstrateBoostChange() {
currBoost -= 1;
setBoost(currBoost);
if (currBoost < 1) {
currBoost = maxBoost;
}
requestAnimationFrame(demonstrateBoostChange);
}
requestAnimationFrame(demonstrateBoostChange);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#boost-bar {
bottom: 10px;
position: absolute;
right: 20%;
left: 20%;
height: 20px;
border-radius: 12px;
border-style: solid;
border-width: 2px;
border-color: rgb(0, 0, 0);
}
#available-boost {
margin: 0 auto;
height: 20px;
width: 100%;
text-align: center;
font-weight: bold;
border-radius: 10px;
background-color: rgb(0, 225, 255);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boost-bar">
<div id="available-boost">Boost</div>
</div></code></pre>
</div>
</div>
<sup>(I see the slight glitch where the text moves when very little boost remains, but I can solve that later. )</sup></p>
<p>The performance hit is probably not noticeable since it is the only thing running, but I have used Chrome DevTools to see that it is the slowest part of my code. I think this is because changing the width is triggering a reflow.</p>
<p><strong>How can I improve the performance of the above code?</strong></p>
<p>Some considerations:</p>
<ul>
<li>I am already using a canvas for some other things, would it be faster to just put the bar on that?</li>
<li>The boost can change at different rates, depending on the <code>maxBoost</code>.</li>
</ul>
| [] | [
{
"body": "<p>You may put your text \"Boost\" in a seperate element and position it.\nCheck this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code... | {
"AcceptedAnswerId": "200862",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T17:06:42.840",
"Id": "200836",
"Score": "3",
"Tags": [
"javascript",
"performance",
"html",
"css",
"animation"
],
"Title": "Changing the width of a centered progress bar"
} | 200836 |
<p>I did the following Excercise from Stroustrups PPP-Book (CH10 EX6)</p>
<blockquote>
<p>Define a <code>Roman_int</code> class for holding Roman numerals (as <code>int</code>s) with a <code><<</code> and <code>>></code>. Provice <code>Roman_int</code> with an <code>as_int()</code> member that returns the <code>int</code> value, so that if <code>r</code> is a <code>Roman_int</code>, we can write <code>cout<< "Roman" <<r <<" equals " << r.as_int() <<'\n';</code></p>
</blockquote>
<p>I revised my own solution after finishing the book so I used all language facilities available, not only the ones to use until that chapter in the book.</p>
<p>I wonder what can be still improved with readability, good practice etc.</p>
<p>Heres the code:</p>
<p><b> Roman_int.h </b></p>
<pre><code>#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <map>
namespace roman_int
{
using Roman = std::string;
using Roman_value = std::string;
using Integer = int;
using Integer_value = int;
class Roman_int {
public:
Roman_int() = default;
explicit Roman_int(const Integer& value)
:integer{ value }, roman{ integer_to_roman(value) }
{
}
explicit Roman_int(const Roman& value)
:integer{ roman_to_integer(value) }, roman{ value }
{
}
Roman as_roman() const { return roman; }
Integer as_integer()const { return integer; }
private:
struct Roman_integer_values {
Roman_integer_values(const Roman_value& roman_digit, const Integer_value& integer_digit)
:roman{ roman_digit }, integer{ integer_digit }
{
};
Roman_value roman;
Integer_value integer;
};
using Lockup_table = std::vector<Roman_integer_values>;
static const Lockup_table lookup_table;
Roman roman{};
Integer integer{};
Integer Roman_int::roman_to_integer(const Roman& roman);
Roman integer_to_roman(const Integer& integer);
bool is_valid_roman(const Roman& roman);
};
std::ostream& operator<<(std::ostream& os, const Roman_int& roman);
std::istream& operator>>(std::istream& is, Roman_int& roman);
Roman_int operator*(const Roman_int& a, const Roman_int& b);
Roman_int operator/(const Roman_int& a, const Roman_int& b);
Roman_int operator+(const Roman_int& a, const Roman_int& b);
Roman_int operator-(const Roman_int& a, const Roman_int& b);
bool operator==(const Roman_int& a, const Roman_int& b);
bool operator!=(const Roman_int& a, const Roman_int& b);
Roman_int operator%(const Roman_int& a, const Roman_int& b);
}
</code></pre>
<p><b> Roman_int.cpp </b></p>
<pre><code>#include <algorithm>
#include "Roman_int.h"
namespace roman_int
{
const Roman_int::Lockup_table Roman_int::lookup_table =
{
{ "M",1000 },
{ "CM",900 },
{ "D",500 },
{ "CD",400 },
{ "C",100 },
{ "XC",90 },
{ "L",50 },
{ "X",10 },
{ "IX",9 },
{ "V",5 },
{ "IV",4 },
{ "I",1 },
};
Roman Roman_int::integer_to_roman(const Integer& integer)
{
if (integer <1) {
throw std::runtime_error(
"Roman Roman_int::integer_to_roman(const Integer& integer)\n"
"Invalid Integer value it must be >= 1 \n"
);
}
Roman roman;
Integer tmp_integer = integer;
for (auto it = lookup_table.cbegin(); it != lookup_table.cend(); ++it) {
while (tmp_integer - it->integer >= 0) {
tmp_integer -= it->integer;
roman += it->roman;
}
}
return roman;
}
Integer Roman_int::roman_to_integer(const Roman& roman)
{
if (!is_valid_roman(roman)) {
throw std::runtime_error(
"Integer Roman_int::roman_to_integer(const Roman& roman)\n"
"Invalid input for roman\n"
);
}
Integer integer = 0;
for (const auto& roman_value : roman) {
for (const auto& element : lookup_table){
if (element.roman.size() != 1) {
continue;
}
if (roman_value == element.roman[0]) {
integer += element.integer;
break;
}
}
}
return integer;
}
bool Roman_int::is_valid_roman(const Roman& roman)
{
for (const auto roman_value : roman) {
bool valid = false;
for (const auto& element : lookup_table){
if (element.roman.size() != 1) {
continue;
}
if (roman_value == element.roman[0]) {
valid = true;
break;
}
}
if (!valid) {
return false;
}
}
return true;
}
std::ostream& operator<<(std::ostream& os, const Roman_int& roman)
{
return os << roman.as_roman();
}
std::istream& operator>>(std::istream& is, Roman_int& roman)
{
Roman input;
is >> input;
if (!is) {
is.setstate(std::ios::failbit);
return is;
}
else {
for (size_t i = 0; i < input.size(); i++) {
if (!isdigit(input[i])) {
is.setstate(std::ios::failbit);
return is;
}
}
roman = Roman_int(input);
return is;
}
}
Roman_int operator*(const Roman_int& a, const Roman_int& b)
{
Roman_int r{ a.as_integer() * b.as_integer() };
return r;
}
Roman_int operator/(const Roman_int& a, const Roman_int& b)
{
Roman_int r{ a.as_integer() / b.as_integer() };
return r;
}
Roman_int operator+(const Roman_int& a, const Roman_int& b)
{
Roman_int r{ a.as_integer() + b.as_integer() };
return r;
}
Roman_int operator-(const Roman_int& a, const Roman_int& b)
{
int result = a.as_integer() - b.as_integer();
if (result < 0) {
result = 1;
}
Roman_int r{ r };
return r;
}
bool operator==(const Roman_int& a, const Roman_int& b)
{
if (a.as_integer() == b.as_integer() && a.as_roman() == b.as_roman())
return true;
return false;
}
bool operator!=(const Roman_int& a, const Roman_int& b)
{
return !(a == b);
}
Roman_int operator%(const Roman_int& a, const Roman_int& b)
{
Roman_int r{ a.as_integer() % b.as_integer() };
return r;
}
}
</code></pre>
<p><b> main.cpp </b></p>
<pre><code>#include <iostream>
#include "Roman_int.h"
int main()
try {
for (int i = 1; i < 100; ++i) {
roman_int::Roman_int test{ i };
std::cout << test.as_integer() << '\t' << test << '\n';
}
std::cin.get();
}
catch (std::runtime_error& e) {
std::cerr << e.what() << "\n";
std::cin.get();
}
catch (...) {
std::cerr << "unknown error\n";
std::cin.get();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T19:21:26.260",
"Id": "386833",
"Score": "0",
"body": "Did you really mean to call it `Lockup_table` instead of `Lookup_table`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T20:11:15.670",
"Id": ... | [
{
"body": "<h2>A few errors in the code</h2>\n\n<p>There are a few errors in your code: <code>r</code> being initialized with itself in <code>operator-</code>, a wrong initialization order in your constructors, and an superfluous class specifier in <code>Integer Roman_int::roman_to_integer(const Roman& roma... | {
"AcceptedAnswerId": "200887",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T17:23:24.310",
"Id": "200841",
"Score": "6",
"Tags": [
"c++",
"roman-numerals"
],
"Title": "Roman_int class in C++"
} | 200841 |
<p>For some of the algorithms that I am implementing it turned out to be useful storing ids in order to iterate on objects, while also avoiding having to think about reallocation and invalidation of pointers.</p>
<p>It turned out that being able to iterate on sets of ids is something which is quite useful in general (at least to me): iterating over subsets, filtering, etc. I have made a relatively simple iterable that took care of the details for me, and that I could also use with STL algorithms.</p>
<p>I'm trying to avoid having these classes become too bulky, so I haven't tried to add all iterator methods I could have; for example, the iterator implemented could be a random-access one, but it has nowhere near the amount of stuff it should have in order to be classified as one. At the same time I'm open to adding functionality if it obviously missing and doesn't have a high line count.</p>
<p>I'm looking for any kind of comments: naming, API, performance, etc. Thanks!</p>
<pre><code>#include <utility>
#include <type_traits>
/**
* @brief This class is an iterable construct on a list of ids on a given container.
*
* This class allows to iterate over a given subset of ids on the input
* container as if they were laid out continuously in a single object.
*
* Both ids and items must be stored in containers accessible via
* square-brakets and ids.
*
* By default the iterable will copy the input ids and own them. If this is not
* desirable (maybe one wants to change the ids over time without being forced
* to copy them multiple times), the class accepts a pointer to an ids
* container, and it will automatically store a single reference to it, rather
* than doing a copy.
*
* @tparam IdsContainer The type of the input ids in the constructor.
* @tparam Container The type of the container to be iterated on.
*/
template <typename IdsContainer, typename Container>
class SubsetIterable {
public:
template <typename T>
class SubsetIterator;
using value_type = typename Container::value_type;
using iterator = SubsetIterator<typename copy_const<value_type, Container>::type>;
using const_iterator = SubsetIterator<const value_type>;
/**
* @brief The type used to contain the ids in the iterable.
*
* This is a constant copy of the input ids if we own them, and
* otherwise a const reference if we don't (and thus they can change).
*/
static constexpr bool OwnsIds = !std::is_pointer_v<IdsContainer>;
using IdsStorage = typename std::conditional<OwnsIds,
const IdsContainer,
const std::remove_pointer_t<IdsContainer> &
>::type;
/**
* @brief Basic constructor for owning iterable.
*
* This constructor stores a copy of all the ids and a reference to the
* container over which to iterate.
*
* This class and its iterators do *NOT* perform any bound checking on
* the size of the container and the input ids, neither at construction
* nor during operation.
*
* This class and its iterators *WILL* be invalidated if the item
* container is destroyed.
*
* @param ids The ids to iterate over.
* @param items The items container.
*/
template <bool Tmp = OwnsIds, typename std::enable_if_t<Tmp, int> = 0>
SubsetIterable(IdsContainer ids, Container & items) : ids_(std::move(ids)), items_(items) {}
/**
* @brief Basic constructor for non-owning iterable.
*
* This constructor stores the pointer to the ids and items over which
* to iterate.
*
* This class and its iterators do *NOT* perform any bound checking on
* the size of the container and the input ids, neither at construction
* nor during operation.
*
* This class and its iterators *WILL* be invalidated if the ids
* container or the item container are destroyed.
*
* If the ids change, all previously generated iterators are invalidated.
*
* @param ids The ids to iterate over.
* @param items The items container.
*/
template <bool Tmp = OwnsIds, typename std::enable_if_t<!Tmp, int> = 0>
SubsetIterable(IdsContainer ids, Container & items) : ids_(*ids), items_(items) {}
/**
* @brief This function returns an iterator to the beginning of this filtered range.
*/
iterator begin() { return ids_.size() ? iterator(this) : iterator(); }
/**
* @brief This function returns a const_iterator to the beginning of this filtered range.
*/
const_iterator begin() const { return cbegin(); }
/**
* @brief This function returns a const_iterator to the beginning of this filtered range.
*/
const_iterator cbegin() const { return ids_.size() ? const_iterator(this) : const_iterator(); }
/**
* @brief This function returns an iterator to the end of this filtered range.
*/
iterator end() { return iterator(); };
/**
* @brief This function returns a const_iterator to the end of this filtered range.
*/
const_iterator end() const { return cend(); }
/**
* @brief This function returns a const_iterator to the end of this filtered range.
*/
const_iterator cend() const { return const_iterator(); }
/**
* @brief This function returns the size of the range covered.
*/
size_t size() const { return ids_.size(); }
private:
friend iterator;
friend const_iterator;
// Const reference if non-owning, const value otherwise.
IdsStorage ids_;
Container & items_;
};
/**
* @brief This class is a simple iterator to iterate over filtered values held in a SubsetIterable.
*/
template <typename IdsContainer, typename Container>
template <typename T>
class SubsetIterable<IdsContainer, Container>::SubsetIterator {
private:
// The type of the SubsetIterable that defined this instance of the class
using Owner = typename copy_const<SubsetIterable<IdsContainer, Container>, T>::type;
public:
using value_type = T;
/**
* @brief Basic constructor for end iterators.
*/
SubsetIterator() : currentId_(0), parent_(nullptr) {}
/**
* @brief Basic constructor for begin iterators.
*
* @param parent The parent iterable object holding ids and values.
*/
SubsetIterator(Owner * parent) : currentId_(0), parent_(parent) {}
value_type& operator*() { return parent_->items_[parent_->ids_[currentId_]]; }
value_type* operator->() { return &(operator*()); }
/**
* @brief This function returns the equivalent item id of this iterator in its container.
*/
size_t toContainerId() const { return parent_->ids_[currentId_]; }
void operator++() {
++currentId_;
if ( currentId_ >= parent_->ids_.size() ) {
currentId_ = 0;
parent_ = nullptr;
}
}
bool operator==(const SubsetIterator & other) {
if ( parent_ == other.parent_ ) return currentId_ == other.currentId_;
return false;
}
bool operator!=(const SubsetIterator & other) { return !(*this == other); }
private:
size_t currentId_;
Owner * parent_;
};
</code></pre>
<p>Example usage:</p>
<pre><code>int main() {
std::vector<std::string> test{"abc", "cde", "lol", "lal", "foo", "baz"};
std::vector<size_t> ids{0,3,4,5};
SubsetIterable itt(ids, test);
for (const auto & s : itt)
std::cout << s << '\n';
std::cout << '\n';
SubsetIterable itt2(&ids, test);
for (const auto & s : itt2)
std::cout << s << '\n';
std::cout << '\n';
ids[0] = 1;
for (const auto & s : itt2)
std::cout << s << '\n';
std::cout << '\n';
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T19:33:16.173",
"Id": "386834",
"Score": "2",
"body": "Did you forget to include the header files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T08:08:30.010",
"Id": "386880",
"Score": "0",
... | [
{
"body": "<ol>\n<li><p>You should use default initialization for your members, see <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-in-class-initializer/\" rel=\"nofollow noreferrer\" title=\"CoreGuildlines C.45\">1</a></p>\n\n<pre><code> SubsetIterator() = default;\n...\nprivate:\n... | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T17:54:01.617",
"Id": "200843",
"Score": "5",
"Tags": [
"c++",
"iterator",
"c++17"
],
"Title": "Iterable object on set of ids"
} | 200843 |
<p>I have written a simple packet-framing class, for converting un-encoded 'packets' into encoded/delimited 'frames,' to be sent over a P2P serial connection. The functionality is based on the RFC 1662 "Point-to-Point" protocol, and the general design was inspired by the article "<a href="https://eli.thegreenplace.net/2009/08/12/framing-in-serial-communications/" rel="nofollow noreferrer">Framing in Serial Communications</a>" by Eli Bendersky.</p>
<p>One notable departure from the design in the article: this implementation has opted to use a single 'frame terminator' byte at the end, rather than separate 'begin/end' bytes.</p>
<p>The code leverages template arguments and standard iterator; users can choose to use whichever standard container is appropriate for their environment. In particular, it is an ideal utility for use in a (C++11-compatible) embedded environment - a fixed-size array with standard 'inserter' iterator support can be used.</p>
<pre><code>#pragma once
#include <cstdint>
// The simple_frame_encoding class provides packet/frame encoding and decoding, using a simple
// framing strategy with the following rules:
//
// - The end of an input packet is suffixed with the "frame separator" reserved byte.
// - Any occurrences of incidental 'reserved bytes' within the input packet are escaped:
// - The reserved byte is prefixed with the "escape" reserved byte (signaling that the next byte must be decoded).
// - The reserved byte is XOR'd using the "XOR encode" byte.
//
// When decoding, the reserve strategy is employed:
// - Append bytes to the decoded packet
// - When the 'escape' is encountered, make sure the next byte is 'decoded' (XOR) before appending
// - The frame is complete once the 'frame separator' is encountered
template<std::uint8_t FrameSeparator, std::uint8_t Escape, std::uint8_t XorEncode>
class simple_frame_encoding final {
public:
// Ensure none of the 'reserved' bytes (separator, escape) conflict with encoded versions of the same
static_assert((FrameSeparator ^ XorEncode) != FrameSeparator, "Encoded byte conflict: the encoded 'FrameSeparator' byte is equal to the unencoded 'FrameSeparator' byte");
static_assert((FrameSeparator ^ XorEncode) != Escape, "Encoded byte conflict: the encoded 'FrameSeparator' byte is equal to the unencoded 'Escape' byte");
static_assert((Escape ^ XorEncode) != FrameSeparator, "Encoded byte conflict: the encoded 'Escape' byte is equal to the unencoded 'FrameSeparator' byte");
static_assert((Escape ^ XorEncode) != Escape, "Encoded byte conflict: the encoded 'Escape' byte is equal to the unencoded 'Escape' byte");
simple_frame_encoding() = default;
~simple_frame_encoding() = default;
// Iterate over the specified packet range, encoding the contents
// and inserting the resulting 'encoded' frame bytes in the 'output' inserter.
template<typename TInputIter, typename TInserter>
void encode(TInputIter first, TInputIter last, TInserter output) {
// Append each byte to the encoded packet;
// ensure any 'reserved' bytes are XOR'd, and prepended with an escape character
while (first != last) {
if (is_reserved(*first)) {
*output++ = Escape;
*output++ = (*first ^= XorEncode);
}
else {
*output++ = *first;
}
first++;
}
// Append the frame separator, after the contents
*output++ = FrameSeparator;
}
// Frame decoding occurs over a stream of individual bytes, and tracks internal state;
// the decoder class encapsulates the current frame-decoding state into a self-contained class.
// The decoder is fed with individual 'encoded' bytes, automatically decoding
// them and inserting them into a 'decoded' packet structure, as appropriate.
class decoder {
public:
// Decode the next byte, appending the result to the output iterator.
// Return true if the packet is 'complete.'
template<typename TInserter>
bool decode_next_byte(std::uint8_t byte, TInserter output) {
// If we encounter the 'escape' byte, mark the next byte for decoding
// and return *without* appending
if (byte == Escape) {
decode_next_byte_ = true;
return false;
}
// If we encounter the 'separator' byte, then the packet is done!
// Return true and reset the state.
if (byte == FrameSeparator) {
reset();
return true;
}
// If the previous byte was an 'escape' char,
// decode this byte before adding it to the packet
if (decode_next_byte_) {
byte ^= XorEncode;
decode_next_byte_ = false;
}
// If we reach this point, simply append the byte to the packet in progress...
*output++ = byte;
return false;
}
void reset() {
decode_next_byte_ = false;
}
private:
bool decode_next_byte_ = false;
};
// Create and return an instance of a frame decoder, for the current encoding
decoder create_decoder() {
return decoder();
}
protected:
// Determine if a given byte is reserved by the FrameSeparator or Escape characters
static bool is_reserved(std::uint8_t byte) {
return byte == FrameSeparator || byte == Escape;
}
};
// Default frame encoding, effectively matching RFC 1662, the point-to-point protocol.
using default_simple_frame_encoding = simple_frame_encoding<0x7E, 0x7D, 0x20>;
</code></pre>
<p>When decoding: the <code>decode_next_packet</code> function will return <code>true</code> when the frame delimiter was found. This indicates the packet is 'complete' and should be dispatched to the next layer of application code.</p>
<p>Users are left to clear their own 'in progress' packet buffer, prior to receiving the next byte.</p>
<p>Example usage when encoding a packet to be sent over the wire:</p>
<pre><code>auto packet = vector<uint8_t>{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
vector<uint8_t> frame;
auto encoding = default_simple_frame_encoding();
encoding.encode(begin(packet), end(packet), back_inserter(frame));
serialPort.send(frame);
</code></pre>
<p>Example usage, when receiving a stream of frame-encoded bytes:</p>
<pre><code>auto encoding = default_simple_frame_encoding();
auto decoder = encoding.create_decoder();
uint8_t nextByte = 0;
static_buffer packet;
while (serialPort.waitNextByte(nextByte)) {
if(decoder.decode_next_byte(nextByte, back_inserter(packet)) {
dispatch_completed_packet(packet);
packet.clear();
}
}
</code></pre>
<p>I am looking for any and all criticisms on style, efficiency, reusability, and readability.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T18:21:04.653",
"Id": "200846",
"Score": "1",
"Tags": [
"c++",
"c++11",
"template",
"serialization",
"serial-port"
],
"Title": "A simple and efficient packet frame encoder/decoder"
} | 200846 |
<p>I was given a question during interview, and I decided to code it up and learn the difference way to implement this problem. Find the Maximum Sum of a Contiguous Subsequence in a List. I was wondering if you can code review the different ways of solving this problem. </p>
<p>Given a list consisting of both positive and negative integers, find the maximum sum among all the contiguous subsequences of the input list.
Write a function that takes in a list of integers and returns the maximum sum.</p>
<pre><code># Example: input = [6, -1, 3, 5, -10]
# output = 13 (6 + -1 + 3 + 5 = 13)
</code></pre>
<p>another example.</p>
<pre><code>#maxSubArraySum([-1,-2,3,4,5]) ==> 12
#maxSubArraySum([1,2,3,-2,5]) ==> 9
</code></pre>
<p>my first solution </p>
<pre><code>def maxSubArraySum(arr):
max_so_far =arr[0]
curr_max = arr[0]
for i in range(1,len(arr)):
curr_max = max(arr[i], curr_max + arr[i])
max_so_far = max(max_so_far,curr_max)
return max_so_far
# Driver function to check the above function
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print"Maximum contiguous sum is" , maxSubArraySum(a)
</code></pre>
<p>my second solution
Dynamic programming solution</p>
<pre><code>def maxSubArraySum(nums):
if not nums: return 0
n = len(nums)
s = [0] * n
res, s, s_pre = nums[0], nums[0], nums[0]
for i in xrange(1, n):
s = max(nums[i], s_pre + nums[i])
s_pre = s
res = max(res, s)
return res
</code></pre>
<p>it passes all the test </p>
<pre><code># input: count {List} - keeps track out how many tests pass and how many total
# in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
# indicating if test passed
# output: {None}
def expect(count, name, test):
if (count is None or not isinstance(count, list) or len(count) != 2):
count = [0, 0]
else:
count[1] += 1
result = 'false'
error_msg = None
try:
if test():
result = ' true'
count[0] += 1
except Exception as err:
error_msg = str(err)
print(' ' + (str(count[1]) + ') ') + result + ' : ' + name)
if error_msg is not None:
print(' ' + error_msg + '\n')
print('max_consecutive_sum Tests')
test_count = [0, 0]
def test():
example = max_consecutive_sum([6, -1, 3, 5, -10])
return example == 13
expect(test_count, 'should work on example input', test)
def test():
example = max_consecutive_sum([5])
return example == 5
expect(test_count, 'should work on single-element input', test)
def test():
example = max_consecutive_sum([])
return example == 0
expect(test_count, 'should return 0 for empty input', test)
def test():
example = max_consecutive_sum([-1, 1, -3, 4, -1, 2, 1, -5, 4])
return example == 6
expect(test_count, 'should work on longer input', test)
print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')
</code></pre>
<blockquote>
<pre><code>max_consecutive_sum Tests
1) true : should work on example input
2) true : should work on single-element input
3) true : should return 0 for empty input
4) true : should work on longer input
PASSED: 4 / 4
</code></pre>
</blockquote>
| [] | [
{
"body": "<p>The first solution is quite fine, with minor issues:</p>\n\n<ul>\n<li>It doesn't support empty list</li>\n<li>Instead of <code>for i in range(1,len(arr)):</code>, it would be simpler to <code>for value in arr[1:]:</code></li>\n<li>Formatting and function naming doesn't follow <a href=\"http://www.... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T18:26:57.087",
"Id": "200848",
"Score": "1",
"Tags": [
"python"
],
"Title": "Find the Maximum Sum of a Contiguous Subsequence in a List"
} | 200848 |
<p>I have a need to take in a payload that looks like this:</p>
<pre><code>{
"Registry":[
{"Token":"@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","ProcessId":"1"},
{"Token":"@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","ProcessId":"2"},
{"Token":"@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","ProcessId":"3"}
]
}
</code></pre>
<p>Read each record and remove the "@!!!@" and then search the database for the value (represented by xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx). This is web api 2.0. The return payload should look like this:</p>
<pre><code>{
"Registry": [{
"ProcessId": "1",
"Code": 200,
"Value": "Test",
"Token": "@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ProcessId": "2",
"Code": 404,
"Message": "Could not resolve token.",
"Token": "@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"ProcessId": "3",
"Code": 200,
"Message": "Test2",
"Token": "@!!!@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}]
}
</code></pre>
<p>If a "process id" is provided return that same number with the return record if not provided return a unique process id "counter". </p>
<p>I have a service that is handling this on an exposed API controller and it seems to work rather quickly but I feel as if it is written poorly. This is what I have so far:</p>
<pre><code> [Route("get")]
[HttpPost]
public async Task<HttpResponseMessage> GetPIIRegistry([FromBody] JObject registryArry)
{
ReturnCodes.UsedCodes = new List<int>();
JArray registryArray = null;
registryArray = (JArray)registryArry["Registry"];
var payloadTokens = registryArray.Values("Token");
int processIdCounter = 1;
HttpResponseMessage response;
List<string> values = new List<string>();
foreach (var item in payloadTokens)
{
values.Add(item.ToString().Contains("@!!!@") ? item.ToString().Replace("@!!!@", "") : item.ToString());
}
List<REGISTRY> returnVals = new List<REGISTRY>();
using (var dataContext = new registryEntries())
{
dataContext.Configuration.AutoDetectChangesEnabled = false;
var query =
from registries in dataContext.REGISTRies
where values.Contains(registries.Token)
select registries;
returnVals = query.ToList();
}
JArray returnObjects = new JArray();
foreach (JObject registryObj in registryArray)
{
var returnObj = new JObject();
var resultSet = returnVals.Where("Token.Equals(@0)", registryObj["Token"].ToString().Replace("@!!!@",""));
if (resultSet.Count() > 0)
{
foreach (var item in resultSet)
{
returnObj = new JObject();
if(registryObj["ProcessId"] != null)
{
if (string.IsNullOrEmpty(registryObj["ProcessId"].ToString()))
{
returnObj["ProcessId"] = processIdCounter.ToString();
}
else
{
returnObj["ProcessId"] = registryObj["ProcessId"];
}
}
else
{
returnObj["ProcessId"] = processIdCounter.ToString();
}
if (item.Remote == 0)
{
returnObj["Code"] = ReturnCodes.OK;
returnObj["Value"] = item.Value;
returnObj["Token"] = "@!!!@" + item.Token;
returnObj["Remote"] = item.Remote;
if(!ReturnCodes.UsedCodes.Contains(ReturnCodes.OK)) ReturnCodes.UsedCodes.Add(ReturnCodes.OK);
}
else
{
//remote get not enabled
returnObj["Code"] = ReturnCodes.NotFound;
returnObj["Message"] = "Remote service not implemented. No matching values found.";
returnObj["Token"] = "@!!!@"+item.Token;
if (!ReturnCodes.UsedCodes.Contains(ReturnCodes.NotFound)) ReturnCodes.UsedCodes.Add(ReturnCodes.NotFound);
}
returnObjects.Add(returnObj);
}
}
else
{
if (registryObj["ProcessId"] != null)
{
if (string.IsNullOrEmpty(registryObj["ProcessId"].ToString()))
{
returnObj["ProcessId"] = processIdCounter.ToString();
}
else
{
returnObj["ProcessId"] = registryObj["ProcessId"];
}
}
else
{
returnObj["ProcessId"] = processIdCounter.ToString();
}
returnObj["Code"] = ReturnCodes.NotFound;
returnObj["Message"] = "Provided token produced no matches.";
returnObj["Token"] = "@!!!@"+registryObj["Token"].ToString().Replace("@!!!@","");
returnObjects.Add(returnObj);
if (!ReturnCodes.UsedCodes.Contains(ReturnCodes.NotFound)) ReturnCodes.UsedCodes.Add(ReturnCodes.NotFound);
}
processIdCounter++;
}
var returns = returnObjects.ToString();
returns = "{Registry:" + returns + "}";
var json = JObject.Parse(returns);
if (ReturnCodes.UsedCodes.Count() > 1)
{
response = Request.CreateResponse((HttpStatusCode)ReturnCodes.MultiStatus, json);
}
else
{
try
{
response = Request.CreateResponse((HttpStatusCode)200, json);
}
catch
{
response = Request.CreateResponse((HttpStatusCode)ReturnCodes.Error, json);
}
}
return response;
}
</code></pre>
<p>Any thoughts on how to clean this up?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T19:13:11.700",
"Id": "200851",
"Score": "2",
"Tags": [
"json",
"asp.net-web-api",
"json.net"
],
"Title": "Looping JSON to get matching values from Database"
} | 200851 |
<p>I was trying to solve this problem called lattice path from Project Euler:</p>
<blockquote>
<p>Count the number of unique paths to travel from the top left to the bottom right of a lattice of squares.</p>
</blockquote>
<p>How many such routes are there through a 20×20 grid? It takes me forever to get an answer...</p>
<p><a href="https://i.stack.imgur.com/dw8Pc.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dw8Pc.gif" alt="https://projecteuler.net/project/images/p015.gif"></a><br>
<sub>(source: <a href="https://projecteuler.net/project/images/p015.gif" rel="nofollow noreferrer">projecteuler.net</a>)</sub> </p>
<blockquote>
<pre><code> # Input: An interger N (which is the size of the lattice)
# Output: An interger (which represents the number of unique paths)
#
# Example: input: 2
#
# (2 x 2 lattice of squares)
# __ __
# |__|__|
# |__|__|
#
</code></pre>
</blockquote>
<p>When moving through the lattice, you can only move either down or to the right.</p>
<p>I currently have 1 solution, and I am not sure how much better if we memoize it. But I wanted to ask for code review for my solution below:</p>
<pre><code>def lattice_paths(m, n):
if m == 0 and n == 0:
return 1
if m < 0 or n < 0:
return 0
return lattice_paths(m - 1, n) + lattice_paths(m, n - 1)
Here is the time complexity and space complexity of my first solution.
# Time Complexity: O(2^(M+N))
# Auxiliary Space Complexity: O(M+N)
</code></pre>
<p>Dynamic approach with the memorized solution:</p>
<pre><code>def lattice_paths(m, n): # m rows and n columns
def helper(x, y):
if x > helper.m or y > helper.n:
return 0
if helper.cache.get((x, y)) is not None:
return helper.cache[(x, y)]
helper.cache[(x, y)] = helper(x + 1, y) + helper(x, y + 1)
return helper.cache[(x, y)]
helper.cache = {}
helper.m = m
helper.n = n
helper(0,0)
if m == 0 and n == 0:
return 1
elif m < 0 or n < 0:
return 0
else:
return helper.cache[(0, 0)]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T21:44:33.057",
"Id": "386851",
"Score": "1",
"body": "That's more of a mathematics and algorithm problem than a coding one. Check out this [excellent blog post](http://code.jasonbhill.com/python/project-euler-problem-15/)"
}
] | [
{
"body": "<p>here's a solution that uses cache to memoize the solution</p>\n\n<pre><code>def lattice_paths(m, n):\n cache = [1]\n larger = max(m, n)\n smaller = min(m, n)\n while(len(cache) < larger + 1):\n for i in range(1, len(cache)):\n cache[i] += cache[i - 1]\n cach... | {
"AcceptedAnswerId": "200921",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T20:03:51.303",
"Id": "200855",
"Score": "0",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"combinatorics"
],
"Title": "Lattice path from Project Euler with Python solution"
} | 200855 |
<p>This game has 4 people moving randomly, one unit in one of the four directions (up, down, left, right), with a fifth person as a designated tagger. If this fifth person tags someone, the person is out. Game ends when there is one survivor left.</p>
<pre><code>import random
class Player:
def __init__(self, name, status, speed, health, position):
self.name = name
self.status = status
self.speed = speed
self.health = health
self.position = position
def move(self, arena_limits, player_pos):
change = {"left": -1, "right": 1, "up": 1, "down": -1}
direction = random.choice(list(change.keys()))
if not self.is_stuck(arena_limits, player_pos):
if direction in ("left", "right"):
in_limits = 0 <= self.position[0] + (change[direction] * self.speed) <= arena_limits[0]
if in_limits and [self.position[0] + (change[direction] * self.speed), self.position[1]] not in player_pos:
self.position[0] += change[direction] * self.speed
else:
self.move(arena_limits, player_pos)
if direction in ("up", "down"):
in_limits = 0 <= self.position[1] + (change[direction] * self.speed) <= arena_limits[0]
if in_limits and [self.position[0], self.position[1] + (change[direction] * self.speed)] not in player_pos:
self.position[1] += change[direction] * self.speed
else:
self.move(arena_limits, player_pos)
else:
pass
def is_stuck(self, arena_limits, player_pos):
can_go_left = ([self.position[0] + (-1 * self.speed), self.position[1]] not in player_pos) and \
0 <= self.position[0] + (-1 * self.speed) <= arena_limits[0]
can_go_right = ([self.position[0] + (1 * self.speed), self.position[1]] not in player_pos) and \
0 <= self.position[0] + (1 * self.speed) <= arena_limits[0]
can_go_up = ([self.position[0], self.position[1] + (1 * self.speed)] not in player_pos) and \
0 <= self.position[1] + (1 * self.speed) <= arena_limits[1]
can_go_down = ([self.position[0], self.position[1] + (-1 * self.speed)] not in player_pos) and \
0 <= self.position[1] + (-1 * self.speed) <= arena_limits[1]
if not (can_go_up or can_go_down or can_go_left or can_go_right):
return True
else:
return False
def tag(self, player_list):
if self.status == "IT":
done = False
turns = 0
while not done:
turns += 1
player_pos = [user.position for user in player_list] + [self.position]
for player in player_list:
player.move([8, 8], player_pos)
above_or_under = player.position[0] in (self.position[0] + 1, self.position[0] - 1)
left_or_right = player.position[1] in (self.position[1] + 1, self.position[1] - 1)
if above_or_under or left_or_right:
del player_list[player_list.index(player)]
print(player.name + " has been eliminated after " + str(turns) + " turn(s)!")
if len(player_list) == 1:
print(player_list[0].name + " is the winner!")
print("-" * 20)
done = True
self.move([8, 8], player_pos)
tagger = Player("TAGGER", "IT", 1, 0, [8, 8])
for b in range(10000):
victims = []
for i in range(4):
victims.append(Player("Player" + str(i), "", 1, 0, [random.randint(0, 6), random.randint(0, 6)]))
tagger.tag(victims)
</code></pre>
<p>Some quick comments about the code:</p>
<ul>
<li>Comments will be added to my code soon</li>
<li><code>self.health</code> is currently not used but is planned on being used</li>
<li>The field is <code>8x8</code> and each person can move once in one of the four directions. If they are stuck <code>is_stuck()</code>, they will simply not move</li>
<li>A player is out if they are directly above, next to, or below the tagger. Diagonally does not count</li>
</ul>
<p>Main question here, can I shorten the code and can I make it more Pythonic?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T07:05:40.733",
"Id": "386871",
"Score": "0",
"body": "You said that `health` is reserved for future improvements, but there is no real point in having `speed` either. Do you plan to use different values in the future too?"
},
{
... | [
{
"body": "<h2>Buggy game mechanics</h2>\n\n<p>Your program reports \"Player<i>p</i> has been eliminated after <i>t</i> turn(s)!\", but without any visual confirmation, so you're blindly trusting that the logic is correct. But is it?</p>\n\n<p>If I do add a visualization, then I see bizarre things like this ha... | {
"AcceptedAnswerId": "200871",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-02T21:29:45.580",
"Id": "200857",
"Score": "7",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"simulation"
],
"Title": "A game of automated tag"
} | 200857 |
<p>I've created a program that translates any word into the form of igpay atinlay or pig Latin!</p>
<p>I got the project idea from <a href="https://www.dreamincode.net/forums/topic/78802-martyr2s-mega-project-ideas-list/" rel="nofollow noreferrer">here</a> and you can read the <strong>rules</strong> <a href="https://en.wikipedia.org/wiki/Pig_Latin" rel="nofollow noreferrer">here</a>.</p>
<p>My program outputs the same translation as in the rules section in the link above, except for the word "always". It isn't really a big deal as the program translates almost any word correctly.</p>
<pre><code>package pigLatin;
import java.util.Scanner;
public class PigLatin
{
String str;
Scanner scan = new Scanner(System.in);
char firstVow;
char secondVow;
int i;
public void init()
{
str = scan.next();
i = 0; //beginning of a string
if (str.length() <= 3 && (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u'))
{
System.out.println(str + "ay");
scan.close();
}
else if (str.length() > 3 && (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')) {
firstVow = str.charAt(i);
i = 1;
while (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')
{
i++;
if (i == str.length() - 1 && (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')) {
System.out.println(str + "ay");
break;
} else if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
secondVow = str.charAt(i);
//issues arise if the first vowel is equal to the second one
if (firstVow != secondVow) {
System.out.print(str.substring(str.indexOf(secondVow), str.length()));
System.out.print(str.substring(str.indexOf(firstVow), str.indexOf(secondVow)));
System.out.println("ay");
break;
} else if (firstVow == secondVow) {
System.out.print(str.substring(2));
System.out.print(firstVow);
System.out.print(str.charAt(1));
System.out.print("ay");
break;
}
scan.close();
}
}
//checks for words that begin with consonants
} else {
i = 0;
while (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')
{
i++;
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
firstVow = str.charAt(i);
System.out.print(str.substring(str.indexOf(firstVow), str.length()) + str.substring(0, str.indexOf(firstVow)) + "ay");
break;
}
}
}
scan.close();
}
public static void main(String[] args) {
new PigLatin().init();
}
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Your leading whitespace is much smaller than is typical. Prefer 4 spaces for a level of indent.</p></li>\n<li><p>In java we typically put the curly brace <code>{</code> on the same line. If you insist on doing it on a new line, do it consistently (<code>main</code>) and don't add a blank... | {
"AcceptedAnswerId": "200919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T00:29:45.667",
"Id": "200859",
"Score": "5",
"Tags": [
"java",
"beginner",
"programming-challenge",
"pig-latin"
],
"Title": "Pig Latin Anslatortray"
} | 200859 |
<p>I have decided to rewrite what I did <a href="https://codereview.stackexchange.com/questions/195423/creating-a-generic-single-linked-list-follow-up">here</a>, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate. </p>
<p>I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community in their effort in evaluating my code, I really appreciate it and I believe it is slowly but surely taking my coding skills to the next level.</p>
<p>Here is my header file:</p>
<pre><code>#ifndef SingleLinkedList_h
#define SingleLinkedList_h
#include <iostream>
template <class T>
class SingleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
Node(T x) : data(x), next(nullptr) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
// This function is for the overloaded operator <<
void display(std::ostream &str) const {
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
str << "\n";
}
public:
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
// Rule of 5
SingleLinkedList(SingleLinkedList &&move) noexcept; // move constructor
SingleLinkedList& operator=(SingleLinkedList &&move) noexcept; // move assignment operator
~SingleLinkedList();
// Overload operators
SingleLinkedList& operator=(SingleLinkedList const &rhs);
friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
data.display(str);
return str;
}
// Memeber functions
void swap(SingleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int getSize() const;
void push(const T &theData);
void push(T &&theData);
void display() const;
void insertHead(const T &theData);
void insertTail(const T &theData);
void insertPosition(int pos, const T &theData);
void deleteHead();
void deleteTail();
void deleteSpecific(int delValue);
bool search(const T &x);
};
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
for(Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push(loop->data);
}
}
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
while (head != nullptr) {
deleteHead();
}
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int SingleLinkedList<T>::getSize() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
void SingleLinkedList<T>::push(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (head == nullptr) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push(T &&thedata) {
std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));
if (head == nullptr) {
head = std::move(newnode);
tail = head.get();
}
else {
tail->next = std::move(newnode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::display() const {
Node* newNode = head.get();
while (newNode != nullptr) {
std::cout << newNode->data << "\t";
newNode = newNode->next;
}
}
template <class T>
void SingleLinkedList<T>::insertHead(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
}
template <class T>
void SingleLinkedList<T>::insertTail(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
tail->next = std::move(newNode);
tail = tail->next.get();
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
if (pos > getSize() || pos < 0) {
throw std::out_of_range("The insert location is invalid.");
}
auto node = head.get();
int i = 0;
for (; node && node->next && i < pos; node = node->next.get(), i++);
if (i != pos) {
throw std::out_of_range("Parameter 'pos' is out of range.");
}
auto newNode = std::make_unique<Node>(theData);
if (node) {
newNode->next = std::move(node->next);
node->next = std::move(newNode);
}
else {
head = std::move(newNode);
}
}
template <class T>
void SingleLinkedList<T>::deleteHead() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
auto next = std::move(current->next);
head = std::move(next);
}
template <class T>
void SingleLinkedList<T>::deleteTail() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
Node* previous = nullptr;
while (current->next != nullptr) {
previous = current;
current = current->next.get();
}
tail = previous;
previous->next = nullptr;
}
template <class T>
void SingleLinkedList<T>::deleteSpecific(int delValue) {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto temp1 = head.get();
Node* temp2 = nullptr;
while (temp1->data != delValue) {
if (temp1->next == nullptr) {
throw std::invalid_argument("Given node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1->next.get();
}
temp2->next = std::move(temp1->next);
}
template <class T>
bool SingleLinkedList<T>::search(const T &x) {
auto current = head.get();
while (current != nullptr) {
if (current->data == x) {
return true;
}
current = current->next.get();
}
return false;
}
#endif /* SingleLinkedList_h*/
</code></pre>
<p>Here is the main.cpp file:</p>
<pre><code>#include <algorithm>
#include <cassert>
#include <iostream>
#include <ostream>
#include <iosfwd>
#include "SingleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Single Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
SingleLinkedList<int> obj;
obj.push(2);
obj.push(4);
obj.push(6);
obj.push(8);
obj.push(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-----------------Inserting At End-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertTail(20);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertHead(50);
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << std::endl;
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.getSize() << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteHead();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteTail();
std::cout << obj << std::endl;
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteSpecific(4);
std::cout << obj << std::endl;
std::cout << std::endl;
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
SingleLinkedList<int> obj1 = obj;
std::cout << obj1 << std::endl;
//std::cout << "\n-------------------------------------------------------------------------\n";
//std::cout << "--------------Testing to insert in an empty list----------------------------";
//std::cout << "\n-------------------------------------------------------------------------\n";
//SingleLinkedList<int> obj2;
//obj2.insertPosition(5, 60);
//std::cout << obj2 << std::endl;
std::cin.get();
}
</code></pre>
| [] | [
{
"body": "<p>Your header file shouldn't require other headers to be included first. You are missing includes of <code><memory></code> and <code><utility></code> for it to be usable. You can help yourself spot such omissions by including your own headers first, before the standard library headers,... | {
"AcceptedAnswerId": "200914",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T01:13:26.480",
"Id": "200861",
"Score": "5",
"Tags": [
"c++",
"linked-list"
],
"Title": "Generic Single Linked List using smart pointers"
} | 200861 |
<p>I wrote this function to map value to a color</p>
<p>I am looking for some general feedback on how I can improve the efficiency of the function. and if there is better way to do it.</p>
<pre><code>function getColor($value, $values_range, $opacity = '0.7') {
$deltaS = ($values_range['max'] - $values_range['min']) / 2;
$ds = ($value - $values_range['min']) / $deltaS;
$nearest_color_index = floor($ds);
$alpha = $ds - $nearest_color_index;
$r = $g = $b = -1;
$colors = [['r'=>255,'g' => 60,'b' => 40],
['r' => 255,'g' => 247,'b' =>40],
['r' => 12,'g' => 197,'b' => 17]];
if ($nearest_color_index != 2) {
$r = round($colors[$nearest_color_index]['r'] + $alpha * ($colors[$nearest_color_index + 1]['r'] - $colors[$nearest_color_index]['r']));
$g = round($colors[$nearest_color_index]['g'] + ($alpha * ($colors[$nearest_color_index + 1]['g'] - $colors[$nearest_color_index]['g'])));
$b = round($colors[$nearest_color_index]['b'] + $alpha * ($colors[$nearest_color_index + 1]['b'] - $colors[$nearest_color_index]['b']));
return "rgba($r,$g,$b,$opacity)";
} else {
$r = round($colors[$nearest_color_index]['r']);
$g = round($colors[$nearest_color_index]['g']);
$b = round($colors[$nearest_color_index]['b']);
return "rgba($r,$g,$b,$opacity)";
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T22:17:05.130",
"Id": "387019",
"Score": "0",
"body": "is this in a class or purely functional ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-04T00:20:07.380",
"Id": "387027",
"Score": "0",
... | [
{
"body": "<h2>Function name</h2>\n\n<p>The function name <code>getColor</code> isn't representative of what it does its better of being named <code>createRgbaString</code> (or something along those lines) </p>\n\n<h2>Return early</h2>\n\n<p>Your script returns in two different places, this should be changed so... | {
"AcceptedAnswerId": "200944",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T02:43:09.847",
"Id": "200864",
"Score": "1",
"Tags": [
"performance",
"php",
"algorithm"
],
"Title": "Map value to color rgba"
} | 200864 |
<p>I created a small Python utility to analyze multiple same-size files and report on the difference byte-by-byte (i.e. <a href="https://en.wikipedia.org/wiki/Hamming_distance" rel="nofollow noreferrer">Hamming distance</a>, not <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshtein distance</a>.) I am planning to extend the capabilities to allow a GUI display. Mostly, I'm interested in scalability and usability, with efficiency still being a high priority. I've already examined <a href="https://codereview.stackexchange.com/questions/171003/python-code-that-compares-two-files-byte-by-byte">Python code that compares two files byte by byte</a> and <a href="https://codereview.stackexchange.com/search?q=%5Bpython%5D+file+differences">other similar questions</a>, but none seem to involve the same type of analysis for the purpose of reporting on differences.</p>
<p>Specifically, I'm interested in two details:</p>
<ol>
<li><p>Is there anything else I should consider in my <code>Difference</code> container structure and its handling?</p></li>
<li><p>Are there any downsides to my frequent use of generators? I tried to let it cycle through each difference via generator, minimizing memory usage, but I think that also has a few performance implications.</p></li>
</ol>
<hr>
<pre><code>import os
import os.path
from enum import IntEnum
from collections import defaultdict
def compare_iterator_elements(lst, f=lambda x: x):
'''Returns true if all the elements of an iterator are true, else returns false.'''
try:
first = f(next(lst))
for i in lst:
if first != f(i):
return False
return True
except StopIteration:
return True
# Source: https://stackoverflow.com/a/312464
def chunks(l, n):
'''Yield successive n-sized chunks from l. If len(l) is not divisible by n, the last chunk will be len(l) % n sized.'''
for i in range(0, len(l), n):
yield l[i:i + n]
class Settings:
'''Container class for difference formatting options.'''
class Separation(IntEnum):
CLUMPED = 0
WIDTH_BROKEN = 1
BLOCK_SEPARATED = 2
separation = Separation.BLOCK_SEPARATED
block_width = 0x10
# Planned future settings:
# byte_group = 1
# big_endian_groups = True
# align_offset = 0
class Difference():
'''Dictionary wrapper representing the difference at a specific point in a file.'''
def __init__(self, difference, start):
self.difference = difference
self.start = start
def extend(self, other):
if other.start < self.start:
raise ValueError(f'Differences can only be extended to differences with larger start values ({other.start} < {other.start}).')
blank_width = other.start - (self.start + len(self))
if blank_width < 0:
raise ValueError(f'Extending to an overlapping Difference is not allowed.')
for file, v in self.difference.items():
v += [' '] * blank_width + other.difference[file]
def __len__(self):
return len(next(iter(self.difference.values())))
def __getitem__(self, value):
difference = {k: v[value] for k,v in self.difference.items()}
if isinstance(value, slice):
return Difference(difference, self.start + (value.start if value.start else 0))
else:
return Difference(difference, self.start + value)
def _cli_difference(differences, start, settings):
'''Outputs a difference in the command line.'''
name_width = settings.name_width
start_display = hex(start)[:-1] + 'X' if settings.separation > settings.Separation.CLUMPED else hex(start)
print(f'{start_display.rjust(name_width)}:', end='')
if settings.separation > settings.Separation.CLUMPED:
print(' ' + ''.join((f' {i:x}' for i in range(settings.block_width))), end='')
print()
offset = start % settings.block_width
for file_name, b in differences.items():
print(f'{file_name.rjust(name_width)}: ', end='')
if settings.separation > settings.Separation.CLUMPED:
print(' ' * offset,
''.join(b[:settings.block_width - offset]),
sep='', end='')
for line in chunks(b[settings.block_width - offset:], settings.block_width):
print('\n', ' ' * (name_width + 2), *line, sep='', end='')
print()
else:
print(''.join(b))
print()
def _separate_line_by_line(differences, settings):
'''Generator function that separates and combines differences into fixed width blocks.'''
current = next(differences)
try:
while True:
offset = current.start % settings.block_width
if offset + len(current) > settings.block_width:
next_block = settings.block_width - offset
yield current[:next_block]
current = current[next_block:]
else:
next_diff = next(differences)
block_start = current.start - offset
if next_diff.start in range(block_start, block_start+settings.block_width):
current.extend(next_diff)
else:
yield current
current = next_diff
except StopIteration:
yield current
def report_cli_differences(differences, settings):
'''Outputs an iterable of differences in the command line.'''
print('Differences:\n')
if settings.separation == Settings.Separation.BLOCK_SEPARATED:
differences = _separate_line_by_line(differences, settings)
for diff in differences:
_cli_difference(diff.difference, diff.start, settings)
print('End of differences.')
def compare_files(file_args, difference_mask):
'''Generator function that returns Difference objects for each aligned difference in same size files.'''
if not compare_iterator_elements(iter(file_args), os.path.getsize):
raise ValueError('The file sizes must be equal.')
files = [open(file_name, 'rb') for file_name in file_args]
while True:
comparison = {f.name: f.read(1) for f in files}
if not list(comparison.values())[0]:
break
bytes_different = lambda: not compare_iterator_elements(iter(comparison.values())) and compare_iterator_elements((comparison[file_name] for file_name in difference_mask))
if bytes_different():
start = files[0].tell()
different_bytes = defaultdict(list)
while True:
for file_name, b in comparison.items():
different_bytes[file_name].append(f'{ord(b):0>2x}')
comparison = {f.name: f.read(1) for f in files}
if not bytes_different():
break
yield Difference(different_bytes, start)
for f in files:
f.close()
if __name__ == '__main__':
import argparse
arg_parser = argparse.ArgumentParser(description='Compares two files for differences.')
arg_parser.add_argument('files', metavar='files', nargs='+', default=[f for f in os.listdir() if os.path.isfile(f)], help='file names to compare')
arg_parser.add_argument('--separation', default=2, type = int, help='Specifies the level of difference separation. 0 is no separation, 1 is carriage returns after every block, and 2 separates every new block into a new comparison.')
arg_parser.add_argument('--ignored_diff', metavar='FILES', nargs='+', help='For the purpose of reporting on differences, ignore the positions where differences occur between the given files.', default=[])
args = arg_parser.parse_args()
file_args = args.files
settings = Settings()
settings.separation = Settings.Separation(args.separation)
ignore_differences = args.ignored_diff
settings.name_width = max(len(str(os.path.getsize(file_args[0]))),
*(len(file_name) for file_name in file_args))
report_cli_differences(compare_files(file_args,
ignore_differences), settings)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T03:03:14.067",
"Id": "200867",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "Comparing same-size files and reporting on the differences byte-by-byte"
} | 200867 |
<pre><code>open class Heap<T>: Iterable<Heap.Data<T>> {
data class Data<T>(val item: T, var priority: Int) {
operator fun compareTo(other:Data<T>): Int {
return priority - other.priority
}
}
protected var positions = mutableMapOf<T, Int>()
protected var data: Array<Data<T>?>
protected var heap_size:Int = 0
override fun iterator(): Iterator<Heap.Data<T>> {
return object : Iterator<Heap.Data<T>> {
var index = 0
override fun hasNext() = index < heap_size
override fun next() = data[index++]!!
}
}
constructor() {
data = arrayOfNulls(1)
}
private fun swap(a:Int, b:Int) {
val tmp = data[a]
data[a] = data[b]
data[b] = tmp
positions[data[a]!!.item] = a
positions[data[b]!!.item] = b
}
private fun left(root: Int) = (2 * root) + 1
private fun right(root: Int) = (2 * root) + 2
private fun parent(root: Int) = (root - 1) / 2
fun insert(item: T, priority: Int) {
insert(Data(item, priority))
}
protected fun insert(item: Data<T>) {
if (heap_size == data.size)
data = resize_arr(data.size * 2)
var index = heap_size
change_val(index, item)
heap_size++
}
protected fun change_val(root: Int, new_val: Data<T>) {
data[root] = new_val
var index = root
if (index != 0) {
while (index != 0 && data[parent(index)]!! > data[index]!!) {
swap(parent(index), index)
index = parent(index)
}
} else
positions[new_val.item] = root
}
fun pop(): Data<T>? {
if (heap_size == 1)
return data[--heap_size]!!
if (heap_size == data.size / 4) {
val new_size = if (data.size / 2 == 0) 2 else data.size / 2
data = resize_arr(new_size)
}
val root = data[0]
data[0] = data[heap_size - 1]
heap_size--
heapify(0)
return root
}
private fun resize_arr(new_size: Int): Array<Data<T>?> {
val new_arr = arrayOfNulls<Data<T>>(new_size)
var index = 0
while (index < heap_size) {
new_arr[index] = data[index]
index++
}
return new_arr
}
protected fun heapify(root: Int) {
var left:Int
var right:Int
var min = root
var _root = root
while (true) {
left = left(_root)
right = right(_root)
if (left < heap_size && data[left]!! < data[_root]!!)
min = left
if (right < heap_size && data[right]!! < data[min]!!)
min = right
if (min != _root) {
swap(min, _root)
_root = min
min = _root
continue
}
break
}
}
fun change_priority(item: T, new_priority: Int) {
val tmp = data[positions[item]!!]!!
tmp.priority = new_priority
data[positions[item]!!] = data[heap_size - 1]
data[heap_size - 1] = null
heap_size--
heapify(positions[item]!!)
insert(tmp)
}
}
fun main(args:Array<String>) {
val min_heap = Heap<String>()
min_heap.insert("A", 5)
min_heap.insert("B", 6)
min_heap.insert("C", 7)
min_heap.change_priority("A", 8)
min_heap.change_priority("C", 1)
min_heap.insert("D", 0)
println(min_heap.pop())
println(min_heap.pop())
println(min_heap.pop())
println(min_heap.pop())
}
</code></pre>
<p>output is:</p>
<pre><code>Data(item=D, priority=0)
Data(item=C, priority=1)
Data(item=B, priority=6)
Data(item=A, priority=8)
</code></pre>
<p>Am I doing this right?
is this implementation bad?
any helpful tips and tricks for this newbie?</p>
<p>I wanted to implement a PriorityQueue that you can change values with.</p>
<p>and this is my attempt at it. any feedback would be great</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T06:32:27.760",
"Id": "200869",
"Score": "1",
"Tags": [
"algorithm",
"kotlin"
],
"Title": "Dynamic Priority Heap - Kotlin"
} | 200869 |
<p>I've made a useful PowerShell script to automate our code deployments to Salesforce. After a couple of afternoons learning PS and some try/error, I finished my script and it's working.</p>
<p>Nonetheless, since it's my first long PS script I was hoping you guys could tip me in how I could do things better, make the script more readable, etc. I'm used to OOP, but this is a whole different story from what I've seen lol</p>
<p>Just as a quick introduction, what the code does is:</p>
<ol>
<li><p>Validates that the repository I want to deploy to a Salesforce org has a package.xml (a file which enumerates what I'm going to deploy, like a check list)</p></li>
<li><p>Authenticates against Salesforce</p></li>
<li><p>Deploys all the repository and polls the server to update the status in the console</p></li>
<li><p>Runs the test and keeps polling to update the visual status</p></li>
<li><p>Reacts to deployment/test errors by printing them on the console</p></li>
</ol>
<p>In order to achieve this I used the <a href="https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/" rel="nofollow noreferrer">sfdx CLI</a> which Salesforce provides, so it did save me a LOT of time.</p>
<pre><code>param([string] $repositoryDirectory, [bool] $isProduction)
Write-Host -ForegroundColor green ":: Validating Repository ::"
$srcDirectory = [System.IO.Path]::Combine($repositoryDirectory, "src")
if(![System.IO.File]::Exists([System.IO.Path]::Combine($srcDirectory,"package.xml"))) {
Write-Host -ForegroundColor red "ERROR: package.xml not found in the ./src directory."
exit
}
Write-Host -ForegroundColor green "`n:: Authenticating to Salesforce ::"
if($isProduction) {
sfdx force:auth:web:login -s -r "https://login.salesforce.com"
}
else {
sfdx force:auth:web:login -s -r "https://test.salesforce.com"
}
Write-Host -ForegroundColor green "`n:: Deploying source code ::"
$deployJob = sfdx force:mdapi:deploy -d $srcDirectory -l "RunLocalTests" --json | ConvertFrom-Json
$deployJobId = $deployJob.result.id
$startedTests = $false
do {
$report = sfdx force:mdapi:deploy:report -i $deployJobId --json --verbose 2>&1 | ConvertFrom-Json
if($null -eq $report) {
continue
}
# Deployment progress block.
if($report.result.numberComponentsTotal -ne 0 -and $componentsRemaining -ne 0) {
$deploymentRatio = [Math]::Ceiling(100 * ($report.result.numberComponentsDeployed / $report.result.numberComponentsTotal))
$componentsRemaining = $report.result.numberComponentsTotal - $report.result.numberComponentsDeployed - $report.result.numberComponentsFailed
# If the percentage is not yet 100%, update it.
if($deploymentRatio -le 100) {
Write-Host -NoNewLine "`rComponents deployed: " $deploymentRatio "%"
}
# If the deployment has failed
if($report.result.status -eq "Failed") {
break
}
}
# Write next header.
if(($report.result.numberTestsTotal -ne 0) -and ($startedTests -eq $false)) {
$startedTests = $true
Write-Host -ForegroundColor green "`n`n:: Running tests ::"
}
# Write Test progress
if($report.result.numberTestsTotal -ne 0 -and $testsRemaining -ne 0) {
$testRatio = [Math]::Ceiling((100 * ($report.result.numberTestsCompleted / $report.result.numberTestsTotal)))
$testsRemaining = $report.result.numberTestsTotal - $report.result.numberTestErrors - $report.result.numberTestsCompleted
Write-Host -NoNewLine "`rTests passed: " $testRatio "% | Tests remaining: " $testsRemaining
}
if($testsRemaining -eq 0 -and $report.result.numberTestErrors -gt 0) {
Write-Host -ForegroundColor red "`nERROR: $($report.result.numberTestErrors) tests have failed"
exit
}
} while(($report.result.status -eq "InProgress") -or ($report.result.status -eq "Pending"))
# FAILED DEPLOYMENT ANALYSIS
if($report.result.status -eq "Failed") {
Write-Host -ForegroundColor red "`n`nERROR Deployment Failed!"
$report = sfdx force:mdapi:deploy:report -i $deployJobId --json --verbose 2>&1 | ConvertFrom-Json
foreach($failure in $report.result.details.componentFailures) {
Write-Host -ForegroundColor red "`t - " $failure.problem
}
exit
}
# SUCCESSFUL DEPLOYMENT MESSAGE
Write-Host -ForegroundColor green "`n:: Deployment Successful! ::"
</code></pre>
| [] | [
{
"body": "<p>In parameters for your script, you usually want a <code>[switch]</code> instead of <code>[bool]</code>. It's more convenient to use when launching the script and works the same way in the script.</p>\n\n<p>Since your script doesn't work without a <code>repositoryDirectory</code>, you should make t... | {
"AcceptedAnswerId": "201084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T06:40:43.913",
"Id": "200870",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "PowerShell Script to deploy repository to Salesforce"
} | 200870 |
<p>By applying the <code>get_name</code> and <code>get_mac</code> functions to the specified IP address, it is possible to estimate the network availability of a segment:</p>
<pre><code>#include <Winsock2.h>
#include <iphlpapi.h>
#include <cstdio>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
bool get_name(unsigned char* name, char dest[32])
{
struct in_addr destip;
struct hostent* info;
destip.s_addr = inet_addr(dest);
info = gethostbyaddr((char*)&destip, 4, AF_INET);
if (info != NULL)
{
strcpy((char*)name, info->h_name);
}
else
{
return false;
}
return true;
}
bool get_mac(unsigned char* mac, char dest[32])
{
struct in_addr destip;
ULONG mac_address[2];
ULONG mac_address_len = 6;
destip.s_addr = inet_addr(dest);
SendARP((IPAddr)destip.S_un.S_addr, 0, mac_address, &mac_address_len);
if (mac_address_len)
{
BYTE* mac_address_buffer = (BYTE*)&mac_address;
for (int i = 0; i < (int)mac_address_len; i++)
{
mac[i] = (char)mac_address_buffer[i];
}
}
else
{
return false;
}
return true;
}
int main()
{
char address[][32] = { { "192.168.14.101" },{ "192.168.14.102" },
{"192.168.14.103" },{ "192.168.14.106 "} };
WSADATA sock;
if (WSAStartup(MAKEWORD(2, 2), &sock) != 0)
{
printf("Failed to initialise winsock. (%d)\n", WSAGetLastError());
return 1;
}
for (int i = 0; i < (int)sizeof(address) / 32; i++)
{
unsigned char mac[6] = { '\0' };
unsigned char name[100] = { '\0' };
if (get_mac(mac, address[i]))
{
printf("%s : %s : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n", address[i],
(get_name(name, address[i])) ? (char*)name : "-",
mac[0],mac[1],mac[2],mac[3], mac[4], mac[5]);
fflush(stdout);
}
}
printf("\nDone.\n");
fflush(stdout);
system("PAUSE");
return 0;
}
</code></pre>
<p>An attempt to implement a program that scans the subnet and displays IP address, host name, and MAC of machines on the network.</p>
| [] | [
{
"body": "<p>I won't cover any bugs in your implementation, I'll only have a look at your coding style. It looks like you were writing plain c but tagged it as c++. I think I didn't even found a single c++-only feature you made usage of.</p>\n\n<h2>Don't use a string as data storage unless it's necessary</h2>\... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T08:16:20.123",
"Id": "200876",
"Score": "0",
"Tags": [
"c++",
"socket",
"winapi"
],
"Title": "Scanning the subnet by ip range"
} | 200876 |
<p>I saw this question on MSE and went ahead and wrote a solution to it:
<a href="https://meta.stackexchange.com/questions/313561/determining-users-reputation-as-of-particular-date">https://meta.stackexchange.com/questions/313561/determining-users-reputation-as-of-particular-date</a></p>
<p>This calculates the reputation a user should have had at a certain date. I attempt to factor in everything that SEDE allows me to see. So -1 events from downvoting posts and serial voting reversal as well as the documentation reputation aren't factored in.</p>
<p>I'm curious about what could be improved here</p>
<pre><code>SELECT
-- Total Reputation
(
SUM(CASE WHEN r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits > 200 THEN 200 ELSE r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits END)
+ SUM(r2d.ReputationFromBounties)
+ COALESCE((SELECT SUM(v4.BountyAmount * -1) FROM Votes AS v4 WHERE v4.VoteTypeId = 8 AND v4.UserId = ##UserId## AND v4.CreationDate < ##UntilDate:string## ),0)
+ COALESCE((SELECT COUNT(*) * 2 FROM Posts AS p3 WHERE p3.OwnerUserId = ##UserId## AND p3.AcceptedAnswerId IS NOT NULL),0)
+ SUM(r2d.ReputationFromAccepts)
) AS TotalReputation,
-- Rep Capped Activities with the Cap Factored in
SUM(
CASE
WHEN r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits > 200 THEN 200
ELSE r2d.ReputationFromVotes + r2d.ReputationFromSuggestedEdits
END) AS ReputationFromRepCap,
-- Total Bounties recieved
SUM(r2d.ReputationFromBounties) AS ReputationFromBounties,
-- Total Bounties given
COALESCE((SELECT SUM(v4.BountyAmount * -1) FROM Votes AS v4 WHERE v4.VoteTypeId = 8 AND v4.UserId = ##UserId## AND v4.CreationDate < ##UntilDate:string## ),0) AS ReputationGivenAsBounties,
-- Total Reputation from Accepting Answers
COALESCE((SELECT COUNT(*) * 2 FROM Posts AS p3 WHERE p3.OwnerUserId = ##UserId## AND p3.AcceptedAnswerId IS NOT NULL),0) AS ReputationFromAcceptingAnswers,
-- Total Reputation from Accepted Answers
SUM(r2d.ReputationFromAccepts) AS ReputationFromAcceptedAnswers
FROM
(
SELECT
v.CreationDate AS VoteDate,
-- Total Reputation from Post Upvotes
-- PostTypeId 1 = Question, 2 = Answer
-- VoteTypeId 2 = Upvote, 3 = Downvote
-- CommunityOwnedDate is when a post was made CW.
-- Votes before that count, after not.
-- Vote Date is truncated to full days only so grouping works
SUM((CASE
WHEN (p.PostTypeId = 1 AND v.VoteTypeId = 2 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 5
WHEN (p.PostTypeId = 2 AND v.VoteTypeId = 2 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 10
WHEN (v.VoteTypeId = 3 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN -2
ELSE 0
END)) AS ReputationFromVotes,
-- Total Reputation from Answer Bounties
-- VoteTypeId 9 = Bounty Close (Bounty Awarded)
-- BountyAmount = Amount of Reputation awarded
SUM(CASE
WHEN v.VoteTypeId = 9 THEN v.BountyAmount
ELSE 0
END) AS ReputationFromBounties,
-- Total Reputation from Answer Accepts
-- VoteTypeId 1 = AcceptedByOriginator (Answer Accepted)
SUM(CASE
WHEN (v.VoteTypeId = 1 AND (p.CommunityOwnedDate > v.CreationDate OR p.CommunityOwnedDate IS NULL)) THEN 15
ELSE 0
END) AS ReputationFromAccepts,
-- Total Reputation from Suggested Edits
-- if ApprovalDate isn't NULL and RejectionDate is NULL it's been approved and not overriden
-- Group by the same Date as Votes for Rep-Cap evaluation (They count towards it)
COALESCE((SELECT
SUM(CASE WHEN (se.ApprovalDate IS NOT NULL AND se.RejectionDate IS NULL) THEN 2 ELSE 0 END)
FROM SuggestedEdits AS se
WHERE se.OwnerUserId = ##UserId##
AND YEAR(v.CreationDate) = YEAR(se.ApprovalDate)
AND MONTH(v.CreationDate) = MONTH(se.ApprovalDate)
AND DAY(v.CreationDate) = DAY(se.ApprovalDate) ),0) AS ReputationFromSuggestedEdits
FROM Posts AS p
INNER JOIN Votes AS v ON v.PostId = p.Id
WHERE p.OwnerUserId = ##UserId:int##
AND v.CreationDate <= ##UntilDate:string##
GROUP BY v.CreationDate
) as r2d
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T09:24:18.333",
"Id": "386906",
"Score": "0",
"body": "For comparison, see @rolfl's [Reputation Races](http://data.stackexchange.com/stackoverflow/query/164480/reputation-races) query."
}
] | [
{
"body": "<p>This is a partial answer as these were the bits I could verify easily.</p>\n\n<p>In your column query for <code>ReputationFromSuggestedEdits</code> you can move all of the projection to the where clause of that query and then use a count(*) and a multiplication to get you final result. It is key t... | {
"AcceptedAnswerId": "201024",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T08:59:03.790",
"Id": "200880",
"Score": "6",
"Tags": [
"sql",
"sql-server",
"t-sql",
"stackexchange"
],
"Title": "Find how much reputation a user had on a given date"
} | 200880 |
<p>I have written this program to find anagrams in a "pile" of letters (it'd be an effective way to cheat at Scrabble...)</p>
<p>Run it like <code>anagram abcedeede</code> to get a list of all the words that can be made from the letters <code>abcedeede</code> (you might want to pipe to <code>head</code>, since there will be many).</p>
<p>This is my first "major" attempt to write something in Rust--it is an adaptation of a Python program I wrote a while ago. I would love comments both on style and on any "stupid"/non-idiomatic things I've done that lead to problems in Rust.</p>
<pre><code>// main.rs
#![feature(test)]
extern crate test;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
/// A struct containing a string "word" and its "hash," a map between characters and counts
pub struct CountedWord {
/// The "pretty" version of the word that has been counted
word: String,
/// A map of characters to counts of characters for the word
letter_counter: HashMap<char, u32>,
}
impl CountedWord {
/// Create a `CountedWord` from an input `&str`
pub fn new(word: &str) -> CountedWord {
CountedWord {
word: word.to_string(),
letter_counter: CountedWord::hash(word),
}
}
/// Compute the "hash" for the input word
///
/// The "hash" is the count of each of the letters in the word.
/// i.e. for "attack" the hash is "2 a's, 1 c, 1 k, and 2 t's"
fn hash(word: &str) -> HashMap<char, u32> {
let clean_word = word.trim().to_lowercase();
let mut letter_counter = HashMap::new();
for ch in clean_word.chars().filter(|ch| ch.is_alphabetic()) {
letter_counter
.entry(ch)
.and_modify(|e| *e += 1)
.or_insert(1);
}
letter_counter
}
/// Determine if the other `CountedWord` can be made from the letters in `self`.
/// (That is--is `self` an anagram of `other`, with some letters allowed to be left over in
/// `self`?)
///
/// Returns `true` if it can be made, `false` otherwise.
pub fn is_possibility(&self, other: &CountedWord) -> bool {
let mut iter_other_chars = other.letter_counter.iter();
loop {
let item = iter_other_chars.next();
match item {
Some((character, number_in_other)) => {
let number_in_self = self.letter_counter.get(character);
match number_in_self {
Some(number_in_self) => {
if number_in_self >= number_in_other {
// this letter doesn't rule it out
continue;
} else {
// we don't have enough of this letter, not a possibility
break false;
}
}
// we don't have this letter, not a possiblity
None => break false,
}
}
// we didn't fail above, so this word must be a possibility
None => break true,
}
}
}
}
fn main() {
// process all the words in the dictionary
let f = File::open("/usr/share/dict/words").expect("dictionary not found");
let lines = BufReader::new(f).lines();
let mut dictionary_words = Vec::new();
for word in lines {
match word {
Ok(word) => {
dictionary_words.push(CountedWord::new(&word));
}
Err(_e) => continue,
};
}
// process the "pile" of letters we have to anagram from the arguments
// spaces are ignored--everything except the program name is collected here
let pile = CountedWord::new(&env::args().collect::<Vec<String>>()[1..].join(""));
// determine what words from the dictionary can be made from the letters in the pile
let mut possibilities = Vec::new();
for word in dictionary_words.iter() {
if pile.is_possibility(&word) {
possibilities.push(word)
}
}
// output the possiblities in alphabetical order by length
let mut stdout = io::stdout();
possibilities.sort_unstable_by_key(|k| (-(k.word.len() as i32), k.word.to_lowercase()));
for possibility in possibilities {
// using `if let` and `writeln!` here so if you pipe to (e.g.) head, we can catch the panic when the pipe is closed early
if let Err(_) = writeln!(stdout, "{}", possibility.word) {
break;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
/// Test `CountedWord::hash`
#[test]
fn test_counted_word_hash() {
let counter = CountedWord::hash("test");
let mut test_counter = HashMap::new();
test_counter.insert('t', 2);
test_counter.insert('e', 1);
test_counter.insert('s', 1);
assert_eq!(counter, test_counter);
}
/// Test `CountedWord::new`
#[test]
fn test_create_counted_word() {
let test_word = CountedWord::new("test");
assert_eq!(test_word.word, "test");
let mut test_counter = HashMap::new();
test_counter.insert('t', 2);
test_counter.insert('e', 1);
test_counter.insert('s', 1);
assert_eq!(test_word.letter_counter, test_counter);
}
/// Test `CountedWord::is_possibility`
#[test]
fn test_counted_word_is_possiblity() {
let test_word_1 = CountedWord::new("test");
let test_word_2 = CountedWord::new("assessment");
let input_letters = CountedWord::new("tssettioupuqwerwe");
assert!(input_letters.is_possibility(&test_word_1));
assert!(!input_letters.is_possibility(&test_word_2));
}
/// Benchmark `CountedWord::hash`
#[bench]
fn bench_hashing_word(b: &mut Bencher) {
b.iter(|| CountedWord::hash("tssettioupuqwerwe"));
}
/// Benchmark `CountedWord::is_possibility` when `is_possibility` is true
#[bench]
fn bench_checking_possibility_true(b: &mut Bencher) {
let test_word = CountedWord::new("test");
let input_letters = CountedWord::new("tssettioupuqwerwe");
b.iter(|| input_letters.is_possibility(&test_word));
}
/// Benchmark `CountedWord::is_possibility` when `is_possibility` is false
#[bench]
fn bench_checking_possibility_false(b: &mut Bencher) {
let test_word = CountedWord::new("assessment");
let input_letters = CountedWord::new("tssettioupuqwerwe");
b.iter(|| input_letters.is_possibility(&test_word));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T10:10:06.487",
"Id": "386916",
"Score": "0",
"body": "Also, I've noticed ~4s run times with debug builds and sub-0.5s run times with release builds. This seems like a large discrepancy--is there a particular reason for this in my co... | [
{
"body": "<ol>\n<li><p>I don't think \"anagram\" usually means \"can have letters left over\". You may want to find a better term.</p></li>\n<li><p>Modern Rust uses braced imports to import multiple things from the same crate / module instead of separate lines.</p></li>\n<li><p>I appreciate the documentation, ... | {
"AcceptedAnswerId": "202409",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T10:06:43.127",
"Id": "200889",
"Score": "4",
"Tags": [
"rust"
],
"Title": "Finding Anagrams in Rust"
} | 200889 |
<p>I made a function to censor a certain word from a piece of text. Is there anything I should fix or do more efficiently? What are some other approaches I could have taken to detecting words and censoring them?(This took me a lot of time to brainstorm)</p>
<p>Also, I would appreciate it if you told me how you brainstorm how to write a program.</p>
<pre><code>def detect_word_start(text,word):
count = 0
text_count = 0
for x in text:
text_count+=1
if x == word[count]:
count+=1
if count == len(word):
return text_count - len(word) + 1
else:
count = 0
def censor(text,word):
word_start = detect_word_start(text,word)
censored_text = ''
count = 0
for x in text:
count += 1
if count >= word_start and count < word_start+len(word):
censored_text += '*'
else:
censored_text += x
print(censored_text)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T10:38:53.253",
"Id": "386920",
"Score": "2",
"body": "You could have a look [here](https://codereview.stackexchange.com/questions/174097/function-to-censor-single-word-in-a-sentence) if you're searching for ideas :)"
},
{
"C... | [
{
"body": "<p>Let's start by removing print from the loop and add a return value</p>\n\n<pre><code>def censor(text,word):\n #[...]\n else:\n censored_text += x\n return censored_text\n</code></pre>\n\n<p>now we have a testable function. we add some tests</p>\n\n<pre><code>import unittest... | {
"AcceptedAnswerId": "200936",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T10:15:31.763",
"Id": "200892",
"Score": "7",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Simple Censor Program"
} | 200892 |
<p>I have the following code:</p>
<pre><code>let id = '';
let text = '';
// Note: `match` = [full match, id (first group), text (second group)]
if (match.length > 1) {
[, id] = match;
}
if (match.length > 2) {
[, id, text] = match;
}
return { id, text };
</code></pre>
<p><code>match</code> could be null, or lengths between 1-3.</p>
<p><code>id</code> and <code>text</code> need to be empty strings by default and only set if <code>match</code> is not null and of certain length.</p>
<p><strong>How can I shorten this up?</strong></p>
<p>Possibly avoiding the if statements.</p>
| [] | [
{
"body": "<p>I discovered that array destructing has the capability of providing default values.</p>\n\n<pre><code>const [, id = '', text = ''] = match;\nreturn { id, text };\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Arra... | {
"AcceptedAnswerId": "200898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T11:52:38.963",
"Id": "200894",
"Score": "0",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Destructure array and use object shorthand assignment"
} | 200894 |
<p>The aim of this script is to snapshot the current working directory of a git repository to another branch. Afterwards, it switches back to the original branch and restores the original state, including the working directory and staged changes.</p>
<pre><code>#!/bin/sh
function git_snapshot() {
# Usage: SNAPSHOT=$(git_snapshot <backup_branch> "<commit message>")
set -e
# Save the current state.
BEFORE=$(git rev-parse --abbrev-ref HEAD)
if [[ "$BEFORE" == 'HEAD' ]]; then
BEFORE=$(git rev-parse HEAD)
fi
(>&2 echo "Starting at $BEFORE.")
git stash push --include-untracked
(>&2 echo "Stashed changes ($(git rev-parse stash@{0})).")
# Commit files to other branch.
git checkout "$1"
git read-tree -um $BEFORE
git commit -m "$2"
(>&2 echo "Saved last commit ($(git rev-parse HEAD)).")
git stash apply --index stash@{0}
git add -A
git commit --amend --no-edit
(>&2 echo "Amended uncommitted changes ($(git rev-parse HEAD)).")
SNAPSHOT=$(git rev-parse HEAD)
# Switch back and restore state.
git checkout $BEFORE
git stash apply --index stash@{0}
(>&2 echo "Restored changes.")
echo $SNAPSHOT
}
</code></pre>
| [] | [
{
"body": "<p>Putting it <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">through shellcheck.net</a> results in quite a lot of cleanups.</p>\n\n<p>Apart from the issues raised there, I'd suggest that at the end of your script, you might want to <code>git stash pop</code> instead of <code>git ... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T12:41:37.383",
"Id": "200897",
"Score": "2",
"Tags": [
"shell",
"git",
"sh"
],
"Title": "Commit the working directory to different branch and switch back"
} | 200897 |
<p>I am working on a university project that consists of creating a map application with openlayers as well as the necessary User-Interface. I am using jQuery, native JavaScript, PHP and of course HTML/CSS </p>
<p>The problem I have (mostly because I am not that experienced in web development with jQuery and JavaScript) is that I have lots of code inside a jQuery click callback function or an ajax success-callback . I have the feeling that this way is not the right way and also somehow overloaded. I did not find answers while googling around that deal with this specific problem and provide a better way. </p>
<p>To give you an example here is the code of one js-file I was currently working on. I want to post the full code to illustrate my dilemma.</p>
<p>The general purpose of this file is to load step by step UI elements with specific content fetched from a database, as well as updating or removing when certain contents are chosen.</p>
<pre><code>var $info_panel = $("#route-update-info-panel"); //global -> namespace from sources.js
// eventually put html code in hidden divs and show them step by step?!
$("#route-update-get-dataset").click(function() {
if ($("#update-routes-select-container").length) {
$("#update-routes-select-container").remove();
$("#route-update-get-data").remove();
$("#update-slider-container").remove();
$("#update-single-routes-container").remove();
$("#route-update-button-container").remove();
}
var $route_type = $("#route-update-routelist").val();
if (!$route_type) {
$info_panel.html('<p>Routeklasse auswählen!</p>');
return;
} else {
$info_panel.html('');
$(`<div id="update-routes-select-container" class="input-field col s12">
<select id="update-routes-select">
<option value="" disabled selected>zu bearbeitende Route auswählen</option>
</select>
</div>`)
.appendTo('#update-routes');
}
$route_list = $("#update-routes-select");
$route_list.on('contentChanged', function() {
$(this).material_select();
});
// https://stackoverflow.com/questions/29132125/how-to-dynamically-modify-select-in-materialize-css-framework
$.post('get_dataset.php',
{
route_type: $route_type
},function(data, status) {
$(data).appendTo("#update-routes-select");
$route_list.trigger('contentChanged');
$(`<button id="route-update-get-data" class="btn waves-effect waves-light" type="submit" name="action">Bearbeiten
<i class="material-icons right">create</i>
</button>`)
.appendTo("#update-routes");
});
});
var slider3; // bad globals -> namespace from sources.js
$("#update-routes").on('click', '#route-update-get-data', function(evt) {
$id = $("#update-routes-select").val();
$route_type = $("#route-update-routelist").val();
if (!$id) {
$info_panel.html('<p>Route auswählen!</p>');
return;
} else {
$info_panel.html('');
}
$.post('get_data.php',
{
id: $id,
route_type: $route_type
}, function(data, status) {
removeFromMap([
{
map_identifier: 'name',
val: 'updateRouteLayer'
}
]);
var geojson = new ol.format.GeoJSON();
var features = geojson.readFeatures(data, {
defaultDataProjection: 'EPSG:4326',
featureProjection:'EPSG:3857' }
);
var updateRouteVectorSource = new ol.source.Vector({
features: features
});
var updateRouteVectorLayer = new ol.layer.Vector({
name: 'updateRouteLayer',
source: updateRouteVectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'tomato',
width: 4
})
})
});
var feature = features[0];
var extent = updateRouteVectorSource.getExtent();
map.addLayer(updateRouteVectorLayer);
map.getView().fit(extent, {
size: map.getSize(),
duration: 500
});
var s_pav = parseInt(feature.get('s_pav')*100);
if (!$("#update-slider-container").length) {
$(`<div id="update-slider-container">
<p>Anteil von befestigtem und unbefestigtem Belag wählen</p>
<div id="update-route-surface-choice-slider"></div>
<div id="update-route-surface-choice-vals"></div>
</div>`)
.appendTo("#update-routes");
slider3 = document.getElementById('update-route-surface-choice-slider');
noUiSlider.create(slider3, {
start: [s_pav],
connect: [true, true],
behaviour: 'drag',
step: 1,
tooltips: false,
orientation: 'horizontal', // 'horizontal' or 'vertical'
range: {
'min': 0,
'max': 100
},
format: wNumb({
decimals: 0
})
});
} else {
slider3.noUiSlider.set(s_pav);
}
var update_pav, update_unpav;
slider3.noUiSlider.on('update', function() {
update_pav = slider3.noUiSlider.get();
update_unpav = 100-slider3.noUiSlider.get();
$('#update-route-surface-choice-vals').html(`<p>befestigt: ${update_pav} % | unbefestigt: ${update_unpav} %</p>`);
});
var art = parseInt(feature.get('art'));
if (!$("#update-single-routes-container").length) {
$(`<div id="update-single-routes-container" class="input-field col s12">
<select id="route-update-routetype" multiple>
<option id="update-routetype-select-heading" value="" disabled selected>Routentyp wählen</option>
</select>
</div>`)
.appendTo("#update-routes");
$update_route_type = $("#route-update-routetype");
$update_route_type.on('contentChanged', function() {
$(this).material_select();
});
}
$("#update-routetype-select-heading")
.nextAll()
.each(function(i, elem) {
elem.remove();
});
// very ugly but until now it does the job :)
switch(art) {
case 1:
$(`<option value="001" selected>naturnah</option>
<option value="010">stadtnah</option>
<option value="100">innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 2:
$(`<option value="001">naturnah</option>
<option value="010" selected>stadtnah</option>
<option value="100">innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 3:
$(`<option value="001" selected>naturnah</option>
<option value="010" selected>stadtnah</option>
<option value="100">innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 4:
$(`<option value="001">naturnah</option>
<option value="010">stadtnah</option>
<option value="100" selected>innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 5:
$(`<option value="001" selected>naturnah</option>
<option value="010">stadtnah</option>
<option value="100" selected>innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 6:
$(`<option value="001">naturnah</option>
<option value="010" selected>stadtnah</option>
<option value="100" selected>innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
case 7:
$(`<option value="001" selected>naturnah</option>
<option value="010" selected>stadtnah</option>
<option value="100" selected>innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
default:
$(`<option value="001">naturnah</option>
<option value="010">stadtnah</option>
<option value="100">innerstädtisch</option>`)
.appendTo("#route-update-routetype");
$update_route_type.trigger('contentChanged');
break;
}
if (!$("#route-update-button-container").length) {
$(`<div id="route-update-button-container">
<button id="update-route-send" class="btn waves-effect waves-light" type="submit" name="action">Abschicken
<i class="material-icons right">send</i>
</button>
&nbsp;
<button id="update-route-reset" class="btn waves-effect waves-light" type="submit" name="action">Zurücksetzen
<i class="material-icons right">delete</i>
</button>
</div>`)
.appendTo("#update-routes");
});
});
</code></pre>
<p>At the moment this file is not finished at all but while writing the code that feeling mentioned above grew bigger and bigger. Any help or advice, criticism is greatly appreciated on how to write not such overloaded callback functions... </p>
| [] | [
{
"body": "<p>It's always a good idea to decouple low-level code, like the one jQuery is intended for (show a div, a click event) from high-level code (an action about your businness, in this case, the map).</p>\n\n<p>A simple example is: imagine that the logic you have inside that click event callback should b... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T13:40:13.527",
"Id": "200899",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"ajax",
"dom",
"callback"
],
"Title": "jQuery handler to update map UI based on AJAX response"
} | 200899 |
<p>I am creating a playbook that takes a variable <code>ver</code> at runtime and then runs tasks based on that variable. If that <code>ver</code> is defined, it takes the version number and installs a version according to that. If the <code>ver</code> is not defined, it defaults to a default version.</p>
<p>My playbook for now looks like:</p>
<pre><code>- name: Download Maven from remote repository.
unarchive:
src: "{{ baseurl }}/{{ versions[ver] }}"
dest: /usr/local/
remote_src: yes
become: yes
when: ver is defined
- name: Rename maven folder.
command: mv /usr/local/apache-maven-{{ver}} /usr/local/maven-{{ver}}
become: yes
when: ver is defined
- name: Create symbolic link to maven folder.
file:
src: "/usr/local/maven-{{ver}}"
dest: "/usr/local/maven"
state: link
become: yes
when: ver is defined
- name: Download Default Maven from remote repository.
unarchive:
src: "{{ baseurl }}/{{ versions[default_version] }}"
dest: /usr/local/
remote_src: yes
list_files: yes
become: yes
when: ver is not defined
- name: Rename maven folder.
command: mv /usr/local/apache-maven-{{default_version}} /usr/local/maven-{{default_version}}
become: yes
when: ver is not defined
- name: Create symbolic link to maven folder.
file:
src: "/usr/local/maven-{{default_version}}"
dest: "/usr/local/maven"
state: link
become: yes
when: ver is not defined
</code></pre>
<p>As you can see, based on whether a variable is defined or not, I have to write whole new tasks for it.</p>
<p>The above works but I think it's not optimized as I'm writing too much code to get this to work. One idea that I have is to create have <code>main.yaml</code> invoke another task file when <code>ver</code> is defined and a separate task file when <code>ver</code> is not defined.</p>
<p>Is there another way to optimize this? I have many other tasks that deal with version number.</p>
| [] | [
{
"body": "<p>Use the filter <a href=\"https://docs.ansible.com/ansible/devel/user_guide/playbooks_filters.html#providing-default-values\" rel=\"nofollow noreferrer\"><em>default</em></a>. For example</p>\n<pre class=\"lang-yaml prettyprint-override\"><code> - set_fact:\n version: "{{ ver | defau... | {
"AcceptedAnswerId": "200982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T14:22:40.360",
"Id": "200902",
"Score": "1",
"Tags": [
"ansible"
],
"Title": "Tasks based on variable definition"
} | 200902 |
<p>I'm a C++ developer trying to learn Rust for fun and XP.
I decided to implement some of the Unix tools for practice.</p>
<p>Below is a simplified implementation of the <code>find</code> command. The program takes 0 to 2 arguments: The first being the file to find, the second being the directory to start searching (I'm aware that the args aren't very robust).</p>
<p>I get the feeling there is a more succinct way to do what I'm trying to accomplish.</p>
<pre><code>use std::env;
use std::io;
use std::collections::VecDeque;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::exit;
fn find(query: &String, start: &OsString) -> io::Result<Vec<PathBuf>> {
let start = PathBuf::from(start);
let mut dirs = VecDeque::from(vec![start]);
let mut result = Vec::new();
while let Some(dir) = dirs.pop_front() {
for entry in dir.read_dir()? {
let path = entry?.path();
if path.is_dir() {
dirs.push_back(path.clone());
}
if let Some(name) = path.file_name() {
if query.is_empty() || query.as_str() == name {
result.push(path.clone());
}
}
}
}
Ok(result)
}
fn main() {
let query = match env::args().nth(1) {
Some(query) => query,
None => String::new(),
};
let start = match env::args().nth(2) {
Some(start) => OsString::from(start),
None => OsString::from("."),
};
match find(&query, &start) {
Ok(paths) => {
for path in paths {
if let Some(p) = path.to_str() {
println!("{}", p);
}
}
},
Err(err) => {
eprintln!("Error: {}", err);
exit(1);
},
};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T14:53:21.827",
"Id": "386959",
"Score": "0",
"body": "@Ludisposed yes. If I understand this correctly, it works because it is creating a copy of path (much like C++ would do implicitly)."
},
{
"ContentLicense": "CC BY-SA 4.... | [
{
"body": "<p>Your code can be simplified a little bit:</p>\n\n<pre><code>use std::collections::VecDeque;\nuse std::ffi::{OsStr, OsString};\nuse std::io;\nuse std::path::PathBuf;\n\nfn find(query: &str, start: &OsStr) -> io::Result<Vec<PathBuf>> {\n let start = PathBuf::from(start);\n ... | {
"AcceptedAnswerId": "200910",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T14:30:14.943",
"Id": "200904",
"Score": "4",
"Tags": [
"beginner",
"rust"
],
"Title": "A simple implementation of the Unix find command written in Rust"
} | 200904 |
<p>I created a simple Pomodoro timer using React JS.<br>
In my example: </p>
<ul>
<li>Timer should count down seconds until it reaches 00:00</li>
<li>Timers should switch between 25 and 5 minutes</li>
<li>Timer should be able to start, stop, and reset</li>
</ul>
<p>My questions:</p>
<ul>
<li>how can I improve the switching between the "work" and "relax" modes? Now I use 2 functions for this: toogleWork() and toogleRelax().</li>
<li>my functions for stop, start and reset look very simple and I always think that there is something missing here...</li>
</ul>
<p>Thank you for your time and any suggestions you can provide.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Timer extends React.Component {
constructor(props) {
super(props)
this.state = {
time: props.time,
}
}
format(seconds) {
let m = Math.floor(seconds % 3600 / 60);
let s = Math.floor(seconds % 3600 % 60);
let timeFormated = (m < 10 & '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
return timeFormated
}
startTimer = () => this.interval = setInterval(this.countDown, 1000)
countDown = () => {
if (this.state.time !== 0) {
this.setState(prevState => ({time: prevState.time - 1}))
} else {
this.stopTimer()
}
}
stopTimer = () => clearInterval(this.interval)
resetTime = () => {
this.stopTimer()
this.setState({time: this.props.time})
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
return (
<div >
<div className='time'>{this.format(this.state.time)}</div>
<button onClick={this.startTimer}>Start</button>
<button onClick={this.stopTimer}>Stop</button>
<button onClick={this.resetTime}>Reset</button>
</div>
);
}
}
class App extends React.Component{
constructor(props){
super(props)
this.state = {
work: true,
}
}
toogleWork = () => this.setState({work: true})
toogleRelax = () => this.setState({work: false})
render() {
return (
<div className='App'>
<button onClick={this.toogleWork}>Work</button>
<button onClick={this.toogleRelax}>Relax</button>
{this.state.work && <Timer time={1500} />}
{!this.state.work && <Timer time={300} />}
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.App {
text-align: center;
}
button {
margin: 15px 5px;
padding: 10px;
border: none;
}
.time {
font-size: 32px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>You can replace</p>\n\n<blockquote>\n<pre><code><button onClick={this.toogleWork}>Work</button>\n<button onClick={this.toogleRelax}>Relax</button>\n</code></pre>\n</blockquote>\n\n<p>with</p>\n\n<pre><code><button onClick={this.toggleState}>{this.state.work? 'Relax' :... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T14:43:48.847",
"Id": "200907",
"Score": "0",
"Tags": [
"object-oriented",
"react.js",
"timer",
"jsx"
],
"Title": "Pomodoro timer in React"
} | 200907 |
<p>I'm trying to understand conception of creating unit tests for the frontend applications.</p>
<p>I have created higher order reducer:</p>
<pre><code>// @flow
type action = {
type: string,
payload?: any
};
/**
* Async Reducer Factory to reduce duplicated code in async reducers.
* Higher Order Reducer.
*
* @param {String} name - Reducer name.
* @returns {Function}
*/
export const asyncReducerFactory = (name: String) => {
return (
state = { data: null, isLoading: false, error: null },
action: action
) => {
switch (action.type) {
case `FETCH_${name}_STARTED`:
return { data: null, isLoading: true, error: null };
case `FETCH_${name}_SUCCESS`:
return { data: action.payload, isLoading: false, error: null };
case `FETCH_${name}_ERROR`:
return { data: null, isLoading: false, error: action.payload };
default:
return state;
}
};
};
</code></pre>
<p>Tests:</p>
<pre><code>import { asyncReducerFactory } from "./factories";
describe("Test async reducers factory", () => {
const factory = asyncReducerFactory("TEST");
it("should create reducer", () => {
expect(factory).not.toBe(null);
});
it("should start fetching", () => {
expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
data: null,
isLoading: true,
error: null
});
});
it("should end fetching with success", () => {
expect(
factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
).toEqual({
data: "success",
isLoading: false,
error: null
});
});
it("should end fetching with error", () => {
expect(
factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
).toEqual({
data: null,
isLoading: false,
error: "error"
});
});
it("should return default state", () => {
expect(factory({}, { type: "DIFFERENT" })).toEqual({});
});
});
</code></pre>
<p>I would really appreciate, if you could let me know:</p>
<ol>
<li>if i'm using flow correctly?</li>
<li>if my tests are reliable?</li>
<li>how could i make it more generic?</li>
</ol>
| [] | [
{
"body": "<p>I have very minimal <strong>flow</strong> experience, but the action definition looks right. You may also be able to define a <code>state</code> type for this reducer.</p>\n\n<p>It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called <code>fetchReducerFa... | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T15:52:26.947",
"Id": "200912",
"Score": "6",
"Tags": [
"javascript",
"unit-testing",
"react.js"
],
"Title": "Testing higher order reducer with jest"
} | 200912 |
<p>I written code to solve <a href="https://www.geeksforgeeks.org/longest-consecutive-sequence-binary-tree/" rel="nofollow noreferrer">this problem</a> which I found on leetcode. My solution worked for the vast majority of the test cases run against it but failed on 2 for some reason. The first test case it failed on had a extremely large input size for the tree so it's really hard to determine what is actually wrong with the algorithm I wrote: </p>
<pre><code>class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def lcs(root):
if root is None:
return 0
left_lcs = lcs(root.left)
right_lcs = lcs(root.right)
add_to_left = 0
add_to_right = 0
if root.left is not None:
if root.left.val - root.val == 1:
add_to_left = 1
if root.right is not None:
if root.right.val - root.val ==1:
add_to_right =1
if root.right is None and root.left is None:
return 1
return max(add_to_left + left_lcs, add_to_right + right_lcs)
</code></pre>
<p><strong>Are there any glaring issues with the code that I'm just missing?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T17:43:20.117",
"Id": "386998",
"Score": "1",
"body": "If the longest consecutive sequence is longer than the stack size (1000 by default), this will raise an exception. So in Python you might want to use an iterative approach instea... | [
{
"body": "<p>Recursion is probably your main problem, as <a href=\"https://codereview.stackexchange.com/questions/200916/binary-tree-longest-consecutive-sequence#comment386998_200916\">Graipher</a> mentioned in the comments.</p>\n\n<p>You could refactor it to be iterative:</p>\n\n<pre><code>def lcs(root):\n ... | {
"AcceptedAnswerId": "200930",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-03T16:31:38.897",
"Id": "200916",
"Score": "0",
"Tags": [
"python",
"algorithm",
"tree"
],
"Title": "Binary Tree Longest Consecutive Sequence"
} | 200916 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.