body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I don't have any experience in cryptography and I've written some crypto code that seem to be working, but I'm not sure if it safe and if the tools and methods I used are right.</p>
<h2>Objective</h2>
<ul>
<li>Make it possible to store data (JSON) on remote server without this server being able to read it in plaintext.</li>
</ul>
<h2>My Approach</h2>
<ol>
<li>Upon registration, don't send the real user password to the server, use Argon2 hash of the real password instead. In my understanding, it should be pretty hard for a server to infer the real password based on Argon2 hash and without salt.</li>
<li>Use <strong>sha256(email + password)</strong> to create deterministic salt. It allows users to log in from other devices and still pass password validation. In my understanding, deterministic salt doesn't make the resulting "API password" weaker.</li>
<li>Using the password and salt, create an "API password" <strong>(Argon2(password, salt))</strong></li>
<li>Use API password to sign up. Server would only know the derived password and not the original one (entered and known by the user).</li>
<li>Create another Argon2 hash and use it as a key to AES-encrypt the JSON payload (<strong>AES-256/CBC/Pkcs</strong>).</li>
<li>Attach IV and random salt to encrypted payload. All of that is necessary to decrypt the payload later.</li>
<li>Push the resulting data to back end server.</li>
</ol>
<h2>Code</h2>
<pre class="lang-rust prettyprint-override"><code>use argon2::{self, Config};
use sha2::{Digest, Sha256};
use crypto::{ symmetriccipher, buffer, aes, blockmodes };
use crypto::buffer::{ ReadBuffer, WriteBuffer, BufferResult };
use rand::{ Rng };
fn main() {
// Step 1: Generating "password" that will be used for API sign up
let email = "foo@bar.com";
println!("Email: {}", email);
let password = "foobar";
// Never leaves client
println!("Password: {}", password);
let mut sha_hasher = Sha256::new();
sha_hasher.input(format!("{}{}", email, password));
let salt = sha_hasher.result();
let argon_config = Config::default();
let password_hash = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
println!("Password hash (full): {}", password_hash);
let password_hash_parts: Vec<&str> = password_hash.split("$").collect();
let password_hash = password_hash_parts[5];
// will be used for API sign up
println!("Password hash (short): {}", password_hash);
// Step 2: Encrypting some JSON client side
let payload = "[{ name: \"Secret Name\" }]";
println!("Original payload: {}", payload);
let encrypted_payload = encrypt_payload(&payload, &password);
let decrypted_payload = decrypt_payload(encrypted_payload, &password);
println!("Decrypted payload: {}", decrypted_payload);
// Step 3: Pushing encrypted payload to server
// (omitted, out of scope of review)
}
fn encrypt_payload(payload: &str, password: &str) -> Vec<u8> {
let salt = rand::thread_rng().gen::<[u8; 16]>();
let argon_config = Config::default();
let key = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
let iv = rand::thread_rng().gen::<[u8; 16]>();
let encrypted_bytes = encrypt(payload.as_bytes(), key.as_bytes(), &iv).ok().unwrap();
let encrypted_bytes : Vec<u8> = salt.iter().chain(&iv).chain(&encrypted_bytes).cloned().collect();
encrypted_bytes
}
fn decrypt_payload(encrypted_payload: Vec<u8>, password: &str) -> String {
let salt = &encrypted_payload[0..16];
let iv = &encrypted_payload[16..32];
let encrypted_message = &encrypted_payload[32..];
let argon_config = Config::default();
let key = argon2::hash_encoded(password.as_bytes(), &salt, &argon_config).unwrap();
let decrypted_message = decrypt(&encrypted_message[..], key.as_bytes(), &iv).ok().unwrap();
String::from_utf8(decrypted_message).unwrap()
}
</code></pre>
<h2>Full code (Rust crate)</h2>
<p>Here is the full code with encrypt/decrypt boilerplate based on <a href="https://github.com/DaGenix/rust-crypto/blob/master/examples/symmetriccipher.rs" rel="nofollow noreferrer">this example</a>:</p>
<p><a href="https://cloud.bubelov.com/s/imarc3356ikngB2/download" rel="nofollow noreferrer">crypto.tar.gz</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:09:31.110",
"Id": "464267",
"Score": "0",
"body": "what's the use case for this? I'm guessing the client is a web browser that doesn't have persistent storage, but would be good to confirm. assuming that's the case, what's to stop the server from \"going rogue\" and inserting a gadget that reveals the password to the server?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T05:58:31.997",
"Id": "464316",
"Score": "0",
"body": "@SamMason I'm prototyping a portfolio tracking service. The clients are native mobile apps (Android and iOS for now). Most of the API endpoints are not sensitive (asset price data, etc) but when it comes to user portfolios, especially the amounts of assets held, I don't really want to hold that data. One reason for that is pragmatic: that would make data breaches less consequential. Another reason is mostly ethical: I don't want to hold other people's personal data which is not critical for providing a service."
}
] |
[
{
"body": "<p>a few comments, from high to low-level:</p>\n\n<h1>Usability</h1>\n\n<p>users are generally pretty terrible with passwords! having them \"lose\" all their data if they forget their password often isn't something they expect. i.e. they just want to do a \"password reset\" and get access to everything again. I know this is at odds with what you (and lots of similar designs) are trying to do, but thought it useful to point out</p>\n\n<h1>Separate authentication from encryption</h1>\n\n<p>I'd be tempted to use a more conventional protocol for authentication, probably also separating out passwords used for authentication and encryption. This would let you, e.g., incrementally increase the Argon2 complexity without invalidating their login (this is something you really need to allow for). It would also let you use some sort of federated authentication system which might be nice</p>\n\n<h1>Crypto usage</h1>\n\n<ul>\n<li>CBC doesn't provide any authenticity. i.e. you won't know if the right password has been used / some attacker is trying to decieve you. I'd suggest using another block mode, or maybe a stream cipher like <code>chacha20-poly1305</code></li>\n<li>I'd probably just use the hash of the email as the salt, using password as well doesn't seem to help much.</li>\n<li>your use of Argon2 in <code>encrypt_payload</code> seems to misunderstand its purpose as a general <a href=\"https://en.wikipedia.org/wiki/Key_derivation_function\" rel=\"nofollow noreferrer\">KDF</a>. You should just request the amount of output you want, e.g., 48 bytes of keying material from Argon2 and use 32 bytes of that as key and 16 bytes as IV. that means you just need a single 128bit \"key\" per file rather than a \"salt\" and an \"IV\". your usage isn't any more secure, 128bits is a big enough state space to stop a brute force attack while access to your storage server would give them the header anyway</li>\n</ul>\n\n<h1>API usage</h1>\n\n<ul>\n<li><code>argon2::hash_encoded</code> is mostly designed for hashing passwords for authentication. you almost certainly want to be using <code>hash_raw</code> to just get the keying material out</li>\n<li>it might be useful if your design allowed the <code>Config</code> parameters over time to increase computation complexity. you really want to record the parameter values used somewhere so the right ones can be used</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T16:47:16.307",
"Id": "464356",
"Score": "0",
"body": "Thanks for a detailed answer! Not that I understand it completely but it has all of the keywords to dig further so I guess it's just a matter of time :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T16:58:40.207",
"Id": "464357",
"Score": "0",
"body": "I agree on usability and it a tough compromise indeed. The idea of separating auth and encryption looks interesting. Data encryption might be implemented as an opt-in feature so users could decide for themselves."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T12:50:41.107",
"Id": "236887",
"ParentId": "236836",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Upon registration, don't send the real user password to the server, use Argon2 hash of the real password instead. In my understanding, it should be pretty hard for a server to infer the real password based on Argon2 hash and without salt.</p>\n</blockquote>\n\n<p>It makes it harder, by a constant factor. If the password is weak, it can still be found. Password based authentication should not be preferred, and if it is used, it should be surrounded by as many extra measures you can think of (with a maximum amount of tries and password strength indication to the user, for instance).</p>\n\n<blockquote>\n <p>Use sha(email + password) to create deterministic salt. It allows users to log in from other devices and still pass password validation. In my understanding, deterministic salt doesn't make the resulting \"API password\" weaker.</p>\n</blockquote>\n\n<p>Well, kind of. If a adversary can guess then they can still precompute tables for a specific user, who may use different passwords on the same site for instance. This is detectable if you don't use a random salt.</p>\n\n<blockquote>\n <p>Use API password to sign up. Server would only know the derived password and not the original one (entered and known by the user).</p>\n</blockquote>\n\n<p>So you don't use a username to authenticate? Or is that simply missing from your scheme? And you use a static value to sign up, send over an unencrypted line, that anybody may intercept? That cannot be right?</p>\n\n<p>Are you going to search through all password hashes to get to the right one?</p>\n\n<blockquote>\n <p>Create another Argon2 hash and use it as a key to AES-encrypt the JSON payload (AES-256/CBC/Pkcs).</p>\n</blockquote>\n\n<p>CBC with PKCS#7 padding is absolutely terrible as it allows for padding oracle attacks. 128 tries per byte, and that is if other plaintext oracle attacks cannot be made even more efficiently.</p>\n\n<p>Creating another Argon2 hash means double the work for you, and still single the work to an attacker. Instead, you can split the key into two using a KBKDF function such as HKDF (or a poor mans KDF such as using HMAC with the secret as key and an info string as message to distinguish two or more keys).</p>\n\n<blockquote>\n <p>Attach IV and random salt to encrypted payload. All of that is necessary to decrypt the payload later.</p>\n</blockquote>\n\n<p>Ah, so now you are using a random salt? If that's true, you don't need a random IV, because the key would be unique.</p>\n\n<hr>\n\n<p>All in all, your scheme is far from complete and far from bullet proof. Showing CBC in here shows the limited understanding of creating secure protocols. You're much better off using an existing one, e.g. TLS also has options for pre-shared keys. Those you can use if both sides can create a password hash.</p>\n\n<p>If you would log in using that email address then you can send a random salt stored with the hash, and have the user perform HMAC over a random challenge using the result of passsword derivation Argon2 with the hash as key. That would be much more secure as a standalone authentication method.</p>\n\n<hr>\n\n<p>The code is already shortly referred to by Sam, so I won't go into it. It seems relatively clear, but I think you are due to rewrite it anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:02:31.630",
"Id": "464949",
"Score": "0",
"body": "... on the bright side, you are looking at a password hash at least."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:20:25.847",
"Id": "464955",
"Score": "0",
"body": "\"So you don't use a username to authenticate?\" - nope. Just email + password. \"And you use a static value to sign up, send over an unencrypted line, that anybody may intercept?\" - it supposed to be sent via secure connection, of course. It's not about protecting the data in transit, my understanding is: SSL takes care of this. \"Are you going to search through all password hashes to get to the right one?\" - not sure if I understand your question. Same password + deterministic salt should give the same hash on any device so server would log it in just fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:23:31.507",
"Id": "464957",
"Score": "0",
"body": "Hey, if you don't say what data you use to login then don't blame me for not getting it right. There is not a word about TLS either. Getting somebody to log in is not hard; securing it is the trick."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:37:03.903",
"Id": "464965",
"Score": "0",
"body": "Sure, there is a lot of stuff going on out of the scope of this code and I really appreciate the feedback. I did some reading and asked around since posting that code and now I think that sha256(app name + email + password) would make a better salt (more likely to be globally unique, although still enables pre-computation attacks) and it seems like it's better to split the auth scheme and data encryption. I think I get the auth part now and the code seems to be fine for my use case, but encryption is certainly not and I'll look into it and read/ask more. Thanks for your feedback!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:01:27.293",
"Id": "237173",
"ParentId": "236836",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236887",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:59:49.703",
"Id": "236836",
"Score": "2",
"Tags": [
"security",
"rust",
"cryptography",
"aes"
],
"Title": "Encrypt data before sending it to server in a way that makes it unreadable to anyone except the user who sent it"
}
|
236836
|
<p>I have designed a messaging system below regarding the following assumptions
I would be appreciated for the valuable reviews.
Especially considering;
Multi-threading / SOLID principles / Design patterns</p>
<p>Assumptions:</p>
<p>Messaging System allows users to communicate with each other via messages.</p>
<p>User can be registered to the system via their information name, email etc.</p>
<p>User can add friends and have friends list.</p>
<p>When users login the system they became active.</p>
<p>Every user can have a conversation list for both private and group ones.</p>
<p>Many user can be added to the system.</p>
<p>2 or more users can have conversation and each conversation can be build up from messages.</p>
<p>2 participant conversation can be considered private conversation.</p>
<p>More than 2 conversation can be accepted as group conversation.</p>
<p>User should be friends to send messages to each other.</p>
<p>To being a friend one party should send a request and the other should accept.</p>
<p>There could be waiting requests friendship requests for each user.</p>
<p>MessageSystem.java</p>
<pre><code>package oopdesign.chatServer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MessageSystem {
public static void main(String[] args) {
User user1 = new User("Nesly", "Surname","nesly@gmail.com");
User user2 = new User("Jack", "Surname","jack@gmail.com");
User user3 = new User("Daniel","Surname","daniel@gmail.com");
UserManagement userManager = UserManagement.getInstance();
userManager.addUser(user1);
userManager.addUser(user2);
userManager.addUser(user3);
// Get all user list
HashMap<Integer, User> userAllMap = userManager.getAllUserList();
System.out.println("All user list");
for(Map.Entry<Integer, User> userEntry : userAllMap.entrySet()){
System.out.println("User :" + userEntry.getValue().getName());
}
FrienshipRequest frienshipRequest = new FrienshipRequest(user1, user2);
userManager.acceptFriendshipRequest(frienshipRequest);
FrienshipRequest frienshipRequest1 = new FrienshipRequest(user2, user3);
userManager.acceptFriendshipRequest(frienshipRequest1);
// Get users friends list
for(Map.Entry<Integer, User> userEntry : userAllMap.entrySet()){
User user = userEntry.getValue();
System.out.println("Friends of :" + user.getName());
HashMap<Integer, User> friendsMap = user.getFriendsList();
for(Map.Entry<Integer, User> friendsMapEntry : friendsMap.entrySet()) {
System.out.println(friendsMapEntry.getValue().getName());
}
}
user1.sendMessageToPrivateConversation(user2,"Hi");
user2.sendMessageToPrivateConversation(user1,"Fine, You ?");
Conversation conversation = user1.getPrivateConversations(user2);
List<Message> messageList = conversation.getConversation();
for(Message message : messageList){
System.out.println("Message : " + message.getContent() + " / Date :" + message.getDate());
}
}
}
</code></pre>
<p>Conversation.java</p>
<pre><code>package oopdesign.chatServer;
import java.util.ArrayList;
import java.util.List;
public abstract class Conversation {
protected int conversationId;
protected List<Message> conversation = new ArrayList<>();
protected List<User> participants = new ArrayList<>();
protected void addParticipant(User user){
participants.add(user);
}
protected void addMessage(Message message){ conversation.add(message); };
public int getConversationId() {
return conversationId;
}
public List<Message> getConversation() {
return conversation;
}
public List<User> getParticipants() {
return participants;
}
}
</code></pre>
<p>FrienshipRequest.java</p>
<pre><code>package oopdesign.chatServer;
public class FrienshipRequest {
private User toUser;
private User fromUser;
public FrienshipRequest(User toUser, User fromUser){
this.toUser = toUser;
this.fromUser = fromUser;
}
public User getToUser() {
return toUser;
}
public User getFromUser() {
return fromUser;
}
}
</code></pre>
<p>GroupConversation.java</p>
<pre><code> package oopdesign.chatServer;
public class GroupConversation extends Conversation {
public GroupConversation() {
super();
}
@Override
protected void addParticipant(User user) {
super.addParticipant(user);
}
@Override
public void addMessage(Message message) { }
}
</code></pre>
<p>Message.java</p>
<pre><code>package oopdesign.chatServer;
import java.util.Date;
public class Message {
private String content;
private Date date;
public Message(String content,Date date){
this.content = content;
this.date = date;
}
public String getContent() {
return content;
}
public Date getDate() {
return date;
}
}
</code></pre>
<p>PrivateConversation.java</p>
<pre><code>package oopdesign.____.chatServer_ness;
public class PrivateConversation extends Conversation {
public PrivateConversation(User user1, User user2) {
participants.add(user1);
participants.add(user2);
}
public User getOtherParticipant(User user){
if(participants.get(0)==user){
return participants.get(1);
}else if(participants.get(1)==user){
return participants.get(0);
}
return null;
}
}
</code></pre>
<p>User.java</p>
<pre><code>package oopdesign.____.chatServer_ness;
import java.util.Date;
import java.util.HashMap;
public class User {
private int id;
private String name;
private String surname;
private String email;
private String status;
private HashMap<Integer, User> waitingRequests = new HashMap<>();
private HashMap<Integer, User> friendList = new HashMap<>();
private HashMap<Integer, PrivateConversation> privateConversation = new HashMap<>();
private HashMap<Integer, GroupConversation> groupConversations = new HashMap<>();
public User(String name,String surname,String email){
this.id = name.hashCode();
this.name = name;
this.surname = surname;
this.email = email;
}
public void sendMessageToPrivateConversation(User toUser,String content){
Message message = new Message(content,new Date());
PrivateConversation conversation = privateConversation.get(toUser.getId());
if(conversation == null){
conversation = new PrivateConversation(this, toUser);
}
conversation.addMessage(message);
privateConversation.put(toUser.getId(),conversation);
toUser.privateConversation.put(this.getId(),conversation);
}
public void sendMessageToGroupConversation(GroupConversation conversation,String content){
Message message = new Message(content,new Date());
GroupConversation groupConversation = groupConversations.get(conversation);
if(conversation == null) {
conversation = new GroupConversation();
}conversation.addMessage(message);
groupConversations.put(conversation.getConversationId(),conversation);
}
public void addContact(User user) {
waitingRequests.remove(user.getId());
friendList.put(user.getId(), user);
}
public void rejectContact(User user) {
waitingRequests.remove(user.getId());
}
public void sendFriendshipRequest(User toUser){
FrienshipRequest fr = new FrienshipRequest(this, toUser);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getEmail() {
return email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public HashMap<Integer, User> getFriendsList() {
return friendList;
}
public HashMap<Integer, User> getWaitingRequests() {
return waitingRequests;
}
public HashMap<Integer, User> getFriendList() {
return friendList;
}
public PrivateConversation getPrivateConversations(User user) {
return privateConversation.get(user.getId());
}
public HashMap<Integer, GroupConversation> getGroupConversations() {
return groupConversations;
}
}
</code></pre>
<p>UserManagement.java</p>
<pre><code>package oopdesign.____.chatServer_ness;
import java.util.HashMap;
public class UserManagement {
public static UserManagement userManagement;
private HashMap<Integer, User> userMap = new HashMap<>();
public static UserManagement getInstance(){
if(userManagement == null){
userManagement = new UserManagement();
}
return userManagement;
}
public void acceptFriendshipRequest(FrienshipRequest fr){
User user1 = fr.getFromUser();
User user2 = fr.getToUser();
user1.addContact(user2);
user2.addContact(user1);
}
public void rejectFriendshipRequest(FrienshipRequest fr){
User user1 = fr.getFromUser();
User user2 = fr.getToUser();
user2.rejectContact(user1);
}
public void addUser(User user){
userMap.put(user.getId(), user);
}
public void removeUser(User user){
userMap.remove(user.getId());
}
public void login(User user){
user.setStatus("ACTIVE");
}
public void logOut(User user){
user.setStatus("PASSIVE");
}
public HashMap<Integer, User> getAllUserList() {
return userMap;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T12:48:23.733",
"Id": "464249",
"Score": "2",
"body": "I'm voting to close at the moment because the codes doesn't seem to be real/working. `waitingRequests` is an empty collection which no way to populate it, but items can be removed through friendship requests... `GroupConversation` essentially just breaks adding messages... It's unclear how this could be used in a meaningful way. Perhaps you need to either add more context, or reduce the scope of the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T11:27:06.197",
"Id": "464329",
"Score": "0",
"body": "I have updated addign a Main MessageSystem class. It is make the functionality clear for al users"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T13:56:50.390",
"Id": "464338",
"Score": "0",
"body": "I've added an extended comment as an answer. There are items about your code that still don't really make sense as 'working' code. For example, half of the code is in a different `package` to the rest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:29:57.637",
"Id": "464842",
"Score": "0",
"body": "You are able to change the date of a message. You should avoid that."
}
] |
[
{
"body": "<p><strong>Missing behaviour</strong></p>\n\n<blockquote>\n<pre><code>public class GroupConversation extends Conversation {\n //...\n @Override\n public void addMessage(Message message) { }\n}\n</code></pre>\n</blockquote>\n\n<p><code>GroupConversation</code>'s <code>addMessage</code> doesn't delegate and it doesn't do anything else with the message. This seems very suspect.</p>\n\n<p><strong>UserManager</strong></p>\n\n<p>It's generally a bad idea to provide direct access to an internal collection that your class depends on.</p>\n\n<blockquote>\n<pre><code>public HashMap<Integer, User> getAllUserList() {\n return userMap;\n}\n</code></pre>\n</blockquote>\n\n<p>By providing this method, it's possible for any client of your <code>userManger</code> to insert/remove items from the <code>userMap</code>. This probably isn't something you want to happen.</p>\n\n<p>I think it's also a little bit odd that you're returning a HashMap. They key in the map seems to be an internal implementation detail, indeed your <code>MessageSystem</code> doesn't use the keys, it only uses the values. It would be better to return something like an <code>UnmodifiableCollection</code> of the map's values.</p>\n\n<p><strong>Friends</strong></p>\n\n<p>The FriendShip request methods don't use any of the class members, (for example to validate that the users being friended both exist within the user manager). The methods <em>could</em> be static.</p>\n\n<p>Your friendship request functions both declare variables <code>user1</code> and <code>user2</code>. These names hide the context from the request. Why not call them <code>fromUser</code> and <code>toUser</code>. Your friendship system as it stands seems incomplete. You crate a request, but never do anything with it...</p>\n\n<blockquote>\n<pre><code>public void sendFriendshipRequest(User toUser){\n FrienshipRequest fr = new FrienshipRequest(this, toUser);\n}\n</code></pre>\n</blockquote>\n\n<p><strong>PrivateConversation</strong></p>\n\n<blockquote>\n<pre><code>public User getOtherParticipant(User user){\n if(participants.get(0)==user){\n return participants.get(1);\n }else if(participants.get(1)==user){\n return participants.get(0);\n }\n return null;\n}\n</code></pre>\n</blockquote>\n\n<p>It's unclear why this method would be required (the client can already get all of the participants). If <code>user</code> isn't one of the participants, consider throwing an exception (seems like an invalid state). Alternately, you could return an Optional to indicate the expectation that a user might not be returned. This also looks suspect <code>participants.get(1)==user</code> are you meaning to do a reference comparison here? It seems like two users should be equivalent if their <code>id</code> is the same.</p>\n\n<p><strong>Map Iteration</strong></p>\n\n<blockquote>\n<pre><code>HashMap<Integer, User> friendsMap = user.getFriendsList();\nfor(Map.Entry<Integer, User> friendsMapEntry : friendsMap.entrySet()) {\n System.out.println(friendsMapEntry.getValue().getName());\n}\n</code></pre>\n</blockquote>\n\n<p>If you only care about the values in the map, then you can iterate over them rather than the entries. Which makes the code a more concise/descriptive:</p>\n\n<pre><code> user.getFriendsList()\n .values()\n .forEach(friend->System.out.println(friend.getName()));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T13:48:32.387",
"Id": "236890",
"ParentId": "236837",
"Score": "2"
}
},
{
"body": "<p>Few possible improvements :</p>\n\n<p>1.User class is highly loaded with collections and methods, it would be better to follow <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation_of_concerns</a> by having user as plain pojo and other responsibility as service like Friendship service, Conversation service.</p>\n\n<p>2.All conversation type can be handled with generic Conversation class defined by you and we can store type information in another collection in order to avoid limitation at storage level.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T20:14:37.490",
"Id": "237183",
"ParentId": "236837",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T12:17:17.593",
"Id": "236837",
"Score": "-1",
"Tags": [
"java",
"object-oriented"
],
"Title": "Messaging System Object Oriented Design"
}
|
236837
|
<p>I wrote a method for a wpf app in .net core to get all users and their group by name if they are in a group from my active directory domaine.</p>
<pre><code>public static void getGroupsWithUsers() {
String currentDomain = Domain.GetCurrentDomain().ToString();
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, currentDomain))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
var SID = WindowsIdentity.GetCurrent().User.ToString();
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(context, de.Properties["samAccountName"].Value.ToString());
if (user != null)
{
// get the user's groups
var groups = user.GetAuthorizationGroups();
foreach (GroupPrincipal group in groups)
{
Console.WriteLine("User: " + user + " is in Group: " + group);
}
}
}
}
}
}
</code></pre>
<p>The method takes 1.5 to 1.8 seconds for a small amount of data and Im afraid that the execution time takes forever for real world data amounts.</p>
|
[] |
[
{
"body": "<p>I suspect you'd better off using a <code>DirectorySearcher</code>, but I don't know Active Directory services are supported by .NET Core.</p>\n\n<p>Here is how I did it in .NET Framework (4.7.2).</p>\n\n<p>Classes to hold the data I needed:</p>\n\n<pre><code>public class Account\n{\n private Account(string name)\n {\n Name = name;\n }\n\n public Account(string name, List<DataCombination> groupData)\n : this(name)\n {\n GroupData = groupData;\n }\n\n public string Name { get; }\n\n public List<DataCombination> GroupData { get; }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class DataCombination\n{\n public string GroupName { get; set; }\n\n public string Account { get; set; }\n}\n</code></pre>\n\n<hr>\n\n<p>The code that queries AD:</p>\n\n<pre><code> var searchResults = new List<SearchResult>();\n\n using (var directoryEntry = new DirectoryEntry(directoryEntryPath))\n {\n directoryEntry.RefreshCache();\n\n using (var directorySearcher = new DirectorySearcher(directoryEntry))\n {\n directorySearcher.SearchRoot = directoryEntry;\n directorySearcher.SearchScope = SearchScope.Subtree;\n directorySearcher.PageSize = 1000;\n directorySearcher.Filter = filter;\n\n directorySearcher.PropertiesToLoad.Clear();\n directorySearcher.PropertiesToLoad.Add(PropertyName.Name);\n directorySearcher.PropertiesToLoad.Add(PropertyName.MemberOf);\n\n searchResults.AddRange(directorySearcher.FindAll().Cast<SearchResult>());\n }\n }\n\n var accounts = searchResults\n .Select(searchResult => _accountFactory.Execute(searchResult.Properties))\n .OrderBy(x => x.Name)\n .ToList();\n\n return accounts;\n</code></pre>\n\n<ul>\n<li><code>directoryEntryPath</code> is an LDAP URI, starts with \"LDAP://\".</li>\n<li><p><code>filter</code> is used to filter using a list of user names and is filled by this method:</p>\n\n<pre><code>public static string Execute(IEnumerable<string> userNames)\n{\n var filter = new StringBuilder();\n filter.Append(\"(&(objectClass=user)(|\");\n\n foreach (var userName in userNames)\n {\n filter.Append($\"(sAMAccountName={userName})\");\n }\n\n filter.Append(\"))\");\n\n return filter.ToString();\n}\n</code></pre></li>\n<li><p><code>PropertyName</code> is a class containing <code>const string</code>s:</p>\n\n<pre><code>internal static class PropertyName\n{\n // https://msdn.microsoft.com/en-us/library/windows/desktop/ms675090.aspx\n public const string Name = \"name\";\n public const string LockoutTime = \"lockoutTime\";\n public const string UserAccountControl = \"userAccountControl\";\n public const string MemberOf = \"memberOf\";\n public const string DisplayName = \"displayName\";\n}\n</code></pre></li>\n</ul>\n\n<p>This is the <code>_accountFactory</code> which converts the data returned by the <code>DirectorySearcher</code> into my classes:</p>\n\n<pre><code>internal class GroupAccountFactory : BaseDirectorySearcher, IAccountFactory\n{\n public Account Execute(ResultPropertyCollection properties)\n {\n var accountName = GetValue<string>(properties, PropertyName.Name);\n\n var groupData = GetGroupData(properties, accountName);\n\n return new Account(accountName, groupData);\n }\n\n private List<DataCombination> GetGroupData(ResultPropertyCollection properties, string accountName)\n {\n var groupNames = new List<string>();\n\n foreach (var propertyValue in properties[PropertyName.MemberOf].Cast<string>())\n {\n groupNames.AddRange(propertyValue\n .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\n .Select(part => part.Split('='))\n .Select(x => new\n {\n Key = x[0],\n Value = x[1],\n })\n .Where(x => x.Key == LdapDirectory.CommonName)\n .Select(x => x.Value));\n }\n\n return DataCombinationCollectionCreator.Execute(new HashSet<string>(groupNames), accountName);\n }\n}\n</code></pre>\n\n<p>Its base class:</p>\n\n<pre><code>internal abstract class BaseDirectorySearcher\n{\n protected T GetValue<T>(ResultPropertyCollection properties, string propertyName)\n {\n var value = PropertyValueRetriever.GetObject(properties, propertyName);\n if (value == null)\n {\n return default(T);\n }\n\n return (T)value;\n }\n}\n</code></pre>\n\n<p>And that one uses:</p>\n\n<pre><code>internal class PropertyValueRetriever\n{\n public static string GetString(ResultPropertyCollection properties, string propertyName)\n {\n var value = GetObject(properties, propertyName);\n\n return (string)value;\n }\n\n public static object GetObject(ResultPropertyCollection properties, string propertyName)\n {\n if (properties.Contains(propertyName)\n && properties[propertyName].Count > 0)\n {\n return properties[propertyName][0];\n }\n\n return null;\n }\n}\n</code></pre>\n\n<p>You might have noticed this class:</p>\n\n<pre><code>internal class LdapDirectory\n{\n public const string CommonName = \"CN\";\n public const string OrganizationalUnit = \"OU\";\n public const string DomainComponent = \"DC\";\n}\n</code></pre>\n\n<p>And finally:</p>\n\n<pre><code>internal class DataCombinationCollectionCreator\n{\n public static List<DataCombination> Execute(ICollection<string> groupNames, string accountName)\n {\n var groupData = new List<DataCombination>();\n\n foreach (var groupName in groupNames)\n {\n groupData.Add(CreateDataCombination(groupName, accountName));\n }\n\n return groupData;\n }\n\n private static DataCombination CreateDataCombination(string groupName, string accountName)\n {\n return new DataCombination\n {\n GroupName = groupName,\n Account = accountName\n };\n }\n}\n</code></pre>\n\n<p>(Note that I have stripped away some of the extra logic that is present in my code which only applies for my purposes; thus the whole use of <code>DataCombinationCollectionCreator</code> might be overkill for you.)</p>\n\n<p>It's all fairly self-explanatory. Whether it performs better than your code, I don't know: AD operations can be notoriously slow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:14:12.673",
"Id": "236852",
"ParentId": "236839",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236852",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T12:38:29.927",
"Id": "236839",
"Score": "1",
"Tags": [
"c#",
"performance",
"wpf",
"active-directory"
],
"Title": "scan activedirectory for all users and their groups in domain with c#"
}
|
236839
|
<p>We all know the classic version of counting the number of elements in a C array: <code>sizeof(a)/sizeof(*a)</code></p>
<p>But this is dangerous, because if used on a pointer it will return garbage values.</p>
<p>So I made this macro, utilizing gcc extensions. As far as I can tell, it works the way it is supposed to, which is causing compiler error when used on a pointer instead of array.</p>
<pre><code>#define COUNT(a) (__builtin_choose_expr( \
__builtin_types_compatible_p(typeof(a), typeof(&a[0])), \
(void)0, \
(sizeof(a)/sizeof(a[0]))))
</code></pre>
<pre><code>/* Only to demonstrate how to use the macro. It's not part of the code
I want reviewed. */
int main(void)
{
int arr[5];
int *p;
int x = COUNT(arr);
// This line will yield the compiler error:
// error: void value not ignored as it ought to be
int y = COUNT(p);
}
</code></pre>
<p>Any suggestions? Have I missed anything crucial?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T03:59:10.480",
"Id": "464651",
"Score": "1",
"body": "klutt, Why `int x` and not `size_t x`, the type returned by the division?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T04:06:16.343",
"Id": "464652",
"Score": "0",
"body": "See also [Array-size macro that rejects pointers](https://stackoverflow.com/q/19452971/2410359)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T08:45:00.370",
"Id": "464664",
"Score": "0",
"body": "Why are you trying to write the value of a `void` on the last line of your `main`? What are you trying to illustrate here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:10:20.897",
"Id": "464668",
"Score": "0",
"body": "@chux-ReinstateMonica See comment. Also, I should have realized that a linux kernel developer already thought of this :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:11:16.920",
"Id": "464669",
"Score": "0",
"body": "@Mast Because that will fail. I want a compiler error if it is used on a pointer instead of an array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:27:21.530",
"Id": "464692",
"Score": "0",
"body": "@klutt Ah, you're showing intended failure here. Now it makes sense."
}
] |
[
{
"body": "<p>We need to protect <code>a</code> when it's an expression - we've put parens around <code>a[0]</code> where we should have put them around <code>a</code>:</p>\n\n<pre><code>(sizeof(a)/sizeof(a)[0])\n</code></pre>\n\n<p>For the same reason, I think that the second <code>typeof</code> should be</p>\n\n<pre><code>typeof(&(a)[0])\n</code></pre>\n\n<p>I have to admit that I can't easily contrive an expression of array type where the parens make a difference, but better safe than sorry...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T15:10:50.750",
"Id": "236842",
"ParentId": "236841",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T14:41:37.407",
"Id": "236841",
"Score": "4",
"Tags": [
"c",
"gcc",
"c-preprocessor"
],
"Title": "Macro for counting number of elements in an array"
}
|
236841
|
<p>Thanks again to everyone for their very useful suggestions concerning a huge integer class <a href="https://codereview.stackexchange.com/q/236585">I posted here several days ago</a>. I have made many of the suggested changes, perhaps the biggest being in the implementation. In particular, I am now using an array of <code>uint32_t</code> type to store digits with each member representing a base <span class="math-container">\$2^{32}\$</span> digit. This replaces the <code>uint8_t</code> used in the previous version. The radix complement is now base - <span class="math-container">\$2^{32}\$</span> complement. This change of type has improved speed performance <em>dramatically</em>. For example, in the previous version calculating <span class="math-container">\$1000!\$</span> took about 43 seconds on my laptop. It is now done in much less than 1 second! I have not made the class a template, as suggested, but that is quite easy to do. I have not made the thousands separator adhere to local practice. I acknowledge the importance of this and it should be done, but, right now, I just need something that makes sense to a numerate human.</p>
<p>Other changes are:</p>
<ol>
<li>The class is in its own namespace.</li>
<li>The non-class inline utility functions are now in an anonymous namespace to restrict access to the translation unit (file).</li>
<li>A conversion constructor now creates/converts from <code>long long int</code> rather than from <code>long int</code>, to make the code more friendly to other operating systems.</li>
<li>Cleaned up the code for the constructor from a C string, which now validates the supplied string. (I did not change type to <code>std::string</code> because 99% of the time the string supplied will be a literal.)</li>
<li>Fixed undefined (okay, plain buggy) behaviour in <code>isZero()</code> and <code>toRawString()</code>. Many thanks to those who pointed this out.</li>
<li>Added static member functions <code>getMinimum()</code> and <code>getMaximum()</code> to return the minimum and maximum, respectively, of the integers that are representable in the base <span class="math-container">\$2^{32}\$</span> scheme.</li>
<li>Added a member function <code>numDecimalDigits()</code> which returns the number of decimal digits in the decimal representation of <code>*this</code>.</li>
<li>Added explicit casts in the inner loops of the arithmetic operators +, -, etc., to ensure that the operands are promoted to <code>uint64_t</code> before carrying out addition, multiplication, etc., so that carries propagate correctly.</li>
<li>Updated the driver program, which now runs much faster and calculates
many, many more digits.</li>
<li>Other minor code aesthetic changes.</li>
</ol>
<p>The default implementation has <code>numDigits</code> hard coded to 300, which gives 2890 decimal digits. You can go considerably higher than this if your hardware can handle it. However, conversion to <code>long double</code> will silently break (if you indeed need it) outputting <code>NaN</code>s, unless you take steps to put the CPU into a state that faults on these errors.</p>
<p>Thanks again to all who contributed to these changes. This project has produced a working class that I think is quite usable, and I am very encouraged by that.</p>
<p>The new code follows. I'd appreciate your comments and suggestions for improvement. Thank you for your time.</p>
<p>HugeInt.h</p>
<pre><code>/*
* HugeInt.h
*
* Definition of the huge integer class
* February, 2020
*
* RADIX 2^32 VERSION
*
* Huge integers are represented as N-digit arrays of uint32_t types, where
* each uint32_t value represents a base-2^32 digit. By default N = 300, which
* corresponds to a maximum of 2890 decimal digits. Each uint32_t contains
* a single base-2^32 digit in the range 0 <= digit <= 2^32 - 1. If `index'
* represents the index of the array of uint32_t digits[N],
* i.e., 0 <= index <= N - 1, and 'value' represents the power of 2^32
* corresponding to the radix 2^32 digit at 'index', then we have the following
* correspondence:
*
* index |...... | 4 | 3 | 2 | 1 | 0 |
* -----------------------------------------------------------------------
* value |...... | (2^32)^4 | (2^32)^3 | (2^32)^2 | (2^32)^1 | (2^32)^0 |
*
* The physical layout of the uint32_t array in memory is:
*
* uint32_t digits[N] = {digits[0], digits[1], digits[2], digits[3], ... }
*
* which means that the units (2^32)^0 appear first in memory, while the power
* (2^32)^(N-1) appears last. This LITTLE ENDIAN storage represents the
* number in memory in the REVERSE order of the way we write decimal numbers,
* but is convenient.
*
* Negative integers are represented by their radix complement. With the
* base 2^32 implementation here, we represent negative integers by their base
* 2^32 complement. With this convention the range of
* non-negative integers is:
* 0 <= x <= (2^32)^N/2 - 1
* The range of base 2^32 integers CORRESPONDING to negative values in the
* base 2^32 complement scheme is:
* (2^32)^N/2 <= x <= (2^32)^N - 1
* So -1 corresponds to (2^32)^N - 1, -2 corresponds to (2^32)^N - 2, and so on.
*
* The complete range of integers represented by a HugeInt using radix
* complement is:
*
* -(2^32)^N/2 <= x <= (2^32)^N/2 - 1
*/
#ifndef HUGEINT_H
#define HUGEINT_H
#include <string>
#include <iostream>
namespace iota {
class HugeInt {
public:
HugeInt() = default;
HugeInt(const long long int); // conversion constructor from long long int
explicit HugeInt(const char *const); // conversion constructor from C string
HugeInt(const HugeInt&); // copy/conversion constructor
// assignment operator
const HugeInt& operator=(const HugeInt&);
// unary minus operator
HugeInt operator-() const;
// conversion to long double
explicit operator long double() const;
// basic arithmetic
friend HugeInt operator+(const HugeInt&, const HugeInt&);
friend HugeInt operator-(const HugeInt&, const HugeInt&);
friend HugeInt operator*(const HugeInt&, const HugeInt&);
// friend HugeInt operator/(const HugeInt&, const HugeInt&); // TODO:
// increment and decrement operators
HugeInt& operator+=(const HugeInt&);
HugeInt& operator-=(const HugeInt&);
HugeInt& operator*=(const HugeInt&);
// HugeInt& operator/=(const HugeInt&); TODO:
HugeInt& operator++(); // prefix
HugeInt operator++(int); // postfix
HugeInt& operator--(); // prefix
HugeInt operator--(int); // postfix
// relational operators
friend bool operator==(const HugeInt&, const HugeInt&);
friend bool operator!=(const HugeInt&, const HugeInt&);
friend bool operator<(const HugeInt&, const HugeInt&);
friend bool operator>(const HugeInt&, const HugeInt&);
friend bool operator<=(const HugeInt&, const HugeInt&);
friend bool operator>=(const HugeInt&, const HugeInt&);
// input/output
std::string toRawString() const;
std::string toDecimalString() const;
friend std::ostream& operator<<(std::ostream&, const HugeInt&);
friend std::istream& operator>>(std::istream&, HugeInt&);
// informational
int numDecimalDigits() const;
static HugeInt getMinimum();
static HugeInt getMaximum();
private:
static const int numDigits{300}; // max. no. radix 2^32 digits
static const uint64_t twoPow32{4294967296}; // 2^32, for convenience
uint32_t digits[numDigits]{0}; // radix 2^32 digits; default 0
// private utility functions
bool isZero() const;
bool isNegative() const;
HugeInt& radixComplementSelf();
HugeInt radixComplement() const;
HugeInt shortDivide(uint32_t) const;
uint32_t shortModulo(uint32_t) const;
HugeInt shortMultiply(uint32_t) const;
HugeInt& shiftLeftDigits(int);
};
} /* namespace iota */
#endif /* HUGEINT_H */
</code></pre>
<p>HugeInt.cpp</p>
<pre><code>/*
* HugeInt.cpp
*
* Implementation of the HugeInt class. See comments in HugeInt.h for
* details of representation, etc.
*
* February, 2020
*
* RADIX 2^32 VERSION
*
*/
#include <cstdlib> // for abs(), labs(), etc.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <stdexcept>
#include <cmath>
#include "HugeInt.h"
/*
* Non-member utility functions (in anonymous namespace -- file scope only).
*
*/
namespace { /* anonymous namespace */
/*
* Simple function to check for non-digit characters in a C string.
*
* Returns true if string contains all digit characters; otherwise
* false.
*
*/
inline bool validate_digits(const char *const str) {
bool retval = true;
for (size_t i = 0; i < std::strlen(str); ++i) {
if (std::isdigit(static_cast<unsigned char>(str[i])) == 0) {
retval = false;
break;
}
}
return retval;
}
/**
* get_carry32
*
* Return the high 32 bits of a 64-bit uint64_t.
* Return this 32-bit value as a uint32_t.
*
* @param value
* @return
*/
inline uint32_t get_carry32(uint64_t value) {
return static_cast<uint32_t>(value >> 32 & 0xffffffff);
}
/**
* get_digit32
*
* Return the low 32 bits of the two-byte word stored as an int.
* Return this 32-bit value as a uint32_t.
*
* @param value
* @return
*/
inline uint32_t get_digit32(uint64_t value) {
return static_cast<uint32_t>(value & 0xffffffff);
}
} /* anonymous namespace */
/*
* Member functions in namespace iota
*
*/
namespace iota {
/**
* Constructor (conversion constructor)
*
* Construct a HugeInt from a long long int.
*
*/
HugeInt::HugeInt(const long long int x) {
if (x == 0LL) {
return;
}
long long int xp{std::llabs(x)};
int i{0};
// Successively determine units, 2^32's, (2^32)^2's, (2^32)^3's, etc.
// storing them in digits[0], digits[1], digits[2], ...,
// respectively. That is units = digits[0], 2^32's = digits[1], etc.
while (xp > 0LL) {
digits[i++] = xp % twoPow32;
xp /= twoPow32;
}
if (x < 0LL) {
radixComplementSelf();
}
}
/**
* Constructor (conversion constructor)
*
* Construct a HugeInt from a null-terminated C string representing the
* base 10 representation of the number. The string is assumed to have
* the form "[+/-]31415926", including an optional '+' or '-' sign.
*
* WARNING: No spaces are allowed in the decimal string containing numerals.
*
*
* @param str
*/
HugeInt::HugeInt(const char *const str) {
const int len{static_cast<int>(std::strlen(str))};
if (len == 0) {
throw std::invalid_argument{"empty decimal string in constructor."};
}
// Check for explicit positive and negative signs and adjust accordingly.
// If negative, we flag the case and perform a radix complement at the end.
bool flagNegative{false};
int numDecimalDigits{len};
int offset{0};
if (str[0] == '+') {
--numDecimalDigits;
++offset;
}
if (str[0] == '-') {
flagNegative = true;
--numDecimalDigits;
++offset;
}
// validate the string of numerals
if (!validate_digits(str + offset)) {
throw std::invalid_argument{"string contains non-digit in constructor."};
}
// Loop (backwards) through each decimal digit, digit[i], in the string,
// adding its numerical contribution, digit[i]*10^i, to theNumber. Here i
// runs upwards from zero, starting at the right-most digit of the string
// of decimal digits.
uint32_t digitValue{0};
HugeInt theNumber{0LL};
HugeInt powerOfTen{1LL}; // initially 10^0 = 1
for (int i = 0; i < numDecimalDigits; ++i) {
digitValue = static_cast<uint32_t>(str[len - 1 - i]) - '0';
theNumber += powerOfTen.shortMultiply(digitValue);
powerOfTen = powerOfTen.shortMultiply(10);
}
if (flagNegative) {
theNumber.radixComplementSelf();
}
for (int i = 0; i < numDigits; ++i) {
digits[i] = theNumber.digits[i];
}
}
/**
* Copy constructor (could be defaulted)
*
* @param rhs
*/
HugeInt::HugeInt(const HugeInt& rhs) {
// TODO: perhaps call copy assignment?
for (int i = 0; i < numDigits; ++i)
digits[i] = rhs.digits[i];
}
/**
* Assignment operator
*
* @param rhs
* @return
*/
const HugeInt& HugeInt::operator=(const HugeInt& rhs) {
if (&rhs != this) {
for (int i = 0; i < numDigits; ++i) {
digits[i] = rhs.digits[i];
}
}
return *this;
}
/**
* Unary minus operator
*
* @return
*/
HugeInt HugeInt::operator-() const {
return radixComplement();
}
/**
* operator long double()
*
* Use with static_cast<long double>(hugeint) to convert hugeint to its
* approximate (long double) floating point value.
*
*/
HugeInt::operator long double() const {
long double sign{1.0L};
HugeInt copy{*this};
if (copy.isNegative()) {
copy.radixComplementSelf();
sign = -1.0L;
}
long double retval{0.0L};
long double pwrOfBase{1.0L}; // Base = 2^32; (2^32)^0 initially
for (int i = 0; i < numDigits; ++i) {
retval += copy.digits[i] * pwrOfBase;
pwrOfBase *= twoPow32;
}
return retval*sign;
}
/**
* Operator +=
*
* NOTE: With the conversion constructors provided, also
* provides operator+=(long int) and
* operator+=(const char *const)
*
* @param increment
* @return
*/
HugeInt& HugeInt::operator+=(const HugeInt& increment) {
*this = *this + increment;
return *this;
}
/**
* Operator -=
*
* NOTE: With the conversion constructors provided, also
* provides operator-=(long int) and
* operator-=(const char *const)
*
*
* @param decrement
* @return
*/
HugeInt& HugeInt::operator-=(const HugeInt& decrement) {
*this = *this - decrement;
return *this;
}
/**
* Operator *=
*
* NOTE: With the conversion constructors provided, also
* provides operator*=(long int) and
* operator*=(const char *const)
*
* @param multiplier
* @return
*/
HugeInt& HugeInt::operator*=(const HugeInt& multiplier) {
*this = *this * multiplier;
return *this;
}
/**
* Operator ++ (prefix)
*
* @return
*/
HugeInt& HugeInt::operator++() {
*this = *this + 1LL;
return *this;
}
/**
* Operator ++ (postfix)
*
* @param
* @return
*/
HugeInt HugeInt::operator++(int) {
HugeInt retval{*this};
++(*this);
return retval;
}
/**
* Operator -- (prefix)
*
* @return
*/
HugeInt& HugeInt::operator--() {
*this = *this - 1LL;
return *this;
}
/**
* Operator -- (postfix)
*
* @param
* @return
*/
HugeInt HugeInt::operator--(int) {
HugeInt retval{*this};
--(*this);
return retval;
}
////////////////////////////////////////////////////////////////////////////
// Input/Output //
////////////////////////////////////////////////////////////////////////////
/**
* toRawString()
*
* Format a HugeInt as string in raw internal format, i.e., as a sequence
* of base-2^32 digits (each in decimal form, 0 <= digit <= 2^32 - 1).
*
* @return
*/
std::string HugeInt::toRawString() const {
int istart{numDigits - 1};
for ( ; istart >= 0; --istart) {
if (digits[istart] != 0) {
break;
}
}
std::ostringstream oss;
if (istart == -1) // the number is zero
{
oss << digits[0];
} else {
for (int i = istart; i >= 0; --i) {
oss << std::setw(10) << std::setfill('0') << digits[i] << " ";
}
}
return oss.str();
}
/**
* toDecimalString()
*
* Format HugeInt as a string of decimal digits. The length of the decimal
* string is estimated (roughly) by solving for x:
*
* (2^32)^N = 10^x ==> x = N log_10(2^32) = N * 9.63296 (approx)
*
* where N is the number of base 2^32 digits. A safety margin of 5 is added
* for good measure.
*
* @return
*/
std::string HugeInt::toDecimalString() const {
std::ostringstream oss;
// Special case HugeInt == 0 is easy
if (isZero()) {
oss << "0";
return oss.str();
}
// set copy to the absolute value of *this
// for use in shortDivide and shortModulo
HugeInt tmp;
if (isNegative()) {
oss << "-";
tmp = this->radixComplement();
} else {
tmp = *this;
}
// determine the decimal digits of the absolute value
int i{0};
const int numDecimal{static_cast<int>(numDigits * 9.63296) + 5};
uint32_t decimalDigits[numDecimal]{0};
while (!tmp.isZero()) {
decimalDigits[i++] = tmp.shortModulo(10);
tmp = tmp.shortDivide(10);
}
// output the decimal digits
for (int j = i - 1; j >= 0; --j) {
if (j < i - 1) {
if ((j + 1) % 3 == 0) {
oss << ','; // thousands separator
}
}
oss << decimalDigits[j];
}
return oss.str();
}
/////////////////////////////////////////////////////////////////////////////
// Useful informational member functions //
/////////////////////////////////////////////////////////////////////////////
/**
* getMinimum()
*
* Return the minimum representable value for a HugeInt. Static member
* function.
*
* @return
*/
HugeInt HugeInt::getMinimum() {
HugeInt retval;
retval.digits[numDigits - 1] = 2147483648;
return retval;
}
/**
* getMaximum()
*
* Return the maximum representable value for a HugeInt. Static member
* function.
*
* @return
*/
HugeInt HugeInt::getMaximum() {
HugeInt retval;
retval.digits[numDigits - 1] = 2147483648;
--retval;
return retval;
}
/**
* numDecimalDigits()
*
* Return the number of decimal digits this HugeInt has.
*
* We use a simple algorithm using base-10 logarithms. Consider, e.g., 457,
* which we can write as 4.57 * 10^2. Taking base-10 logs:
*
* log10(4.57 * 10^2) = log10(4.57) + 2.
*
* Since 0 < log10(4.57) < log10(10) = 1, we need to round up (always) to get
* the extra digit, corresponding to the fractional part in the eq. above.
* Hence the use of ceil below. Values of x in the range -10 < x < 10 are dealt
* with as a special case.
*
* @return
*/
int HugeInt::numDecimalDigits() const {
if (-10 < *this && *this < 10) {
return 1;
}
else {
long double approx = static_cast<long double>(*this);
return static_cast<int>(std::ceil(std::log10(std::fabs(approx))));
}
}
////////////////////////////////////////////////////////////////////////////
// friend functions //
////////////////////////////////////////////////////////////////////////////
/**
* friend binary operator +
*
* Add two HugeInts a and b and return c = a + b.
*
* Note: since we provide a conversion constructor for long long int's, this
* function, in effect, also provides the following functionality by
* implicit conversion of long long int's to HugeInt
*
* c = a + <some long long int> e.g. c = a + 2412356LL
* c = <some long long int> + a e.g. c = 2412356LL + a
*
* @param a
* @param b
* @return
*/
HugeInt operator+(const HugeInt& a, const HugeInt& b) {
uint32_t carry{0};
uint64_t partial{0};
HugeInt sum;
for (int i = 0; i < HugeInt::numDigits; ++i) {
partial = static_cast<uint64_t>(a.digits[i])
+ static_cast<uint64_t>(b.digits[i])
+ static_cast<uint64_t>(carry);
carry = get_carry32(partial);
sum.digits[i] = get_digit32(partial);
}
return sum;
}
/**
* friend binary operator-
*
* Subtract HugeInt a from HugeInt a and return the value c = a - b.
*
* Note: since we provide a conversion constructor for long long int's, this
* function, in effect, also provides the following functionality by
* implicit conversion of long long int's to HugeInt:
*
* c = a - <some long long int> e.g. c = a - 2412356LL
* c = <some long long int> - a e.g. c = 2412356LL - a
*
* @param a
* @param b
* @return
*/
HugeInt operator-(const HugeInt& a, const HugeInt& b) {
return a + (-b);
}
/**
* friend binary operator *
*
* Multiply two HugeInt numbers. Uses standard long multipication algorithm
* adapted to base 2^32. See comments on implicit conversion before
* HugeInt operator+(const HugeInt&, const HugeInt& ) above.
*
* @param a
* @param b
* @return
*/
HugeInt operator*(const HugeInt& a, const HugeInt& b) {
HugeInt product{0LL};
HugeInt partial;
for (int i = 0; i < HugeInt::numDigits; ++i) {
partial = a.shortMultiply(b.digits[i]);
product += partial.shiftLeftDigits(i);
}
return product;
}
////////////////////////////////////////////////////////////////////////////
// Relational operators (friends) //
////////////////////////////////////////////////////////////////////////////
/**
* Operator ==
*
* @param lhs
* @param rhs
* @return
*/
bool operator==(const HugeInt& lhs, const HugeInt& rhs) {
HugeInt diff{rhs - lhs};
return diff.isZero();
}
/**
* Operator !=
*
* @param lhs
* @param rhs
* @return
*/
bool operator!=(const HugeInt& lhs, const HugeInt& rhs) {
return !(rhs == lhs);
}
/**
* Operator <
*
* @param lhs
* @param rhs
* @return
*/
bool operator<(const HugeInt& lhs, const HugeInt& rhs) {
HugeInt diff{lhs - rhs};
return diff.isNegative();
}
/**
* Operator >
*
* @param lhs
* @param rhs
* @return
*/
bool operator>(const HugeInt& lhs, const HugeInt& rhs) {
return rhs < lhs;
}
/**
* Operator <=
*
* @param lhs
* @param rhs
* @return
*/
bool operator<=(const HugeInt& lhs, const HugeInt& rhs) {
return !(lhs > rhs);
}
/**
* Operator >=
*
* @param lhs
* @param rhs
* @return
*/
bool operator>=(const HugeInt& lhs, const HugeInt& rhs) {
return !(lhs < rhs);
}
////////////////////////////////////////////////////////////////////////////
// Private utility functions //
////////////////////////////////////////////////////////////////////////////
/**
* isZero()
*
* Return true if the HugeInt is zero, otherwise false.
*
* @return
*/
bool HugeInt::isZero() const {
int i{numDigits - 1};
for ( ; i >= 0; --i) {
if (digits[i] != 0) {
break;
}
}
return i == -1;
}
/**
* isNegative()
*
* Return true if a number x is negative (x < 0). If x >=0, then
* return false.
*
* NOTE: In the radix-2^32 complement convention, negative numbers, x, are
* represented by the range of values: (2^32)^N/2 <= x <=(2^32)^N - 1.
* Since (2^32)^N/2 = (2^32/2)*(2^32)^(N-1) = 2147483648*(2^32)^(N-1),
* we need only check whether the (N - 1)'th base 2^32 digit is at
* least 2147483648.
*
* @return
*/
bool HugeInt::isNegative() const {
return digits[numDigits - 1] >= 2147483648;
}
/**
* shortDivide:
*
* Return the result of a base 2^32 short division by divisor, where
* 0 < divisor <= 2^32 - 1, using the usual primary school algorithm
* adapted to radix 2^32.
*
* WARNING: assumes both HugeInt and the divisor are POSITIVE.
*
* @param divisor
* @return
*/
HugeInt HugeInt::shortDivide(uint32_t divisor) const {
uint64_t j;
uint64_t remainder{0};
HugeInt quotient;
for (int i = numDigits - 1; i >= 0; --i) {
j = twoPow32 * remainder + static_cast<uint64_t>(digits[i]);
quotient.digits[i] = static_cast<uint32_t>(j / divisor);
remainder = j % divisor;
}
return quotient;
}
/**
* shortModulo
*
* Return the remainder of a base 2^32 short division by divisor, where
* 0 < divisor <= 2^32 - 1.
*
* WARNING: assumes both HugeInt and the divisor are POSITIVE.
*
* @param divisor
* @return
*/
uint32_t HugeInt::shortModulo(uint32_t divisor) const {
uint64_t j;
uint64_t remainder{0};
for (int i = numDigits - 1; i >= 0; --i) {
j = twoPow32 * remainder + static_cast<uint64_t>(digits[i]);
remainder = j % divisor;
}
return static_cast<uint32_t>(remainder);
}
/**
* shortMultiply
*
* Return the result of a base 2^32 short multiplication by multiplier, where
* 0 <= multiplier <= 2^32 - 1.
*
* WARNING: assumes both HugeInt and multiplier are POSITIVE.
*
* @param multiplier
* @return
*/
HugeInt HugeInt::shortMultiply(uint32_t multiplier) const {
uint32_t carry{0};
uint64_t tmp;
HugeInt product;
for (int i = 0; i < numDigits; ++i) {
tmp = static_cast<uint64_t>(digits[i]) * multiplier + carry;
carry = get_carry32(tmp);
product.digits[i] = get_digit32(tmp);
}
return product;
}
/**
* shiftLeftDigits
*
* Shift this HugeInt's radix-2^32 digits left by num places, filling
* with zeroes from the right.
*
* @param num
* @return
*/
HugeInt& HugeInt::shiftLeftDigits(int num) {
if (num == 0) {
return *this;
}
for (int i = numDigits - num - 1; i >= 0; --i) {
digits[i + num] = digits[i];
}
for (int i = 0; i < num; ++i) {
digits[i] = 0;
}
return *this;
}
/**
* radixComplementSelf()
*
* Perform a radix complement on the object in place (changes object).
*
* @return
*/
HugeInt& HugeInt::radixComplementSelf() {
if (!isZero()) {
uint64_t sum{0};
uint32_t carry{1};
for (int i = 0; i < numDigits; ++i) {
sum = static_cast<uint64_t>(twoPow32 - 1)
- static_cast<uint64_t>(digits[i])
+ static_cast<uint64_t>(carry);
carry = get_carry32(sum);
digits[i] = get_digit32(sum);
}
}
return *this;
}
/**
* radixComplement()
*
* Return the radix-2^32 (base-2^32) complement of HugeInt.
*
* @return
*/
HugeInt HugeInt::radixComplement() const {
HugeInt result{*this};
return result.radixComplementSelf();
}
/**
* operator<<
*
* Overloaded stream insertion for HugeInt.
*
* @param output
* @param x
* @return
*/
std::ostream& operator<<(std::ostream& output, const HugeInt& x) {
output << x.toDecimalString();
return output;
}
/**
* operator >>
*
* Overloaded stream extraction for HugeInt.
*
* @param input
* @param x
* @return
*/
std::istream& operator>>(std::istream& input, HugeInt& x) {
std::string str;
input >> str;
x = HugeInt(str.c_str());
return input;
}
} /* namespace iota */
</code></pre>
<p>Sample driver code:</p>
<pre><code>/*
* Simple driver to test a few features of the HugeInt class.
*
* Improved version.
*
*/
#include <iostream>
#include <iomanip>
#include <limits>
#include "HugeInt.h"
iota::HugeInt read_bounded_hugeint(const iota::HugeInt&, const iota::HugeInt&);
iota::HugeInt factorial_recursive(const iota::HugeInt&);
iota::HugeInt factorial_iterative(const iota::HugeInt&);
iota::HugeInt fibonacci_recursive(const iota::HugeInt&);
iota::HugeInt fibonacci_iterative(const iota::HugeInt&);
void preamble();
// limits to avoid overflow
const iota::HugeInt FACTORIAL_LIMIT{1100LL};
const iota::HugeInt FIBONACCI_LIMIT{13000LL};
int main() {
preamble(); // blah
iota::HugeInt nfac = read_bounded_hugeint(0LL, FACTORIAL_LIMIT);
iota::HugeInt factorial = factorial_iterative(nfac);
long double factorial_dec = static_cast<long double>(factorial);
std::cout << "\nThe value of " << nfac << "! is:\n";
std::cout << factorial << '\n';
std::cout << "\nThis value has " << factorial.numDecimalDigits()
<< " decimal digits.\n";
std::cout.precision(std::numeric_limits<long double>::digits10);
std::cout << "\nIts decimal approximation is: " << factorial_dec << "\n\n";
iota::HugeInt nfib = read_bounded_hugeint(0LL, FIBONACCI_LIMIT);
iota::HugeInt fibonacci = fibonacci_iterative(nfib);
long double fibonacci_dec = static_cast<long double>(fibonacci);
std::cout << "\nThe " << nfib << "th Fibonacci number is:\n";
std::cout << fibonacci << '\n';
std::cout << "\nThis value has " << fibonacci.numDecimalDigits()
<< " decimal digits.\n";
std::cout << "\nIts decimal approximation is: " << fibonacci_dec << '\n';
std::cout << "\nComparing these two values we observe that ";
if (factorial == fibonacci) {
std::cout << nfac << "! == Fibonacci_{" << nfib << "}\n";
}
if (factorial < fibonacci) {
std::cout << nfac << "! < Fibonacci_{" << nfib << "}\n";
}
if (factorial > fibonacci) {
std::cout << nfac << "! > Fibonacci_{" << nfib << "}\n";
}
iota::HugeInt sum = factorial + fibonacci;
iota::HugeInt diff = factorial - fibonacci;
std::cout << "\nTheir sum (factorial + fibonacci) is:\n";
std::cout << sum << '\n';
std::cout << "\n\twhich is approximately " << static_cast<long double>(sum);
std::cout << '\n';
std::cout << "\nTheir difference (factorial - fibonacci) is:\n";
std::cout << diff << '\n';
std::cout << "\n\twhich is approximately " << static_cast<long double>(diff);
std::cout << '\n';
iota::HugeInt x{"-80538738812075974"};
iota::HugeInt y{"80435758145817515"};
iota::HugeInt z{"12602123297335631"};
iota::HugeInt k = x*x*x + y*y*y + z*z*z;
std::cout << "\nDid you know that, with:\n";
std::cout << "\tx = " << x << '\n';
std::cout << "\ty = " << y << '\n';
std::cout << "\tz = " << z << '\n';
std::cout << "\nx^3 + y^3 + z^3 = " << k << '\n';
return 0;
}
/**
* read_bounded_hugeint
*
* Read and return a value in the range min <= value <= max.
* Dies after 5 retries.
*
* @param min
* @param max
* @return
*/
iota::HugeInt read_bounded_hugeint(const iota::HugeInt& min,
const iota::HugeInt& max) {
iota::HugeInt value;
bool fail;
int retries = 0;
do {
try {
std::cout << "Enter an integer (" << min << " - " << max << "): ";
std::cin >> value;
if (value < min || value > max) {
fail = true;
++retries;
}
else {
fail = false;
}
}
catch (std::invalid_argument& error) {
std::cout << "You entered an invalid HugeInt value.";
std::cout << " Please use, e.g., [+/-]1234567876376763.\n";
//std::cout << "Exception: " << error.what() << '\n';
fail = true;
++retries;
}
} while (fail && retries < 5);
if (retries == 5) {
std::cerr << "Giving up...\n";
exit(EXIT_FAILURE);
}
return value;
}
/**
* factorial_recursive:
*
* Recursive factorial function using HugeInt. Not too slow.
*
* @param n
* @return
*/
iota::HugeInt factorial_recursive(const iota::HugeInt& n) {
const iota::HugeInt one{1LL};
if (n <= one) {
return one;
} else {
return n * factorial_recursive(n - one);
}
}
iota::HugeInt factorial_iterative(const iota::HugeInt& n) {
iota::HugeInt result{1LL};
if (n == 0LL) {
return result;
}
for (iota::HugeInt i = n; i >= 1; --i) {
result *= i;
}
return result;
}
/**
* fibonacci_recursive:
*
* Recursively calculate the n'th Fibonacci number, where n>=0.
*
* WARNING: S l o w . . .
*
* @param n
* @return
*/
iota::HugeInt fibonacci_recursive(const iota::HugeInt& n) {
const iota::HugeInt zero;
const iota::HugeInt one{1LL};
if ((n == zero) || (n == one)) {
return n;
}
else {
return fibonacci_recursive(n - 1LL) + fibonacci_recursive(n - 2LL);
}
}
iota::HugeInt fibonacci_iterative(const iota::HugeInt& n) {
const iota::HugeInt zero;
const iota::HugeInt one{1LL};
if ((n == zero) || (n == one)) {
return n;
}
iota::HugeInt retval;
iota::HugeInt fib_nm1 = one;
iota::HugeInt fib_nm2 = zero;
for (iota::HugeInt i = 2; i <= n; ++i) {
retval = fib_nm1 + fib_nm2;
fib_nm2 = fib_nm1;
fib_nm1 = retval;
}
return retval;
}
void preamble() {
long double min = static_cast<long double>(iota::HugeInt::getMinimum());
long double max = static_cast<long double>(iota::HugeInt::getMaximum());
std::cout.precision(std::numeric_limits<long double>::digits10);
std::cout <<"**************************************************************"
<<"*************\n\n";
std::cout << "The range of integers, x, that can be represented in "
<< "the default HugeInt\nconfiguration is, approximately\n"
<< " " << min << " <= x <= " << max << '\n';
std::cout << "\nThe precise values of the upper and lower limits can be "
<< "found using\nHugeInt::getMinimum()/HugeInt::getMaximum().\n";
std::cout << "\nThe maximum number of decimal digits of an integer "
<< "representable with\na HugeInt is: "
<< iota::HugeInt::getMaximum().numDecimalDigits()
<< "\n\n";
std::cout <<"**************************************************************"
<<"*************\n\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T15:35:14.990",
"Id": "464259",
"Score": "0",
"body": "Great stuff! Shame I'm about to leave for the weekend; I might make a start on an answer, but it won't be in any depth if I do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T15:36:15.743",
"Id": "464260",
"Score": "0",
"body": "Thanks for your help Toby! Your suggestions helped a lot; and thanks for the continued encouragement!"
}
] |
[
{
"body": "<p>I recommend including your internal headers first, before any standard headers. This helps expose any accidental dependencies that make it hard to use your types in another program.</p>\n\n<p>So in HugeInt.cpp, I'd write</p>\n\n<pre><code>#include \"HugeInt.h\"\n\n#include <cstdlib> // for abs(), labs(), etc.\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <cstring>\n#include <stdexcept>\n#include <cmath>\n</code></pre>\n\n<hr>\n\n<p>Don't include <code><iostream></code> in the header; that's overkill. We can include <code><iosfwd></code> instead, which is much lighter, and just gives us the forward declarations we need to specify <code>std::istream&</code> and <code>std::ostream&</code> in our signatures, without bringing in the full template definitions that are in <code><iostream></code>. That means that translation units not doing I/O don't carry the overhead.</p>\n\n<hr>\n\n<p>Spelling (throughout): <code>uint32_t</code> and <code>uint64_t</code> are in the <strong><code>std</code></strong> namespace. Your compiler is allowed to also declare them in the global namespace, but is not required to, so you have a portability bug.</p>\n\n<hr>\n\n<p>Perhaps we should provide a <code>divmod()</code> function that gives quotient and remainder in one operation, then use that to implement division and modulo? The \"short\" version of this would certainly be useful, and save duplication when executing <code>toDecimalString()</code>.</p>\n\n<hr>\n\n<p>We use a string-stream to implement <code>toDecimalString()</code>, and then use that to implement <code>operator<<()</code>. I think we should do that the other way around: use <code>operator<<()</code> to implement <code>toDecimalString()</code>. Then streamed output wouldn't need to create a temporary string. Consider using <a href=\"/q/189753/75307\">my stream-saver</a> if you want to preserve its manipulator state.</p>\n\n<hr>\n\n<p>In <code>toDecimalString()</code>, we have this loop that produces one digit at a time:</p>\n\n<pre><code>while (!tmp.isZero()) {\n decimalDigits[i++] = tmp.shortModulo(10);\n tmp = tmp.shortDivide(10);\n}\n</code></pre>\n\n<p>We can reduce the number of divisions ninefold, since <code>shortModulo()</code> accepts <code>std::uint32_t</code>. We can divide by 1 billion rather than ten, if we're careful about how we print the first \"block\":</p>\n\n<pre><code>// determine the decimal digits of the absolute value\nconstexpr int numDecimal{static_cast<int>(numDigits * 1.07032) + 1};\nstd::array<std::uint32_t, numDecimal> decimal;\n\nint i{0};\nwhile (!tmp.isZero()) {\n decimal[i++] = tmp.shortModulo(1'000'000'000);\n tmp = tmp.shortDivide(1'000'000'000);\n}\n\n// output the decimal digits, in threes\noss << std::setw(0) << std::setfill('0');\n--i;\n// first digits\nauto const d0 = decimal[i];\nif (d0 > 1'000'000) {\n oss << (d0 / 1'000'000) << ',' << std::setw(3);\n}\nif (d0 > 1'000) {\n oss << (d0 / 1'000 % 1'000) << ',' << std::setw(3);\n}\noss << (d0 % 1'000);\n// subsequent digits\nwhile (i--) {\n auto const d = decimal[i];\n oss << ',' << std::setw(3) << (d / 1'000'000)\n << ',' << std::setw(3) << (d / 1'000 % 1'000)\n << ',' << std::setw(3) << (d % 1'000);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:57:09.997",
"Id": "464577",
"Score": "0",
"body": "It was late an Friday when you posted this and I forgot to thank you. So a belated thanks for these very good ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:58:47.700",
"Id": "464578",
"Score": "1",
"body": "No problem - it was just minutes before I left for the weekend, too! The green tick is thanks enough..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:10:28.593",
"Id": "236847",
"ParentId": "236843",
"Score": "11"
}
},
{
"body": "<h2>API</h2>\n\n<ul>\n<li>In <code>HugeInt(long long int)</code>, there's no need for the <code>const</code>. In the function declaration it is ignored, at least by the GNU C++ compiler.</li>\n<li>Instead of <code>isZero</code>, I prefer to write <code>== 0</code>. I'd rather implement two <code>==</code> operators that compare <code>HugeInt, long long int</code> and vice versa.</li>\n<li>Same for <code>isNegative</code>, I'd write that as <code>< 0</code>.</li>\n<li>I'd also write <code>huge_int % 100</code> instead of calling <code>huge_int.shortModulo(100)</code>, as the former is much shorter.</li>\n<li>Same for the other mathematical operators.</li>\n<li>Instead of spelling out every digit of 4294967296, why don't you just write <code>uint64_t(1) << 32</code>? That would make the comment redundant.</li>\n<li>I'd rename <code>twoPow32</code> to <code>base</code> or <code>radix</code>.</li>\n<li>The name <code>radixComplementSelf</code> sounds like a bloated description for <code>negate</code>. It should probably be renamed to the latter.</li>\n</ul>\n\n<h2>Implementation</h2>\n\n<ul>\n<li><code>validate_digits</code> should rather be called <code>is_all_digits</code> since it doesn't validate anything, it just tests without rejecting.</li>\n<li>In <code>validate_digits</code>, the <code>retval</code> variable can be removed if you just <code>return</code> from within the loop.</li>\n<li>Still in <code>validate_digits</code>, what answer do you expect for the empty string, true or false?</li>\n<li>In <code>get_carry32</code> the <code>& 0xffffffff</code> is unnecessary since <code>uint32_t</code> is an <em>exact-width</em> integer type.</li>\n<li>Same for <code>get_digit32</code>.</li>\n<li>In <code>get_digit32</code>, the comment \"two-byte word\" probably refers to the old version that had <code>uint8_t</code> as its underlying type.</li>\n<li>Is there a particular reason for using <code>x == 0LL</code> instead of the simpler <code>x == 0</code>? For integer literals I find the latter easier to read, but of course your tools for static analysis may disagree.</li>\n<li><code>std::llabs(x)</code> looks a lot like it would invoke undefined behavior for <code>LLONG_MIN</code>.</li>\n<li>In the <code>const char *</code> constructor, <code>len</code> should be of type <code>std::size_t</code> instead of <code>int</code>.</li>\n<li>Still in the <code>const char *</code> constructor, the value of <code>uint32_t digitValue{0}</code> is unused. This variable should be moved inside the <code>for</code> loop, to make its scope as small as possible.</li>\n<li>Still in the <code>const char *</code> constructor, I think it's more efficient to process the digits from left to right, using <a href=\"https://en.wikipedia.org/wiki/Horner%27s_method\" rel=\"noreferrer\">Horner's method</a>. This could save you both of the temporary <code>HugeInt</code> variables. It certainly feels strange to have two variables of the same type that you are currently constructing, as if there were some hidden recursion.</li>\n<li>In the copy constructor, I wouldn't call the parameter <code>rhs</code> since there is no corresponding <code>lhs</code> variable anywhere nearby.</li>\n<li>In the <code>operator=</code>, I would leave out the <code>&rhs == this</code> test. It's unlikely that a variable gets assigned to itself.</li>\n<li>In <code>operator long double</code>, you should add the missing spaces in the <code>retval*sign</code> expression. The rest looks simple and fine.</li>\n<li>Instead of defining <code>operator+=</code> in terms of <code>operator+</code>, the more efficient variant is the other way round: first implement <code>operator+=</code> as a basic operation and then define <code>operator+</code> using <code>+=</code>. It typically saves a few variable assignments and memory allocations.</li>\n<li>I wonder whether you should really implement <code>operator++(int)</code> and <code>operator--(int)</code>. I don't think they are needed often. I'd wait until I really need them, just out of curiosity.</li>\n<li>In <code>operator--</code> you should rather call <code>operator-=</code> instead of <code>operator-</code>, since that will be more efficient after you rewrote the code.</li>\n<li>Instead of the currently unused <code>HugeInt::toRawString</code> I'd rather provide <code>HugeInt::toHexString</code> since that can be implemented easier and doesn't need any padding. Did you find any use for the current <code>toRawString</code>?</li>\n<li>In <code>toDecimalString</code>, in the case of zero there is no need to allocate an <code>std::ostringstream</code>. You can just write: <code>if (isZero()) return \"0\";</code>.</li>\n<li>Still in <code>toDecimalString</code>, the variable name <code>tmp</code> is always bad. Temporary, sure, but temporary <em>what</em>?</li>\n<li>In <code>getMinimum</code> and <code>getMaximum</code>, you should rather write <code>uint32_t(1) << 31</code> instead of spelling out the digits. It's simpler to read.</li>\n<li>The comment above <code>operator!=</code> contains exactly zero useful characters. It should be removed, and the other comments as well.</li>\n<li>In <code>isZero</code>, it's a waste of time that you have to iterate through all the 300 digits just to check if any of them is nonzero. It would be far more efficient to have a <code>size_t len</code> field in the <code>HugeInt</code>. Then you would only need to check whether <code>len <= 1 && digits[0] == 0</code>.</li>\n<li>In <code>shortModulo</code>, in addition to the \"WARNING: assumes\" comment, you should also add assertions to the code: <code>assert(divisor > 0)</code> and <code>assert(*this >= 0)</code>.</li>\n</ul>\n\n<h2>Test</h2>\n\n<p>In addition to the <code>main</code> function with an interactive test session, you should have lots of automatic unit tests that cover all normal and edge cases. Having these tests and running them regularly provides a safety net for all kinds of refactorings.</p>\n\n<h2>Performance</h2>\n\n<p>Calculating the factorial of 1000 and printing it should be possible in less than a millisecond. For example, the following quickly-written Kotlin code runs in 5 seconds on my machine, which means 0.5 milliseconds per iteration:</p>\n\n<pre><code>class BigIntTest {\n @Test\n fun name() {\n fun fac(n: Int): BigInteger {\n var fac = BigInteger.valueOf(1)\n for (i in 1..n) {\n fac *= BigInteger.valueOf(i.toLong())\n }\n return fac\n }\n\n for (i in 1..10000)\n fac(1000).toString()\n }\n}\n</code></pre>\n\n<p>A similar Go program is even faster, it needs only 0.137 milliseconds per iteration:</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package main\n\nimport (\n \"math/big\"\n \"testing\"\n)\n\nfunc fac(n int) *big.Int {\n fac := big.NewInt(1)\n for i := 1; i <= n; i++ {\n fac.Mul(fac, big.NewInt(int64(i)))\n }\n return fac\n}\n\nvar result string\n\nfunc Benchmark(b *testing.B) {\n for i := 0; i < b.N; i++ {\n result = fac(1000).String()\n }\n}\n</code></pre>\n\n<p>Your code should become similarly fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:54:35.173",
"Id": "464288",
"Score": "0",
"body": "Some very useful suggestions. Thank you for your detailed review. I'll try to respond more fully in due course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:26:42.440",
"Id": "464437",
"Score": "1",
"body": "Just to clarify a few points you raised. I have used names like `ShortModulo` (and kept these private) instead of `%` because these functions (operators) only implement short arithmetic forms of the operations. To confer on them the status of full operators would be misleading at best. Regarding `llabs(x)` invoking undefined behaviour for `x = LLONG_MIN`, if you can suggest an elegant solution, I'd be happy to hear it. Regarding `toRawString()`, this was (is) useful in early development testing. Having it convert to Hex would simply obfuscate, in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:27:27.190",
"Id": "464438",
"Score": "0",
"body": "Regarding `++`/`--`: why not implement them? \nI use them in the sample code provided (for demonstration), although looping \nwith `int`s is possible, too, and faster. Regarding performance: this project started out\nas a weekend coding exercise on a topic I find interesting. To compare it in its \nnascent form with highly-researched and well-developed code is a bit unfair. \nHowever, I am interested in improvement and, time permitting, will look into\nalgorithmic improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:55:35.513",
"Id": "464453",
"Score": "0",
"body": "Regarding `ShortModulo`: I didn't notice that the method was private. If it's possible to have private operators, that would still make sense I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:57:05.753",
"Id": "464454",
"Score": "1",
"body": "Regarding `llabs`: Some C libraries either do all computations in the negative range, and some others just have a special case for `LLONG_MIN` and then handle the rest as usual."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:59:04.320",
"Id": "464455",
"Score": "0",
"body": "Regarding the postfix `++/--`: I suggested to not implement them because they are less efficient than their prefix counterparts. Idiomatic C++ code uses the prefix operators anyway, therefore these missing operators would directly point out a possible performance optimization to the caller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T16:01:59.747",
"Id": "464456",
"Score": "0",
"body": "Regarding performance: I did not know that this was just a pet project of yours. The code looks generally useful, and I did not intend an unfair comparison. I just stated what I (and many others) expect from such code, which is to be reasonably fast. When you said \"about 45 seconds for 1000!\" in your first question, I knew immediately that something was wrong with your code. That is just too slow to be of any practical use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T16:07:56.667",
"Id": "464457",
"Score": "0",
"body": "Thanks Roland. Your comments are much appreciated and I have learned from them."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:44:11.167",
"Id": "236854",
"ParentId": "236843",
"Score": "10"
}
},
{
"body": "<p>The multiplication approach could be improved, even without non-portable optimization (significant gains are possible from that too, for example using <code>_mulx_u64</code>). Sadly it would make the code for multiplication less pretty, it looks nice now and with the following approach it wouldn't look as nice.</p>\n\n<p>A not so nice thing that is happening here is that the order of the computation forces the creation of big partial products which are added one by one, each taking an explict shift and a full BigInt addition. For the factorial benchmark this is not a concern, as one operand is always tiny. For a benchmark that stresses \"balanced\" multiplication, you could for example extend the Fibonacci tests to exponentiating a 2x2 matrix.</p>\n\n<p>An alternative arrangement is to generate the small partial products (one limb of the multiplier times one limb of the multiplicand) in the order of their <em>weight</em>, so a group of partial products (and a carry) of equal weight can be summed immediately without lots of temporary storage and then result in a limb of the final result. Handling carries is a bit tricky.</p>\n\n<p>For clarity, here is a diagram of that ordering:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yiY9jm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yiY9jm.png\" alt=\"partial product order\"></a></p>\n\n<p>(source: cryptographic hardware and embedded systems)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T19:12:20.200",
"Id": "464293",
"Score": "0",
"body": "That is interesting and very helpful. This was meant to be a simple C++ coding project, but as someone who is interested in algorithms, I appreciate you helpful suggestion. I shall definitely look into it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:55:40.663",
"Id": "236856",
"ParentId": "236843",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "236847",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T15:27:42.880",
"Id": "236843",
"Score": "12",
"Tags": [
"c++",
"performance",
"integer"
],
"Title": "Huge integer class using base 2^32 (was 256) follow up"
}
|
236843
|
<p>I have been looking for the best approach to creating an extension method that would give me the ability to select in a linq query using async/await with a max degree of parallelism. I'm aware that this can be achieved with the use of different libraries but wanted to create one without. Using postings I found online I made a few changes to convert a ForEachAsync to the following:</p>
<pre><code>public static async Task<IEnumerable<TOut>> SelectAsync<TIn, TOut>(this IEnumerable<TIn> source,
Func<TIn, Task<TOut>> body,
int maxDegreeOfParallelism)
{
var bag = new ConcurrentBag<TOut>();
var selectAsync = Partitioner.Create(source)
.GetPartitions(maxDegreeOfParallelism)
.Select(async partition =>
{
using (partition)
{
while (partition.MoveNext())
{
var item = await body(partition.Current);
bag.Add(item);
}
}
});
await Task
.WhenAll(selectAsync);
return bag;
}
</code></pre>
<p>Here is the unit test:</p>
<pre><code>[TestMethod]
public async Task SelectAsync_EnsureMaxConcurrency_SuccessfulOnChecksAsync()
{
// Arrange
const int itemsMax = 10;
const int dop = 5;
const int delayInMs = 1000;
var itemsToProcess = Enumerable
.Range(1, itemsMax);
// Act
var started = DateTime.Now;
var result = await itemsToProcess
.SelectAsync(async item =>
{
await Task.Delay(1000);
return item;
}, dop);
var elapsed = (DateTime.Now - started)
.TotalMilliseconds;
const double expected = (double)itemsMax / dop * delayInMs;
// Assert
Debug.WriteLine($"Elapsed:{elapsed} Expected:{expected}");
Assert.AreEqual(itemsMax, result.Count());
Assert.IsTrue(elapsed > expected);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T23:36:37.603",
"Id": "464308",
"Score": "1",
"body": "Thread count (and thus max parallelism) isn't decided in code, it's decided in the environment. The same compiled application will run on different machines with different specs (and thus potentially different thread counts). Your application will always inherently receive however many threads the environment has deemed appropriate (or less if you simply don't have enough going on to warrant all the available threads).. For direct control, you'd need to use threads, not tasks. But this question feels more like an XY problem or a misunderstanding of asynchronicity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T05:31:44.890",
"Id": "464312",
"Score": "0",
"body": "@Flater I appreciate your input. This isn't an XY problem nor is it a misunderstanding of asynchronicity. What I'm attempting to accomplish is much like what is described in this SO answer https://stackoverflow.com/a/25877042/5121114 rather than simply return a Task, I want to return a Task<T> - moreover I understand that I don't have direct control with Tasks but I'm trying to throttle threads requested from the thread pool as described point 6 of this async/await antipattern blog posted by Mark Heath https://markheath.net/post/async-antipatterns"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:09:42.023",
"Id": "236846",
"Score": "1",
"Tags": [
"c#",
"linq",
"async-await"
],
"Title": "SelectAsync With Max Degree Of Parallelism"
}
|
236846
|
<p>I have this logic that seems complicated checking the length and adding a colon. I'd like to see if any of you C# experts can help me simplify it. If the replace remove the full text then I am just adding the word Result. If it removes the make then I am just displaying the model.</p>
<p>Is there a way I can remove the if statement and combine into one? </p>
<pre><code>namespace DupName
{
public class Program
{
static void Main(string[] args)
{
StringBuilder childName = new StringBuilder();
List<Item> items = new List<Item>()
.AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi" })
.AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" });
foreach (var item in items)
{
string temp = item.ChildName.Replace(item.Name, "").Trim();
if (temp.Length == 0)
{
Console.WriteLine(string.Format("{0}","Result"));
}else
{
Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
}
}
}
}
public static class Extensions
{
public static List<T> AddAlso<T>(this List<T> list, T item)
{
list.Add(item);
return list;
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string ChildName { get; set; }
}
</code></pre>
<p>Output</p>
<pre class="lang-none prettyprint-override"><code>Result: A3 Premium Plus - Audi
Result
Result
Result: S5 Premium Plus 3.0 TFSI quattro - Audi
Result: S3 Premium Plus 3.0 TFSI quattro - Audi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:40:53.433",
"Id": "464283",
"Score": "1",
"body": "Welcome to Code Review. To get a useful review, you should [edit] your question so that it follows the [recommendations](https://codereview.stackexchange.com/help/how-to-ask) for questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T20:53:35.240",
"Id": "464299",
"Score": "1",
"body": "please clarify your question. Simplify what exactly ? what is wrong with `temp.Length == 0` ?what complications that you are experiencing ? and what do you want to achieve ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T21:10:26.467",
"Id": "464300",
"Score": "0",
"body": "Just wanted to see if there is a better way to do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T23:32:25.133",
"Id": "464307",
"Score": "2",
"body": "@Jefferson: To do **what** exactly? You haven't explained the goal of the code, nor exactly what you want reviewed (if not the full code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:49:56.013",
"Id": "464594",
"Score": "0",
"body": "Why have you not taken into account any of the reviews of https://codereview.stackexchange.com/q/235780/10582 , which is basically the same code as you've posted here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:17:51.823",
"Id": "464599",
"Score": "0",
"body": "that example used index of I added a section for this one that is checking the Length"
}
] |
[
{
"body": "<p>If I understand correctly, your frustration is with the necessary computation for knowing whether to print <code>Result</code> or <code>Result: temp - childname</code>. That's because you're doing more steps than <em>necessary</em>.</p>\n\n<p>Instead of:</p>\n\n<ol>\n<li>Calculating the (ChildName - Name) string</li>\n<li>Trimming any whitespaces in the resulting string</li>\n<li>And then checking if this string is empty</li>\n</ol>\n\n<p>You could just check if both the Name and ChildName are equal. If they are, your variable <code>temp</code> isn't used. Also, since result is written independently of such calculation, you could always print it.</p>\n\n<p>So, I would suggest exchanging</p>\n\n<pre><code>foreach (var item in items) {\n string temp = item.ChildName.Replace(item.Name, \"\").Trim();\n if (temp.Length == 0) {\n Console.WriteLine(string.Format(\"{0}\",\"Result\"));\n } else {\n Console.WriteLine(string.Format(\"{0}: {1} - {2}\", \"Result\", temp, item.Name));\n }\n}\n</code></pre>\n\n<p>for</p>\n\n<pre><code>foreach (var item in items) {\n Console.Write(\"Result\");\n\n if (item.Name != item.ChildName) {\n string childNameWithoutName = item.ChildName.Replace(item.Name, \"\").Trim();\n Console.Write(string.Format(\": {1} - {2}\", childNameWithoutName, item.Name));\n }\n\n Console.WriteLine();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:00:17.137",
"Id": "236945",
"ParentId": "236849",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Is there a way I can remove the if statement and combine into one? </p>\n</blockquote>\n\n<p>Not sure if you can remove it completely, but you may simplify it by using the <a href=\"https://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary operator</a> (:?) and extracting the logic into a method within the Item class (see example below) or into it's own class which make sense if the logic is more complicated.</p>\n\n<p>Furthermore, you could </p>\n\n<ul>\n<li>use <a href=\"https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> for concatenate strings which makes the code more readably.</li>\n<li>Use array initialization syntax which makes the <code>AddAlso</code> extension obsolete.</li>\n</ul>\n\n<p>Restructuring the code using the suggestions above could look like that:</p>\n\n<pre><code>public class Program\n{\n static void Main(string[] args)\n {\n StringBuilder childName = new StringBuilder();\n\n var items = new List<Item>\n {\n new Item { Id = 1, Name = \"Audi\", ChildName = \"Audi A3 Premium Plus\" },\n new Item { Id = 2, Name = \"Audi\", ChildName = \"Audi\" },\n new Item { Id = 1, Name = \"Audi\", ChildName = \"Audi\" },\n new Item { Id = 2, Name = \"Audi\", ChildName = \"S5 Premium Plus 3.0 TFSI quattro\" },\n new Item { Id = 2, Name = \"Audi\", ChildName = \"S3 Premium Plus 3.0 TFSI quattro\" },\n };\n\n items.ForEach(x => Console.WriteLine(x.ToDisplayName()));\n }\n}\n\npublic class Item\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public string ChildName { get; set; }\n\n public string ToDisplayName()\n {\n string childNamePrefix = ChildName.Replace(Name, \"\").Trim();\n return childNamePrefix.Length == 0\n ? \"Result: -\"\n : $\"Result: {childNamePrefix} - {Name}\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T07:04:37.307",
"Id": "236967",
"ParentId": "236849",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236967",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:50:01.847",
"Id": "236849",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Check for length in a string"
}
|
236849
|
<p>I recently had to do a test for a job interview, and the prompt was to code a function that returns the closest number to 0 given an array of negative and positive numbers.</p>
<p>My function works correctly but I heard back from the recruiter saying that my function is not very performant and that the readability was not great, here are the problem that they mentioned:</p>
<p>Performances à double check (filter + sort + for + push + reserve + shift, 4 identical call to Math.abs)
Lack of readability ( 4 if / else if)
I would like to know how I could have improved my function to make it more performant and more readable?</p>
<p>here's my function:</p>
<pre><code>const closestToZero = (arr) => {
// 1-a variables:
let positiveNumbers = [];
let negativeNumbers = [];
// 1-b returns 0 if the input is either undefined or an empty array
if(typeof(arr) === 'undefined' || arr.length === 0) {
return 0
}
// 2- filter out non-number values then sort the array
const onlyNumbers = arr.filter(item => typeof(item) === 'number').sort((a,b) => a-b);
// 3- split the numbers into positive numbers and negative numbers
for(let i = 0; i < onlyNumbers.length; i++) {
if(onlyNumbers[i] > 0) {
positiveNumbers.push(onlyNumbers[i])
} else if (onlyNumbers[i] < 0) {
negativeNumbers.push(onlyNumbers[i])
}
}
// 4- reverse the negative array to get the closest to 0 at the first index
let reversedNegativeArray = negativeNumbers.reverse()
// 5- get rid of all the other values and keep only the closest to 0, if array empty return 0
let closestPositiveNumber = positiveNumbers.length > 0 ? positiveNumbers.shift() : 0
let closestNegativeNumber = reversedNegativeArray.length > 0 ? reversedNegativeArray.shift() : 0
// 6- Compare the result of the substraction of the closestPositiveNumber and the closestNegativeNumber to find the closestToZero
if(closestPositiveNumber - Math.abs(closestNegativeNumber) > 0 && closestNegativeNumber === 0 ) {
return closestPositiveNumber
} else if (closestPositiveNumber - Math.abs(closestNegativeNumber) < 0 && closestPositiveNumber === 0) {
return closestNegativeNumber
} else if(closestPositiveNumber - Math.abs(closestNegativeNumber) > 0) {
return closestNegativeNumber
} else if (closestPositiveNumber - Math.abs(closestNegativeNumber) <= 0) {
return closestPositiveNumber
}
}
</code></pre>
<p>requirements:</p>
<ul>
<li>if the closest number in input could be either negative or positive, the function returns the positive one</li>
<li>if the input array is undefined or empty, the function returns 0</li>
</ul>
<p>when input is [8, 5, 10] the function returns 5</p>
<p>when input is [5, 4, -9, 6, -10, -1, 8] the function returns -1</p>
<p>when input is [8, 2, 3, -2] the functions return 2</p>
|
[] |
[
{
"body": "<p>Your reviewers are correct. You are doing way too much work here. To find the number closest to zero you only need to find the smallest absolute value in the list. You should also clarify in the interview if the list can contain non-numeric values. There's no reason to test that the values are numbers unless you need to for the purpose of the review, although asking about this shows that you are thinking about edge cases, which is good. </p>\n\n<p>Either way, this can be done in a single loop with no storage other than keeping track of the current minimum:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function absSmallest(arr){\n if (!arr || arr.length === 0 ) return 0 // address requirement to return 0 when arr is undefined or empty\n let res = undefined // smallest value seen so far\n for (let i = 0; i < arr.length; i++){\n if (res === undefined || Math.abs(arr[i]) <= Math.abs(res)){\n res = Math.abs(arr[i]) === Math.abs(res) // address requirement of positive value when there's a tie \n ? Math.max(res, arr[i] )\n : res = arr[i]\n }\n }\n return res\n}\n\nconsole.log(absSmallest([5, 4, -9, 6, -10, -1, 8] ))\nconsole.log(absSmallest([8, -2, 3, 2] ))\n// check order of tied values\nconsole.log(absSmallest([8, 2, 3, -2] ))\n\n// edge case empty list returns 0:\nconsole.log(absSmallest())\nconsole.log(absSmallest([]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:34:01.040",
"Id": "464279",
"Score": "1",
"body": "The code can be made even simpler using [`for (const num of arr)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of). Did you choose the longer form intentionally?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:52:51.300",
"Id": "464287",
"Score": "0",
"body": "That code doesn't satisfy the second requirement: \"_if the input array is undefined or empty, the function returns 0_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T19:01:32.087",
"Id": "464290",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ that requirement was added later. It's easy enough to satisfy, I'll edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T19:02:59.857",
"Id": "464291",
"Score": "1",
"body": "@RolandIllig yes I chose the longer `for` form to use the idiom the poster was using."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:56:00.460",
"Id": "236855",
"ParentId": "236850",
"Score": "4"
}
},
{
"body": "<p>I would like to point out few things in your code:-</p>\n\n<ol>\n<li><p>This should be at the first place of your function.</p>\n\n<p>if(typeof(arr) === 'undefined' || arr.length === 0) {\n return 0\n }</p></li>\n<li><p>You have used arrow function here which is of no use here, as according to rules if I tell you, arrow function must be used in one liner function.</p></li>\n<li><p>You could have not used anonymous function or have used class.</p></li>\n<li><p>Hardest part here, what you could have done is just find the element next to 0 and before 0 after sorting it, compare there diff with 0, which has least that is the closest element.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T07:29:38.597",
"Id": "237211",
"ParentId": "236850",
"Score": "0"
}
},
{
"body": "<p>From the advise of <a href=\"https://codereview.stackexchange.com/a/236855/218372\">MarkM</a>. Finding the min of absolute values of the array. A bit more readable than his approach (personal opinion). </p>\n\n<pre><code>function closestToZero(arr) {\n if (!arr || arr.length === 0) {\n return 0;\n }\n\n let closestToZero = arr[0];\n arr.forEach(function(number) {\n if (Math.abs(number) < Math.abs(closestToZero)) {\n closestToZero = number;\n }\n });\n\n return closestToZero;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T13:59:45.400",
"Id": "237234",
"ParentId": "236850",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:52:41.493",
"Id": "236850",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"array"
],
"Title": "How can I Implement a better version of my function find the closest number to zero?"
}
|
236850
|
<p>This function formats raw buffer output in manner as Wireshark and many others does:</p>
<pre><code>0x00: 68 65 6C 6C 6F 20 77 6F 72 6C 64 02 6B 68 67 61 |hello world.khga|
0x10: 76 73 64 20 0B 20 0A 05 58 61 73 6A 68 6C 61 73 |vsd . ..Xasjhlas|
0x20: 62 64 61 73 20 6A 61 6C 73 6A 64 6E 13 20 20 30 |bdas jalsjdn. 0|
0x30: 31 32 33 34 35 36 37 38 39 |123456789 |
</code></pre>
<p>Please review and assess code quality.</p>
<pre><code>std::string format_hex_payload(const char* payload, size_t payload_len)
{
const char line_placeholder[] = "0x00: | |";
size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
size_t sizeof_output = sizeof line_placeholder * number_of_lines;
char *output = (char*)alloca(sizeof_output); //POSSIBLE REIMPL USE C++RVO std::string out; out.reserve(sizeof_output);
char *pout = output; //POSSIBLE REIMPL char *pout = out.data();
const char *p = payload;
const char *const end = payload + payload_len;
size_t ascii_offset = strchr(line_placeholder,'|') - line_placeholder + 1; //could be calculated at compile time
unsigned short offset = 0;
for(unsigned l=0; l < number_of_lines; l++, offset+=16)
{
char* pline_begin = pout;
char* pline = pout;
strcpy(pline,line_placeholder);
pline += sprintf(pline, "0x%02X: ", offset);
for(unsigned i=0; i<16 && p < end; ++i, ++p){
pline += sprintf(pline, "%02X ", *p);
*(pline_begin+ascii_offset+i) = isprint(*p) ? *p : '.';
}
*pline=' ';
pout += sizeof line_placeholder; // move pointer to next line
pout[-1] = '\n';
}
pout[-1] = '\0';
assert(pout == output + sizeof_output); // sanity check
return output; //POSSIBLE REIMPL return out;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T19:11:18.663",
"Id": "464292",
"Score": "0",
"body": "What happens when offset is >= 256 (more than 16 lines)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:23:43.117",
"Id": "464720",
"Score": "0",
"body": "@1201ProgramAlarm, nothing criminal, but format will be shifted https://i.imgur.com/rlMNjc0.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:33:22.247",
"Id": "464737",
"Score": "2",
"body": "@kyb: The policy on this site is *not to add, remove, or edit code* in a question after you've received an answer, because it invalidates existing answers. This is explained in [What to do when someone answers](/help/someone-answers). On the other hand, your original question was unclear/off-topic (tagged [C] but invalid C code), which is probably why you code 3 close votes up to now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:33:34.917",
"Id": "464738",
"Score": "3",
"body": "@kyb: (Cont.) Following [feedback in chat](https://chat.stackexchange.com/transcript/message/53504197#53504197), I have done a rollback the question to revision 3, i.e. the original code but with the [C++] tag, so that both Q and A make sense. I suggest to ask a *new question* about the C implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:39:25.940",
"Id": "464775",
"Score": "0",
"body": "[Follow up question](https://codereview.stackexchange.com/q/237086) (Compiles to C rather than C++ now)"
}
] |
[
{
"body": "<ol>\n<li><p>I think probably the first thing to do is decide whether you're really using C, or really using C++.</p>\n\n<ul>\n<li><p>If you're really using C, then you need to get rid of the <code>std::string</code>, and allocate space for your return differently (e.g., using <code>malloc</code>).</p></li>\n<li><p>If you're really using C++, then I'd at least consider using iostreams and manipulators to do most of the work. They are fairly verbose, but most people using C++ expect to deal with iostreams rather than raw buffers and C-style string manipulation.</p></li>\n</ul></li>\n<li><p>I think I'd break the code up into a few more functions. For example, I'd probably have <code>format_hex</code>, which would repeatedly call <code>format_line</code>, which might in turn call some <code>format_hex_value</code> (or something on that order) to write out each individual value.</p></li>\n<li><p>I'd probably avoid using the line placeholder, for a couple of reasons. The first (and probably most important) is that as you've done things right now, the last line is (as I see things) somewhat malformed. You've surrounded the ASCII part of the display with <code>|</code> as delimiters, but for that to make sense, you want the delimiter right next to the data, so that part of the last line should look like: <code>|123456789|</code>, so you immediately know there's no more data after the <code>9</code> (where your current display looks like there are space characters after the <code>9</code>).</p></li>\n<li><p>I'd definitely expand the addresses on the left out to at least 4 characters, and maybe more. In theory, you should probably be thinking in terms of 16 characters (allowing 64-bit addresses), but in all honesty I've rarely seen much point in hex dump of multiple gigabytes of data (but I certainly have seen good uses for more than 256 bytes).</p></li>\n</ol>\n\n<p>Putting those together, one possibility (going the C++ route) might come out something on this order:</p>\n\n<pre><code>#include <cctype>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n\nstruct hex {\n unsigned value;\n int digits;\npublic:\n hex(unsigned value, int digits) : value(value), digits(digits) { }\n\n friend std::ostream &operator<<(std::ostream &os, hex const &h) {\n auto oldfill = os.fill('0');\n\n // Yeah, iostreams get really verbose. Sorry.\n os << std::hex \n << std::setw(h.digits) \n << std::uppercase \n << std::setprecision(h.digits)\n << h.value;\n os.fill(oldfill);\n return os;\n }\n};\n\nvoid fmt_line(std::ostream &os, char const *data, size_t offset, size_t len) { \n os << hex(offset, 8) << \":\";\n\n for (size_t i=0; i<len; i++) {\n os << \" \" << hex(data[offset+i], 2);\n }\n\n os << std::setw((16-len)*3 +2) << \"|\";\n for (size_t i=0; i<len; i++) {\n char ch = data[offset+i];\n os << (std::isprint((unsigned char)ch) ? ch : '.');\n }\n os << \"|\\n\";\n}\n\nstd::string format_hex(char const *data, size_t len) { \n unsigned lines = len/16;\n std::stringstream out;\n\n for (size_t line=0; line<lines; line++)\n fmt_line(out, data, line*16, 16);\n fmt_line(out, data, lines*16, len%16);\n return out.str();\n}\n\nint main() { \n char input[] = \"hello world\\02khgavsd \\xb \\xa\\x5Xasjhlasbdas jalsjdn\\xd 0123456789\";\n std::cout << format_hex(input, sizeof(input));\n}\n</code></pre>\n\n<p>This could use some further improvement. For one thing, it's probably not immediately obvious what some things like: <code>os << std::setw((16-len)*3 +2) << \"|\";</code> are really doing, so they could undoubtedly use at least a little more work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T10:41:45.280",
"Id": "236883",
"ParentId": "236851",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236883",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:53:04.177",
"Id": "236851",
"Score": "0",
"Tags": [
"c++",
"formatting"
],
"Title": "Format raw bytes in hex and ascii in manner like Wireshark does"
}
|
236851
|
<p>You can find the complete code on <a href="https://github.com/Siito/n_body" rel="nofollow noreferrer">github</a>. Since I'm rather new to C++ I thought that it might be a good idea to write a simulation of the <a href="https://en.wikipedia.org/wiki/N-body_problem" rel="nofollow noreferrer">n-body problem</a> to apply some of the concepts that I learned in class. The relevant part can be found in <code>main.cpp</code> on the above linked github repo, but the imporant part is given by:</p>
<pre><code>#include <string>
#include <eigen3/Eigen/Dense>
#include <utility>
#include <iostream>
#include <chrono>
#include <cmath>
#include <fstream>
#include "integrate.hpp"
#include <vector>
using mass_t = double const;
using name_t = std::string const;
using vector_t = Eigen::Vector3d;
using phase_t = Eigen::VectorXd;
using rhs_t = phase_t (*)(double const &, phase_t const &);
using step_t = phase_t (*)(rhs_t , phase_t const &, double, double);
double square(double x){ // the functor we want to apply
return std::pow(x,2);
}
double norm(vector_t const& v){
return std::sqrt(v.unaryExpr(&square).sum());
}
// Class representing a stellar object
class StellarObject{
public:
explicit StellarObject( vector_t pos = vector_t(0,0,0), //Position of the sun relative to itself
vector_t speed = vector_t(0,0,0), //Velocity of the sun relative to itself
mass_t const& mass = 1.00000597682, //Mass of the Sun [kg]
name_t const& name = "Sun") : mass_(mass),
name_(name),
position_(std::move(pos)),
velocity_(std::move(speed)) {};
vector_t get_position() const {
return position_;
}
vector_t get_velocity() const {
return velocity_;
}
double get_mass() const {
return mass_;
}
private:
vector_t position_;
vector_t velocity_;
name_t name_;
mass_t mass_;
};
phase_t nbody_prod(double const & t, phase_t const & z,
std::vector<double> const& masses, double const & G){
int const N = masses.size();
phase_t q(3*N); //space for positions of the particles
q << z.head(3*N); //fill it with the relevant elements from z
phase_t ddx(3*N); //space for the rhs of the ODE
ddx.fill(0); //make sure that set to zero everywhere
for(std::size_t k = 0; k<N; ++k){
vector_t tmp; //tmp object to store ddx
tmp.fill(0);
vector_t qk = q.segment(3*k,3); //get position of k-th object
for(std::size_t i=0; i < N; ++i){
if(i!=k){ //calculate acceleration of k-th object
vector_t qi = q.segment(3*i,3);
vector_t diff = qi-qk;
double normq = std::pow(norm(diff),3);
tmp += masses[i]/normq * diff;
}
}
ddx.segment(3*k,3) = G * tmp;
}
return ddx;
}
// z = [r_(1,x), r_(1,y), r_(1,z), r_(2,x), .... r_(N,z), v_(1,x), v_(1,y), ..., v_(N, z)]
phase_t nbody_rhs(double const & t, phase_t const & z, std::vector<double> const& masses,
double const G){
int const N = masses.size();
phase_t rhs(6*N); //space for the rhs
rhs.head(3*N) = z.tail(3*N); // fill velocities in first 3*N elements of rhs
rhs.tail(3*N) = nbody_prod(t, z, masses, G); // fill last 3*N elements with nbody_prod
return rhs;
}
static double G;
static std::vector<double> masses;
Eigen::MatrixXd n_body_solver(std::vector<StellarObject> const & planets){
int const N = planets.size();
phase_t z0(6*N);
for(std::size_t k=0; k < N; ++k) {
z0.segment(3*k,3) = planets[k].get_position();
}
for(std::size_t k=N; k < 2*N; ++k) {
z0.segment(3*k,3) = planets[k%N].get_velocity();
}
for(auto & planet : planets){
masses.push_back(planet.get_mass());
}
G = 2.95912208286e-4;
auto reduced_rhs = [](double const & t, phase_t const & z0) {return nbody_rhs(t, z0, masses, G);};
return explicit_midpoint(reduced_rhs, z0, 60000, 40000);
}
</code></pre>
<p>Note that I left out the <code>main</code>-function of <code>main.cpp</code> since there is nothing interesting happening there.. Just the setup for a simple test. </p>
<hr>
<p>The code works, it produces results that are sensible (if you have a working phyton environment and are using a Unix based machine you can run <code>run.sh</code> file inside the repo and should get a nice animation of the stellar movement), but there are several things that bother me about the code.</p>
<p>First of all: I'd like to put all of these different function into one <code>solver</code> class, which I think would make it much easier to use and understand. The goal would be something like the following code (but I can't get it to work...)</p>
<pre><code>class n_body_solver{
public:
n_body_solver(std::vector<StellarObject> const & planets,
double const & G=2.95912208286e-4) : N_(planets.size()) {
G_= G;
for(std::size_t k=0; k < N_; ++k) {
z0_.segment(3*k,3) = planets[k].get_position();
}
for(std::size_t k=N_; k < 2*N_; ++k) {
z0_.segment(3*k,3) = planets[k%N_].get_velocity();
}
for(auto & planet : planets){
masses_.push_back(planet.get_mass());
}
}
phase_t nbody_prod(double const & t, phase_t const & z,
std::vector<double> const& masses, double const & G){
int const N = masses.size();
phase_t q(3*N); //space for positions of the particles
q << z.head(3*N); //fill it with the relevant elements from z
phase_t ddx(3*N); //space for the rhs of the ODE
ddx.fill(0); //make sure that set to zero everywhere
for(std::size_t k = 0; k<N; ++k){
vector_t tmp; //tmp object to store ddx
tmp.fill(0);
vector_t qk = q.segment(3*k,3); //get position of k-th object
for(std::size_t i=0; i < N; ++i){
if(i!=k){ //calculate acceleration of k-th object
vector_t qi = q.segment(3*i,3);
vector_t diff = qi-qk;
double normq = std::pow(norm(diff),3);
tmp += masses[i]/normq * diff;
}
}
ddx.segment(3*k,3) = G * tmp;
}
return ddx;
}
// z = [r_(1,x), r_(1,y), r_(1,z), r_(2,x), .... r_(N,z), v_(1,x), v_(1,y), ..., v_(N, z)]
phase_t nbody_rhs(double const & t, phase_t const & z, std::vector<double> const& masses,
double const G){
int const N = masses.size();
phase_t rhs(6*N); //space for the rhs
rhs.head(3*N) = z.tail(3*N); // fill velocities in first 3*N elements of rhs
rhs.tail(3*N) = nbody_prod(t, z, masses, G); // fill last 3*N elements with nbody_prod
return rhs;
}
void solve(double const & time_intervall, unsigned int const & bins){
auto reduced_rhs = [](double const & t, phase_t const & z0) {return nbody_rhs(t, z0, masses_, G_);};
result_ = explicit_midpoint(reduced_rhs, z0_, time_intervall, bins);
}
Eigen::MatrixXd get_result() const {
return result_;
}
private:
phase_t z0_;
unsigned short const N_;
static double G_;
static std::vector<double> masses_;
Eigen::MatrixXd result_;
};
</code></pre>
<hr>
<p>Other than that I'd be happy to receive feedback regarding general C++ coding style, choices of containers, types, etc. Anything that you notice when reading the code. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T21:23:02.790",
"Id": "464301",
"Score": "1",
"body": "You should not assume that each potential reviewer knows what the n-body problem is. A simple link to Wikipedia helps, you can just [edit] your question. Other than that, it's a good question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T21:34:43.047",
"Id": "464302",
"Score": "0",
"body": "@RolandIllig That's absolutely fair, edited!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T22:46:40.890",
"Id": "464305",
"Score": "0",
"body": "I'm not very familiar with Eigen, but is it really intended to be used like this? You are taking a Nx3 matrix and iterating over it in a n^2 fashion. I assume Eigen has some way to abstract that so that you're using fewer loops, and possibly get a benefit of hardware support. Is this code actually leveraging Eigen in a way that's better than just using a `std::vector` of `struct {float x,y,z;};` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T23:16:21.523",
"Id": "464306",
"Score": "0",
"body": "@butt To be honest, I don't know. I'm not that familiar with Eigen either, actually, I did this exercise here precisely to become a bit familiar with it (almost all of the functions I used here from Eigen, I used for the first time...). So if there is a faster (better) way of doing this, I'm more than open to hear about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T14:40:14.850",
"Id": "464346",
"Score": "0",
"body": "Here is another n body c++ program you can reference https://codereview.stackexchange.com/questions/231191/simple-n-body-class-in-c. A reason to leave an uninteresting main in the program is so that others can test the code and see how the classes are used."
}
] |
[
{
"body": "<p>Your code makes me think that you don't understand what exactly you want to model.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>explicit StellarObject(\n vector_t pos = vector_t(0,0,0), //Position of the sun relative to itself\n vector_t speed = vector_t(0,0,0), //Velocity of the sun relative to itself\n mass_t const& mass = 1.00000597682, //Mass of the Sun [kg]\n name_t const& name = \"Sun\"\n)\n</code></pre>\n\n<p>When creating a (model of a) stellar object, there is absolutely nothing that should be related to the sun. The sun is just a random star and has no relation to any of the fundamental <a href=\"https://en.wikipedia.org/wiki/Physical_constant\" rel=\"noreferrer\">physical constants</a>.</p>\n\n<p>The comments to the right reference the sun though, which makes the whole code look wrong. I very much doubt that the sun's mass is a single kilogram.<sup>[citation needed]</sup></p>\n\n<p>It is wrong to provide default values for any of the parameters of this constructor since it doesn't make sense to have 5 objects with the same name or the same position or the same mass, that's just not a realistic scenario. The caller of this constructor must be forced to think about all these values explicitly.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>G = 2.95912208286e-4;\n</code></pre>\n\n<p>This is a magic number. The symbol <code>G</code> usually stands for the <a href=\"https://en.wikipedia.org/wiki/Gravitational_constant\" rel=\"noreferrer\">gravitational constant</a>, whose value is approximately <span class=\"math-container\">\\$ 6.67430\\cdot10^{-11} \\frac{\\text{m}^3}{\\text{kg} \\cdot \\text{s}^2}\\$</span>. Your value of <span class=\"math-container\">\\$2.9\\cdot10^{-4}\\$</span> is nowhere near that value, therefore you must document where you got that number from and what its dimension is. In physical simulations, it's important to carry the dimensions around in the calculations to prevent typos and other mistakes. For example it doesn't make sense to add seconds to meters and divide by Ampère.</p>\n\n<p>Always use the <a href=\"https://en.wikipedia.org/wiki/International_System_of_Units\" rel=\"noreferrer\">Internation System of Units</a>, don't accept any other measurement units unless you document exactly why you have to use different units and how you did the conversion.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>vector_t tmp; //tmp object to store ddx\n</code></pre>\n\n<p>The variable name <code>tmp</code> is terrible, it should be forbidden. You should have named it <code>next_ddx</code>, since it collects the positions after the next simulation step. This naming scheme would also suggest a better name for <code>vector_t qk</code> and <code>q</code>. To avoid confusion, these should be called <code>next_pk</code> and <code>next_p</code>. Sure, the names are a bit longer, but the name <code>q</code> does not really tell (me) much, except that it is the letter following p in several Latin alphabets. If that's a well-known naming convention among physicists, it's ok if the code is ever only read by physicists.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>double normq = std::pow(norm(diff),3);\ntmp += masses[i]/normq * diff;\n</code></pre>\n\n<p>It's confusing to see a division by <span class=\"math-container\">\\$r^3\\$</span> when I only expect a division by <span class=\"math-container\">\\$r^2\\$</span>. The code would be easier to understand if you just divided by <span class=\"math-container\">\\$r^2\\$</span> first and did the direction calculations afterwards and independently. The code is easy to understand if the commonly known formulas like <span class=\"math-container\">\\$F = \\text{G} \\cdot \\frac{m_1 \\cdot m_2}{r^2}\\$</span> appear exactly in this form. Every deviation from this makes the code more difficult to read and to verify.</p>\n\n<p>I did not analyze the rest of the code in detail. I saw many helpful comments that explained the short variable names, which is good for understanding the code. I also saw many questionable comments that contradicted the code, and these are bad. You should probably <a href=\"https://en.wikipedia.org/wiki/Rubber_duck_debugging\" rel=\"noreferrer\">read the code aloud to someone else</a> and while doing that, listen to your words to see whether they make sense. If they don't, the code is wrong. Or the model of the world you are building. Either way, something needs to be fixed in these cases.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T22:12:30.890",
"Id": "236862",
"ParentId": "236860",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T20:51:19.797",
"Id": "236860",
"Score": "3",
"Tags": [
"c++",
"performance"
],
"Title": "N body simulation in C++"
}
|
236860
|
<p>I was following this tutorial for JavaFX and Gradle:</p>
<p><a href="https://thecodinginterface.com/blog/javafx-dev-setup-gradle-and-eclipse/" rel="nofollow noreferrer">JavaFX with Gradle, Eclipse and, Scene Builder on OpenJDK11</a></p>
<p>After completion of the tutorial you will have a simple GUI which you input a lower and upper bound and generate random numbers between them. The generated numbers and their bounds are then saved and listed in another view.</p>
<p>After completion of this tutorial I wanted to integrate MySQL as the back end.</p>
<p>The tutorial creator acknowledged at some point that a database like SQLite would be the preferred back end but that it was outside the scope of the tutorial. Luckily it seems he designed the app in such a way that he uses DAO class and I just replaced his code in there with my own JDBC implementation.</p>
<pre><code>package RandomNumber.repository;
import java.util.*;
import java.sql.*;
import RandomNumber.models.RandomNumber;
public class LocalRandomNumberDAO implements RandomNumberDAO {
public LocalRandomNumberDAO() {
}
private List<RandomNumber> numbers = new ArrayList<>();
private Connection openConn() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/numbers?" +
"user=demo_java&password=1234");
}
@Override
public boolean save(RandomNumber number) {
boolean res = false;
try (
var conn = openConn();
var stmt = conn.prepareStatement("insert into numbers_tabl values(?,?,?,?,?)");
) {
stmt.setInt(1, 0);
stmt.setInt(2, number.getNumber());
stmt.setInt(3, number.getLowerBounds());
stmt.setInt(4, number.getUpperBounds());
stmt.setDate(5, java.sql.Date.valueOf(number.getCreatedAt()));
res = stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return res;
}
@Override
public void loadNumbers() {
try (
var conn = openConn();
var stmt = conn.createStatement();
) {
String strQuery = "select * from numbers_tabl;";
var rset = stmt.executeQuery(strQuery);
numbers.clear();
while(rset.next()) {
numbers.add(new RandomNumber(
rset.getDate("created").toLocalDate(),
rset.getInt("number"),
rset.getInt("min"),
rset.getInt("max")
)
);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<RandomNumber> getNumbers() {
return Collections.unmodifiableList(numbers);
}
}
</code></pre>
<p>I am also calling loadNumbers each time the generate button is pressed, so I essentially insert 1 row, and then query all rows in the database.</p>
<p>Questions:
1. Must I always provide a value for the Primary Key to the PreparedStatement in the save method? my table description follows:</p>
<pre><code>mysql> describe numbers_tabl;
+---------+------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| number | int | NO | | NULL | |
| min | int | NO | | NULL | |
| max | int | NO | | NULL | |
| created | date | YES | | NULL | |
+---------+------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
</code></pre>
<p>2. What best practices am I blatantly ignoring?<br>
3. Is there a better way? Or rather, is there a library or framework that is more worth my time?<br>
4. This is my first time using Java-11. I have always used pretty much only Java 7 or 8 features. Is my usage of the var keyword appropriate?</p>
|
[] |
[
{
"body": "<p>You're not following Java naming conventions. Package names should be all lower case.</p>\n\n<p>The JDBC URL is hard coded. This should be provided as a parameter. Or better yet, provide the connection with dependency injection so you can unit test it with mocks.</p>\n\n<p>Worst \"offense\" is hiding the exceptions from the caller. Instead of printing the stack trace (which is only visible to the end user) you should wrap it in a domain specific exception. This way the application using your library can take proper actions.</p>\n\n<p>When saving the number you list all columns as parameters in the SQL. Including the automatically generated index, which you insert as zero. That was confusing. You should list only the columns that you provide as \"INSERT INTO numbers_tabl (number, min, max) ...\" and let the database handle the columns that can be generated automatically (index and creation date).</p>\n\n<p>Instead of returning a boolean from saveNumber you could return the RandomNumber object updated with it's new database identifier and creation date.</p>\n\n<p>The names in the database table don't describe their purposes. Table us named \"numbers_tabl\" but it contains random numbers. The name should tell the reader what the table contains. Also the _tabl suffix is probably a bit pointless. The \"created\" column name suggests that the value is a boolean. It should be \"creation_time\". I don't remember MySQL data types from memory but it probably should be a timestamp, not just date.</p>\n\n<p>The method choice comes from the tutorial, right? It's a bit weird to load the numbers into memory and access them from there. After saving a number you have to call loadNumbers before you get the latest number back from getNumbers. The getNumbers should load the numbers from the database. If you want to cache the numbers in memory then the saveNumbers should invalidate the cache, but that's probably a subject for a later tutorial. :) Also there are libraries for that (Ehcache for example).</p>\n\n<p>The standard library for this purpose is JPA (Java Persistence API or Jakarta Persistence). It makes boilerplate SQL so much easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T18:53:02.427",
"Id": "464362",
"Score": "0",
"body": "\"you list all columns as parameters in the SQL. Including the automatically generated index, which you insert as zero.\" I made this assumption and left out the id from the prepared statement. I got an error \"SQLException: Column count doesn't match value count at row 1\" from line 37: stmt.execute() line. Maybe something in my table definition isn't right?\nhttps://stackoverflow.com/questions/17438288/insert-using-preparedstatement-how-do-i-auto-increment-the-id this answer supports what you say but when i code it like that I get the column count mismatch error.\nThanks a ton."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T19:05:10.097",
"Id": "464364",
"Score": "0",
"body": "I wasn't coding it exactly like the referenced SO answer. i need to explicitly mention the columns i'm inserting to and leave out the id:\n\"insert into numbers_tabl (number, min, max, created) values (?,?,?,?)\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T06:52:27.393",
"Id": "236877",
"ParentId": "236861",
"Score": "2"
}
},
{
"body": "<p>I use <code>var</code> almost everywhere. To me, it makes the code more concise and easier to refactor. Essentially, unless it makes the code harder to read / understand I use it. An important element of this is variable naming. For example:</p>\n\n<blockquote>\n<pre><code>boolean res = false;\n</code></pre>\n</blockquote>\n\n<p><code>res</code> probably means result, why not call it that... or better still, what it's represents the result of:</p>\n\n<pre><code>var saved = false;\n</code></pre>\n\n<p>Similarly, <code>rset</code> could be <code>resultSet</code> or <code>rows</code>. It's also fairly out of fashion to include variable types in variable names, so rather than <code>strQuery</code>, you probably want to just go with <code>query</code>.</p>\n\n<p>It's been a while since I used this type of connection, however result sets often need to be cleaned up after you're done with them. It looks like there's a close method on it, so you might want to wrap it in a try with resources block as well...</p>\n\n<pre><code>try(var rows = statement.executeQuery(query)) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T18:41:24.380",
"Id": "464361",
"Score": "0",
"body": "I thought about adding rset to the try with resource block, but it wouldn't allow me to assign it to null. So maybe I should have then defined the query string in the block as well, but I went the other way and made sure the query string was not in the resource block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T19:08:04.913",
"Id": "464365",
"Score": "1",
"body": "@Victor I'm not sure I understand why you'd need to assign it to `null`, you can create a nested try block at the point you're ready to create the resultset."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T11:30:53.137",
"Id": "236886",
"ParentId": "236861",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236877",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T21:53:37.683",
"Id": "236861",
"Score": "4",
"Tags": [
"java",
"mysql",
"jdbc"
],
"Title": "MySQL JDBC integration into App from tutorial"
}
|
236861
|
<p>I have a big file with a lot of "phrases", like:</p>
<blockquote>
<p>sayndz zfxlkl attjtww cti sokkmty brx fhh suelqbp xmuf znkhaes pggrlp</p>
<p>zia znkhaes znkhaes nti rxr bogebb zdwrin sryookh unrudn zrkz jxhrdo</p>
<p>gctlyz bssqn wbmdc rigc zketu ketichh enkixg bmdwc stnsdf jnz mqovwg</p>
<p>ixgken flawt cpott xth ucwgg xce jcubx wvl qsysa nlg qovcqn zxcz</p>
<p>vojsno nqoqvc hnf gqewlkd uevax vuna fxjkbll vfge qrzf phwuf ligf xgen</p>
<p>vkig elptd njdm gvqiu epfzsvk urbltg dqg sfpku viwihi fje umdkwvi</p>
<p>ejzhzj qrbl sfpku sad nawnow ksnku nzhj mfudick ueaa jnhz kpy pzk</p>
</blockquote>
<p>What I need to do is check if any 'phrase' didn't appear twice in a line and count lines where it didn't</p>
<pre><code>def check(phrase):
phrases = phrase.split()
for i in range(len(phrases)):
phrase_tmp = phrases.pop(0)
if phrase_tmp in phrases:
return False
phrases.append(phrase_tmp)
return True
with open('file_with_phrases.txt', 'r') as file:
counter = 0
for line in file:
if check(line):
counter += 1
print(counter)
</code></pre>
<p>Can you tell me if I did it all good? </p>
|
[] |
[
{
"body": "<ol>\n<li><p>Clarifying terms makes both code and documentation easier to understand. You use the word \"phrase\" (which usually refers to an arbitrary group of words) to refer to both a <strong>line</strong> (one of a set of linebreak-delimited strings) and a <strong>word</strong> (one of a set of whitespace-delimited strings). If you're talking about a single word, say \"word\". :)</p></li>\n<li><p>Give your function a descriptive name! Maybe <code>has_unique_words</code>?</p></li>\n<li><p>Type annotations and a docstring also make functions easier to understand.</p></li>\n</ol>\n\n<p>Here's what we've got so far:</p>\n\n<pre><code>def has_unique_words(phrase: str) -> bool:\n \"\"\"Checks whether any (whitespace-delimited) words in the phrase are repeated.\n Returns True only if all words are unique.\"\"\"\n words = phrase.split()\n</code></pre>\n\n<ol start=\"4\">\n<li>Mutating an iterable as you iterate over it is an easy way to confuse yourself, and it's usually better to iterate over the elements of an list rather than the range of its indices (although because you're mutating it that might not work well here). It might be better to find a solution that doesn't involve mutating the list. Here are a few possibilities that are all simpler alternatives to popping/searching/re-inserting:</li>\n</ol>\n\n<pre><code># Count the number of occurrences of each word.\n# If each occurs exactly once, all words are unique.\nword_counts: Dict[str, int] = defaultdict(int)\nfor word in words:\n word_counts[word] += 1\nreturn all(count == 1 for count in word_counts.values())\n</code></pre>\n\n<pre><code># Iterate through each word and check whether we've already seen it.\nseen_words: Set[str] = set() # this could be a list, but a set is faster to check\nfor word in words:\n if word in seen_words:\n return False\n seen_words.add(word)\nreturn True\n</code></pre>\n\n<p>This one-line check is what I would do:</p>\n\n<pre><code># Build a set (which guarantees uniqueness) out of the list of words.\n# If the number of elements is the same, all the list elements are unique.\nreturn len(set(words)) == len(words)\n</code></pre>\n\n<ol start=\"5\">\n<li>In the interest of brevity I'd use <code>sum</code> and a comprehension to build the count rather than a named variable:</li>\n</ol>\n\n<pre><code>with open('file_with_phrases.txt', 'r') as file:\n print(sum(1 for line in file if has_unique_words(line)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T00:43:19.970",
"Id": "236867",
"ParentId": "236865",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236867",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T00:05:27.513",
"Id": "236865",
"Score": "1",
"Tags": [
"python"
],
"Title": "Python - checking if phrase appears on a list"
}
|
236865
|
<p>how can I optimize my code for a large set (10000 elements)?</p>
<pre><code>found = False
def subset_sum(numbers, target, partial=[]):
global found
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print("sum(%s)=%s" % (partial, target))
raise Exception('element found')
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
</code></pre>
<p>For example, for 50 elements it takes 41 seconds.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T06:17:14.660",
"Id": "464509",
"Score": "0",
"body": "How large are the numbers and the target?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:10:17.153",
"Id": "464932",
"Score": "0",
"body": "It's not entirely clear to me what you're trying to achieve. Would you mind adding some examples? For instance if `numbers` is `[1, 2, 9, 3, 4]` and `target` is 5, what do you expect to see? an `Exception` because 1+4 or 2+3 = 5 or nothing because no _contiguous_ elements sum to 5?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T01:01:29.323",
"Id": "236868",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"combinatorics"
],
"Title": "Find only one subset sum with a specified value in python for large sets"
}
|
236868
|
<p>I'm sure anyone who has used WPF is familiar with the irritating boilerplate code surrounding properties, usually of this form.</p>
<pre><code>class TestViewModel : ObservableObject
{
string m_someValue;
decimal m_someOtherValue;
public string SomeValue
{
get => m_someValue;
set
{
if (m_someValue != value)
{
m_someValue = value;
RaisePropertyChanged();
}
}
}
public decimal SomeOtherValue
{
get => m_someOtherValue;
set
{
if (m_someOtherValue != value)
{
m_someOtherValue = value;
RaisePropertyChanged();
}
}
}
}
</code></pre>
<p>In this case, <code>ObservableObject</code> is just a basic convenience class that implements <code>INotifyPropertyChanged</code></p>
<p>In the interest of getting rid of this junk, I've come up with a small class that wraps the property code, called <code>BindableProperty<TValue></code></p>
<pre><code>/// <summary>
/// An object that raises <see cref="INotifyPropertyChanged.PropertyChanged"/> whenever it's value
/// is modified.
/// </summary>
/// <typeparam name="TValue">The type of value that this property holds.</typeparam>
class BindableProperty<TValue> : ObservableObject, IBindableProperty<TValue>
{
/// <summary>
/// An action that is raised when the value changes.
/// </summary>
readonly Action<TValue, TValue> m_onPropertyChangedAction;
TValue m_value;
/// <summary>
/// The value of this property. Raises <see cref="INotifyPropertyChanged.PropertyChanged"/> when modified.
/// </summary>
public TValue Value
{
get => m_value;
set
{
if (!EqualityComparer<TValue>.Default.Equals(m_value, value))
{
TValue previousValue = m_value;
m_value = value;
RaisePropertyChanged();
// Raise the delegate if one has been set.
m_onPropertyChangedAction?.Invoke(previousValue, m_value);
}
}
}
/// <summary>
/// Creates a new bindable property with the default value for the type.
/// </summary>
public BindableProperty() {}
/// <summary>
/// Creates a new bindable property with the given value.
/// </summary>
public BindableProperty(TValue value) : this()
{
Value = value;
}
/// <summary>
/// Creates a new bindable property with the given value, and an action that will be
/// raised when the value changes.
/// </summary>
/// <param name="onPropertyChagnedAction">The action to raise whenever the value changes. The first
/// parameter of this action will be the old value, and the second will be the new value.</param>
/// <exception cref="ArgumentNullException"></exception>
public BindableProperty(TValue value, Action<TValue, TValue> onPropertyChagnedAction) : this(value)
{
m_onPropertyChangedAction = onPropertyChagnedAction ?? throw new ArgumentNullException(nameof(onPropertyChagnedAction));
}
}
</code></pre>
<p>With the following interfaces.</p>
<pre><code>/// <summary>
/// An object that raises <see cref="INotifyPropertyChanged.PropertyChanged"/> whenever it's value
/// is modified.
/// </summary>
/// <typeparam name="TValue">The type of value that this property holds.</typeparam>
interface IBindableProperty<TValue> : IBindableReadOnlyProperty<TValue>
{
/// <summary>
/// The value of this property. Raises <see cref="INotifyPropertyChanged.PropertyChanged"/> when modified.
/// </summary>
new TValue Value { set; }
}
/// <summary>
/// A read only variant of <see cref="IBindableProperty{TValue}"/>.
/// </summary>
/// <typeparam name="TValue"></typeparam>
interface IBindableReadOnlyProperty<TValue>
{
TValue Value { get; }
}
</code></pre>
<h2>Usage</h2>
<p>Is can be used in the following ways.</p>
<pre><code>class OtherViewModel
{
IBindableProperty<string> SomeValue { get; } = new BindableProperty<string>("Default value for \"Some value\"");
IBindableProperty<decimal> SomeOtherValue { get; } = new BindableProperty<decimal>();
}
</code></pre>
<p>If you need some code to happen after the value changes, then an action can be passed in.</p>
<pre><code>public OtherViewModel()
{
SomeValue = new BindableProperty<string>("Default value for \"Some value\"", OnSomeValueChanged);
}
/// <summary>
/// This will be called when SomeValue.Value is modified.
/// </summary>
void OnSomeValueChanged(string oldValue, string newValue)
{
// TODO: Whatever needs to happen here.
}
</code></pre>
<p>Additionally, if for whatever reason you want the value to be changeable by the view, but private to other classes that can reference the view model, then the following can be done.</p>
<pre><code>class OtherViewModel
{
/// <summary>
/// This value can still be modified internally.
/// </summary>
readonly IBindableProperty<string> m_someValue;
/// <summary>
/// Only expose the readonly type, so that other view model's can modify it.
/// </summary>
IBindableReadOnlyProperty<string> SomeValue => m_someValue;
public OtherViewModel()
{
m_someValue = new BindableProperty<string>();
}
}
</code></pre>
<p>In this case, the view can still bind to the <code>BindableProperty</code> backing the interface property and access its <code>set;</code> property, but other classes will only have access to the <code>get;</code> through <code>IBindableReadOnlyProperty</code>.</p>
<p>A bit hacky, perhaps, but no more so than the equivalent using regular properties.</p>
<h2>The Question</h2>
<p>I've seen plenty of WPF samples, but I've never seen anything like this before, which leads me to wonder <em>why</em>. There's no way I could have been the first to have thought of this, and if this were a good idea you'd think it would have spread, so I want to know if there's some obvious problem with this approach that I'm not seeing.</p>
<p>I haven't actually used it in any projects yet, so perhaps doing so would reveal its flaws, whatever they may be.</p>
<p>Is it because this somewhat pollutes the view model's interface, with <code>IBindableProperty<TValue></code> instead of just <code>TValue</code>?</p>
<p>Is it because everyone else is just using <code>PropertyChanged.Fody</code>, or some other such package, and so this is redundant?</p>
<p>Please let me know what, if anything, is wrong with this idea.</p>
|
[] |
[
{
"body": "<p>One thing I don't see you address, is that <code>INotifyPropertyChanged.PropertyChanged</code> has the signature of:</p>\n\n<pre><code>public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);\n</code></pre>\n\n<p>where <code>object sender</code> should be the owner of the property (typically <code>this</code>). You don't provide the code for <code>ObservableObject</code>, but from your code above it seems that the owner of the property in the <code>BindableProperty</code> property (inheriting <code>ObservableObject</code>) is the <code>BindableProperty</code> and not the owner of the <code>BindableProperty</code>. If my assumptions are correct you break the ownership hierarchy, which may confuse the consumer of the <code>PropertyChanged</code> event, because it doesn't have access to the original source of the event.</p>\n\n<hr>\n\n<blockquote>\n <p><code>if (!EqualityComparer<TValue>.Default.Equals(m_value, value))</code></p>\n</blockquote>\n\n<p>Maybe you should provide a constructor that takes a custom <code>EqualityComparer<T></code> (or <code>IEnqualityComparer<T></code>as argument. The above seems a little rigid. </p>\n\n<hr>\n\n<blockquote>\n <p>Is it because this somewhat pollutes the view model's interface, with\n IBindableProperty instead of just TValue?</p>\n</blockquote>\n\n<p>IMO, yes. You pollute your code with a new layer of complexity and obfuscate a quite simple and well established workflow, just because it's irritating to write the same code again and again.</p>\n\n<p>If you are using Visual Studio, you have the opportunity to write and use <a href=\"https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets?view=vs-2019\" rel=\"nofollow noreferrer\">code snippets</a> to make your coding life easier:</p>\n\n<p>The below creates a property that calls the <code>PropertyChanged</code> event:</p>\n\n<pre><code> <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<CodeSnippets xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\">\n <CodeSnippet Format=\"1.0.0\">\n <Header>\n <Title>propnotify</Title>\n <Shortcut>propnotify</Shortcut>\n <Description>Code snippet for property and backing field in a property changed class</Description>\n <Author>Henrik Hansen</Author>\n <SnippetTypes>\n <SnippetType>Expansion</SnippetType>\n </SnippetTypes>\n </Header>\n <Snippet>\n <Declarations>\n <Literal>\n <ID>type</ID>\n <ToolTip>Property type</ToolTip>\n <Default>string</Default>\n </Literal>\n <Literal>\n <ID>property</ID>\n <ToolTip>Property name</ToolTip>\n <Default>MyProperty</Default>\n </Literal>\n <Literal>\n <ID>field</ID>\n <ToolTip>The variable backing this property</ToolTip>\n <Default>myVar</Default>\n </Literal>\n </Declarations>\n <Code Language=\"csharp\"><![CDATA[private $type$ m_$field$;\n public $type$ $property$\n {\n get { return m_$field$;}\n set \n { \n m_$field$ = value;\n OnPropertyChanged(nameof($property$));\n }\n }\n $end$]]>\n </Code>\n </Snippet>\n </CodeSnippet>\n</CodeSnippets>\n</code></pre>\n\n<p>Write \"propnotify\" in the editor and press TAB and then modify the yellow parts that are likely to change by tabbing between them. You may need to change some pieces to accommodate your style of naming etc. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:57:47.197",
"Id": "464707",
"Score": "1",
"body": "Yeah, I assumed it was probably the interface that would sink this idea the most. I was actually aware of code snippets to solve this problem, but I've never really bothered to look into creating custom ones myself. But, I've written enough WPF properties to be able to write them in my sleep at this point, so I think I'll finally look into automating them away."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T08:23:39.473",
"Id": "236881",
"ParentId": "236870",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "236881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T01:07:30.370",
"Id": "236870",
"Score": "8",
"Tags": [
"c#",
"wpf",
"wrapper",
"properties",
"databinding"
],
"Title": "WPF BindableProperty<TValue> to Reduce Boiler Plate"
}
|
236870
|
<p>I have a list of raw data like following mockData and need to generate to a object[] format, some key-value pair are required from raw data like first, last, state. but some key-value pair are option like nickname. Eventually, I need to build a object array with some same key-value like raw data, and some key's value depends on another key's value like fullname, address. If there is a better way for me to do it and make it more dynamically? because I will have more than 20 different key-value set like fullname, address that need to be built by some function related on raw data</p>
<pre><code>export const mockData: Human[] = [
{
first: 'name1',
last: 'v1',
state: 'ny',
},
{
first: 'name2',
last: 'v2',
state: 'pa',
nickname: 'rocketman',
}]
export interface Human {
first: string;
last: string;
state: string;
nickname?: string;
}
export interface Student extends Human{
fullname: string;
address: string;
}
function setFullName(first: string, last: string): string {
return `${first} ${last}`
}
function setAddress(first: string, last: string, state: string): string {
return `${first} ${last} live a ${state}`
}
function buildStudentData(jsons: Human[]): Student[] {
return jsons.map((json) => <Student> {
first: json.first,
last: json.last,
nickname: json.hasOwnProperty('nickname') ? json.nickname : json.first,
fullname: setFullName(json.first, json.last),
address: setAddress(json.first, json.last, json.state)})
}
console.log(buildStudentData(mockData));
</code></pre>
|
[] |
[
{
"body": "<p>You have kind of \"logic\" in your mapping (nickname, fullname and adress). And I assume that this will be the case also for the other data sets you mentioned. That makes generalizing hard. Especially when there is not much in common.</p>\n\n<p>You COULD write a generator were you can configurate for each attribute the mapping strategy, but this would take more time then write the mapping of those 20-30 values directly.</p>\n\n<p>I personally use in quite some cases classes instead of interfaces and then apply a public static \"fromJSON(...)\" or in your case \"fromHuman(...)\" method onto it. Its MORE code to write, but it makes everything explicit. And you are able to ensure that a object (a student) ALWAYS has a proper name. Such things make refactoring later easier. But as i said, the negative part is that you implement more code to gain this safety.</p>\n\n<p>For example in the following code there is only ONE way to create a student. And if the primary identifier of this object (the firstname / lastname combination) is missing then it errors out.</p>\n\n<pre><code>export class Student implements Human {\n readonly first: string;\n readonly last: string;\n state: string;\n nickname?: string;\n fullname: string;\n address: string;\n\n private constructor(firstname: string, lastname: string{\n if(firstname && lastname){\n throw Error('Students must have a first and a lastname!');\n }\n this.first = firstname;\n this.last = lastname;\n }\n\n public static fromHuman(human: Human): Student {\n const student: Student = new Student(human.first, human.last);\n student.state= human.state;\n student.nickname = human.nickname | human.first\n // if you are using TSD 3.7 or above you should use the ?? operator\n // ...\n }\n}\n</code></pre>\n\n<p>If some of the values may change, then i would think about NOT storing calculated values (like the adress) but use a GET method. The reason is, IF one of the values used for calculation (e.g. the state) changes, then a stored \"adress\" would have to get updated manually.</p>\n\n<pre><code>export class Student ...{\n // ...\n public get adress(): string{\n return `${this.first} ${this.last} live a ${this.state}`\n }\n }\n}\n</code></pre>\n\n<p>PRO: Values get updated automaticly\nCON: Values have to get recalculated each time. This may be a performance issue, depending on the usage.</p>\n\n<p>At the end (as always) it depends what you want to achieve. If you need a quick way to generate data, then i would personally stick to your way.<br>\nIf you are using the objects heavily in your application, then i would think about how they are used from the business perspective (which values may not change, which may change often ,...) and treat them as Business Objects. And then guard the objects against misuse. Even if only you are using that code, this may guard you against mistakes and help you understand your code when you have to fix a bug or add a feature a few months later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:02:52.760",
"Id": "464853",
"Score": "0",
"body": "Those are great suggestion and explanation. However I was turned down by other developer about using class. Because he feels like it is not transparent enough which I do not really know why. But like you say. I will need to return lots of different combination of json data by calling different format of setAddress or setFullname function. Which bring me to only different between each buildstudentdata is `fullname: setFullName(json.first, json.last),\n address: setAddress(json.first, json.last, json.state)})\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:55:45.823",
"Id": "464894",
"Score": "0",
"body": "Classes for these kind of things are quite \"heavy\". Therefor a lot of developers do not like to invest that much effort if they can achieve the result with an interface much easier. In my experience, as soon as the application gets a certain size, and if multiple developers are working on it, then the class approach will return the invested effort in no time. Also with business data models instead of DTOs the class explains the business usage of this data. But as always, the solution depends on the problem and the context around it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:06:40.993",
"Id": "236998",
"ParentId": "236873",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T06:06:38.760",
"Id": "236873",
"Score": "2",
"Tags": [
"typescript"
],
"Title": "build up object[] from raw data set"
}
|
236873
|
<p>I have an array of bytes 6144 bytes long. I want to extract a set of 4 bytes every 6th set of 4 bytes . So every 24 bytes I want to extract 4 of those bytes and join them in a new array. So
<code>arr=[a0, a1 ,a2 ,a3 ,a4 ...a6143]</code> should become
<code>arrNew=[a0, a1, a2, a3, a24 , a25, a26, a27, ...a1020, a1021, a1022, a1023]</code></p>
<p>I have done this by using</p>
<pre><code># data holds 6144 bytes
j=0
n=0
ll=bytearray()
while(n<256)
ll.extend(data[0+j:4+j])
j=j+24
n=n+1
</code></pre>
<p>This works but is too slow for what I am trying to do. Is there a faster way to do it. I was hoping one line of numpy could do it but I couldn't find anything that would work so easily.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T08:23:40.000",
"Id": "464323",
"Score": "3",
"body": "The code as provided has some syntax errors, and so it is impossible for it to run. Please provide your actual Python code. Also you're currently not using numpy, so the numpy tag is unneeded and misleading."
}
] |
[
{
"body": "<ul>\n<li>Your formatting is bad, adhere to PEP8 for readability.</li>\n<li><code>j</code> is always <code>n * 24</code>, so you could eliminate one of them. I'd probably use <code>j</code> exclusively.</li>\n<li>Instead of manually iterating an integer in a while loop, use <code>range()</code>. In particular, check out the third argument to it.</li>\n<li>Since you know the final size of <code>ll</code>, you could allocate the required amount of storage up front and then fill in the parts. As it stands, every rotation of the loop requires making a new allocation for storage, copying the existing data over and release of the old storage.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T08:09:26.377",
"Id": "236880",
"ParentId": "236879",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236880",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T07:20:44.660",
"Id": "236879",
"Score": "-1",
"Tags": [
"python",
"performance",
"array",
"numpy"
],
"Title": "Trying to get every 6th set of 4 bytes from a python array"
}
|
236879
|
<p>Please review my code with the following in mind: Does anyone see a reason to make this asynchronous, why would i do that? How do i work out the maximum number of users it can handle at one time? at what point will i need to optimise it and are there any easy things i can do to handle more users.</p>
<pre><code>import os
import sqlite3
import hashlib
import binascii
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado.options import define, options
define('port', default=80, help='port to listen on')
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True,
cookie_secret="changethis",
login_url="/login",
# xsrf_cookies=True,
)
def hash_password(password):
"""Hash a password for storing."""
salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii')
pwdhash = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'),
salt, 100000)
pwdhash = binascii.hexlify(pwdhash)
return (salt + pwdhash).decode('ascii')
def verify_password(stored_password, provided_password):
"""Verify a stored password against one provided by user"""
salt = stored_password[:64]
stored_password = stored_password[64:]
pwdhash = hashlib.pbkdf2_hmac('sha512',
provided_password.encode('utf-8'),
salt.encode('ascii'), 100000)
pwdhash = binascii.hexlify(pwdhash).decode('ascii')
return pwdhash == stored_password
try:
db = sqlite3.connect('file:aaa.db?mode=rw', uri=True)
except sqlite3.OperationalError:
db = sqlite3.connect("aaa.db")
db.execute("CREATE TABLE Users (id INTEGER PRIMARY KEY, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL);")
class BaseHandler(RequestHandler):
def get_current_user(self):
return self.get_secure_cookie("session")
class IndexHandler(BaseHandler):
def get(self):
if not self.current_user:
self.write("not logged in")
return
count = db.execute("SELECT COUNT(*) FROM Users;").fetchone()
self.write('{} users so far!'.format(count[0]))
class LoginHandler(BaseHandler):
def get(self):
if self.current_user:
self.write("already logged in")
return
self.render("login.html")
def post(self):
if self.current_user:
self.write("already logged in")
return
name=self.get_body_argument("username")
query= db.execute("SELECT COUNT(*) FROM Users WHERE username = ?;", (name,)).fetchone()
if query[0] == 0:
self.write("user does not exist")
else:
hashed_password = db.execute("SELECT (password) FROM Users WHERE username = ?;", (name,)).fetchone()[0]
if verify_password(hashed_password, self.get_body_argument("password")):
self.set_secure_cookie("session", name)
self.write("cookie set, logged in")
else:
self.write("wrong password")
class SignupHandler(BaseHandler):
def get(self):
if self.current_user:
self.write("already logged in")
return
self.render("signup.html")
def post(self):
if self.current_user:
self.write("already logged in")
return
name=self.get_body_argument("username")
password=self.get_body_argument("password")
try:
with db:
db.execute("INSERT INTO Users(username,password) VALUES (?,?);", (name, hash_password(password)))
except sqlite3.IntegrityError:
self.write("user exists")
return
self.write("user added")
class LogoutHandler(BaseHandler):
def get(self):
self.clear_cookie("session")
self.write("logged out")
def main():
routes=(
(r'/', IndexHandler),
(r'/login', LoginHandler),
(r'/logout', LogoutHandler),
(r'/signup', SignupHandler),
)
app = Application(routes, **settings)
app.listen(options.port)
IOLoop.current().start()
if __name__=="__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T14:55:52.690",
"Id": "464349",
"Score": "0",
"body": "Welcome to the code review site where we review working code to provide suggestions on how to improve the code. It is not clear that you are asking for a code review, in fact it almost seems like you are asking for a feature request which would make the question off-topic for code review. Please see the guidelines at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T15:20:23.040",
"Id": "464351",
"Score": "0",
"body": "haha i got told the opposite on stackoverflow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T15:39:00.910",
"Id": "464352",
"Score": "0",
"body": "The rewording the question definitely helped."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T14:02:37.477",
"Id": "236892",
"Score": "2",
"Tags": [
"python",
"security",
"tornado"
],
"Title": "Production ready user signup, login and logout using python and tornado"
}
|
236892
|
<p>I'm learning Rust by working through Jamis Buck's <a href="https://pragprog.com/book/jbtracer/the-ray-tracer-challenge" rel="nofollow noreferrer"><em>The Ray Tracer Challenge</em></a>. The book instructs the reader on what to build in what order, and provides all required test cases.</p>
<p>Included here are my implementations of 1) an RGB color representation, and 2) a canvas, which is essentially an editable 2-d array of color objects with plaintext PPM image printing capability.</p>
<p>My particular concerns are 1) how can this noob write more idiomatic Rust, and 2) can it be more performant, particularly for large canvases with millions of pixels?</p>
<p>color.rs:</p>
<pre><code>use approx::AbsDiffEq;
use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Sub;
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Color {
pub r: f32,
pub g: f32,
pub b: f32,
}
pub fn build_color(r: f32, g: f32, b: f32) -> Color {
Color { r: r, g: g, b: b }
}
impl Add for Color {
type Output = Color;
fn add(self, other: Color) -> Color {
Color {
r: self.r + other.r,
g: self.g + other.g,
b: self.b + other.b,
}
}
}
impl Sub for Color {
type Output = Color;
fn sub(self, other: Color) -> Color {
Color {
r: self.r - other.r,
g: self.g - other.g,
b: self.b - other.b,
}
}
}
// scalar multiplication (commutative)
impl Mul<f32> for Color {
type Output = Color;
fn mul(self, scalar: f32) -> Color {
Color {
r: self.r * scalar,
g: self.g * scalar,
b: self.b * scalar,
}
}
}
// scalar multiplication (commutative)
impl Mul<Color> for f32 {
type Output = Color;
fn mul(self, color: Color) -> Color {
color * self
}
}
// scalar division
impl Div<f32> for Color {
type Output = Color;
fn div(self, scalar: f32) -> Color {
Color {
r: self.r / scalar,
g: self.g / scalar,
b: self.b / scalar,
}
}
}
// Multiplying two Color objects produces a mix of the two colors using the Hadamard product
impl Mul<Color> for Color {
type Output = Color;
fn mul(self, other: Color) -> Color {
Color {
r: self.r * other.r,
g: self.g * other.g,
b: self.b * other.b,
}
}
}
// required for equality tests because floating point numbers must be compared approximately
impl AbsDiffEq for Color {
type Epsilon = f32;
fn default_epsilon() -> Self::Epsilon {
f32::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
f32::abs_diff_eq(&self.r, &other.r, epsilon)
&& f32::abs_diff_eq(&self.g, &other.g, epsilon)
&& f32::abs_diff_eq(&self.b, &other.b, epsilon)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_adding_colors() {
let c1 = build_color(0.9, 0.6, 0.75);
let c2 = build_color(0.7, 0.1, 0.25);
abs_diff_eq!(c1 + c2, build_color(1.6, 0.7, 1.0));
}
#[test]
fn test_subtracting_colors() {
let c1 = build_color(0.9, 0.6, 0.75);
let c2 = build_color(0.7, 0.1, 0.25);
abs_diff_eq!(c1 - c2, build_color(0.2, 0.5, 0.5));
}
#[test]
fn test_multiply_color_by_scalar() {
let c = build_color(0.2, 0.3, 0.4);
abs_diff_eq!(c * 2.0, 2.0 * c);
abs_diff_eq!(c * 2.0, build_color(0.4, 0.6, 0.8));
}
#[test]
fn test_mix_colors_by_multiplication() {
let c1 = build_color(1.0, 0.2, 0.4);
let c2 = build_color(0.9, 1.0, 0.1);
abs_diff_eq!(c1 * c2, build_color(0.9, 0.2, 0.04));
}
}
</code></pre>
<p>canvas.rs:</p>
<pre><code>use crate::color::{build_color, Color};
pub struct Canvas {
pub width: usize,
pub height: usize,
data: Vec<Vec<Color>>,
}
// Create a canvas initialized to all black
pub fn build_canvas(width: usize, height: usize) -> Canvas {
Canvas {
width: width,
height: height,
data: vec![vec![build_color(0.0, 0.0, 0.0); width]; height],
}
}
const MAX_COLOR_VAL: i16 = 255;
const MAX_PPM_LINE_LENGTH: usize = 70;
// length of "255" is 3
// TODO: this should be evaluated programmatically, but "no matching in consts allowed" error prevented this
const MAX_COLOR_VAL_STR_LEN: usize = 3;
impl Canvas {
pub fn write_pixel(&mut self, x: usize, y: usize, color: Color) -> () {
self.data[y][x] = color;
}
pub fn pixel_at(&self, x: usize, y: usize) -> Color {
self.data[y][x]
}
// scale/clamp color values from 0-1 to 0-255
fn scale_color(&self, rgb: f32) -> u8 {
(rgb * MAX_COLOR_VAL as f32)
.min(MAX_COLOR_VAL as f32)
.max(0.0) as u8
}
// If current line has no more room for more RGB values, add it to the PPM string and clear it;
// otherwise, add a space separator in preparation for the next RGB value
fn write_rgb_separator(&self, line: &mut String, ppm: &mut String) {
if line.len() < MAX_PPM_LINE_LENGTH - MAX_COLOR_VAL_STR_LEN {
(*line).push(' ');
} else {
ppm.push_str(&line);
ppm.push('\n');
line.clear();
}
}
// Return string containing PPM (portable pixel map) data representing current canvas
pub fn to_ppm(&self) -> String {
let mut ppm = String::new();
// write header
ppm.push_str("P3\n");
ppm.push_str(&(format!("{} {}\n", self.width, self.height)));
ppm.push_str(&(format!("{}\n", MAX_COLOR_VAL)));
// Write pixel data. Each pixel RGB value is written with a separating space or newline;
// new rows are written on new lines for human reading convenience, but lines longer than
// MAX_PPM_LINE_LENGTH must also be split.
let mut current_line = String::new();
for row in 0..self.height {
current_line.clear();
for (i, column) in (0..self.width).enumerate() {
let color = self.pixel_at(column, row);
let r = self.scale_color(color.r);
let g = self.scale_color(color.g);
let b = self.scale_color(color.b);
current_line.push_str(&r.to_string());
self.write_rgb_separator(&mut current_line, &mut ppm);
current_line.push_str(&g.to_string());
self.write_rgb_separator(&mut current_line, &mut ppm);
current_line.push_str(&b.to_string());
// if not at end of row yet, write a space or newline if the next point will be on this line
if i != self.width - 1 {
self.write_rgb_separator(&mut current_line, &mut ppm);
}
}
if current_line.len() != 0 {
ppm.push_str(&current_line);
ppm.push('\n');
}
}
ppm
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_height_and_width() {
let c = build_canvas(15, 10);
assert_eq!(c.width, 15);
assert_eq!(c.height, 10);
}
#[test]
fn test_write_and_read_pixels() {
let mut canvas = build_canvas(10, 5);
let color = build_color(0.1, 0.2, 0.3);
canvas.write_pixel(7, 4, color);
assert_eq!(canvas.pixel_at(7, 4), color);
}
#[test]
fn test_ppm_header() {
let c = build_canvas(20, 5);
let ppm = c.to_ppm();
let mut lines = ppm.lines();
assert_eq!(lines.next().unwrap(), "P3");
assert_eq!(lines.next().unwrap(), "20 5");
assert_eq!(lines.next().unwrap(), "255");
}
#[test]
fn test_ppm_pixel_data() {
let mut c = build_canvas(5, 3);
c.write_pixel(0, 0, build_color(1.5, 0.0, 0.0));
c.write_pixel(2, 1, build_color(0.0, 0.5, 0.0));
c.write_pixel(4, 2, build_color(-0.5, 0.0, 1.0));
let ppm = c.to_ppm();
let mut lines = ppm.lines();
// ignore header
lines.next();
lines.next();
lines.next();
assert_eq!(lines.next().unwrap(), "255 0 0 0 0 0 0 0 0 0 0 0 0 0 0");
// book says 128, but I'll trust Rust's rounding for now
assert_eq!(lines.next().unwrap(), "0 0 0 0 0 0 0 127 0 0 0 0 0 0 0");
assert_eq!(lines.next().unwrap(), "0 0 0 0 0 0 0 0 0 0 0 0 0 0 255");
}
#[test]
fn test_splitting_long_ppm_lines() {
let mut canvas = build_canvas(10, 2);
let color = build_color(1.0, 0.8, 0.6);
// TODO: maybe turn this into a function on canvas?
for row in 0..canvas.height {
for column in 0..canvas.width {
canvas.write_pixel(column, row, color);
}
}
let ppm = canvas.to_ppm();
let mut lines = ppm.lines();
// skip header
lines.next();
lines.next();
lines.next();
assert_eq!(
lines.next().unwrap(),
"255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204"
);
assert_eq!(
lines.next().unwrap(),
"153 255 204 153 255 204 153 255 204 153 255 204 153"
);
assert_eq!(
lines.next().unwrap(),
"255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204"
);
assert_eq!(
lines.next().unwrap(),
"153 255 204 153 255 204 153 255 204 153 255 204 153"
);
}
}
</code></pre>
<p>Permalink to current repository state: <a href="https://github.com/garfieldnate/ray_tracer_challenge/tree/e7fd5ebc2f6af209ea1db0f1ce3a04519bed7bf0" rel="nofollow noreferrer">https://github.com/garfieldnate/ray_tracer_challenge/tree/e7fd5ebc2f6af209ea1db0f1ce3a04519bed7bf0</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T04:38:20.577",
"Id": "465344",
"Score": "1",
"body": "You can replace for 4 of use with one: `use std::ops::{Add,Div,Mul,Sub}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T04:48:32.450",
"Id": "465346",
"Score": "1",
"body": "`build_color` could be a called a `new` and be implemented inside `impl Color` block. This will allow you to crate `Color` with `Color::new()`. you cloud also provide a builder for color. `ColorBuilder::new().green(1f32).red(0.4f32).blue(0.2f32).build()` This will help people not accidentally mix red with blue."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T15:42:43.497",
"Id": "236895",
"Score": "1",
"Tags": [
"performance",
"rust",
"graphics"
],
"Title": "color and canvas implementations in Rust for Ray Tracer Challenge"
}
|
236895
|
<p>I have completed a solution for the below problem and uploaded it in Git Repo. I would be grateful if somebody can review in term of code quality, design and Kotlin language usage.</p>
<p><a href="https://github.com/ganesara/canvasDrawing" rel="nofollow noreferrer">Repo</a></p>
<blockquote>
<p>You're given the task of writing a simple console version of a drawing
program. At this time, the functionality of the program is quite
limited but this might change in the future.</p>
<p>In a nutshell, the program should work as follows:</p>
<ol>
<li>Create a new canvas</li>
<li>Start drawing on the canvas by issuing various commands</li>
<li>Quit</li>
</ol>
<p></p>
<pre class="lang-none prettyprint-override"><code>Command Description
C w h Should create a new canvas of width w and height h.
L x1 y1 x2 y2 Should create a new line from (x1,y1) to (x2,y2). Currently only
horizontal or vertical lines are supported. Horizontal and vertical lines
will be drawn using the 'x' character.
R x1 y1 x2 y2 Should create a new rectangle, whose upper left corner is (x1,y1) and
lower right corner is (x2,y2). Horizontal and vertical lines will be drawn
using the 'x' character.
B x y c Should fill the entire area connected to (x,y) with "colour" c. The
behavior of this is the same as that of the "bucket fill" tool in paint
programs.
Q Should quit the program.
</code></pre>
<p><strong>Sample I/O</strong></p>
<p>Below is a sample run of the program. User input is prefixed with
enter command: ``` enter command: C 20 4</p>
<h2>---------------------- | | | | | | | |</h2>
<p>enter command: L 1 2 6 2</p>
<h2>---------------------- | | |xxxxxx | | | | |</h2>
<p>enter command: L 6 3 6 4</p>
<h2>---------------------- | | |xxxxxx | | x | | x |</h2>
<p>enter command: R 14 1 18 3</p>
<h2>---------------------- | xxxxx | |xxxxxx x x | | x xxxxx | | x |</h2>
<p>enter command: B 10 3 o</p>
<h2>---------------------- |oooooooooooooxxxxxoo| |xxxxxxooooooox xoo| | xoooooooxxxxxoo| | xoooooooooooooo|</h2>
<p>enter command: Q ```</p>
<p><a href="https://i.stack.imgur.com/UgQbB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UgQbB.jpg" alt="enter image description here"></a></p>
</blockquote>
<h2>Code to Review</h2>
<p><strong>Pixel.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.canvas
open class Pixel() {
var text: String = ""
constructor(txt: String): this() {
this.text = txt
}
fun isBlank():Boolean {
return this.text.isBlank()
}
override fun equals(other: Any?): Boolean {
return this.text == (other as? Pixel)?.text ?: "UNKNOWN"
}
override fun hashCode(): Int {
return this.text.hashCode()
}
override fun toString(): String {
return this.text
}
}
data class Position(val x: Int, val y:Int)
class WidthBorder : Pixel( txt = CanvasConstants.WIDTH_BORDER_CHAR)
class HeightBorder : Pixel(txt = CanvasConstants.HEIGHT_BORDER_CHAR)
</code></pre>
<p><strong>CanvasConstants.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.canvas
object CanvasConstants {
const val WIDTH_BORDER_CHAR = "-"
const val HEIGHT_BORDER_CHAR = "|"
const val DEFAULT_DISPLAY_CHAR = " "
const val INVALID_TEXT_CHAR = "~"
const val LINE_DISPLAY_CHAR = "*"
}
</code></pre>
<p><strong>ICanvas.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.canvas
interface ICanvas {
fun createCanvas(width: Int, height:Int): Boolean
fun printScreen()
fun isPositionAvailable(pos: Position): Boolean
fun isPositionWritable(pos: Position): Boolean
fun getPixelValueAt(pos: Position): String
fun setPixelValueAt(pos: Position, value: String, overwrite: Boolean = true) : Boolean
fun setPixelValueBetween(inclusiveStart: Position,
inclusiveEnd: Position,
value: String,
overwrite: Boolean = true) : List<Position>
fun writableChildrenOf(pos: Position): List<Position>
}
</code></pre>
<p><strong>Canvas.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.canvas
import org.slf4j.LoggerFactory
class Canvas(private var width: Int = 0, private var height: Int = 0) : ICanvas {
companion object {
private val logger = LoggerFactory.getLogger(Canvas::class.java)
}
private var pixels: Array<Array<Pixel>>
init {
pixels = initPixel(width = width, height = height)
}
private fun initPixel(width: Int, height: Int): Array<Array<Pixel>> {
return Array(size = height + 2) {i ->
Array(size = width + 2){j ->
if(i == 0 || i == height + 1) {
WidthBorder()
} else if(j == 0 || j == width + 1) {
HeightBorder()
} else {
Pixel(txt = CanvasConstants.DEFAULT_DISPLAY_CHAR)
}
}
}
}
override fun createCanvas(width: Int, height: Int): Boolean {
return if(this.width == 0 || this.height == 0) {
this.width = width
this.height = height
this.pixels = initPixel(width = width, height = height)
true
} else {
false
}
}
override fun printScreen() {
for(i in this.pixels.indices) {
if(i != 0) {
println("")
}
for(j in this.pixels[i].indices) {
print(this.pixels[i][j])
}
}
println()
}
override fun isPositionAvailable(pos: Position): Boolean {
if(this.pixels.isEmpty()) {
logger.error("Position is not available")
return false
}
return pos.x > 0
&& pos.y >0
&& this.pixels.size -1 > pos.y
&& this.pixels[0].size -1 > pos.x
}
override fun isPositionWritable(pos: Position): Boolean {
return this.isPositionAvailable(pos)
&& this.pixels[pos.y][pos.x].isBlank()
}
override fun getPixelValueAt(pos: Position): String {
return if(this.isPositionAvailable(pos)) {
this.pixels[pos.y][pos.x].text
} else {
CanvasConstants.INVALID_TEXT_CHAR
}
}
override fun setPixelValueAt(pos: Position, value: String, overwrite: Boolean) : Boolean {
return if(!overwrite && this.isPositionWritable(pos = pos)) {
this.pixels[pos.y][pos.x].text = value
true
} else if(overwrite){
this.pixels[pos.y][pos.x].text = value
true
} else {
false
}
}
override fun setPixelValueBetween(inclusiveStart: Position,
inclusiveEnd: Position,
value: String,
overwrite: Boolean) : List<Position> {
val start = inclusiveStart
val end = inclusiveEnd
val affectedList = mutableListOf<Position>()
if(!this.isPositionAvailable(pos = start)
|| !this.isPositionAvailable(pos = end)) {
return affectedList
}
val yRange = if (start.y <= end.y) start.y..end.y else start.y downTo end.y
val xRange = if (start.x <= end.x) start.x..end.x else start.x downTo end.x
for(y in yRange) {
for(x in xRange) {
val pixel = this.pixels[y][x]
pixel.text = value
affectedList.add(Position(x = x, y = y))
}
}
return affectedList
}
override fun writableChildrenOf(pos: Position): List<Position> {
val list = mutableListOf<Position>()
if (this.isPositionWritable(Position(x = pos.x, y = pos.y + 1 ))) {
list.add(Position(x = pos.x, y = pos.y + 1 ))
}
if (this.isPositionWritable(Position(x = pos.x, y = pos.y - 1 ))) {
list.add(Position(x = pos.x, y = pos.y - 1 ))
}
if (this.isPositionWritable(Position(x = pos.x + 1, y = pos.y))) {
list.add(Position(x = pos.x + 1, y = pos.y))
}
if (this.isPositionWritable(Position(x = pos.x - 1, y = pos.y))) {
list.add(Position(x = pos.x - 1, y = pos.y))
}
return list
}
}
</code></pre>
<p><strong>Painter.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.painter
import org.draw.paint.canvas.ICanvas
import org.draw.paint.common.Status
import org.draw.paint.common.Success
interface Painter {
fun validate(canvas: ICanvas): Status = Success()
fun paint(canvas: ICanvas) : Status
}
</code></pre>
<p><strong>Line Painter.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.painter
import org.draw.paint.canvas.CanvasConstants
import org.draw.paint.canvas.ICanvas
import org.draw.paint.canvas.Position
import org.draw.paint.common.Failed
import org.draw.paint.common.Status
import org.draw.paint.common.Success
import org.slf4j.LoggerFactory
class LinePainter(private val start: Position, private val end: Position) : Painter {
companion object {
val logger = LoggerFactory.getLogger(LinePainter::class.java)
}
val affectedPositions = mutableListOf<Position>()
override fun validate(canvas: ICanvas) : Status {
return if( !canvas.isPositionAvailable(start)) {
logger.error("Start Position is Unknown, Can't paint Line")
Failed(reason = "Start Position Unknown")
} else if( !canvas.isPositionAvailable(end)) {
logger.error("End position Unknown. Can't paint line")
Failed(reason = "End Position Unknown")
} else if( (this.start.x == this.end.x)
.xor(this.end.y == this.start.y).not() ){
logger.error("Co-ordinates are not suitable for drawing horizontal or vertical line")
Failed("Only horizontal or vertical line are possible")
} else {
Success()
}
}
override fun paint(canvas: ICanvas): Status {
val validationStatus = this.validate(canvas)
if(validationStatus is Failed) {
logger.error("Line painter Validation Failed")
return validationStatus
}
affectedPositions += canvas.setPixelValueBetween(inclusiveStart = this.start,
inclusiveEnd = this.end, value = CanvasConstants.LINE_DISPLAY_CHAR
)
logger.debug("Affected positions Count = ${affectedPositions.size}")
logger.trace("Affected positions : $affectedPositions")
logger.info("Painting of LinePainter completed ")
return Success()
}
}
</code></pre>
<p><strong>FillPainter.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.painter
import org.draw.paint.canvas.ICanvas
import org.draw.paint.canvas.Position
import org.draw.paint.common.Failed
import org.draw.paint.common.Status
import org.draw.paint.common.Success
import org.slf4j.LoggerFactory
class FillPainter(private val start:Position, private val colour: String): Painter {
val affectedPositions = mutableListOf<Position>()
companion object {
private val log = LoggerFactory.getLogger(FillPainter::class.java)
}
override fun validate(canvas: ICanvas): Status {
return if( !canvas.isPositionAvailable(start) ) {
Failed("Position Not available")
} else if(!canvas.isPositionWritable(start)){
Failed("Position Filled already")
} else {
Success()
}
}
override fun paint(canvas: ICanvas): Status {
var status = this.validate(canvas = canvas)
if(status is Failed) {
return status
}
status = this.fillByBreadthFirstSearch(canvas = canvas)
log.debug("Affected positions Count = ${affectedPositions.size}")
log.trace("Affected positions : $affectedPositions")
log.info("Painting of LinePainter completed ")
return status
}
private fun fillByBreadthFirstSearch(canvas: ICanvas) : Success {
var temp = start
val trackList = mutableListOf<Position>()
canvas.setPixelValueAt(pos = temp, value = colour, overwrite = false)
affectedPositions.add(temp)
var children = canvas.writableChildrenOf(pos = temp)
children.forEach { p ->
canvas.setPixelValueAt(pos = p, value = colour, overwrite = false)
affectedPositions.add(p)
trackList.add(p)
}
while(trackList.size > 0) {
temp = trackList.last()
trackList.removeAt(trackList.size - 1)
children = canvas.writableChildrenOf(pos = temp)
children.forEach { p ->
canvas.setPixelValueAt(pos = p, value = colour, overwrite = false)
affectedPositions.add(p)
trackList.add(p)
}
}
return Success()
}
}
</code></pre>
<p><strong>BoxPainter.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.painter
import org.draw.paint.canvas.CanvasConstants
import org.draw.paint.canvas.ICanvas
import org.draw.paint.canvas.Position
import org.draw.paint.common.Failed
import org.draw.paint.common.Status
import org.draw.paint.common.Success
import org.slf4j.LoggerFactory
open class BoxPainter(protected val start: Position, protected val end: Position) : Painter {
companion object {
val log = LoggerFactory.getLogger(BoxPainter::class.java)
}
val affectedPosition = LinkedHashSet<Position>()
override fun validate(canvas: ICanvas): Status {
return if(!canvas.isPositionAvailable(start)) {
log.error("Start Position is out of Canvas focus")
Failed("Start Position is not available")
} else if(!canvas.isPositionAvailable(this.end)){
log.error("End Position is out of Canvas focus")
Failed("End Position is not available")
} else if(this.start.x == this.end.x){
log.error("Column Positions are Same. can't draw Box")
Failed("Column Positions are Same. can't draw Box")
} else if(this.start.y == this.end.y){
log.error("Row Positions are Same. can't draw Box")
Failed("Row Positions are Same. can't draw Box")
} else {
Success()
}
}
override fun paint(canvas: ICanvas): Status {
val validationStatus = this.validate(canvas= canvas)
if(validationStatus is Failed) {
log.error("Box painter Validation Failed")
return validationStatus
}
val positions = mutableListOf<Position>()
positions += canvas.setPixelValueBetween(inclusiveStart = start,
inclusiveEnd = Position(x = start.x, y = end.y),
value = CanvasConstants.LINE_DISPLAY_CHAR)
positions += canvas.setPixelValueBetween(inclusiveStart = Position(x = start.x, y = end.y),
inclusiveEnd = end,
value = CanvasConstants.LINE_DISPLAY_CHAR)
positions += canvas.setPixelValueBetween(inclusiveStart = end,
inclusiveEnd = Position(x = end.x, y = start.y),
value = CanvasConstants.LINE_DISPLAY_CHAR)
positions += canvas.setPixelValueBetween(inclusiveStart = Position(x = end.x, y = start.y),
inclusiveEnd = start,
value = CanvasConstants.LINE_DISPLAY_CHAR)
affectedPosition.addAll(positions)
log.debug("Affected positions Count = ${affectedPosition.size}")
log.trace("Affected positions : $affectedPosition")
log.info("Painting of LinePainter completed ")
return Success()
}
}
</code></pre>
<p><strong>RectanglePainter.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.painter
import org.draw.paint.canvas.ICanvas
import org.draw.paint.canvas.Position
import org.draw.paint.common.Failed
import org.draw.paint.common.Status
import org.draw.paint.common.Success
import org.slf4j.LoggerFactory
import kotlin.math.abs
class RectanglePainter(start: Position, end: Position)
: BoxPainter(start = start, end = end) {
companion object {
val log = LoggerFactory.getLogger(RectanglePainter::class.java)
}
override fun validate(canvas: ICanvas): Status {
val status = super.validate(canvas)
return if (status is Failed) {
status
} else if(abs(start.x - end.x) == abs(start.y - end.y)){
log.error("Can't form Rectangle square co-ordinates")
Failed("Position forms Square not rectangle")
} else {
Success()
}
}
}
</code></pre>
<p><strong>Status.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.common
enum class StatusTypes {
SUCCESS, FAILED
}
open class Status(val status: StatusTypes) {
companion object{
fun statusProcessor(status: Status) {
when(status) {
is Success -> println("Done.")
is Failed -> println("Err: ${status.reason}")
}
}
}
fun isSuccess(): Boolean {
return status == StatusTypes.SUCCESS
}
}
class Success: Status(status = StatusTypes.SUCCESS)
class Failed(val reason: String):Status(status = StatusTypes.FAILED)
</code></pre>
<p><strong>CanvasException.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.exception
class CanvasExceptions: RuntimeException {
constructor(msg: String):super(msg)
constructor(throwable: Throwable): super(throwable)
}
</code></pre>
<p><strong>CommandParser</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint.command
import org.draw.paint.canvas.ICanvas
import org.draw.paint.canvas.Position
import org.draw.paint.common.Failed
import org.draw.paint.common.Status
import org.draw.paint.exception.CanvasExceptions
import org.draw.paint.painter.*
import org.slf4j.LoggerFactory
import kotlin.system.exitProcess
object CommandParser {
private val createPainterFunList = mutableListOf<(String) -> Painter?> (
this::createCanvasPainter,
this::createFillCommandPainter,
this::createLineCommandPainter,
this::quiteCommandPainter,
this::rectangleCommandPainter
)
private val log = LoggerFactory.getLogger(CommandParser::class.java)
fun parse(cmd: String): Painter {
var failed: Painter = object: Painter {
override fun validate(canvas: ICanvas): Status = Failed(reason = "Unable to Execute Command")
override fun paint(canvas: ICanvas) : Status = Failed(reason = "Unable to Execute Command")
}
try {
this.createPainterFunList.forEach { fn ->
val painter = fn(cmd)
if(painter != null) return painter
}
} catch (e: Exception) {
failed = object: Painter {
override fun validate(canvas: ICanvas): Status = Failed(reason = e.localizedMessage)
override fun paint(canvas: ICanvas) : Status = Failed(reason = e.localizedMessage)
}
}
return failed
}
private fun parseCommand(regex: Regex, string: String): MatchResult.Destructured ? {
try {
if(regex.matches(string)) {
val result = regex.find(string)
return result?.destructured ?: throw CanvasExceptions("Unable to parse Canvas Command")
}
} catch (e: Exception) {
log.error("Error Parsing the Canvas Command", e)
throw CanvasExceptions(throwable = e)
}
return null
}
fun createCanvasPainter(cmd: String):Painter? {
val cmdPattern = """[Cc]\s+(\d+)\s+(\d+)""".toRegex()
val (width , height) = this.parseCommand(regex = cmdPattern, string = cmd) ?: return null
return CanvasPainter(width = width.toInt(), height = height.toInt())
}
private fun createFillCommandPainter(cmd: String): Painter? {
val templateRegex = """[Bb]\s+(\d+)\s+(\d+)\s+(.)""".toRegex()
val (sw,sh,colour) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null
return FillPainter(start = Position(x = sw.toInt(), y = sh.toInt()) ,colour = colour)
}
private fun createLineCommandPainter(cmd:String): Painter? {
val templateRegex = """[Ll]\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)""".toRegex()
val (sw,sh,ew,eh) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null
return LinePainter(start = Position(x = sw.toInt(), y= sh.toInt()),
end = Position(x = ew.toInt(), y = eh.toInt()))
}
private fun quiteCommandPainter(cmd: String) : Painter? {
val templateRegex = """[Qq]""".toRegex()
if(templateRegex.matches(cmd)) {
exitProcess(status = 0)
}
return null
}
private fun rectangleCommandPainter(cmd: String): Painter? {
val templateRegex = """[Rr]\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)""".toRegex()
val (sw,sh,ew,eh) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null
return RectanglePainter(start = Position(x = sw.toInt(), y = sh.toInt()),
end = Position(x = ew.toInt(), y = eh.toInt()))
}
}
</code></pre>
<p><strong>CanvasRunner.kt</strong></p>
<pre class="lang-none prettyprint-override"><code>package org.draw.paint
import org.draw.paint.canvas.Canvas
import org.draw.paint.canvas.ICanvas
import org.draw.paint.command.CommandParser
import org.draw.paint.common.Status
import org.draw.paint.exception.CanvasExceptions
import org.slf4j.LoggerFactory
import java.util.*
fun main(args: Array<String>) {
val canvasRunner = CanvasRunner()
canvasRunner.start()
}
class CanvasRunner {
companion object {
private val log = LoggerFactory.getLogger(CanvasRunner::class.java)
}
private var canvas: ICanvas = Canvas()
private fun readLine(): String {
val scanner = Scanner(System.`in`)
return scanner.nextLine()
}
internal fun executeCommand(command: String) {
val status = CommandParser.parse(cmd = command).paint(canvas = canvas)
if(status.isSuccess()) {
canvas.printScreen()
}
Status.statusProcessor(status = status)
}
private fun executeConsoleCommands() {
var command: String
do {
print("Enter Command :")
command = this.readLine()
log.trace("Received instruction as $command")
this.executeCommand(command = command)
} while (true)
}
fun start() {
executeConsoleCommands()
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:22:22.287",
"Id": "464435",
"Score": "0",
"body": "Code to be reviewed is uploaded to Git hub. https://github.com/ganesara/canvasDrawing. I need someone to evaluate my design (complexity, quality) and coding standards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:58:22.690",
"Id": "464556",
"Score": "0",
"body": "Canvaspainter failes if width or height is null <> Canvas.createCanvas fails if CanvasPainter doesnt fail. is this a bug?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T15:56:11.633",
"Id": "236896",
"Score": "2",
"Tags": [
"canvas",
"kotlin"
],
"Title": "Canvas Drawing / Bucket Filing Kotlin"
}
|
236896
|
<p>I'm going through the <em>Head First Design Patterns</em> book and I want to check whether I'm understanding some aspects of the first chapter. Does the code below program correctly to interfaces, encapsulate changeable behavior, and employ composition in a reasonable manner?</p>
<pre><code>// trying to enforce some design pattern habits
// create a duck, that prints a line to the page as text
class DuckAbilities {
constructor() {
this.flying = new FlyBehavior()
}
addToPage() {
this.statement = document.createElement("p")
this.statement.innerHTML=this.flying.fly()
document.body.append(this.statement)
}
}
//interface for behaviors
class FlyBehavior {
fly() {
null
}
}
class DoesFly{
fly() {
return "I'm flying"
}
}
class DoesNotFly {
fly() {
return "not flying"
}
}
class Mallard {
constructor() {
this.abilities = new DuckAbilities()
this.abilities.flying = new DoesFly()
}
}
class Rubber{
constructor() {
this.abilities = new DuckAbilities()
this.abilities.flying = new DoesNotFly()
}
}
window.onload = ()=> {
let mallard = new Mallard()
mallard.abilities.addToPage()
let rubber = new Rubber()
rubber.abilities.addToPage()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T04:11:24.997",
"Id": "464421",
"Score": "2",
"body": "As Javascript, no, this is not \"spiritually\" nor technically an `Interface` implementation. Due to JS's nature proper interface-y code will not look like the examples in `Head First.` Google for JS specific examples - which will be different depending on the version of JS you use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T04:25:29.280",
"Id": "464422",
"Score": "0",
"body": "And [searching StackOverflow can be very helpful](https://stackoverflow.com/q/3710275/463206) as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T04:34:54.217",
"Id": "464423",
"Score": "1",
"body": "Javascript syntax does not map well to the classic OOP pattern class diagrams. I'd stick with the `Head First` book and forget JS for its sake - I like the `Head First` series a lot & have several of their titles, including `Design Patterns`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T05:09:29.593",
"Id": "464506",
"Score": "0",
"body": "Thank you for the additional insight! I'll try to implement code from this book in a language that has interfaces, and I think it will confuse me less because it will be of obvious use."
}
] |
[
{
"body": "<p>There are some issues with your class, but I don't think that they are so specific to implementing a strategy pattern.</p>\n\n<pre><code>addToPage() {\n this.statement = document.createElement(\"p\")\n this.statement.innerHTML=this.flying.fly()\n document.body.append(this.statement)\n}\n</code></pre>\n\n<p>This assumes there is a global document variable, and that <code>statement</code> is part of the abilities object. If such a method is present, I would expect <code>document</code> to be a parameter of the method and <code>statement</code> to be a local variable. But even that doesn't seem right because you would be mixing representation (a paragraph <code>\"p\"</code>) and a data class.</p>\n\n<pre><code>//interface for behaviors\nclass FlyBehavior {\n fly() {\n null\n }\n }\n</code></pre>\n\n<p>Now that doesn't seem right. If you have JS ducktyping then you don't need this class. Furthermore, specifying <code>null</code> is just asking for null pointer exceptions at a later stage.</p>\n\n<pre><code>this.abilities = new DuckAbilities()\n</code></pre>\n\n<p>OK, so now we have <code>DuckAbilities</code> object but without a valid state, just <code>null</code>, which we then adjust in the next call. There seem to be two ways of resolving this issue:</p>\n\n<ol>\n<li>having the fying behavior as parameter to the <code>DuckAbilities</code> constructor;</li>\n<li>removing the <code>DuckAbilities</code> altogether and just assigning the various flybehaviors to a field.</li>\n</ol>\n\n<hr>\n\n<p>So when we're using classes anyway, lets implement it using those.</p>\n\n<p>I've created an \"abstract\" class Duck because we require inheritance there. I don't like to create an interface for the strategies because JavaScripts duck-typing should be sufficient.</p>\n\n<pre><code>'use strict'\n\nclass Duck { // this is the context\n constructor(flyAbility) {\n // ES2015 only, avoid instantiation of Duck directly\n // if (new.target === Abstract) {\n // throw new TypeError(\"Cannot construct Abstract instances directly\");\n // }\n\n this.flyAbility = flyAbility;\n }\n\n // this is the operation, returning the flyBehavior as a string\n showFlyBehavior() {\n return \"This duck \" + this.flyAbility.flyBehavior();\n }\n}\n\n// Strategy interface is missing due to JS ducktyping\n\n// Strategy #1 \nclass DoesFly {\n // with algorithm #1\n flyBehavior() {\n return \"flies\";\n }\n}\n\n// Strategy #2\nclass DoesNotFly {\n // with algorithm #2\n flyBehavior() {\n return \"doesn't fly\";\n }\n}\n\n// Context #1\nclass Mallard extends Duck {\n constructor() {\n super(new DoesFly());\n }\n}\n\n// Context #2\nclass Rubber extends Duck {\n constructor() {\n super(new DoesNotFly());\n }\n}\n\nlet duck = new Mallard();\nconsole.log(duck.showFlyBehavior());\n\nduck = new Rubber();\nconsole.log(duck.showFlyBehavior());\n</code></pre>\n\n<p>Sorry about using NodeJS, but in principle only <code>console.log</code> is NodeJS specific ... I hope.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T22:32:11.933",
"Id": "465174",
"Score": "0",
"body": "Direct answer, I'd still use a different language at least to *study* design patterns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T22:40:48.813",
"Id": "465175",
"Score": "0",
"body": "In Python `FlyBehavior` would be an [ABC](https://docs.python.org/3/library/abc.html), which is known simply as [abstract classes](https://en.wikipedia.org/wiki/Class_(computer_programming)#Abstract_and_concrete) elsewhere. If JavaScript supported this; do you think it would be a good use case here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T22:43:51.870",
"Id": "465176",
"Score": "0",
"body": "No, not really, because `FlyBehavior` doesn't have any generic behavior. Python is as much ducktyped as JavaScript, so it is just not necessary. However, with Python you could at least make `Duck` an abstract base class (ABC) to avoid instantiation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T22:51:29.160",
"Id": "465177",
"Score": "0",
"body": "Ok, that makes a lot of sense to me. I would assume if this were TypeScript - since the duck typing kinda flys out the window, `FlyBehaviour` would become an interface. Thank you. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T22:29:29.993",
"Id": "237263",
"ParentId": "236897",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237263",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T17:45:56.260",
"Id": "236897",
"Score": "3",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "Attempting a Strategy design pattern in JS"
}
|
236897
|
<p>I've been reading Haskell tutorials and books for a while, but I never actually did serious stuff with it. This is my first attempt.</p>
<p>It parses an OBJ-file in text format. Later on I will add some mesh-representation and more geometry stuff.</p>
<p>Could you please review my code and check for "haskeliness" (like, best practices and maybe if something can be done in a simpler way)?
Also I have the feeling, that the <code>ObjFileLine</code> type is redundant. But I can't think of a way to avoid it.</p>
<p>An OBJ-file looks basically like this (see <a href="https://en.wikipedia.org/wiki/Wavefront_.obj_file#File_format" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Wavefront_.obj_file#File_format</a>):</p>
<pre><code># List of geometric vertices, with (x, y, z [,w]) coordinates, w is optional and defaults to 1.0.
v 0.123 0.234 0.345 1.0
v ...
# List of texture coordinates, in (u, [,v ,w]) coordinates, these will vary between 0 and 1. v, w are optional and default to 0.
vt 0.500 1 [0]
vt ...
# List of vertex normals in (x,y,z) form; normals might not be unit vectors.
vn 0.707 0.000 0.707
vn ...
# Parameter space vertices in ( u [,v] [,w] ) form; free form geometry statement ( see below )
vp 0.310000 3.210000 2.100000
vp ...
# Polygonal face element (see below)
f 1 2 3
f 3/1 4/2 5/3
f 6/4/1 3/5/3 7/6/5
f 7//1 8//2 9//3
f ...
# Line element (see below)
l 5 8 1 2 4 9
</code></pre>
<p>I have one file <code>Obj/Obj.hs</code> for the data types, which looks like this:</p>
<pre><code>module Obj.Obj where
import Data.List
-- mesh vertices
data ObjVertex =
Vertex Double Double Double
| Vertex4 Double Double Double Double
deriving Eq
instance Show ObjVertex where
show (Vertex a b c) = "v " ++ show a ++ " " ++ show b ++ " " ++ show c
show (Vertex4 a b c d) = show (Vertex a b c) ++ " " ++ show d
-- uv coordinates for textures
data ObjTexture =
Texture1 Double
| Texture2 Double Double
| Texture3 Double Double Double
deriving Eq
instance Show ObjTexture where
show (Texture1 a) = "vt " ++ show a
show (Texture2 a b) = show (Texture1 a) ++ " " ++ show b
show (Texture3 a b c) = show (Texture2 a b) ++ " " ++ show c
-- face normals
data ObjNormal =
Normal Double Double Double
deriving Eq
instance Show ObjNormal where
show (Normal a b c) = "vn " ++ show a ++ " " ++ show b ++ " " ++ show c
-- parameter space
data ObjParameter =
Parameter1 Double
| Parameter2 Double Double
| Parameter3 Double Double Double
deriving Eq
instance Show ObjParameter where
show (Parameter1 a) = "vp " ++ show a
show (Parameter2 a b) = show (Parameter1 a) ++ " " ++ show b
show (Parameter3 a b c) = show (Parameter2 a b) ++ " " ++ show c
-- face connectivites
data ObjVertexIndex =
VertexIndex Int
| VertexTexture Int Int
| VertexNormal Int Int
| VertexTextureNormal Int Int Int
deriving Eq
instance Show ObjVertexIndex where
show (VertexIndex a) = show a
show (VertexTexture a b) = show a ++ "/" ++ show b
show (VertexNormal a b) = show a ++ "//" ++ show b
show (VertexTextureNormal a b c) = show a ++ "/" ++ show b ++ "/" ++ show c
-- faces
data ObjFace = Face [ObjVertexIndex]
deriving Eq
instance Show ObjFace where
show (Face vertices) = "f " ++ (intercalate " " $ map show vertices)
-- polylines
data ObjPolyLine = Line [Int]
deriving Eq
instance Show ObjPolyLine where
show (Line vertices) = "l " ++ (intercalate " " $ map show vertices)
data ObjFile = File
{ vertices :: [ObjVertex]
, textures :: [ObjTexture]
, normals :: [ObjNormal]
, parameters :: [ObjParameter]
, faces :: [ObjFace]
, polylines :: [ObjPolyLine]
}
instance Show ObjFile where
show file = unlines $ concat [
fmap show (vertices file),
fmap show (textures file),
fmap show (normals file),
fmap show (parameters file),
fmap show (faces file),
fmap show (polylines file)]
data ObjFileLine =
V ObjVertex
| VT ObjTexture
| VN ObjNormal
| VP ObjParameter
| F ObjFace
| L ObjPolyLine
deriving Eq
instance Show ObjFileLine where
show (V v) = show v
show (VT t) = show t
show (VN n) = show n
show (VP p) = show p
show (F f) = show f
show (L l) = show l
</code></pre>
<p>And a <code>Obj/Parse.hs</code> for the parsers which looks like this:</p>
<pre><code>module Obj.Parse ( parseFile ) where
import Control.Applicative ((<|>), liftA)
import Data.Char (isDigit)
import Text.ParserCombinators.ReadP
import Obj.Obj
-- Parser combinators for an OBJ file.
-- Parse numbers.
parseSign :: (Num a) => ReadP a
parseSign = do
sign <- option '+' (char '-')
return $ if sign == '+' then 1 else -1
parseInteger :: ReadP Int
parseInteger = do
sign <- parseSign
s <- many1 $ satisfy isDigit
return $ sign * read s
parseDouble :: ReadP Double
parseDouble = (do
sign <- parseSign
int <- many1 $ satisfy isDigit
char '.'
decimal <- many1 $ satisfy isDigit
let s = int ++ "." ++ decimal
return $ sign * read s
)
parseNumber = fmap fromIntegral parseInteger <|> parseDouble
-- Parse elements of an OBJ file.
vertex :: ReadP ObjVertex
vertex = do
string "v "
numbers <- sepBy parseNumber skipSpaces
case numbers of
[a, b, c] -> return $ Vertex a b c
[a, b, c, d] -> return $ Vertex4 a b c d
_ -> fail ""
texture :: ReadP ObjTexture
texture = do
string "vt "
numbers <- sepBy parseNumber skipSpaces
case numbers of
[a] -> return $ Texture1 a
[a, b] -> return $ Texture2 a b
[a, b, c] -> return $ Texture3 a b c
_ -> fail ""
normal :: ReadP ObjNormal
normal = do
string "vn "
numbers <- sepBy parseNumber skipSpaces
case numbers of
[a, b, c] -> return $ Normal a b c
_ -> fail ""
parameter :: ReadP ObjParameter
parameter = do
string "vp "
numbers <- sepBy parseNumber skipSpaces
case numbers of
[a] -> return $ Parameter1 a
[a, b] -> return $ Parameter2 a b
[a, b, c] -> return $ Parameter3 a b c
_ -> fail ""
vertexIndex :: ReadP ObjVertexIndex
vertexIndex = do
a <- parseInteger
return $ VertexIndex a
<|> do
a <- parseInteger
char '/'
b <- parseInteger
return $ VertexTexture a b
<|> do
a <- parseInteger
string "//"
b <- parseInteger
return $ VertexNormal a b
<|> do
a <- parseInteger
char '/'
b <- parseInteger
char '/'
c <- parseInteger
return $ VertexTextureNormal a b c
face :: ReadP ObjFace
face = do
string "f "
vertices <- sepBy vertexIndex skipSpaces
return $ Face vertices
objPolyline :: ReadP ObjPolyLine
objPolyline = do
string "l "
elements <- sepBy parseInteger skipSpaces
return $ Line elements
-- Parse any line of an OBJ file.
parseLine :: ReadP ObjFileLine
parseLine =
liftA V vertex
<|> liftA VT texture
<|> liftA VN normal
<|> liftA VP parameter
<|> liftA F face
<|> liftA L objPolyline
-- An empty OBJ file.
emptyFile :: ObjFile
emptyFile = File {
vertices = [],
textures = [],
normals = [],
parameters = [],
faces = [],
polylines = []
}
-- Fold a list of lines to an obj file.
fileFromLines :: [ObjFileLine] -> ObjFile
fileFromLines = foldl addLine emptyFile
where
addLine file (V vertex) = file { vertices = vertices file ++ [vertex] }
addLine file (VT texture) = file { textures = textures file ++ [texture] }
addLine file (VN normal) = file { normals = normals file ++ [normal] }
addLine file (VP parameter) = file { parameters = parameters file ++ [parameter] }
addLine file (F face) = file { faces = faces file ++ [face] }
addLine file (L line) = file { polylines = polylines file ++ [line] }
-- Parse an OBJ file.
parseFile :: ReadP ObjFile
parseFile = fileFromLines <$> many (do
line <- parseLine
char '\n'
return line)
</code></pre>
|
[] |
[
{
"body": "<p><code>Read</code> provides compatibility with <code>ReadP</code>.</p>\n\n<pre><code>parseInteger :: ReadP Int\nparseInteger = readS_to_P $ readsPrec 0\n\nparseDouble :: ReadP Double\nparseDouble = readS_to_P $ readsPrec 0\n</code></pre>\n\n<p>Note that usually, <code>Show</code> instances are supposed to produce strings that can be pasted into .hs files to reproduce the value.</p>\n\n<p>Why not have <code>ObjFile = [ObjFileLine]</code>, and <code>ObjFileLine</code> as a single type with 15 constructors?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:59:25.330",
"Id": "236949",
"ParentId": "236900",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236949",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T19:13:29.910",
"Id": "236900",
"Score": "2",
"Tags": [
"parsing",
"haskell"
],
"Title": "Parse Wavefront OBJ using ReadP"
}
|
236900
|
<p>I'm a Haskell beginner, and I wanted to make a color annotator or color highlighter, one which takes a text as standard input, and outputs that text, with its color words highlighted using the colors themselves. So, it should replace all instances of the word "red" in a text with <code><span class="color" style="color: #ff0000">red</span></code>. </p>
<p>I'm using <a href="https://xkcd.com/color/rgb.txt" rel="nofollow noreferrer">the color map from XKCD, here</a>, <a href="https://blog.xkcd.com/2010/05/03/color-survey-results/" rel="nofollow noreferrer">which is also discussed in this blog post.</a></p>
<p>The packages I'm using are <code>lucid replace-attoparsec cabal-install optparse-generic text</code>, so I think you can run this file with something like <code>stack runhaskell ThisFile.hs --package attoparsec replace-attoparsec text optparse-generic</code>.</p>
<p>The main problem I'm aware of is that the output of the parser is the parsed string, not the string used to generate the parser. So that means I have to look up the color again, which means it's really slow, and it doesn't find all of them. I don't really know of the best way to fix that.</p>
<p>Edit: a few gotchas that make this problem hard for me: </p>
<ul>
<li>I can rewrite this to run lots of little parsers over the whole text, but the problem there is with re-parsing the same text. For instance, I don't want to end up with nested replacements, like <code><span ...>light blue <span ...>green</span></span></code>. </li>
<li>Running one big parser, with <code>choice</code>, seems to fix the issue of overlapping parses, but then I don't seem to have access to the expression that generated the parser, and its associated hex code. </li>
</ul>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
module AnnotateColor where
import Data.List (intersperse, sort, sortBy)
import Lucid
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.IO as TIO
import Data.Function (on)
import Replace.Attoparsec.Text
import Data.Attoparsec.Text as AT
import qualified Data.Text as T
import Data.Either
import Data.Char
import qualified Data.Map.Strict as M
import Control.Applicative ((<|>), empty)
import Options.Generic
-- | Just some useful aliases here
type ColorWord = T.Text
type Hex = T.Text
wordBoundary :: Parser Char
wordBoundary = satisfy (inClass " \n\r\"\'")
-- | Takes a list of words like "light green blue" and makes a
-- parser which will find "light green blue" and also "light green-blue",
-- "light green\nblue" and so on.
wordListParser :: [T.Text] -> Parser T.Text
wordListParser [w] = do -- One word case
boundaryBefore <- wordBoundary
word <- asciiCI w
boundaryAfter <- wordBoundary
return word
wordListParser (w:ws) = do -- Multi-word case
satisfy (inClass " \n\r\"\'") -- Word boundary first
a <- asciiCI w -- word, case insensitive
b <- satisfy (inClass " -\n\r") -- a separator
c <- wordListParser ws -- more words
return (a `T.append` (T.singleton b) `T.append` c) -- singleton :: Char -> Text
-- | Make one big parser out of our color map, and the expressions
-- generated from wordListParser.
colorParser :: [(ColorWord, Hex)] -> Parser T.Text
colorParser colormap = choice $ map (wordListParser . T.words . fst) $ colormap
-- | Makes HTML from a color word and hex pair.
-- I.e. "red" -> "<span class="color" style="color: #ff0000">"
makeSpan :: T.Text -> T.Text -> TL.Text
makeSpan colorWord hex = TL.concat [" ", t, " "] where
t = renderText $ span_ attrs (toHtml colorWord)
attrs = [ class_ "color", style_ (T.concat ["color: ", hex])::Attribute ]
-- | Maps a function across both items in a tuple
mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)
-- | Processes the plain text (TSV) color map from XKCD,
-- and converts it to the list of tuples we'll be using for
-- a color map.
xkcdMap :: T.Text -> [(T.Text, T.Text)]
xkcdMap rawMap = reverse $ sortBy (compare `on` T.length . fst) unsorted
where
textLines = tail $ T.lines rawMap
unsorted = [ mapTuple T.strip ( T.breakOn "\t" ln ) | ln <- textLines ]
-- | The parser returns what it parsed, which may or may not contain
-- hyphens. But we want the non-hyphenated version so that we can
-- look up its hex in the color map. It sucks that we have to
-- look up the hex code again, but I can't think of a better way.
-- So this cleans up the color expression as found by the parser,
-- so that it can be used by the lookup.
punctToSpace :: T.Text -> T.Text
punctToSpace str = T.map p2s str where
p2s = (\c -> if T.isInfixOf (T.singleton c) "-\n\r" then ' ' else c)
-- | Using a map-ified version of our color map, this looks
-- up each word found by the parser, and if found, turns it
-- into HTML, highlighting it using its color.
annotate :: M.Map ColorWord Hex -> T.Text -> T.Text
annotate cmm color = case cmm M.!? ((punctToSpace . T.strip) color) of
Nothing -> (T.concat ["CANTFIND", color])
Just hex -> TL.toStrict $ makeSpan (T.strip color) hex
main :: IO ()
main = do
-- Load color map. (Data from https://xkcd.com/color/rgb.txt )
rawText <- TIO.readFile "../data/xkcd/rgb.txt"
-- Process color map
let cm = xkcdMap rawText
-- Make Data.Map map out of it
let cmm = M.fromList cm
-- Parse command-line argument, and read the filename given
-- by the first argument.
fileName <- getRecord "Color word annotator."
inFile <- TIO.readFile fileName
-- Run the parser, annotate it, print the results.
TIO.putStr $ streamEdit (colorParser cm) (annotate cmm) inFile
</code></pre>
|
[] |
[
{
"body": "<p>I'm also beginner, so not sure if can make a good review, but just want to notice. If you just need to replace a bunch of string (the list of colors), maybe it's better to use Aho-Corasick algorithm to find all matches and then just use fold through all matches. I did it for similar task.<br>\n<a href=\"https://en.m.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm\" rel=\"nofollow noreferrer\">https://en.m.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm</a><br>\nI used this implementation:<br>\n<a href=\"https://hackage.haskell.org/package/AhoCorasick-0.0.3/docs/Text-AhoCorasick.html\" rel=\"nofollow noreferrer\">https://hackage.haskell.org/package/AhoCorasick-0.0.3/docs/Text-AhoCorasick.html</a><br>\nAs I remember, I had some issues and made changes in this library to make it working with the current GHC version, but these were very simple changes.<br>\nBut it will be very interesting for me to read answers.</p>\n\n<p>P.S. I remembered what was the problem and how I \"solve\" it. I just used this commit from this fork:<br>\n<a href=\"https://github.com/stackbuilders/AhoCorasick/commit/9a825aef5d19c707d2306befca688a1a72d50bb0\" rel=\"nofollow noreferrer\">https://github.com/stackbuilders/AhoCorasick/commit/9a825aef5d19c707d2306befca688a1a72d50bb0</a><br>\nSomeone already fixed the issue. So just add in stack.yaml </p>\n\n<pre><code>extra-deps:\n - github: stackbuilders/AhoCorasick\n commit: 9a825aef5d19c707d2306befca688a1a72d50bb0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T01:22:40.213",
"Id": "464500",
"Score": "1",
"body": "That's a cool looking algorithm, but is there a way to get it to work for non-overlapping matches?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T01:43:47.970",
"Id": "464501",
"Score": "0",
"body": "You can always decide what to do. You have position and length. So just skip all next matches before match position become more then old match position + old match length. Surely it's more difficult in case you have strings to search like `a b` and `b c` and text like `a b c`. But for such case you have the same problem for any algorithm. For any other cases it's easy to define what to do. And yes, from Aho-Corasick algorithm you have matches \"sorted\" by position. So if you don't have partially overlapped search terms, longest match will be always first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T02:44:29.143",
"Id": "464502",
"Score": "0",
"body": "Sorry, I have error, matches are sorted by position, but if you have `dark` and `dark green` you can have match with `dark` first. So, you need to do something about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T04:25:15.763",
"Id": "464504",
"Score": "0",
"body": "@Jonathan, sorry, looks like my case wasn't the same as your. I had finished HTML parts that I was need to replace with other. With open and close tag and so on. But in your case you can have word `blues` and so on. I tried to implement what you need with Aho-Corasick and not sure if it's faster then your approach with parser. It's possible to optimize it, but it will be to difficult to read then. Here is what I tried: \nhttps://gist.github.com/DKurilo/611d736cfb76947a5684a8c8470967b9\nYou would also need to add all possible colors like dark-blue. Parser is better here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:46:40.167",
"Id": "464657",
"Score": "0",
"body": "Nice. I really want to try that out, but I don't use stack, and I'm having trouble making a shell.nix file for it. Or any file that gets it to compile, actually. Here's the latest thing I tried: https://stackoverflow.com/questions/60161518/how-can-i-add-a-haskell-package-from-github-to-my-shell-nix-file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:08:02.410",
"Id": "464754",
"Score": "0",
"body": "@Jonathan, try to use shell.nix like this one: https://gist.github.com/DKurilo/611d736cfb76947a5684a8c8470967b9#file-shell-nix There is wrong commit in the example you added."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T00:07:40.040",
"Id": "236955",
"ParentId": "236901",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T19:44:06.283",
"Id": "236901",
"Score": "1",
"Tags": [
"performance",
"parsing",
"haskell"
],
"Title": "Color highlighter / annotator in Haskell"
}
|
236901
|
<p>I got asked this question in an interview and I came up with a solution which I shared in the below but apparently it was not enough to pass. I'm looking forward to hearing how this problem could be solved.</p>
<p>The question is : You are given an array of numbers e.g arr= [1, 3, 2, 0, 1, 2, 8, 4, 1] that represents a board and a position that represents an index in the array, and your goal is to find whether you can reach to 0 in the array or not. If you can find the zero, you win the game. If you can't, you lose.</p>
<p>So you can only move to the right or to the left in the array. The rule for moving your index is as the value of the index in that array. </p>
<p>Example: arr[1,3,2,0,1,2,8,4,1] and you are given a position 0. </p>
<p>Position 0 is 1. So you can only move 1 to the left or 1 to the right. You can't move to the left because the index is out of bounds, but you can move to right. Then, you are at second index whose value is 3, then you can again move three to the left and right, (assuming you move right 3 times, you are at the 5th index whose value is 1. Then, you can move 1 to the left to get 0. Thus, you can win from a given position. I hope it's clear enough.</p>
<p>This is my solution that I've used dfs. It works for the above case but it does not work when there is 1,1 next to each other. Then, it loops to the infinity. I'm looking forward to hearing other solutions in terms of how to solve it or how to optimize this solution. I feel like graph algorithms could be used for this problem but I was not sure how to start or initiate a matrix to represent a graph from this list. Thank you so much</p>
<pre><code> def findWinner(arr, pos):
def dfs(arr, pos):
if pos < 0 or pos >= len(arr):
return False
num = arr[pos]
if arr[pos] == 0:
return True
return dfs(arr, pos+num) or dfs(arr, pos-num)
num = arr[pos]
if arr[pos] == 0:
return True
return dfs(arr, pos+num) or dfs(arr, pos-num)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:09:07.453",
"Id": "464377",
"Score": "1",
"body": "Why nest functions like that?"
}
] |
[
{
"body": "<p>Unfortunately for your interview hopes, the code you wrote doesn't solve the problem. Try this input:</p>\n\n<pre><code>findWinner([2,0,2], 0)\n</code></pre>\n\n<p>The way I would solve this problem is indeed to use a \"graph algorithm\" — something like flood-fill. Start with an array of bools, of the same size as your input array. Color the starting cell <code>True</code>. Then look at the neighbors of that cell. For each neighbor which is currently <code>False</code>, color it <code>True</code> and recurse on it. Eventually you'll run out of <code>False</code> neighbors and the recursion will end. Then check (or during the coloring, check) to see if any of the <code>True</code> (reachable) cells in your array have value <code>0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T21:54:57.543",
"Id": "464375",
"Score": "0",
"body": "Yup, I already said it does not work :). Thanks for the answer though. Would it be possible to share a source code to understand it better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T23:01:12.717",
"Id": "464392",
"Score": "0",
"body": "I added an answer based on your suggestion, it seems like it's working. can you check if I can make any optimization on it? I feel like the way I use recursion function definitely could be improved @Quuxplusone"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T21:36:25.520",
"Id": "236907",
"ParentId": "236906",
"Score": "1"
}
},
{
"body": "<p>Here is the answer based on @Quuxplusone's suggestion- thanks. Also, I don't understand why my question got downvoted without any comments, I'd appreciate if you add some comments why you did not like the question or what can be improved if you want to make a better community for all. So, I could improve my way of asking questions and wouldn't ask in the same style again. Thanks!</p>\n\n<pre><code>def findWinner(arr, pos):\n\n visited = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n num = arr[pos]\n visited[pos] = 1\n if arr[pos] == 0:\n return True\n return dfs(arr, pos+num, visited) or dfs(arr, pos-num, visited)\n\n\ndef dfs(arr, pos, visited):\n if pos < 0 or pos >= len(arr):\n return False\n\n if visited[pos] == 1:\n return False\n visited[pos] = 1\n\n num = arr[pos]\n if arr[pos] == 0:\n return True\n return dfs(arr, pos+num, visited) or dfs(arr, pos-num, visited)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:28:16.663",
"Id": "464411",
"Score": "1",
"body": "The downvotes were probably because you said it's non-working code; one of the codereview rules is that the code has to already be in a working state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:32:11.643",
"Id": "464412",
"Score": "0",
"body": "I mean the code is working but it just doesn't work for some of the test cases and it just needed a little bit of a fix as it can be seen above. I just wanted to put my own solution as well, so people wouldn't think I am looking for an answer even without trying it, but apparently it backfired. I'll never understand the negativity here. Thanks for your comment anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:40:14.657",
"Id": "464414",
"Score": "0",
"body": "Some people on this site are VERY particular. I don't understand that mindset myself, but just be aware that if you even hint that you're looking to fix rather than polish a piece of code, it's gonna get a lot of automatic downvotes before anyone's even read your post. :P"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T23:02:59.147",
"Id": "236910",
"ParentId": "236906",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T21:22:50.997",
"Id": "236906",
"Score": "-1",
"Tags": [
"python",
"algorithm",
"graph",
"depth-first-search"
],
"Title": "algorithm to find a zero in a board game"
}
|
236906
|
<p><strong>Problem</strong></p>
<p>Balanced number is the number that the sum of all digits to the left of the middle digit(s) and the sum of all digits to the right of the middle digit(s) are equal. The middle digit(s) should not be considered when determining whether a number is balanced or not.</p>
<p>If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0.</p>
<p>Given a number, find if it is balanced or not. Number passed is always Positive. Return the result as String.</p>
<p><strong>My solution</strong></p>
<p>I solved it. But I am not sure, how to fold the similarly looking code for odd and even lengths.</p>
<pre><code>data ListLength a = ListLength {list :: [a], len :: Int} deriving Show
digs :: Integral x => x -> ListLength x
digs 0 = ListLength [0] 1
digs x = let
helper :: Integral x => x -> [x] -> Int -> ListLength x
helper 0 acc len = ListLength acc len
helper n acc len = helper (n `div` 10) ((n `mod` 10) : acc) $ len + 1
in
helper x [] 0
balancedNum :: Int -> String
balancedNum n | n > 0 = let digits = digs n
middle = (len digits) `div` 2
in
if even (len digits) then
let (left, right) = splitAt (middle - 1) (list digits) in
if (sum left) == (sum $ drop 2 right) then
"Balanced"
else
"Not Balanced"
else
let (left, right) = splitAt middle (list digits) in
if (sum left) == (sum $ tail right) then
"Balanced"
else
"Not Balanced"
| otherwise = error "Number must be positive"
</code></pre>
|
[] |
[
{
"body": "<p>Here my thoughts on your solution. But I'm also learning Haskell right now, so I'm not an expert..</p>\n\n<p>You don't need the data type. You can use base 10 logarithm to get the number of digits. Like this:</p>\n\n<pre><code>(floor $ logBase 10 $ fromIntegral n) + 1\n</code></pre>\n\n<p>I like the fact that <code>digs</code> is tail recursive. It looks simpler without the data type:</p>\n\n<pre><code>digits :: Int -> [Int]\ndigits = digits_tr []\n where\n digits_tr :: [Int] -> Int -> [Int]\n digits_tr l 0 = l\n digits_tr l n = digits_tr (n `mod` 10 : l) (n `div` 10)\n</code></pre>\n\n<p>Why does <code>balancedNum</code> give a string? A boolean would be more natural.\nIf you want to handle errors, why not use <code>Maybe</code> instead of <code>error</code>? Like in <code>balancedNum :: Int -> Maybe Bool</code>. Anyway according to the problem description you wouldn't need it: a negative number is just not balanced, so the function should just give <code>False</code> back.</p>\n\n<p>Here is my solution:</p>\n\n<pre><code>balanced :: Int -> Bool\nbalanced n\n | n >= 0 = (sum $ take middle $ digits n) == (sum $ take middle $ reverse $ digits n)\n | otherwise = False\n where\n len = (floor $ logBase 10 $ fromIntegral n) + 1\n middle = if len `mod` 2 == 0 then len `div` 2 - 1 else len `div` 2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:45:50.623",
"Id": "464612",
"Score": "0",
"body": "\"You can use base 10 logarithm to get the number of digits.\" - this is a good option. On the other hand we can skip the logarithm calculation, using some memory for storage. We are traversing the list anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:49:46.957",
"Id": "464613",
"Score": "0",
"body": "\"Why does balancedNum give a string? A boolean would be more natural.\" - I agree, but this was the exercise condition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:12:26.483",
"Id": "464616",
"Score": "1",
"body": "Oh, there is an error in this solution: `balanced 56239814` returns False, while it it should return True."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:50:59.770",
"Id": "464803",
"Score": "0",
"body": "You're right: `round` after the logarithm was wrong (and didn't make sense). Now it should work."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:11:42.937",
"Id": "236911",
"ParentId": "236908",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236911",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:03:04.833",
"Id": "236908",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Balanced number checking"
}
|
236908
|
<p><strong>Problem Statement</strong></p>
<ol>
<li>An airline wants to allocate seats in their aircrafts such that each group of four passengers travelling together are to be seated next to each other in clusters of 4. A contiguous cluster can have an isle running through it - for example, you can sit one passenger on one side of the isle, and three on the other side, as long as there are no passengers from other parties in that cluster. Clusters must be on the same row.</li>
<li>There are 10 seats in each row, arranged in a 2 - 6 - 2 pattern (i.e. 2 seats, then an isle, then 6 seats, then an isle, then two seats). Rows range from 1 .. 40 and seats from A - K, skipping I</li>
<li>You are given an integer number of rows (N) and a space-delimited string (S) representing occupied seats. For example, "1A 2A 3B 5C 40F" would indicate occupied seats in rows 1 - 40. Similarly, "1A 2A 3B 5C" would indicated occupied seats in rows 1 - 5.</li>
<li>You are required to write a function <code>seat(N,S)</code>, representing the number of rows and occupied seats respectively, and have to return the maximum number of 4-passenger contiguous clusters.</li>
</ol>
<p><strong>Solution Approach</strong></p>
<ol>
<li>Check for the trivial case of S = '' and N = 1 and return 2</li>
<li>Parse the occupied seats string into a list of strings using S.split(' ') to get individual seat allocation</li>
<li>Map the letters A - K into numbers 0 - 9</li>
<li>Create a 2D matrix map of seats</li>
<li>Parse the matrix row by row, looking for a patterns of 4 seats and return their count</li>
</ol>
<p><strong>Code</strong></p>
<p>Fully documented code as follows:</p>
<pre><code>import re
def printMatrix (M):
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in M]))
def sliceMatrix (M, C):
counter = 0;
clusters = 0;
# the approach here is to keep a count of where we checked last in the variable counter
# if we fail, we increment the counter by 1 and slice the next cluster of 4
# if we succeed in finding a cluster of 4 available seats, then we increment the number of
# clusters by 1 and the counter by 4.
# we then return the total number of clusters found in a row
for i in range (counter, len(M)):
# loop over array taking a slice of 4 spaces from where the current counter is
fourSlice = M[counter:counter+4];
print(fourSlice)
# check for the number of 0s in that slice
numZeros = fourSlice.count(0);
print("numZeros: ", numZeros);
# success: there are 4 zeros, then this is a cluster
if (numZeros == 4):
print("Found cluster. Clusters now: ", clusters + 1)
# increment the number of clusters found by 1
clusters += 1;
# move the counter 4 spaces
counter += 4;
# skip the rest of the loop iteration
continue;
# failure: increment the counter by 1 and loop
else:
counter += 1;
print ("i: ", i, " counter: ", counter)
print("total clusters found in this row: ", clusters)
# return the total number of clusters found in this row
return (clusters);
def solution(N, S):
# a dictionary to map column labels to numbers.
# this is necessary to obtain numerical values for the 2D matrix seat map. Is there a better way?
columnDict = {'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3, 'E' : 4, 'F' : 5, 'G' : 6, 'H' : 7, 'J' : 8, 'K' : 9}
# check the trivial case whereby only one empty row exists and return 2
if (N == 1 and S==''):
return 2;
# construct an empty 2D matrix map of the aircraft seating of the format N x 10
seatMap = [[0 for n in range(10)] for y in range(N)];
# convert the occupied string list into a list of individual seat strings
S = S.split(' ');
# iterate over the array, and populate 2D map
for seat in S:
# search for one or more digits, followed by a single letter, placing each in a group
# digits are row numbers, letters are seat labels
m = re.search ("(\s*[\d]+)([abcdefghjkABCDEFGHJK]\s*)", seat)
if m:
# grab the first group from the match object, representing row number
occupiedRow = m.group(1);
# grab the second group from the match object, representing column label
occupiedColumn = m.group(2);
# convert the row number into a matrix index by decrementing it by 1. this is to account for
# machine representation of indexes, which start at 0
MR = int(occupiedRow) - 1;
# map the seat label to a number so that it can also be used as a matrix index.
# this is done as a dictionary lookup from the columnDict hash defined earlier
MC = columnDict[occupiedColumn];
# now we have a [row][column] matrix number, populate that entry as occupied
seatMap[MR][MC] = seat;
# just be helpful, and print the seat map
printMatrix(seatMap);
# next, iterate over seat map row by row, and extract each row to a 1d array
# but first, we initialise a total cluster counter, to keep cumulative track
# of how many clusters we get from the seat map matrix
totalClusters = 0;
for i in range(N):
# slice a row from the seat map into a 1d array
rowSlice = seatMap[i][0:9]
# pass that slice to the sliceMatrix function to get the number of clusters in that row
numClusters = sliceMatrix(rowSlice, 4)
# keep cumulative track of clusters we get
totalClusters += numClusters;
# return the total number of clusters found
return (totalClusters)
# this is a sample occupancy string of an aircraft with 7 rows (N = 7)
S = "1A 1B 1F 2A 2B 2C 2D 3A 3C 3D 4A 4B 4E 5A";
N = 7;
Clusters = solution(N, S);
print ("Total Clusters: ", Clusters);
</code></pre>
<p><strong>Thoughts</strong></p>
<p>Could this be done any more efficiently or better/faster/...etc? Could the splitting of string S be done without regex, remembering that row numbers can be single or double digits?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:53:25.413",
"Id": "464415",
"Score": "1",
"body": "Welcome to Code Review. Please read https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T02:11:11.033",
"Id": "464418",
"Score": "4",
"body": "In the title, you should state what your code does. This is clearly stated in [ask]. You should [edit] the question to give it an appropriate title. This will help in getting reviewers to look at your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T08:00:30.257",
"Id": "464427",
"Score": "0",
"body": "Why can't I find a *function `seat(N,S)`*? Please edit into your problem statement: How is *maximum number of 4-passenger contiguous clusters* to be interpreted, especially *maximum*? If it is about allocated seats (if it was about free seats, it would read *4-seat clusters*, wouldn't it?), how do \"5-seat clusters not part of a 6-seat cluster\" count: two (overlapping) 4-seat clusters, one, or none?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T08:07:34.400",
"Id": "464428",
"Score": "0",
"body": "Please properly attribute quoted contents if at all possible - you tagged this [tag:programming-challenge]. The conventional MarkDown is a block quote (`> ` line prefix/`\"` in the *post editor* tool-bar)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T12:30:49.753",
"Id": "464442",
"Score": "0",
"body": "OK,thanks for your stylistic comments everyone, appreciated. Grateful if someone can actually look at the code and give tech feedback?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:18:34.577",
"Id": "464610",
"Score": "0",
"body": "`[\"thanks\", everyone]` have a look at some reviews with a score of at least two of code presented in questions with score at least one. Take a guess how much time you'd need to invest to present a review equally useful."
}
] |
[
{
"body": "<p>Two comments on your comments:</p>\n\n<ol>\n<li><p>Have the comment be at the same indentation level as the block that you're commenting. Having all the comments start at column 0 forces the eye to rapidly scan from left to right, and it makes it impossible to discern the overall structure of the program at a glance from the left-hand margin of the code. (It looks like not all the code has this problem, but enough of it does to be very distracting.)</p></li>\n<li><p>Comments should describe and rephrase the purpose of a block (a logical chunk) of code, not describe what each individual line of code does. For example, this:</p>\n\n<pre><code># pass that slice to the sliceMatrix function to get the number of clusters in that row\nnumClusters = sliceMatrix(rowSlice, 4)\n</code></pre></li>\n</ol>\n\n<p>is not a useful comment, because I can already see that you're calling the <code>sliceMatrix</code> function, I can see that you're passing <code>rowSlice</code> to it, and I can see that you're calling the result <code>numClusters</code>.</p>\n\n<hr>\n\n<p>On the matter of how to parse a seat string, this is simple enough that you don't really need a regex or even the manually specified letter:number mapping. The fact that the column is always expressed as a single letter makes it easy to do by slicing:</p>\n\n<pre><code># Seats are specified as a row number followed by a column letter, e.g. \"22D\".\n# Our seat map is zero-indexed so row 1, column A corresponds to 0, 0.\nrow = int(seat[:-1]) - 1 # raises ValueError if the row isn't a number\ncol = ord(seat[-1:].upper()) - ord('A')\nseat_map[row][col] = seat # raises IndexError if seat is out of bounds\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T12:32:02.350",
"Id": "464443",
"Score": "0",
"body": "OK,thanks for your stylistic comments, appreciated. Now the crucks of the question: is there anything which could be improved? how about feedback on writing the same answer without resorting to regular expression matching?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:23:45.513",
"Id": "464485",
"Score": "3",
"body": "The easier your code is to read, the more substantive feedback you'll get on code review; I focused on the commenting style first because it was distracting to the point that I was hindered from reading the code to be able to suggest improvements. :) I'll do a quick edit to add a non-regexy way to parse seats though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:15:57.883",
"Id": "464558",
"Score": "0",
"body": "Using `ord(seat[-1].upper()) - ord('A')`, how do you suggest to handle *no column capital i*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:22:56.407",
"Id": "464573",
"Score": "0",
"body": "I didn't even notice the omission of I. Assuming that wasn't a typo, I'd just do `if col >= 8: col -= 1 # column I(8) doesn't exist` to handle the \"skipped\" column."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:37:59.217",
"Id": "236914",
"ParentId": "236913",
"Score": "3"
}
},
{
"body": "<h1><code>;</code></h1>\n\n<p>why all the <code>;</code>. Python is not JS. They don't do any harm to the program, but they are unnecessary and hamper the readability</p>\n\n<h1>1 letter variable names</h1>\n\n<p>I try to avoid those as much as possible, unless they are the standard jargon in for example mathematical formula's, <code>i</code> as counter or <code>x</code> and <code>y</code> as coordinate</p>\n\n<h1>Comments</h1>\n\n<p>As already noted in the other answers. Comments should explain why you did something. What you do should be clear from the code, variable names, .... They should explain the edge cases, limitations, why you do the -1 to get to 0-based indexing.</p>\n\n<p>Part of this can be helped by splitting the code into smaller functions with their doctstring</p>\n\n<h1>reassigning variable names</h1>\n\n<p>Like you do in <code>S = S.split(' ');</code> is a practice that leads to simple errors. Better to give the parsed product another name</p>\n\n<h1>split the work in functions</h1>\n\n<p>Your <code>Solution</code> method does a lot of work. It \n- translates the input string\n- assembles the plane\n- iterates over the rows\n- asks <code>sliceMatrix</code> the number of free clusters\n- sums the number for all rows</p>\n\n<p>Better would be to split this into more functions</p>\n\n<h1>translating the input string</h1>\n\n<p>A simple method that translates the coordinates to row and column indices can be as simple as:</p>\n\n<pre><code>def translate_seats(input_string):\n \"\"\"\n Translates the input string to 0-indexed seat, row, column tuples\n\n skips the row \"I\". \n case insensitive\n\n example: \n \"1A 1B 1F 2A 2B 2C 2D 3A 3C 3D 4A 4B 4E 5A 6K\"\n --> [\n (\"1A\", 0, 0),\n (\"1B\", 0, 1),\n (\"1F\", 0, 5),\n (\"2A\", 1, 0),\n (\"2B\", 1, 1),\n (\"2C\", 1, 2),\n (\"2D\", 1, 3),\n (\"3A\", 2, 0),\n (\"3C\", 2, 2),\n (\"3D\", 2, 3),\n (\"4A\", 3, 0),\n (\"4B\", 3, 1),\n (\"4E\", 3, 4),\n (\"5A\", 4, 0),\n ('6K', 5, 9),\n ]\n \"\"\"\n if not input_string:\n return\n COLUMNS = {\n \"a\": 0,\n \"b\": 1,\n \"c\": 2,\n \"d\": 3,\n \"e\": 4,\n \"f\": 5,\n \"g\": 6,\n \"h\": 7,\n \"j\": 8,\n \"k\": 9,\n }\n for seat in input_string.split(\" \"):\n row = int(seat[:-1]) - 1\n column = COLUMNS[seat[-1].lower()]\n yield seat, row, column\n</code></pre>\n\n<p>The docstring immediately makes clear what this method does, and it being separate enables easy testing</p>\n\n<h1>'Building' the plane</h1>\n\n<p>Instead of 0 as placeholder for an empty seat, I've use <code>None</code>, since I think this better describes the chair being empty</p>\n\n<pre><code>def assemble_plane(rows, seats, columns=10):\n \"\"\"\n < docstring >\n \"\"\"\n plane = [\n [None] * columns\n for _ in range(rows)\n ]\n for seat, row, column in translate_seats(seats):\n plane[row][column] = seat\n return plane\n</code></pre>\n\n<blockquote>\n<pre><code>rows = 7\nseats = \"1A 1B 1F 2A 2B 2C 2D 3A 3C 3D 4A 4B 4E 5A\"\nassemble_plane(rows, seats, columns=10)\n</code></pre>\n</blockquote>\n\n<pre><code>[['1A', '1B', None, None, None, '1F', None, None, None, None],\n ['2A', '2B', '2C', '2D', None, None, None, None, None, None],\n ['3A', None, '3C', '3D', None, None, None, None, None, None],\n ['4A', '4B', None, None, '4E', None, None, None, None, None],\n ['5A', None, None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None, None, None],\n [None, None, None, None, None, None, None, None, None, None]]\n</code></pre>\n\n<p>I've added <code>columns</code> as an optional argument, should you ever wish wider or narrower planes.</p>\n\n<p>In the inner loop, <code>[None] * columns</code> works since a new list is generated for each row, but the outer loop needs the <code>for _ in range(rows)</code> instead of <code>* rows</code></p>\n\n<h1><code>sliceMatrix</code></h1>\n\n<p>Has a number of things wrong. <code>C</code> and <code>i</code> are not used. It prints and calculates. If you want to see what happens, you either use a debugger, or use the logging module.</p>\n\n<p>Instead of counting the number of <code>0</code>s, you can also use the <code>any()</code> builtin if you used a <code>False</code>y placeholder for empty seats to test whether any of the seats is occupied.</p>\n\n<p>Instead of the <code>for</code>-loop, I would make this an explicit <code>while</code>-loop with your own indexer (<code>location</code>)</p>\n\n<p>I changed the magic number 4 you had in your method to an optional argument.</p>\n\n<pre><code>import logging\ndef clusters_in_row(row, cluster_length=4):\n \"\"\"\n < docstring >\n \"\"\"\n counter = 0\n location = 0\n\n while location < len(row) - cluster_length + 1:\n # no need to check the last 3 seats for a cluster of 4\n my_slice = row[location : location + cluster_length]\n if any(my_slice): # an occupied seat, move on\n location += 1\n continue\n counter += 1\n logging.debug(f\"empty cluster found starting on {location}\")\n location += cluster_length\n return counter\n</code></pre>\n\n<p>Yet again, this is a small function whose function is clear, and can be independently tested</p>\n\n<h1>putting it together</h1>\n\n<pre><code>def solution(rows: int, seats: str):\n columns = 10 # plane is 10 seats wide\n cluster_length = 4\n plane = assemble_plane(rows, seats, columns=columns)\n total = 0\n\n for i, row in enumerate(plane, 1):\n empty_clusters = clusters_in_row(row, cluster_length=cluster_length)\n logging.debug(f\"row {i} has {empty_clusters} empty clusters\")\n total += empty_clusters\n return total\n</code></pre>\n\n<p>If you don't need the extra debug logging, you can even use the builtin <code>sum</code></p>\n\n<pre><code>def solution(rows: int, seats: str):\n columns = 10 # plane is 10 seats wide\n cluster_length = 4\n plane = assemble_plane(rows, seats, columns=columns)\n total = 0\n\n return sum(\n clusters_in_row(row, cluster_length=cluster_length) for row in plane\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:12:10.560",
"Id": "464789",
"Score": "0",
"body": "Many thanks for everyone's valuable feedback.\nI come from a C/C++/Assembly background, writing real-time code for safety-critical applications; hence the comment describing what each line does: you'd get slaughtered by the reviewers in these domains if your code is documented this way, however mundane the comments are.\nStill; this is really useful feedback for me to take on my journey towards acquiring Python as a dev tool."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T14:33:08.137",
"Id": "236996",
"ParentId": "236913",
"Score": "1"
}
},
{
"body": "<p>While this is <em>Code Review</em>@SE:</p>\n\n<p>Do not start coding while not confident the task is well defined.</p>\n\n<p>A good way to check is <em>test first</em>:<br>\nIf you don't know how to test it, you don't know what to achieve.<br>\n(Your program (sort of) outputs</p>\n\n<blockquote>\n<pre><code>1A 1B 0 0 0 1F 0 0 0 0 \n2A 2B 2C 2D 0 0 0 0 0 0 \n3A 0 3C 3D 0 0 0 0 0 0 \n4A 4B 0 0 4E 0 0 0 0 0 \n5A 0 0 0 0 0 0 0 0 0 \n 0 0 0 0 0 0 0 0 0 0 \n 0 0 0 0 0 0 0 0 0 0 \n</code></pre>\n</blockquote>\n\n<p>- how many clusters of 4 do you see? Your program: <code>Total Clusters: 9</code>) </p>\n\n<p>Almost as helpful is to <em>somehow</em> record the approach envisioned (viability of updates and version handling as welcome as with code) -<br>\n<strong>well done</strong>, presenting it before going into detail.<br>\nI would have loved it if it was <em>in the code</em>.</p>\n\n<p>Two things irritating about the problem statement:<br>\n • no indication what is <em>maximum</em> about the <em>maximum number of clusters</em> to return<br>\n • mention of <em>isles</em>, which seem to be dispensable</p>\n\n<hr>\n\n<p>There are conventions, lowering the threshold to grasp someone else's work.<br>\nMany Python conventions a formalised as <a href=\"https://www.python.org/dev/peps\" rel=\"nofollow noreferrer\">Python Enhancement Proposals</a>. I put first:</p>\n\n<ol>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python Code</a><br>\nthere is no <em>just about style</em>: it's <em>about</em> <strong>readability</strong></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">PEP 257 -- Docstring Conventions</a><br>\n\"If you violate these conventions, the worst you'll get is some dirty looks.\"<br>\nAnd <em>not the best software for the given effort</em>.\nI wish I found <code>Fully documented code</code>.</li>\n</ol>\n\n<p>Going through the code top to bottom, <em>not</em> commenting deviations from PEP 8 (<em>Everyone</em> is using tool help) and referring to <a href=\"https://codereview.stackexchange.com/a/236914/93149\">Sam Stafford's answer</a> regarding useful code comments: </p>\n\n<ul>\n<li><code>printMatrix(M)</code><br>\n• flawless use of comprehensions.<br>\n• Lacks a docstring -<br>\n <code>Print the matrix using no less than four characters per item.</code>?<br>\n• Unified alignment: <code>'{:<4}'.format(item)</code></li>\n<li><code>sliceMatrix(M, C)</code><br>\n• Not named for what it returns/computes/modifies.<br>\n• Lacks a docstring -<br>\n <code>Return the count of contiguous clusters of size C in M.</code>?<br>\n• Features not only the magic literal <code>4</code>:<br>\n what could(/should?) be (is?!) a parameter leaks into the name of a variable.<br>\n• Contains \"tracing-<code>print()</code>s\" not easy to disable.<br>\n• <code>i</code> used exclusively for trace printing<br>\n• (Misses the opportunity to advance four seats when <code>num_zeros</code> is 0<br>\n <strong><em>“Premature optimisation is the root of all evil</strong> (or at least most of it) <strong>in programming.”</em></strong> - D.E. Knuth)<br>\n• Keeps going when <code>n_columns < counter + cluster_size</code></li>\n<li><code>solution(N, S)</code><br>\n• Lacks a docstring -<br>\n <code>Return the maximum number of 4-passenger contiguous clusters.</code>?<br>\n• Is on the long side - consider factoring out <em>taking reservations into account</em> and <em>counting clusters</em><br>\n• An alternative to <code>columnDict[occupiedColumn]</code> is <code>\"ABCDEFGHJK\".find(occupied_column)</code><br>\n• does not iterate seatMap \"the pythonic way\": <code>for row in seat_map:</code><br>\n• creates a slice without striking need\n\n<ul>\n<li>using explicit start and end instead of <code>row_slice = row[:]</code>\n\n<ul>\n<li>not using a symbolic upper bound: <code>row_slice = row[0:seats_per_row]</code>\n\n<ul>\n<li>using a literal of <code>9</code>, which is the last valid index and one less than a tolerable upper bound <strong>leading to wrong (low) results</strong> when there is a block of unoccupied seats \"on the right\" with a length divisible by 4 </li>\n</ul></li>\n</ul></li>\n</ul></li>\n<li><code>seat(N, S)</code><br>\n• Missing, but specified by the problem statement. </li>\n<li>put your \"tinker test\" after an<br>\n<code>if __name__ == '__main__':</code> - if more than a couple of lines, better define a <code>main()</code></li>\n</ul>\n\n<hr>\n\n<p>There are many ways to reach a solution -</p>\n\n<ul>\n<li>start at the problem</li>\n<li>design and code the way <em>you</em> think about problem and solution<br>\ngiving others (including your later self (<strong>!</strong>)) a chance to follow your thinking:<br>\n<strong>Document your design.<br>\nDocument your code. In the code.</strong></li>\n</ul>\n\n<hr>\n\n<p>My take of \"the map approach\", sans module docstring:</p>\n\n<pre><code>def seating(N, empty, S):\n ''' Return a seating of N rows initially <empty>,\n with taken seats from S blanked out. '''\n seats = [empty]*N\n for taken in S.split():\n row = int(taken[:-1]) - 1\n seats[row] = seats[row].replace(taken[-1], ' ', 1)\n\n return seats\n\n\ndef count_clusters(seating, cluster_size):\n ''' Return the count of contiguous cluster_size clusters in seating. '''\n return sum(len(cluster) // cluster_size for row in seating\n for cluster in row.split())\n\n\ndef seat(N, S):\n ''' Return the maximum number of 4-passenger contiguous clusters. '''\n return count_clusters(seating(N, \"ABCDEFGHJK\", S), cluster_size=4)\n</code></pre>\n\n<hr>\n\n<p>Sketch of an \"interval approach\":</p>\n\n<ul>\n<li>start with one interval per row</li>\n<li>for each reservation<br>\n• split every interval at the seat specified<br>\n• discard all short intervals </li>\n<li>count intervals</li>\n</ul>\n\n<p>food for thought:<br>\n• ordering reservations (say, by ascending row) allows handling row by row \n• manipulating some form of \"dance card\" is equivalent to bucket sorting reservations </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:38:53.323",
"Id": "464585",
"Score": "0",
"body": "nice and simple. I do not like the reuse of the `seating` name in the `count_clusters` method, but for the rest this is very elegant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:14:49.453",
"Id": "237001",
"ParentId": "236913",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237001",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T00:28:36.047",
"Id": "236913",
"Score": "-1",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Find the maximum number of 4-passengers contiguous clusters"
}
|
236913
|
<p>I have built a Blackjack simulator in Python. I need to decrease the execution time. I have used a profiler to identify key bottlenecks in the execution.
The following function is responsible for about 15% of the total run time.</p>
<pre><code>def value(self):
value = 0
has_ace = False
for card in self.cards:
value += card.value
if card.rank == "A":
has_ace = True
if has_ace and value <= 11:
value += 10
return value
</code></pre>
<p>The above function is used to calculate the score of a hand.
A hand can have multiple cards.
A card has a value and a rank.</p>
<p>In Blackjack, an Ace can be worth 1 or 11.</p>
<p>Is there a better way to go?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T04:52:54.797",
"Id": "464424",
"Score": "1",
"body": "The best and biggest optimizations involve changing multiple areas of the code. Yes, this function may be significant, I do think you should share the rest of the program, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:55:31.017",
"Id": "464439",
"Score": "1",
"body": "I don't understand the logic behind the condition `if has_ace and value <= 11: value += 10`. What if the cards include more than a single ace? E.g. 2, A, A, A? Would the value of the hand be 5 or 15?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:59:53.103",
"Id": "464441",
"Score": "0",
"body": "@RonKlein Try think of it in regards to black jack, if you have AAAA you'd play it as 4 or 14, not 24, 34 or 44. As all of those other ones are bust. You'd pick 14 over 4 as it's a higher value - making it so you're more likely to win."
}
] |
[
{
"body": "<p>This function doesn't have any really obvious inefficiencies, so I assume we're looking to shave off every possible clock cycle...</p>\n\n<p>Sometimes it's faster to use Python's built-in aggregation functions than to use a <code>for</code> loop. Here's how you could use <code>sum</code> and <code>any</code>:</p>\n\n<pre><code>def value(self) -> int:\n value = sum(card.value for card in self.cards)\n if value <= 11 and any(card.rank == \"A\" for card in self.cards):\n value += 10\n return value\n</code></pre>\n\n<p>Note the ordering of the <code>and</code> expression to make sure that the <code>any</code> iteration only happens if the value condition has already been met!</p>\n\n<p>If you have flexibility over the representation of the cards, you might try making the <code>rank</code> an <code>Enum</code> with integer values. I'd expect comparing two integer enums to be just a smidge faster than comparing two strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T09:33:16.393",
"Id": "464429",
"Score": "5",
"body": "The `any` expression looks incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:37:11.003",
"Id": "464450",
"Score": "1",
"body": "It worth noting that your comment about comparing strings being faster than comparing integers is not strictly True, at least for CPython. For short strings such as `\"A\"`, it is overwhelmingly likely that the interpreter will have interned them. Therefore, `card.rank` and the literal `\"A\"` will refer to precisely the same objects, which is a special case handle explicitly by `string_richcompare` in `stringobject.c`. Even if interning isn't performed, it would still be a matter comparing a single character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:08:27.160",
"Id": "464475",
"Score": "0",
"body": "Whoops, fixed that `any` typo. I'm not deeply familiar with CPython internals, but my thought was that comparing strings requires dereferencing a pointer before you get to the underlying identical byte, whereas comparing values lets you skip that step. If it's cached by the interpreter it's moot though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:17:21.130",
"Id": "464483",
"Score": "1",
"body": "Picking ints over chars sounds like a premature optimization. As for if it's actually true, you can just use `timeit` to verify. For me they perform the same, and so the optimization all around just seems like bad advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T09:21:26.337",
"Id": "465133",
"Score": "0",
"body": "In addition to Sam's previous answer, the final has_ace test could return immediately without updating local variable value.\nIt could aslo increase your performances to store card ranks as integers instead of strings."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T02:38:51.043",
"Id": "236916",
"ParentId": "236915",
"Score": "2"
}
},
{
"body": "<p>In terms of playing the game, what is the use of the returned value?</p>\n\n<p>For instance, <code>A222</code> would have the value 17, and at that value, most people would stick and not ask for another card. But if it could be counted as 7, everyone <em>would</em> ask for another card.</p>\n\n<p>To be useful, the result will need to be a list of possible values, <code>(7,17)</code> for this example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:09:16.073",
"Id": "236928",
"ParentId": "236915",
"Score": "1"
}
},
{
"body": "<p>I think that <code>10</code> and <code>11</code> are confusing values, and it might be more readable to have them either calculated or more explicitly expressed.</p>\n\n<p>As you say, an ace can be either <code>1</code> or <code>11</code>.</p>\n\n<p>In addition, a valid hand cannot exceed <code>21</code>.</p>\n\n<p>I'd expect the code to have <strong>only</strong> those values hard coded (as constants or something similar).</p>\n\n<p>If you want to implement it in an object oriented way (might not be the best idea here), then all of the cards are an instance of a class, which has the following methods:</p>\n\n<ul>\n<li><code>has_alternative_value</code></li>\n<li><code>get_regular_value</code></li>\n<li><code>get_alternative_value</code></li>\n</ul>\n\n<p>Only the ace would return <code>True</code> to <code>has_alternative_value</code> and so forth.</p>\n\n<p>Having it implemented like that, the code would only have to deal with the magic number <code>21</code>, and you wouldn't have <code>10</code> and <code>11</code> magic numbers.</p>\n\n<p>While this sounds like over-engineering, I think that the main idea could be implemented in a simpler way. I don't have the time to write the entire solution myself, but I hope you catch my drift.</p>\n\n<p>Good luck :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:53:17.457",
"Id": "236936",
"ParentId": "236915",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236916",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T01:00:35.553",
"Id": "236915",
"Score": "4",
"Tags": [
"python"
],
"Title": "Calculate Hand Value in a Blackjack Hand"
}
|
236915
|
<p>I am practicing coding questions on leetcode. I have been an OOP my whole career, and I am trying to wade into the dark abyss that is functional programming. So I am trying to do things purely functional, e.g. using recursion to try to get to the answer. The problem statement is this: <code>Given a string, find the length of the longest substring without repeating characters.</code></p>
<p>Sorry for asking literally this leetcode question that everybody else is asking :D</p>
<p>I have coded up this solution - </p>
<pre><code>class Solution {
fun lengthOfLongestSubstring(str: String): Int {
return when {
str.length == 1 -> 1
str.isEmpty() -> 0
else -> helper(str, 0, 1, 0)
}
}
private tailrec fun helper(str: String, leftIndex: Int, rightIndex: Int, max: Int): Int {
return when {
rightIndex >= str.length+1 -> max
rightIndex >= str.length && isDistinct(str.substring(leftIndex)) ->
helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
isDistinct(str.substring(leftIndex, rightIndex)) ->
helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
}
}
private fun isDistinct(substring: String): Boolean {
return substring.toList().distinct().size == substring.length
}
}
</code></pre>
<p>I have a couple specific questions -
I am using the sliding window approach, is that appropriate in a functional setting? If not, what is a better approach functionally, speaking. </p>
<p>Is there redundancy in my recursion function that I can get rid of?</p>
<p>What things can I do to improve the legibility of the function? Clean code is always best!</p>
<p>What further steps can I take to optimize the solution? Currently this solution is only faster than 10% of other solutions (though those are likely imperative solutions)</p>
<p>Any other tips you can provide outside of the bounds of my question that can help would be awesome. I am also brand new to kotlin programming.</p>
<p>I don't necessarily hate this solution, but I'm sure it can be better. Please advise.</p>
|
[] |
[
{
"body": "<p>Note, I don't think about performance, only about kotlin.</p>\n<h1>Iluminate branch</h1>\n<p>in your when, you check if the <code>rightIndex >= string.length+1</code>.<br />\nthis means in the next branches the size is maximal <code>string.length</code>.\nSubstring is exclusive, so it allows str.length.<br />\nthis means the second and third branches are identical.</p>\n<h1>Use Set</h1>\n<p>It would make more sense to me to use <code>toSet</code> instead of <code>toList.distinct</code>, because sets are meant to hold distinct versions.</p>\n<h1>personal Choices:</h1>\n<h3>Single-expression function</h3>\n<p>A <a href=\"https://kotlinlang.org/docs/reference/functions.html#single-expression-functions\" rel=\"nofollow noreferrer\">single-expression-function</a> is a function with one expression .<br />\nIn kotlin, you can write this in an easier way.<br />\nInstead of writing</p>\n<pre><code>fun lengthOfLongestSubstring(str: String): Int {\n return when {\n ...\n }\n}\n</code></pre>\n<p>you can write</p>\n<pre><code>fun lengthOfLongestSubstring2(str: String): Int = when {\n ...\n}\n</code></pre>\n<p>or even without return-type:</p>\n<pre><code>fun lengthOfLongestSubstring2(str: String) = when {\n ...\n}\n</code></pre>\n<p>I personally like to write these like:</p>\n<pre><code>fun helper(\n str: String,\n leftIndex : Int,\n rightIndex : Int,\n max: Int\n) = when {\n ...\n}\n</code></pre>\n<h3>function with receiver</h3>\n<p>If I'm right functional means:</p>\n<ul>\n<li>The function knows about the type and the type doesn't know about the function</li>\n<li>If a function receives the same input, it should return the same output</li>\n</ul>\n<p>(or only the later)</p>\n<p>The first way is often expressed by having a function that only takes parameters, but is not called on an object: <code>b(a)</code> instead of <code>a.b()</code></p>\n<p>Kotlin allows to let a function like <code>b(a)</code> look like <code>a.b()</code>, if you define it that way. This is called a <a href=\"https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver\" rel=\"nofollow noreferrer\">function with receiver</a>.<br />\nNote, inside de function-body, you refer to the receiver using <code>this</code>.</p>\n<pre><code>isDistinct("hi")\nprivate fun isDistinct(\n substring: String\n): Boolean = substring.toSet().size == substring.length\n</code></pre>\n<p>can be rewritten to</p>\n<pre><code>"hi".isDistinct()\nprivate fun String.isDistinct() : Boolean = this.toSet().size == this.length\n</code></pre>\n<p>And as you don't have to call <code>this</code> inside a scope:</p>\n<pre><code>"hi".isDistinct()\nprivate fun String.isDistinct() : Boolean = toSet().size == length\n</code></pre>\n<p>Or just:</p>\n<pre><code>"hi".isDistinct()\nprivate fun String.isDistinct() = toSet().size == length\n</code></pre>\n<p>Under the scenes it's still the same function.\nInside kotlin, you can't call it the old way anymore</p>\n<h1>New code</h1>\n<pre><code>class Solution {\n fun lengthOfLongestSubstring(\n str: String\n ) = when {\n str.length == 1 -> 1\n str.isEmpty() -> 0\n else -> helper(str, 0, 1, 0)\n }\n\n private tailrec fun helper(\n str: String,\n leftIndex: Int,\n rightIndex: Int,\n max: Int\n ): Int = when {\n rightIndex >= str.length + 1 -> max\n str.substring(leftIndex, rightIndex).isDistinct() ->\n helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))\n else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)\n }\n\n private fun String.isDistinct() = toSet().size == length\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T14:34:09.093",
"Id": "464568",
"Score": "2",
"body": "Wow, great answer! I learned more about kotlin coding techniques and reduced the redundancy of my function. Thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T10:33:46.383",
"Id": "236982",
"ParentId": "236917",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T05:01:37.113",
"Id": "236917",
"Score": "3",
"Tags": [
"algorithm",
"recursion",
"functional-programming",
"kotlin"
],
"Title": "Longest Substring without Repeating Characters Problem - Kotlin Recursion"
}
|
236917
|
<p>After referencing <a href="http://csharpexamples.com/tag/unsafe-bitmap-access/" rel="nofollow noreferrer">http://csharpexamples.com/tag/unsafe-bitmap-access/</a></p>
<p>I tried to put together one for 1 bit per pixel bitmaps. </p>
<p>If you can review this, it would help me greatly in verifying this is the correct way to do it.</p>
<p>This takes a Format1bppIndexed bitmap and locks it in memory, and directly parses the memory bits to form the bits into a boolean array.</p>
<pre><code>using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace AutoBot
{
public class BitData
{
private Rectangle DataRect { get; }
private string DataPath { get; }
private Stream DataStream { get; }
private Image DataImage { get; }
private Bitmap DataMap { get; }
public IEnumerable<bool[]> GetBitDataInMemory()
{
if (DataMap == default && DataRect == default && string.IsNullOrEmpty(DataPath) && DataStream == default && DataImage == default)
{
return default;
}
Bitmap TargetImage;
if (DataMap != default)
{
TargetImage = DataMap;
}
else if (DataRect != default)
{
TargetImage = NativeMethods.GetBlackWhiteAt(DataRect.Location, DataRect.Size);
}
else if (!string.IsNullOrEmpty(DataPath))
{
if (File.Exists(DataPath))
{
using (var Image = new Bitmap(DataPath))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
else
{
return default;
}
}
else if (DataStream != default)
{
using (var Image = new Bitmap(DataStream))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
else
{
using (var Image = new Bitmap(DataImage))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
var Array = InMemGetBooleanArray(TargetImage);
TargetImage.Dispose();
return Array;
}
public IEnumerable<bool[]> GetBitData()
{
if (DataMap == default && DataRect == default && string.IsNullOrEmpty(DataPath) && DataStream == default && DataImage == default)
{
return default;
}
Bitmap TargetImage;
if (DataMap != default)
{
TargetImage = DataMap;
}
else if (DataRect != default)
{
TargetImage = NativeMethods.GetBlackWhiteAt(DataRect.Location, DataRect.Size);
}
else if (!string.IsNullOrEmpty(DataPath))
{
if (File.Exists(DataPath))
{
using (var Image = new Bitmap(DataPath))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
else
{
return default;
}
}
else if (DataStream != default)
{
using (var Image = new Bitmap(DataStream))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
else
{
using (var Image = new Bitmap(DataImage))
TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);
}
var Array = GetBooleanArray(TargetImage);
TargetImage.Dispose();
return Array;
}
public BitData(Rectangle dataRect = default, string dataPath = default, Stream dataStream = default, Image dataImage = default, Bitmap dataMap = default)
{
DataRect = dataRect;
DataPath = dataPath;
DataStream = dataStream;
DataImage = dataImage;
DataMap = dataMap;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static IEnumerable<bool[]> GetBooleanArray(Bitmap bitmap)
{
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
bool[][] ba2 = new bool[bitmap.Height][];
for (int y = 0; y <= bitmap.Height - 1; y++)
{
ba2[y] = new bool[bitmap.Width];
for (int x = 0; x <= bitmap.Width - 1; x++)
{
if (GetIndexedPixel(x, y, data) > 0)
{
ba2[y][x] = true;
}
}
}
bitmap.UnlockBits(data);
return ba2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static IEnumerable<bool[]> InMemGetBooleanArray(Bitmap bitmap)
{
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
bool[][] ba2 = new bool[bitmap.Height][];
unsafe
{
int heightInPixels = data.Height;
int widthInBits = data.Width-1;
byte* PtrFirstPixel = (byte*)data.Scan0;
Parallel.For(0, heightInPixels, y =>
{
ba2[y] = new bool[data.Width];
for (int x = 0; x <= widthInBits; x++)
{
int Index = (y * data.Stride) + (x >> 3);
byte ret = *(PtrFirstPixel + Index);
ret &= (byte)(0x80 >> (x & 0x7));
if (ret > 0)
{
ba2[y][x] = true;
}
}
});
}
bitmap.UnlockBits(data);
return ba2;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetIndexedPixel(int x, int y, BitmapData data)
{
var index = (y * data.Stride) + (x >> 3);
var mask = (byte)(0x80 >> (x & 0x7));
byte ret = Marshal.ReadByte(data.Scan0, index);
ret &= mask;
return ret;
}
}
}
</code></pre>
<p>Search Routine</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoBot
{
public static class ActiveScreenMatch
{
public static Point ScreenMatchInMemory(BitData Target = default)
{
if (Target == default)
{
return default;
}
var TargetArea = Target.GetBitDataInMemory();
int SkippedBlackLines = 0;
foreach (var bl1 in TargetArea)
{
if (bl1.Any(x => x))
{
break;
}
else
{
SkippedBlackLines++;
}
}
TargetArea = TargetArea.Skip(SkippedBlackLines).ToArray();
Bitmap SourceImage = NativeMethods.GetBlackWhiteAt(new Point(0, 0), new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
BitData SourceData = new BitData(dataMap: SourceImage);
var SourceArea = SourceData.GetBitDataInMemory();
SourceImage.Dispose();
var m = TargetArea.Count() - 1;
Point p = default;
WaitHandle[] waitHandles = new WaitHandle[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
void ThreadForward(object State)
{
AutoResetEvent Complete = (AutoResetEvent)State;
_ = Parallel.ForEach(Enumerable.Range(0, SourceArea.Count() - 1), (line, loopState) =>
{
var Index = SubListIndex(SourceArea.ElementAt(line), 0, TargetArea.ElementAt(0));
if (Index != -1 && Index != 0 && line > m && (line + m) < Screen.PrimaryScreen.Bounds.Height)
{
var SourceLast = SourceArea.ElementAt(line + m).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m).ToArray());
var SourceMid = SourceArea.ElementAt(line + (m / 2)).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m / 2).ToArray());
if (SourceLast && SourceMid)
{
p = new Point(Index + (TargetArea.ElementAt(0).Length / 2), line + (TargetArea.ElementAt(0).Length / 2));
loopState.Break();
}
}
});
Complete.Set();
}
void ThreadBackward(object State)
{
AutoResetEvent Complete = (AutoResetEvent)State;
_ = Parallel.ForEach(Enumerable.Range(0, SourceArea.Count() - 1).Reverse(), (line, loopState) =>
{
var Index = SubListIndex(SourceArea.ElementAt(line), 0, TargetArea.ElementAt(0));
if (Index != -1 && Index != 0 && line > m && (line + m) < Screen.PrimaryScreen.Bounds.Height)
{
var SourceLast = SourceArea.ElementAt(line + m).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m).ToArray());
var SourceMid = SourceArea.ElementAt(line + (m / 2)).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m / 2).ToArray());
if (SourceLast && SourceMid)
{
p = new Point(Index + (TargetArea.ElementAt(0).Length / 2), line + (TargetArea.ElementAt(0).Length / 2));
loopState.Break();
}
}
});
Complete.Set();
}
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadForward), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadBackward), waitHandles[1]);
WaitHandle.WaitAny(waitHandles);
return p;
}
public static Point ScreenMatch(BitData Target = default)
{
if (Target == default)
{
return default;
}
var TargetArea = Target.GetBitData();
int SkippedBlackLines = 0;
foreach (var bl1 in TargetArea)
{
if (bl1.Any(x => x))
{
break;
}
else
{
SkippedBlackLines++;
}
}
TargetArea = TargetArea.Skip(SkippedBlackLines).ToArray();
Bitmap SourceImage = NativeMethods.GetBlackWhiteAt(new Point(0, 0), new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
BitData SourceData = new BitData(dataMap: SourceImage);
var SourceArea = SourceData.GetBitData();
SourceImage.Dispose();
var m = TargetArea.Count() - 1;
Point p = default;
WaitHandle[] waitHandles = new WaitHandle[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
void ThreadForward(object State)
{
AutoResetEvent Complete = (AutoResetEvent)State;
_ = Parallel.ForEach(Enumerable.Range(0, SourceArea.Count() - 1), (line, loopState) =>
{
var Index = SubListIndex(SourceArea.ElementAt(line), 0, TargetArea.ElementAt(0));
if (Index != -1 && Index != 0 && line > m && (line + m) < Screen.PrimaryScreen.Bounds.Height)
{
var SourceLast = SourceArea.ElementAt(line + m).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m).ToArray());
var SourceMid = SourceArea.ElementAt(line + (m / 2)).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m / 2).ToArray());
if (SourceLast && SourceMid)
{
p = new Point(Index + (TargetArea.ElementAt(0).Length / 2), line + (TargetArea.ElementAt(0).Length / 2));
loopState.Break();
}
}
});
Complete.Set();
}
void ThreadBackward(object State)
{
AutoResetEvent Complete = (AutoResetEvent)State;
_ = Parallel.ForEach(Enumerable.Range(0, SourceArea.Count() - 1).Reverse(), (line, loopState) =>
{
var Index = SubListIndex(SourceArea.ElementAt(line), 0, TargetArea.ElementAt(0));
if (Index != -1 && Index != 0 && line > m && (line + m) < Screen.PrimaryScreen.Bounds.Height)
{
var SourceLast = SourceArea.ElementAt(line + m).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m).ToArray());
var SourceMid = SourceArea.ElementAt(line + (m / 2)).Skip(Index).Take(TargetArea.ElementAt(0).Length).SequenceEqual(TargetArea.ElementAt(m / 2).ToArray());
if (SourceLast && SourceMid)
{
p = new Point(Index + (TargetArea.ElementAt(0).Length / 2), line + (TargetArea.ElementAt(0).Length / 2));
loopState.Break();
}
}
});
Complete.Set();
}
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadForward), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadBackward), waitHandles[1]);
WaitHandle.WaitAny(waitHandles);
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int SubListIndex(IEnumerable<bool> list, int start, IEnumerable<bool> sublist)
{
for (int listIndex = start; listIndex < list.Count() - sublist.Count() + 1; listIndex++)
{
int count = 0;
while (count < sublist.Count() && sublist.ElementAt(count).Equals(list.ElementAt(listIndex + count)))
count++;
if (count == sublist.Count())
return listIndex;
}
return -1;
}
}
}
</code></pre>
<p>Example usage</p>
<p>I targeted my clock in the system tray.</p>
<pre><code> Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var x1 = new BitData(new Rectangle(1805, 1043, 16, 16));
var p1 = ActiveScreenMatch.ScreenMatchInMemory(x1);
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
stopwatch.Reset();
stopwatch.Start();
var x2 = new BitData(new Rectangle(1805, 1043, 16, 16));
Point p2 = ActiveScreenMatch.ScreenMatch(x2);
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
Console.WriteLine(p1.X + " " + p1.Y);
Console.WriteLine(p2.X + " " + p2.Y);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T09:40:05.390",
"Id": "464430",
"Score": "2",
"body": "While trying your code it's not quite clear, what you're trying to achieve. I assume, that you are trying to convert a monochrome bitmap into a matrix of boolean values. If that's the case it's not working as intended (review the for-loop). If I'm wrong please explain in more details what the outcome should be - e.g. provide a small example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:01:50.817",
"Id": "464433",
"Score": "0",
"body": "Thank you for pointing out that bug with for loop, that was not intended. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T13:14:51.657",
"Id": "464444",
"Score": "1",
"body": "I'm sorry to say, but still can't make it work. Could you include the image, you're using as test case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T17:44:38.110",
"Id": "464465",
"Score": "1",
"body": "It was not a useful edition you made of the for-loop, so take a look again (you'll have to consider the repetitive calls to `BitTest(x, y)`) . And you also have to consider this: `int widthInBytes = data.Width / PixelsPerByte;` for images with a `width < 8` pixels. It's not a bad post, and I look forward to see it updated with working code, before I vote for close :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T17:56:36.400",
"Id": "464467",
"Score": "0",
"body": "Sorry, Henrik, was up really late and this idea came to me while reading that article. After debugging and verifying equality of output this could be correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T18:04:46.877",
"Id": "464469",
"Score": "0",
"body": "I wonder if you actually test the code before you upload it? And in case you do, please provide the image you use. The new update also fails when I test it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:34:57.003",
"Id": "464480",
"Score": "0",
"body": "Added complete code for testing."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T05:16:29.373",
"Id": "236918",
"Score": "4",
"Tags": [
"c#"
],
"Title": "unsafe bit reading.in parallel"
}
|
236918
|
<p>I have created a fractal tree based on a <a href="https://en.m.wikipedia.org/wiki/L-system" rel="nofollow noreferrer">Lindenmayer System</a> in Python. If you could tell me about any algorithmic or efficiency-based problems in the code, I would be grateful.</p>
<pre class="lang-py prettyprint-override"><code>import turtle
import time
t = turtle.Pen()
branch = []
code = "1[0]0" # Change this to modify the structure of the tree
t.left(90)
t.up()
t.backward(300)
t.down()
t.speed(10)
for c in code:
if c == "1":
t.pencolor("brown")
t.forward(100) # Change this to modify the size of the tree
elif c == "0":
t.pencolor("green")
t.forward(3) # Change this to modify the size of the leaves
elif c == "[":
t.left(45)
branch.append((t.position(), t.heading()))
elif c == "]":
t.up()
t.goto(branch[len(branch) -1][0], None)
t.setheading(branch[len(branch) -1][1])
t.right(90)
t.down()
del branch[len(branch) -1]
</code></pre>
|
[] |
[
{
"body": "<p>Personally I don't like multiples if statements inside a for, here is my suggestion:</p>\n\n<pre><code>def handler_option_c(t, b):\n t.pencolor(\"brown\")\n t.forward(100) # Change this to modify the size of the tree\n\nhandlers = { \"c\" : handler_option_c, ....\n</code></pre>\n\n<p>And you do the same for the other options, and then on your main</p>\n\n<pre><code>for c in code:\n handlers[c](t, branch)\n</code></pre>\n\n<p>Or you can put that on a lambda also</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T11:30:42.873",
"Id": "236923",
"ParentId": "236922",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T10:44:07.100",
"Id": "236922",
"Score": "1",
"Tags": [
"python",
"algorithm",
"turtle-graphics"
],
"Title": "Lindenmayer System Python Fractral Tree"
}
|
236922
|
<p>I've been learning C# for around 2 weeks and I'm feeling a bit more confident. I wrote this for general practice and am quite proud but hoping to make it faster and more efficient as I progress and learn more.</p>
<p>This program allows the user to input car data i.e. "Model and Price" and then search for the stored data.
(Next step is to add more values to the arrays).</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many cars are in the workshop?");
int amountofcars = int.Parse(Console.ReadLine());
int[] cars = new int[amountofcars];
double[] carprice = new double[amountofcars];
string[] models = new string[amountofcars];
for(int i = 0; i < amountofcars; i++)
{
Console.WriteLine("List the model of car #{0}", i + 1);
string carmodels = Console.ReadLine();
models[i] = carmodels;
Console.WriteLine("Input car price");
double price = double.Parse(Console.ReadLine());
carprice[i] = price;
}
Console.WriteLine("Data stored");
Console.WriteLine();
Console.WriteLine("What do you want to do next?");
Console.WriteLine("Type \"Search\" to start a new search or any key to leave program");
string responce = Console.ReadLine();
char searchagain = 'Y';
do
{
if (responce == "Search")
{
bool contains = false;
Console.WriteLine("What car did you want to search for?");
string modelsearch = Console.ReadLine();
for (int i = 0; i < amountofcars; i++)
{
if (modelsearch == models[i])
{
contains = true;
Console.WriteLine("{0} {1} ", models[i], carprice[i]);
Console.WriteLine();
Console.WriteLine("What do you want to do next?");
Console.WriteLine("Search again? \"Y\" or any key to exit");
searchagain = char.Parse(Console.ReadLine());
}
if (modelsearch == "All")
{
for (i = 0; i < amountofcars; i++)
{
contains = true;
Console.WriteLine("{0} {1} ", models[i] , carprice[i]);
Console.WriteLine();
}
Console.WriteLine("What do you want to do next?");
Console.WriteLine("Search again? \"Y\" or any key to exit");
searchagain = char.Parse(Console.ReadLine());
}
}
}
} while (searchagain == 'Y');
}
}
</code></pre>
|
[] |
[
{
"body": "<p>first, using <code>Parse</code> for user input it would be a bad practice, as you're parsing the input without any validation. thus, you'll need to use <code>TryParse</code> instead, which will validate the input to the specific type, if it's valid input that would be acceptable by the targeted type, then it would return <code>true</code> and output the parsed value.</p>\n\n<p>Example direct parsing : </p>\n\n<pre><code>// this would pass the value without validation \nint amountofcars = int.Parse(Console.ReadLine());\n</code></pre>\n\n<p>Example of validated parsing : </p>\n\n<pre><code>// this validates the input value, then process :\nbool isValid = int.TryParse(Console.ReadLine(), out int amountofcars);\n// isValid == true, then it's an interger. \n\nif(isValid) // if it's a valid integer\n{\n // process the amountofcars\n}\n</code></pre>\n\n<p>you'll find a lot of System types that already has <code>TryParse</code> like <code>int.TryParse</code>, <code>double.TryParse</code> and so on. You should always use it when parsing user inputs. You can still use <code>Parse</code> but use it whenever you see that you're diffidently sure a hundred percent that the value will always be compatible with the targeted type. </p>\n\n<p>Since you have <code>cars</code>, <code>carprice</code> and <code>models</code> arrays, I assume you need one class model, that would hold car information. something like : </p>\n\n<pre><code>public class Car\n{\n public double Price { get; set; }\n\n public string Model { get; set; }\n}\n</code></pre>\n\n<p>now you can initiate a car array : </p>\n\n<pre><code>Car[] cars = new Car[amountofcars];\n</code></pre>\n\n<p>then inside your loop you can simply do this : </p>\n\n<pre><code>for(int i = 0; i < amountofcars; i++)\n{\n Console.WriteLine(\"List the model of car #{0}\", i + 1);\n string carmodels = Console.ReadLine();\n cars[i].Model = carmodels; \n Console.WriteLine(\"Input car price\");\n double price = double.Parse(Console.ReadLine()); // use TryParse instead;\n cars[i].Price = price;\n}\n</code></pre>\n\n<p>doing this, would let you have and process one array which hold the car information in each element. </p>\n\n<p>I suggest you use <code>List</code> instead of array. It would make things easier for you to process like adding and removing and also you don't need to specify its length. Also, it has more functionality than a system array. </p>\n\n<p>Here is a modified version with some comments that would help you throughout the code, if you feel you need a clarification just let me know. </p>\n\n<pre><code>public class Car\n{\n public double Price { get; set; }\n\n public string Model { get; set; }\n}\n\npublic static class Program\n{\n public static void Main(string[] args)\n {\n List<Car> cars = new List<Car>();\n\n int amountofcars = 0;\n\n do\n {\n // this should forced the user to input a valid integer \n // it won't break this loop until it gets a valid integer.\n Console.WriteLine(\"How many cars are in the workshop?\");\n }\n while (int.TryParse(Console.ReadLine(), out amountofcars) == false);\n\n // now we can process \n for (int i = 0; i < amountofcars; i++)\n {\n\n Console.WriteLine(\"List the model of car #{0}\", i + 1);\n // since it's string, there is no need for type validation, unless you need to include business validation. \n string carmodels = Console.ReadLine();\n\n // repeat the same validation : \n double price = 0;\n do\n {\n // this should forced the user to input a valid integer \n // it won't break this loop until it gets a valid integer.\n Console.WriteLine(\"Input car price\");\n }\n while (double.TryParse(Console.ReadLine(), out price) == false);\n\n cars.Add(new Car { Model = carmodels, Price = price });\n }\n\n\n Console.WriteLine(\"Data stored\");\n Console.WriteLine();\n Console.WriteLine(\"What do you want to do next?\");\n Console.WriteLine(\"Type \\\"Search\\\" to start a new search or any key to leave program\");\n string responce = Console.ReadLine();\n\n while (true)\n {\n //using StringComparison.InvariantCultureIgnoreCase \n // this would make it case-insensitive\n if (responce.Equals(\"Search\", StringComparison.InvariantCultureIgnoreCase))\n {\n Car found = null;\n\n Console.WriteLine(\"What car did you want to search for?\");\n\n string modelsearch = Console.ReadLine();\n\n foreach (var car in cars)\n {\n if (car.Model.Equals(modelsearch, StringComparison.InvariantCultureIgnoreCase))\n {\n found = car;\n }\n }\n\n if (found != null)\n {\n Console.WriteLine($\"{found.Model} {found.Price}\");\n Console.WriteLine();\n }\n else\n {\n Console.WriteLine($\"Model {modelsearch} not found.\");\n Console.WriteLine();\n }\n\n Console.WriteLine(\"What do you want to do next?\");\n Console.WriteLine(\"Search again? \\\"Y\\\" or any key to exit\");\n\n\n // this line would break if it's not a char.\n //searchagain = char.Parse(Console.ReadLine());\n\n var whatnext = Console.ReadLine();\n\n if (whatnext.Equals(\"Y\", StringComparison.InvariantCultureIgnoreCase) == false)\n {\n // if user input anything else will break this loop.\n break;\n }\n }\n else\n {\n // in case if pressed any key, it'll break this loop. \n break;\n }\n\n } \n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:49:29.613",
"Id": "464482",
"Score": "1",
"body": "Really appreciate your time checking this out. I'm currently doing a course that's yet to get to classes so this will help in the next section of the lecture for sure! Kind of just crammed everything I've currently learned into this program. Thanks a million!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T18:10:42.457",
"Id": "236933",
"ParentId": "236927",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236933",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T14:53:51.587",
"Id": "236927",
"Score": "5",
"Tags": [
"c#",
"performance",
"beginner",
"array",
".net-core"
],
"Title": "Car Showroom Database: Taking user inputs and manipulating arrays"
}
|
236927
|
<p>I have recently built a class that is an implementation of kMeans from scratch. I believe there is room for improvement and I would happily receive some feedback. The project can be found at: <a href="https://github.com/EmpanS/kMeans-From-Scratch" rel="nofollow noreferrer">https://github.com/EmpanS/kMeans-From-Scratch</a></p>
<p>All code for the class is found below:</p>
<pre class="lang-py prettyprint-override"><code># Import useful libraries
import numpy as np
class kMeans:
"""A class used to perform the k-means clustering algorithm on a data set. The maximum number of
iterations is set by the user, if it converges to a solution, it stops iterating.
Attributes
----------
AVAILABLE_DIST_F : (list of str)
Contains the available distance functions. L1_norm is the Manhattan distance, L2_norm is the
ordinary Euclidean distance.
k : (int)
Represents the number of clusters
X : (numpy array)
The data to cluster, must be an (m x n)-numpy array with m observations and n features.
verbose : (boolean)
A boolean representing if printing should be done while training the model.
h_params : (dictionary)
Contains two hyper-parameters, number of iterations (n_iter) and distance function (dist_f)
random_state : (int)
Optional setting for the random state. The k-means algorithm does not guarantee finding a
global minimum, but the final clusters depends on the initial random cluters.
labels : (numpy array)
Contains the predicted label for each observation, i.e., what cluster it belongs to.
cluster_centers (numpy array)
Contains the n-dimensional coordinates for each cluster.
Methods
-------
update_h_params(self, h_params)
Updates hyper parameters.
fit(self, X=None)
Performs the k-means algorithm on the passed data X or, if no data is passed, on self.X
__calculate_distances(X, centers)
Calculates the distances between all observations in X and all centers of clusters. Uses the
distance function already specified as a hyper-parameter.
__validate_param(h_param, setting)
Validate new hyper-parameter settings.
"""
def __init__(self, k, X, verbose=True, h_params=None, random_state=None):
self.AVAILABLE_DIST_F = ["L1_norm", "L2_norm"]
self.k = k
self.X = X
self.verbose = verbose
self.h_params = {'n_iter':100, 'dist_f':'L2_norm'}
self.random_state=random_state
if h_params != None:
self.update_h_params(h_params)
self.labels = np.full((X.shape[0], 1), np.nan)
self.cluster_centers = np.full((self.k, 1), np.nan)
def update_h_params(self, h_params):
"""Updates the hyper parameters.
Parameters
----------
h_params : (dict)
Dictionary containing the hyper parameter/s and its updated setting/s.
Returns
-------
None
"""
if type(h_params) != dict:
raise TypeError('The argument must be a dictionary.')
for h_param, setting in h_params.items():
self.__validate_param(h_param, setting)
self.h_params[h_param] = setting
def fit(self, X=None):
"""Performs the k-means algorithm. First, all observations in X gets randomly assigned a
label. Then, the function iterates until a solution is found (converged) or the maximum
number of iterations is reached. Each iteration performs the following:
- Update labels
- Check convergence
- Calculate new cluster centers
Parameters
----------
X : (numpy array)
The data to cluster, must be an (m x n)-numpy array with m observations and n features.
Returns
-------
wss : (numpy array)
A numpy array that saves the within cluster sum of squares for each iteration.
Labels : (numpy array)
A numpy array containing all new labels for the observations in X.
"""
if X == None:
X = self.X
if (n := self.random_state) != None:
np.random.seed(n)
# Initiate array to save within cluster sum of squares
wss = np.zeros((1, self.h_params['n_iter']))
# Randomly draw k observations and set them as the initial cluster centers
center_index = np.random.choice(X.shape[0], size=self.k, replace=False)
cluster_centers = X[center_index]
old_labels = None
for iter in range(self.h_params['n_iter']):
# Label the observations using the updated cluster centers
distances = self.__calculate_distances(X, cluster_centers)
labels = np.argmin(distances, axis=1)
# Calculate the within-sum-of-squares
wss[0,iter] = sum(np.min(distances, axis=1))
# Check convergence
if np.all(labels == old_labels):
if self.verbose:
print(f"Converged to a solution after {iter} iterations!")
return(wss[0,:(iter)], labels)
else:
old_labels = labels
# Calculate new cluster centers
for i in range(self.k):
cluster_centers[i] = np.sum(X[labels==i],axis=0)/(X[labels==i].shape[0])
if self.verbose:
print(f"Did not converged, reached max iterations. Completed {iter+1} iterations.")
return(wss[0,:], labels)
def __calculate_distances(self, X, centers):
"""
Calculates the distances between all observations in X and all cluster centers. The already
specified distance function (found in self.h_params) is used to calculate the distances.
Parameters
----------
X : (numpy array)
A matrix (m x n) containing all observations.
centers : (numpy array)
A matrix (k x n) where k is the number of clusters, containing all cluster centers.
Returns
-------
labels : (numpy array)
A numpy array containing all new labels for the observations in X.
"""
# Initiate a distance matrix
distance_m = np.tile(centers.flatten(), (X.shape[0],1))
# Duplicate data matrix to same dimension as distance matrix
X_m = np.tile(X, (centers.shape[0]))
if self.h_params["dist_f"] == "L2_norm":
# Complete the distance matrix using the L2-norm
distance_m = np.reshape(distance_m - X_m, (X.shape[0]*centers.shape[0], X.shape[1]))
distance_m = np.sum(np.square(distance_m),axis=1, keepdims=True)
# Reshape distance matrix
distance_m = np.sqrt(np.reshape(distance_m, (X.shape[0], len(centers))))
return(distance_m)
elif self.h_params["dist_f"] == "L1_norm":
# Complete the distance matrix using the L1-norm
distance_m = np.reshape(distance_m - X_m, (X.shape[0]*centers.shape[0], X.shape[1]))
distance_m = np.sum(np.abs(distance_m),axis=1, keepdims=True)
# Reshape distance matrix
distance_m = np.reshape(distance_m, (X.shape[0], len(centers)))
return(distance_m)
else:
raise ValueError('Could not calculate distance, no distance function found.')
def __validate_param(self, h_param, setting):
"""
Validates a given hyper-parameter update. The update must must have a valid key and value.
Parameters
----------
h_param : (str)
The hyper parameter to update
setting : (int) or (str)
The new setting of the hyper parameter
Returns
-------
None - (Throws an error if not valid.)
"""
if h_param not in self.h_params.keys():
raise KeyError("No hyper parameter is named " + str(h_param) + ", it is a wrong value of key. Must be either 'n_iter' or 'dist_f'.")
if h_param == "n_iter":
if type(setting) != int or setting <= 0:
raise ValueError("n_iter must be a positive integer which " + str(setting) + " is not.")
else: # Setting for the distance function
if setting not in self.AVAILABLE_DIST_F:
raise ValueError(str(setting) + " is not an available distance function. Available functions are: " + str(self.AVAILABLE_DIST_F))
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Unnecessary type checking</h1>\n\n<p>In <code>update_h_params</code>, you write</p>\n\n<pre><code>if type(h_params) != dict:\n raise TypeError('The argument must be a dictionary.')\n</code></pre>\n\n<p>In Python, we don't care about the actual types of objects, only the interfaces they offer. This ideology is often referred to as <a href=\"https://stackoverflow.com/questions/4205130/what-is-duck-typing\">Duck Typing</a>, stemming from the notion that if something \"walks like a duck, and quacks like a duck, its probably a duck.\" In this method you don't actually care whether or not the user passed a <code>dict</code>, only that whatever they gave you implements an <code>items()</code> method that returns an iterator of tuples. Your end users may very well have a reason to be using a different flavor of dictionary down the road, such as an <code>OrderedDict</code> or a <code>defaultdict</code>, which would be needlessly rejected by the current implementation.</p>\n\n<h1>Using <code>__methods</code> as \"private\" methods</h1>\n\n<p>The double-underscore syntax for method names is <a href=\"https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private\">not intended for creating \"private\" methods</a>. Rather, it's a tool to add namescrambling to method names so that subclasses don't accidentally overwrite a critical method. This doesn't appear to apply to your class.</p>\n\n<p>To mark an attribute or method as \"private\", a single underscore will suffice.</p>\n\n<h1>Re-inventing logging</h1>\n\n<p>Each time you write</p>\n\n<pre><code>if self.verbose:\n print('<some_string>')\n</code></pre>\n\n<p>could be more idiomatically replaced by using the standard <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> module. This has the added benefit of being much more configurable and will lead to fewer surprises when other developers try to use your code and receive unexpected writes to <code>stdout</code>.</p>\n\n<h1>Duplicate constants</h1>\n\n<p>I'd advise replace the attribute </p>\n\n<pre><code>self.AVAILABLE_DIST_F = [\"L1_norm\", \"L2_norm\"]\n</code></pre>\n\n<p>with a single class attribute</p>\n\n<pre><code>class kMeans:\n AVAILABLE_DIST_F = [\"L1_norm\", \"L2_norm\"]\n ...\n</code></pre>\n\n<p>As currently implemented, a new list will be created for each <code>kMeans</code> instance you create, which is a minor, but unnecessary, memory overhead. This also would more clearly convey that <code>AVAILABLE_DIST_F</code> does not change on an instance-by-instance basis.</p>\n\n<h1>Naming Conventions</h1>\n\n<p>Per <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">PEP-8</a>, it is recommend that class names use the <code>CapsWords</code> convention. Therefore, you may wish to rename <code>kMeans</code> to <code>KMeans</code>.</p>\n\n<h1>TMI in Docstrings</h1>\n\n<p>In your docstring for <code>kMeans</code>, you document each of the public methods your class provides, along with a short synopsis of their functionality. It is worth noting that standard Python documentation generating tools, such as <a href=\"https://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">sphinx</a>, will create blocks such as this automatically, making this section somewhat unnecessary. In addition, by documenting methods in two separate locations, you make your class liable to have its methods change without the associated documentation being updated along with them. I'd advise documenting your method in their own respective docstrings and restricting the class-level docstring to the high-level overview of your class' interface.</p>\n\n<h1>Using Type Hints</h1>\n\n<p>You currently only note the expect types of various method parameters in docstrings. This information can be more effectively conveys by adding <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">type hints</a> to the methods themselves. For example, you <code>update_h_params</code> method could be re-written as</p>\n\n<pre><code>from typing import Dict, Any\n\ndef update_h_params(self, h_params: Dict[str, Any]):\n ...\n</code></pre>\n\n<p>Using this feature helps many editors and static type checking tools analyze your program more appropriately. Both PyCharm and <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a> fully support these annotations. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T16:02:45.170",
"Id": "236930",
"ParentId": "236929",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T15:33:17.277",
"Id": "236929",
"Score": "3",
"Tags": [
"python",
"machine-learning",
"clustering"
],
"Title": "Implementation of K-means"
}
|
236929
|
<p>Inspired by <a href="https://stackoverflow.com/a/23853848/9134528">this answer</a> on stackoverflow for AI implementation in 2048 game.</p>
<p>I have been trying to make AI calculate best move by playing the game given specific times in memory preceding by one specific move first, then averaging the score and declaring move with highest score as best move.</p>
<p>The workflow is fine, i am getting results good and as described in the answer, the chances of win in this game at <code>100</code> runs per move is about <code>80%</code>.</p>
<p>The problem is: My implementation in python is really slow.
If somebody please could suggest me improvements in my program to increase speed, that'd be so helpful.</p>
<p>Here's extract of main items:</p>
<pre><code>from random import choice, random
import numpy as np
import time
def left(grid):
#assumption: grid is 4 x 4 numpy matrix
l = grid.copy()
for j in range(4):
res = []
merged = False
for i in l[j]:
if i==0:continue
if res and i == res[-1] and not merged:
res[-1] += i
merged = True
else:
if res: merged = False
res.append(i)
for i in range(4 - len(res)): res.append(0)
l[j] = res
return l
def right(grid):
l = grid.copy()
for j in range(4):
res = []
merged = False
for i in range(4):
t = l[j][i]
if t == 0: continue
if res and t == res[-1] and not merged:
res[-1]+=t
merged = True
else:
if res: merged = False
res.append(t)
for i in range(4-len(res)): res = [0]+res
l[j] = res
return l
def down(grid):
l = grid.copy()
for j in range(4):
res = []
merged = False
for i in range(4):
t = l[i][j]
if t == 0: continue
if res and t == res[-1] and not merged:
res[-1]+=t
merged = True
else:
if res: merged = False
res.append(t)
for i in range(4-len(res)): res=[0]+res
l[:, j] = res
return l
def up(grid):
l = grid.copy()
for j in range(4):
res = []
merged = False
for i in range(4):
t = l[-i-1][j]
if t == 0: continue
if res and t == res[-1] and not merged:
res[-1]+=t
merged = True
else:
if res: merged = False
res.append(t)
for i in range(4-len(res)): res=[0]+res
l[:, j] = res[::-1]
return l
def c(grid, move):
if move == 2: return left(grid)
if move == 0: return up(grid)
if move == 1: return down(grid)
if move == 3: return right(grid)
def isvalid(grid):
if 0 in grid: return True
l = grid
for i in range(3):
for j in range(4):
if l[i][j] == l[i+1][j]: return True
if l[i][0] == l[i][1] or l[i][1] == l[i][2] or l[i][2] == l[i][3]: return True
i = 3
if l[i][0] == l[i][1] or l[i][1] == l[i][2] or l[i][2] == l[i][3]: return True
return False
ind = np.arange(16).reshape(4,4)
def next_play(grid, move):
#assumption: grid is 4 x 4 matrix
if move not in range(4): return grid #invalid move.
moved_grid = c(grid, move) # c moves grid by specific move "move".
moved = not (moved_grid == grid).all()
if not moved: return grid # return as it was
if 0 not in moved_grid: return moved_grid #no spawn needed
idx = choice(ind[moved_grid==0]) #randomly picked empty place's index
moved_grid[idx//4][idx%4] = 2 if random() < .9 else 4
return moved_grid
def rand_moves(data,first_move,times): #data is playing grid, numpy matrix 4 x 4
assert times >0, 'Wrong value of times'
score = 0
k = range(4)
for _ in range(times):
data1 = data.copy()
data1 = next_play(data1, first_move) #next_play moves grid & generate tile randomly on an empty place if moved
while isvalid(data1): #isvalid checks validity of grid, ie playable or not.
data1 = next_play(data1, choice(k)) #choice is random.choice func.
score+= data1.max()
return score/times
def getAvailableMoves(data):
data_list= [(c(data,i),i) for i in range(4)]
ret = []
for data1,i in data_list:
if (data1==data).all():continue
else:
ret.append(i)
return ret
def getBestMove(data, times = 10):
sc, mv = float('-inf'), None
for move in getAvailableMoves(data):
score = 0
score += rand_moves(data.copy(),move,times)
if score > sc:
sc= score
mv = move
elif score == sc:
mv = choice([mv, move]) #randomly choose one of them
return mv #if none, case handing occurs at caller side.
data = np.asarray([[2,0,0,2],
[4,4,0,2],
[32,32,2,8],
[0,0,0,2]]) #a sample grid
t1 = time.time()
print(getBestMove(data, 100))
print(time.time() - t1, 's')
</code></pre>
<p>You can run this whole program by copying it. You'll notice that its taking 2.5 to 4 seconds or more for each move decision. I need at least 100 runs in memory for deciding best move. This is really slow, since at least thousand moves or above are needed for scoring better, which is quite bad for me.</p>
<p>I don't know C++ or C language, thus can't shift in those language or make cython's use to optimize them.</p>
<p>Any suggestions or improvements would be helpful . Thanks.</p>
<p>For ease, directly <a href="https://tio.run/##nVZRb@M2DH7Pr9DO2GKjruukwbAZ8wHbw952TwX2EASFasuJrrZsSG6a/PqOpGRbidvD7tw2biiSIj9@pNSd@0Or7t/eKt02THNVwks2Xat7VhxaWYjYSRdOql6a7sy4YaobRL1sxGJRiorVourDvZZllC0YPAE3BvR72aqMoZxJwzbsBH/WT8N7LU@kW7OcVJKi7c5hRLKq1ewrkwpj2Itw49zio4UBg@1uFDRC70UJsr95bcQoRhcSXdTbr7vJHB9ZMZnnaVa0qpfqRVwv4haQO5jnOX7Z3q52JFBt77a7dOjiIr2bnMnZ4hjjg77aTkDMc2deEM7vTzlLs49y9WJIeNcJVYYymiPhwGS3UC8VgnIUZb5NOtkgaIySX1jH/YsGKBeL4Jg8bLM4yzBXFhR1Wzy/SoglOA7i5AEJANC@t0jsaKTWrRalJU9BzIlZ0x7FD/AHsEJLrNU6GyMdCXmtk851psAjLzlKISatmFEq165Wc1eTfeTBYWEafKHfa1f3H0c1OgrYgNvg6RJHaY68luW8D8X/gDBFgqDaGAhSlQUoL2XBe6CjgIqcWVfzQiyBnEcua/4ka9mfk7FrKaF3GxdXkLrYRBQj5u1qT6WPEl7X4cRBB0@ZeQH5bLQ9sID40GuXcLvn6tcoAd4eeAf7x5uIsFHi1D9C5Ofv4to7LMPo/fSGYMgwkIpKQKoWE8rg0aZ7yXSvbwNWkMxYN09nZjpRyEpaMfuEn588hwOMvnc7RX0QIWaaWATiZaDDN5jnsmev3Ew8cBlOrkdTbzcWqBaC5K8KoBUlUJDsyxNmSedHCHXZThYwb3cRC@yZUgOLZPEMeVxSCkzE6Qq2LTi9u9vs8P3zBofSmsYjOQoj9gdLfqcpyjY@OSYHtjlQ/5EwDkve87iS2vQkiPEYM1DJABew@MgTqfbMFsvvFssL2gdYI9wZaNjnNGbLf3ULRkAA6Ju2sitL0jUFdClEntK3Zxysjj9j3zxOrHLxjH2AYa3ABt/@IemvTfwmScym/AD1cdVn2S9sL5TQ0NkQai3YWJoWaKH8yoydOG77ekCLYeDQlgDg1RO4dSCEKJ4Noy8wLBAcC60UhDV/AmeAATAvuTjTPszOUew5guTs/1g3m0HiBNWLKi7dURluLJCrpOEnB6SjDC3fEfqWM3vR/2mHXC3@GanjKoP/PtbS9HAZCQtLKhnB7@y8jXbDLtPFBXVsLqQ5Osv86WezzXPa1fb1/M4yv0DARle3AJcgvMbE/hKmx5xs4I7GcKSlLj1TwJg6gqSqW96Hy1upqmUUsy@tErNh/02g5g0wSW7y68Z0BI@9zvQhsWaf4Z1dlTa3axdSSgA9eWiNTvJ85oX0Hbe2zdEO6ouxBYstjBoAgVr8IJqLoXME0uPQVXB9LjgoHsAQR0lbFC8azky4XUMdhWZGlnBCLGjk2NPLcK2B4dvtOk7hZ72LZ/c7eLZwpH1j9X4dw@86/u2D9dT5xqQ4M7zpans7WPTYaAh4gh/QGZ2WCm4iM6qs0jQaVj19uFX20JlLs4ze3v4D" rel="nofollow noreferrer">TryItOnline</a></p>
<p><strong>EDIT 1</strong></p>
<p>I tried to store solutions of vectors in dictionary since accessing is faster in dictionary, here's the code:</p>
<pre><code>import pickle
with open('ds_small.pickle', 'rb') as var:
ds = pickle.load(var) #list of dicts
d1 = ds[0] #dictionary containing left shift of all possible tuples of size 4, having elems from 0 to 2048, 2's powers
d2 = ds[1] #dictionary containing right shift of all possible tuples of size 4, having elems from 0 to 2048, 2's powers
def l(grid):
l1=grid.copy()
for i in range(4):
l1[i] = d1[tuple(l1[i])]
return l1
def r(grid):
l1 = grid.copy()
for i in range(4):
l1[i] = d2[tuple(l1[i])]
return l1
def u(grid):
l1 = grid.copy()
for i in range(4):
l1[:,i] = d1[tuple(l1[:,i])]
return l1
def d(grid):
l1 = grid.copy()
for i in range(4):
l1[:,i] = d2[tuple(l1[:,i])]
return l1
def c(grid, move):
if move == 2: return l(grid)
if move == 0: return u(grid)
if move == 1: return d(grid)
if move == 3: return r(grid)
</code></pre>
<p>Performance incremented. Time got low to 1.8 seconds per move average. But you see, its still quite slow. Suggestions please.</p>
<p><strong>Edit 2</strong>
Improved performance by .2 sec by improving <code>isvalid</code> function.</p>
<p>I tried improving <code>next_play</code> function but no success.</p>
<p><strong>Edit 3</strong></p>
<p>I tried cython here, it surely increased performance:</p>
<pre><code>from random import choice, random
import numpy as np
cimport numpy as np
import time
import pickle
cimport cython
@cython.boundscheck(False)
def left(np.ndarray grid):
#assumption: grid is 4 x 4 numpy matrix
cdef np.ndarray l = grid.copy()
cdef int j, i, p, merged;
cdef long t;
cdef list res;
for j in range(4):
res = [];
merged = 0
for i in range(4):
t = l[j][-i-1]
if t == 0: continue
if res and t == res[-1] and merged == 0:
res[-1]+=t
merged = 1
else:
if res: merged = 0
res+=[t]
for p in range(4-len(res)): res = [0]+res
l[j] = res[::-1]
return l
@cython.boundscheck(False)
def right(np.ndarray grid):
cdef np.ndarray l = grid.copy()
cdef int j, i, p, merged;
cdef long t;
cdef list res;
for j in range(4):
res = []
merged = 0
for i in range(4):
t = l[j][i]
if t == 0: continue
if res and t == res[-1] and merged == 0:
res[-1]+=t
merged = 1
else:
if res: merged = 0
res+=[t]
for p in range(4-len(res)): res = [0]+res
l[j] = res
return l
@cython.boundscheck(False)
def down(np.ndarray grid):
cdef np.ndarray l = grid.copy()
cdef int j, i, p, merged;
cdef long t;
cdef list res;
for j in range(4):
res = []
merged = 0
for i in range(4):
t = l[i][j]
if t == 0: continue
if res and t == res[-1] and merged == 0:
res[-1]+=t
merged = 1
else:
if res: merged = 0
res+=[t]
for p in range(4-len(res)): res=[0]+res
l[:, j] = res
return l
@cython.boundscheck(False)
def up(np.ndarray grid):
cdef np.ndarray l = grid.copy()
cdef int j, i, p, merged;
cdef long t;
cdef list res;
for j in range(4):
res = []
merged = 0
for i in range(4):
t = l[-i-1][j]
if t == 0: continue
if res and t == res[-1] and merged == 0:
res[-1]+=t
merged = 1
else:
if res: merged = 0
res+=[t]
for p in range(4-len(res)): res=[0]+res
l[:, j] = res[::-1]
return l
@cython.boundscheck(False)
@cython.wraparound(False)
def c(np.ndarray grid, int move):
if move == 2: return left(grid)
if move == 0: return up(grid)
if move == 1: return down(grid)
if move == 3: return right(grid)
@cython.boundscheck(False)
@cython.wraparound(False)
def isvalid(np.ndarray l):#l is grid
if 0 in l: return True
cdef int i, j;
for i in range(3):
for j in range(4):
if l[i][j] == l[i+1][j]: return True
if l[i][0] == l[i][1] or l[i][1] == l[i][2] or l[i][2] == l[i][3]: return True
i = 3
if l[i][0] == l[i][1] or l[i][1] == l[i][2] or l[i][2] == l[i][3]: return True
return False
cdef np.ndarray ind = np.arange(16).reshape(4,4)
@cython.boundscheck(False)
@cython.wraparound(False)
def next_play(np.ndarray grid, int move):
#assumption: grid is 4 x 4 matrix
if move not in range(4): return grid #invalid move.
cdef np.ndarray moved_grid = c(grid, move) # c moves grid by specific move "move".
cdef int moved = (moved_grid == grid).all()^1
if moved == 0: return grid # return as it was
cdef np.ndarray p = ind[moved_grid==0]
if len(p) == 0: return moved_grid #no spawn needed
cdef int idx = choice(p) #randomly picked empty place's index
moved_grid[idx//4][idx%4] = 2 if random() < .9 else 4
return moved_grid
@cython.boundscheck(False)
def rand_moves(np.ndarray data,int first_move,int times): #data is playing grid, numpy matrix 4 x 4
assert times >0, 'Wrong value of times'
cdef int score = 0;
k = range(4)
cdef int p,m;
cdef np.ndarray data1;
for p in range(times):
data1 = data.copy()
data1 = next_play(data1, first_move) #next_play moves grid & generate tile randomly on an empty place if moved
m = data.max()
while isvalid(data1): #isvalid checks validity of grid, ie playable or not.
data1 = next_play(data1, choice(k)) #choice is random.choice func.
m *= 1 if 2*m not in data else 2
score+= m#data1.max()
return score/times
def getAvailableMoves(np.ndarray data):
data_list= [(c(data,i),i) for i in range(4)]
ret = []
cdef int move;
for data1,move in data_list:
if (data1==data).all():continue
else:
ret.append(move)
return ret
def getMove(data, int times = 10):
cdef float sc = float('-inf')
mv = None
cdef int move;
cdef int score;
for move in getAvailableMoves(data):
score = 0
score += rand_moves(data.copy(),move,times)
if score > sc:
sc= score
mv = move
elif score == sc:
mv = choice([mv, move]) #randomly choose one of them
return mv #if none, case handing occurs at caller side.
#if __name__ == '__main__':
def do():
cdef np.ndarray data = np.asarray([[2,2,0,2],
[4,4,0,2],
[32,32,32,8],
[0,0,0,2]]) #a sample grid
print(data)
t1 = time.time()
from sys import argv
print(getMove(data, 100))#int(argv[1])))
t_time = time.time() - t1
print(t_time, 's')
return t_time
</code></pre>
<p>At this edit, the average speed is 1.35763 seconds per move for 100 runs in memory.
I immensely need atleast 5 moves per second.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T18:01:26.170",
"Id": "464468",
"Score": "2",
"body": "Not the downvoter, but have you done any profiling to determine what precisely is slowing you code down?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T18:14:56.000",
"Id": "464470",
"Score": "0",
"body": "@Brian Its sure that its all because of the game trials in each move. It needs optimization is all i know. The post i linked has js version of that algorithm, this is the link for that js version https://github.com/ronzil/2048-AI. I did see the code and saw that its roughly doing same stuff in ai.js. I think its python's slowness, but since i can't shift to other language, thus trying to see if optimization is possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:45:14.287",
"Id": "464492",
"Score": "0",
"body": "The Javascript version looks a lot different than yours, and not just because of the different language. In that version there is a set of \"prototype vectors\" to deal with the different move directions; in yours you apparently do all kinds of transformations on the entire array to set it up for just a single move."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:46:31.133",
"Id": "464496",
"Score": "0",
"body": "@DavidK I separated each move's function. Still slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:25:38.817",
"Id": "464530",
"Score": "0",
"body": "@Brian Hi, please review my edit, if you've got a minute or so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:18:28.700",
"Id": "464872",
"Score": "0",
"body": "You really need to profile your program. That's the only sane way to find out where it spends its time. Asking a changing question here is IMHO the wrong approach to this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:50:00.990",
"Id": "464925",
"Score": "0",
"body": "@uli Question isn't changing. I am just posting improvements in my algorithm so that answerer could help me in better way. The problem is same as it was in start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:44:01.180",
"Id": "465036",
"Score": "1",
"body": "@Vicrobot: Please update your question in that case. Since you have not received any answer yet, you can freely do so. At the moment it is unclear which of your three solutions should be reviewed, or should all of them be reviewed? I would suggest to pick one (maybe the most vanilla one, or maybe the fastest) and ask about that. You can ask about the other approaches in separate questions (maybe a day or so later in order to incorporate any generically applicable advice you might receive)."
}
] |
[
{
"body": "<p>A couple observations:</p>\n\n<ol>\n<li><p>Using different names for the playing grid (data, grid, l) makes it more difficult to follow the code.</p></li>\n<li><p>For the top level call <code>getMove(data, 100)</code>, let's assume the 'up' is a possible move. Then c(data, up) gets called 101 times. </p>\n\n<p><code>getMove()</code> calls <code>getAvailableMoves()</code> which calls <code>c(data, i)</code> once for each direction (but the moves are discarded).</p>\n\n<p><code>getMove()</code> then calls <code>rand_moves()</code> which calls <code>next_play(data1, first_move)</code> 100 times. And <code>next_play()</code> calls c(data, move).</p></li>\n<li><p>Move constant calculations outside of the loop. In <code>random_moves()</code>:</p>\n\n<pre><code> for p in range(times):\n data1 = data.copy()\n data1 = next_play(data1, first_move)\n m = data.max()\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code> data = next_play(data, first_move)\n m = data.max()\n for p in range(times):\n data1 = data.copy()\n ...\n</code></pre></li>\n<li><p>Extra copying. For example:</p>\n\n<p><code>getMove()</code> calls <code>rand_move()</code> with a copy of <code>data</code>:</p>\n\n<pre><code>rand_moves(data.copy(),move,times)\n</code></pre>\n\n<p><code>rand_move()</code> then makes another copy:</p>\n\n<pre><code>data1 = data.copy()\n</code></pre></li>\n<li><p><code>is_valid()</code> could use features of numpy array:</p>\n\n<p>def isvalid(np.ndarray grid):\n return ( 0 in grid\n or (grid[:3]==grid[1:]).any()\n or (grid[:,:3]==grid[:,1:]).any()\n )</p></li>\n<li><p>It might be possible to cache some of the score calculations. For example, there are many ways to arrive at a grid like:</p>\n\n<pre><code>2 4 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0\n</code></pre>\n\n<p>Figuring out a way to cache the score for that grid might save some duplicate calculations.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T16:04:40.293",
"Id": "464940",
"Score": "0",
"body": "Thanks so much for taking this deep look in there. I implemented what you said, but performance gain was 0.005 seconds only for each real move per 100 runs in memory. I had to leave my hashing of dict because those trivial left right functions are performing better due to most conversion to c types in cython. Is there any way i could use hashing in cython just like dictionary of python?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:09:25.340",
"Id": "237127",
"ParentId": "236931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T16:28:28.470",
"Id": "236931",
"Score": "2",
"Tags": [
"python",
"numpy",
"2048"
],
"Title": "AI In 2048 Game, Calculations so slow"
}
|
236931
|
<p>I'm looking for some feedback on this code I wrote tackling a general solution to the age old "Add 2 numbers represented by Linked Lists". This specific one aims to be able to sum any given number of linked lists.</p>
<p>Ofcourse, the input linked lists must contain the number in reverse order.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<time.h>
typedef struct ListNode {
// Basic Node data structure of a Linked List
int val;
struct ListNode* next;
}node_t;
void appendNode(node_t** headref, int data)
{
// Inserts node with given data
node_t* temp, * node;
node = (node_t*)malloc(sizeof(node_t));
if (node == NULL)
{
printf("An error occured while allocating memory for node in appendNode\n");
exit(1);
}
temp = (node_t*)malloc(sizeof(node_t));
if (temp == NULL)
{
printf("An error occured while allocating memory for temp in appendNode\n");
exit(1);
}
node->val = data;
node->next = NULL;
if (*headref == NULL)
{
*headref = node;
return;
}
temp = *headref;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = node;
}
void createList(node_t** headref, int data[], int length)
{
// Calls appendNode iteratively to assign whole array of data to list
for (int i = 0; i < length; i++)
{
appendNode(headref, data[i]);
}
}
void printList(node_t* headref)
{
// Basic Linked List printing
if (headref == NULL)
{
printf("\nLinked List is empty!\n");
return;
}
printf("HEAD->");
while (headref != NULL)
{
printf("%d->", headref->val);
headref = headref->next;
}
printf("NULL\n");
}
void printListArray(node_t* linkedListArray[], int length)
{
// Calls printList iteratively to print whole array of lists
for (int i = 0; i < length; i++)
{
printList(linkedListArray[i]);
}
}
void destroyList(node_t** headref)
{
node_t* nextNode, * currentNode;
nextNode = (node_t*)malloc(sizeof(node_t));
if (nextNode == NULL)
{
printf("An error occured while allocating memory for nextNode in appendNode\n");
exit(1);
}
currentNode = (node_t*)malloc(sizeof(node_t));
if (currentNode == NULL)
{
printf("An error occured while allocating memory for currentNode in appendNode\n");
exit(1);
}
if (*headref == NULL)
{
printf("\nLinked List is empty!\n");
return;
}
currentNode = *headref;
while (currentNode != NULL)
{
nextNode = currentNode->next;
free(currentNode);
currentNode = nextNode;
}
}
void destroyListArray(node_t** linkedListArray[], int length)
{
// Calls destroyList iteratively to print whole array of lists
for (int i = 0; i < length; i++)
{
destroyList(linkedListArray[i]);
}
}
bool isEnd(node_t* linkedListArray[], int length)
{
// Checks if all lists have been exhausted
int nullCount = 0;
for (int i = 0; i < length; i++)
{
if (linkedListArray[i] == NULL)
{
nullCount++;
}
}
return nullCount == length ? true : false;
}
void resvalAppend(node_t** resultList, int resultingValue, int* overflow)
{
/**
* A recursive function to keep stripping resval until it is single digit
*
* If resultingValue is a multi digit number, the other digits are stripped and put in
* overflow, which is a global variable
*
* If resultingValue is a single digit number, it gets added to the result Linked List
*/
if (resultingValue > 9)
{
*overflow = resultingValue / 10;
resvalAppend(resultList, resultingValue % 10, overflow);
}
else
{
appendNode(resultList, resultingValue);
}
}
node_t* addNumbers(node_t* linkedListArray[], int length)
{
/**
* Accepts an array of pointers to HEAD of Linked Lists
* along with the number of Linked Lists
*
* Returns a pointer to result Linked List
*/
int resultingValue = 0, overflow = 0;
node_t* resultList = NULL;
while (!isEnd(linkedListArray, length) || overflow != 0)
{
// Loop only breaks once all lists are exhausted AND overflow is 0
for (int i = 0; i < length; i++)
{
if (linkedListArray[i] != NULL)
{
// Adding in values to resval, ignoring NULL(s)
resultingValue += linkedListArray[i]->val;
linkedListArray[i] = linkedListArray[i]->next;
}
}
// Adding in overflow, if any
resultingValue += overflow;
overflow = 0;
// Putting resultingValue through the recursive function to strip overflow
resvalAppend(&resultList, resultingValue, &overflow);
resultingValue = 0;
}
return resultList;
}
void testcase()
{
// Mess with inputs here, the below code is just an example
/**
* First Declare all the Pointers to Linked Lists that you'd like to use and assign them to NULL
* Then use createList to create an entire Linked List at once instead of doing multiple appendNode
*
* createList requires the address of the pointer to HEAD, so it can modify the list
* It also needs the dataset itself, which should be an int array
* The final param is the length of this array
*
* Lastly use addNumbers and pass all the Pointers to Linked Lists in an array
* Pass in the length of the array as well
*
* You can then use printList to print the result
*
* If you'd like, you can also use printListArray and pass in the array of pointer to lists
* to print them all at once
* This may be useful to make sure the input lists were created correctly
*/
node_t* l1 = NULL, * l2 = NULL, * l3 = NULL, * l4 = NULL, * l5 = NULL, * l6 = NULL, * l7 = NULL, * l8 = NULL, * l9 = NULL, * l10 = NULL, * l11 = NULL, * l12 = NULL;
node_t* resultList;
createList(&l1, (int[]) { 9 }, 1);
createList(&l2, (int[]) { 9 }, 1);
createList(&l3, (int[]) { 9 }, 1);
createList(&l4, (int[]) { 9 }, 1);
createList(&l5, (int[]) { 9 }, 1);
createList(&l6, (int[]) { 9, 9 }, 2);
createList(&l7, (int[]) { 9, 9 }, 2);
createList(&l8, (int[]) { 9, 9 }, 2);
createList(&l9, (int[]) { 9, 9 }, 2);
createList(&l10, (int[]) { 9, 9 }, 2);
createList(&l11, (int[]) { 9, 9 }, 2);
createList(&l12, (int[]) { 9, 9 }, 2);
node_t* listArray[] = {
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12
};
printListArray(listArray, 12);
resultList = addNumbers(listArray, 12);
printList(resultList);
destroyList(&resultList);
destroyListArray((node_t** []) { &l1, &l2, &l3, &l4, &l5, &l6, &l7, &l8, &l9, &l10, &l11, &l12 }, 12);
}
int main()
{
clock_t t0 = clock();
testcase();
clock_t t1 = clock();
double time = (double) (t1 - t0) / CLOCKS_PER_SEC;
printf("Time: %f\n", time);
return 0;
}
</code></pre>
<p>The <code>testcase()</code> is where new linked lists are created and added, if you'd like to mess around with inputs, do it there!</p>
<p>Alongside the quality of the code, I'd also like feedback on speed and optimization, that's really the primary thing I'm usually concerned with. Also I've not used <code>free()</code> all that much as I was never very good with it for some reason. I'd love advice on where to use <code>free()</code> and how.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:19:35.640",
"Id": "464546",
"Score": "0",
"body": "[This question is being discussed on meta](https://codereview.meta.stackexchange.com/q/9440/52915)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:53:55.583",
"Id": "464606",
"Score": "0",
"body": "While it is true that you don't currently need the entire list of functions, you might want to create a library of functions that you could use for the future. The second thing to consider is that real code needs to be maintained because there will be feature requests."
}
] |
[
{
"body": "<p>The answer uses this structure declared in the program:</p>\n\n<pre><code>typedef struct ListNode {\n // Basic Node data structure of a Linked List\n int val;\n struct ListNode* next;\n} node_t;\n</code></pre>\n\n<h2>Symbolic Constants for Return From <code>main()</code> and <code>exit()</code></h2>\n\n<p>The program is already including <code><stdlib.h></code>. There are two system defined macros or Symbolic Constants supplied by <code><stdlib.h></code>, these are <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a>. These macros can also be using in C++ by including <code><cstdlib></code>.</p>\n\n<h2>Complexity</h2>\n\n<p>Several of the functions are too complex (do too much). One of the problems in these functions is that code is repeated, specifically the calls to <code>malloc()</code> are repeated. One basic principle in programming is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a> sometimes known as DRY code. In this case it would be better to create a function that creates a <code>node_t</code> struct.</p>\n\n<pre><code>node_t *createNode(int data, char *errorLocation) // It is ok to define this function without the string errorLocation but that limits the error message below.\n{\n node_t *newNode = malloc(sizeof(*newNode));\n if (newNode == NULL)\n {\n fprintf(stderr, \"An error occurred while allocating memory for node_t in %s\\n\", errorLocation);\n exit(EXIT_FAILURE);\n }\n\n newNode->val = data;\n newNode->next = NULL;\n\n return newNode;\n}\n</code></pre>\n\n<p>Please note that the cast to <code>node_t*</code> is not necessary because <code>malloc()</code> returns <code>void*</code>. It is also better to use the size of what the variable is pointing to, so that if the type of the variable is changed only one item needs to be changed on the line. It is better to print error messages to <code>stderr</code>, the operating system may highlight errors and error messages will be outside the flow of normal output.</p>\n\n<p>When one works with linked list there are a basic set of functions that should be created:</p>\n\n<ul>\n<li><code>node_t *createNode(int data);</code> - shown above. </li>\n<li><code>node_t *appendNode(node_t *newNode, node_t *listHead);</code> </li>\n<li><code>node_t *insertNode(node_t *newNode, node_t *listHead);</code> </li>\n<li><code>node_t *deleteNode(node_t *node, node_t *listHead);</code> </li>\n<li><code>node_t *findNode(int data, node_t *listHead);</code> </li>\n<li><code>void deleteList(node_t *listHead);</code> </li>\n</ul>\n\n<p>Using the above list of functions makes it much easier to create and manipulate linked lists.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>Here are a few examples of the functions to be created: </p>\n\n<pre><code>node_t *appendNode(node_t* newNode, node_t* listHead)\n{\n if (listHead != NULL)\n {\n node_t *head = listHead;\n while (head->next != NULL)\n {\n head = head->next;\n }\n head->next = newNode;\n return listHead;\n }\n\n return newNode;\n}\n\nnode_t *insertNode(node_t *newNode, node_t *listHead)\n{\n newNode->next = listHead;\n return newNode;\n}\n\nnode_t *createList(int data[], int length)\n{\n node_t *head = NULL;\n for (int i = 0; i < length; i++)\n {\n node_t *newNode = createNode(data[i], \"createList()\");\n head = appendNode(newNode, head);\n }\n\n return head;\n}\n</code></pre>\n\n<p>Rather than passing in a pointer to the list of items to modified, it is better for functions to return lists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:47:06.693",
"Id": "464586",
"Score": "0",
"body": "Thanks for the write up! I had 2 questions : 1) Some of the general linked lists functions (i.e `insertNode`, `deleteNode`, `findNode`) are out of the scope for this specific program and will never be used. Should they still be included?\n\n2) I noticed you mentioned there are several problems regarding complexity in the code but only listed one, could you expand on that please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:44:20.527",
"Id": "464604",
"Score": "0",
"body": "appendNode, and destroyList are both too complex. Specifically in destroyList there is no reason to `malloc()` new nodes. The test case would be much simpler if createList returned a list rather than passing in a list to be modified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:55:34.083",
"Id": "464728",
"Score": "0",
"body": "Perhaps `createNode(int data, const char *errorLocation)`? (add `const`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:25:13.040",
"Id": "237002",
"ParentId": "236932",
"Score": "5"
}
},
{
"body": "<p>There's enough to review in just the <code>appendNode()</code> function; much of this applies to the rest of the code, too.</p>\n<hr />\n<p>Don't cast the result of <code>malloc()</code> like this:</p>\n<blockquote>\n<pre><code>node = (node_t*)malloc(sizeof(node_t));\n</code></pre>\n</blockquote>\n<p>If declared properly, <code>malloc()</code> returns a <code>void*</code>; that's assignable to any pointer type. (If not declared properly, fix that first).</p>\n<p>Also, instead of making readers check the type of <code>node</code>, use it as argument to <code>sizeof</code>. Like this:</p>\n<pre><code>node = malloc(sizeof *node);\n</code></pre>\n<p>In fact, <code>node</code> is declared but not assigned in the line above. Remove that gap, so we can't accidentally add code that uses the uninitialized value:</p>\n<pre><code>node_t *const node = malloc(sizeof *node);\n</code></pre>\n<hr />\n<p>Don't write error messages to <code>stdout</code> - that's for program output. Write such messages to <code>stderr</code>, where users expect them:</p>\n<pre><code> fputs("An error occurred while allocating memory for node in appendNode\\n", stderr);\n</code></pre>\n<p>(I fixed the typo in "occurred" - that sort of thing gives a bad impression.)</p>\n<p>For larger programs, you want to <em>return</em> an indicator of failure, so the calling code can decide whether it can recover or alert the user. This is a good opportunity to return a <em>pointer to the new node</em> (or NULL on failure), so that the caller can pass that back in, and we don't have to walk the whole list every time we add a digit (that's <a href=\"https://www.joelonsoftware.com/2001/12/11/back-to-basics/\" rel=\"nofollow noreferrer\">Shlemiel the painter’s algorithm</a>).</p>\n<hr />\n<p>We point <code>temp</code> to some newly allocated memory, but then ignore that and point it somewhere else instead. That memory is now leaked, with no way to access or release it. Just remove that block.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>node_t *appendNode(node_t** headref, int data)\n{\n node_t *const node = malloc(sizeof *node);\n if (!node) {\n return node;\n }\n node->val = data;\n node->next = NULL;\n\n if (!*headref) {\n *headref = node;\n return node;\n }\n node_t *temp = *headref;\n while (temp->next) {\n temp = temp->next;\n }\n temp->next = node;\n return node;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:03:01.317",
"Id": "237009",
"ParentId": "236932",
"Score": "3"
}
},
{
"body": "<p>The description of <code>resvalAppend()</code> is beside the point to the point of being misleading: </p>\n\n<ul>\n<li>there is no source code entity <code>resval</code></li>\n<li>there is <em>one</em> recursive call, at most<br>\n(serving no purpose I can discern)</li>\n<li><code>overflow</code> no longer is a global variable</li>\n<li><em>added to the result Linked List</em> better be <em>appended</em> to avoid confusion with the arithmetic operation at hand</li>\n</ul>\n\n<p>(almost) keeping the interface:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdlib.h>\n\nint resvalAppend(node_t** digits, int value, int base)\n{\n /** \n * Append one digit of value expressed in base to *digits.\n *\n * Returns value / base\n */\n div_t split = div(value, base);\n appendNode(digits, split.rem);\n return split.quot;\n}\n…\nstatic const int BASE = 10;\n…\n // Putting resultingValue through resvalAppend() to strip overflow\n overflow = resvalAppend(&resultList, resultingValue, BASE);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:45:14.400",
"Id": "237037",
"ParentId": "236932",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>feedback on speed and optimization</p>\n</blockquote>\n\n<p><strong>O(n) to O(1).</strong></p>\n\n<p>Consider changing <code>appendNode()</code> from O(n) to O(1).</p>\n\n<p>Rather than have a link-list point to the head, let the LL point to the tail <strong>and</strong> the tail point to the head.</p>\n\n<p>To append to the end of the list or to the front is a similar O(1) operation.</p>\n\n<pre><code>// add to the end or front of the LL\nvoid addNode(node_t** ref, int data, bool end) {\n node_t* ptr = malloc(sizeof *ptr);\n if (ptr == NULL) ...\n ptr->val = data;\n if (*ref == NULL) {\n *ref = ptr;\n ptr->next = ptr;\n } else {\n ptr->next = (*ref)->next;\n (*ref)->next = ptr;\n if (end) {\n *ref = ptr;\n }\n }\n}\n</code></pre>\n\n<p>Functions that walk the list need to look for a repeat of the <code>(*ref)->next</code> rather than <code>NULL</code> to know when to stop.</p>\n\n<p>Code can pop off the front of the list in O(1). Popping off the end of the list remains O(n).</p>\n\n<hr>\n\n<p>This avoids a huge O(n) on one of the addition functions without the cost of a head <strong>and</strong> tail pointer. It provides for better distribution of activity. </p>\n\n<p>I find this approach useful when code may add to the front, add to the end and remove from just one end.</p>\n\n<hr>\n\n<p><strong>Apply rather than just print</strong></p>\n\n<p>Consider a function the passes in the LL, a function pointer and state and returns error status.</p>\n\n<pre><code>int LL_apply(node_t *ref, int (*f)(void *state, node_t *node), void *state) {\n // pseudo code\n for each `node *` in LL\n int retval = f(state, node);\n if (retval) return retval;\n }\n return 0;\n}\n</code></pre>\n\n<p>Now the print can be had with a supporting helper function <code>f</code>. </p>\n\n<p>All sorts of functions can be <em>applied</em>: search, find max, average, ..., even a simple count.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T04:32:04.393",
"Id": "237041",
"ParentId": "236932",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237002",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T16:52:31.503",
"Id": "236932",
"Score": "3",
"Tags": [
"algorithm",
"c",
"linked-list"
],
"Title": "A general case of Adding numbers represented by Linked List"
}
|
236932
|
<p>I wrote a simple algorithm to encrypt and decrypt files in Python using aes-256-cbc.</p>
<pre><code>from Crypto import Random
from Crypto.Cipher import AES
import base64
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key, key_size=256):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
plaintext = base64.b64encode(plaintext)
print(plaintext)
enc = encrypt(plaintext, key)
with open("file.txt" + ".enc", 'wb') as fo:
fo.write(enc)
def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(ciphertext, key)
dec = base64.b64decode(dec)
with open(file_name[:-4]+ ".dec", 'wb') as fo:
fo.write(dec)
return dec.decode()
key = b'1234sfsfdsafasdf'
encrypt_file('file.txt', key)
decrypt_file('file.txt.enc', key)
</code></pre>
<p>However, I am definitely not a cryptography expert and I suppose my code may be missing something.</p>
<p>Is it safe to use this code for encryption of my files and what could be improved in this algorithm?</p>
<p>Also what do you think about <a href="https://cryptography.io/en/latest/hazmat/primitives/aead/#cryptography.hazmat.primitives.ciphers.aead.AESGCM" rel="nofollow noreferrer">This Implementation</a>, is it secure and could be used in production? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:08:33.630",
"Id": "464476",
"Score": "0",
"body": "`I wrote a simple algorithm to encrypt and decrypt files in Python using aes-256-cbc` if you manage to decrypt AES without following it to the letter, you may have broken it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:21:49.843",
"Id": "464477",
"Score": "0",
"body": "Why is `key_size=256` a default parameter in `encrypt` when you don't even use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T19:29:45.980",
"Id": "464479",
"Score": "0",
"body": "@Linny This parameter was used in example on PyCrypto wiki, so I thought I would leave it there, but it is true, it doesn't do much"
}
] |
[
{
"body": "<pre><code>def pad(s):\n return s + b\"\\0\" * (AES.block_size - len(s) % AES.block_size)\n</code></pre>\n\n<p>Generally a good library should have you covered when it comes to padding and unpadding. Prefer the Python 3 <code>bytearray</code> types rather than the stringified <code>b\"\\0\"</code> trick.</p>\n\n<p>Worse, you're implementing Zero padding, which would strip off zero valued bytes from your text files. That may not harm text files much (well, unless UTF-16LE I suppose), but for binary files that's very very dangerous.</p>\n\n<p>Everybody tends to use PKCS#7 compatible padding for CBC mode.</p>\n\n<pre><code>def encrypt(message, key, key_size=256):\n</code></pre>\n\n<p>The key size is usually required for C-style languages but not here. You're already giving it a key, and the key has a certain size. The only thing you can do is to test the key against the key size if you're (overly) afraid that you might pass a 128 bit / 16 byte key by accident. But in general you should not pass parameters that can be derived from other parameters anyway.</p>\n\n<pre><code> message = pad(message)\n</code></pre>\n\n<p>This creates a copy of the message. Now that's all right for small messages, but for files over 4 GiB it becomes \"a bit of a nuisance\". Especially if you decide to use your logical cores to encrypt many files. In theory AES/CBC pads the messages, but in practice we only pad the last 16 byte block that we need to encrypt.</p>\n\n<pre><code> iv = Random.new().read(AES.block_size)\n</code></pre>\n\n<p>It's not all gloom and doom, you used a cryptographic random number generator to generate an unpredictable IV and you used <code>AES.block_size</code> instead of <code>16</code>. And then prefixed it to the ciphertext. Well done!</p>\n\n<pre><code> return plaintext.rstrip(b\"\\0\")\n</code></pre>\n\n<p>And there's the Zero padding problem being executed. If you have a file consisting of all zero's, it would empty entirely. Oops!</p>\n\n<pre><code> plaintext = base64.b64encode(plaintext)\n</code></pre>\n\n<p>Ah yes, that saves us from the padding problem, as base 64 doesn't contain zero valued bytes. The disadvantage is of course that your ciphertext will now expand 33%, and that you create <strong>another</strong> copy in memory for that size. Sure, the raw plaintext can now be freed up, but your system will still not be happy with you.</p>\n\n<pre><code> with open(\"file.txt\" + \".enc\", 'wb') as fo:\n</code></pre>\n\n<p>The <code>\"file.txt\"</code> name is a bit out of wag with the <code>'wb'</code> flag, don't you thing? And besides, although you base 64 encoded your plaintext, you didn't do it with the ciphertext. And you should not need to, just keeping everything in binary is fine for files.</p>\n\n<p>Besides that, you probably should do something with a <code>filename</code> parameter. At least create a note to fix things later when you're experimenting.</p>\n\n<pre><code> with open(file_name[:-4]+ \".dec\", 'wb') as fo:\n</code></pre>\n\n<p>Ah, we just replace the last 4 characters now, without checking if the filename even <em>has</em> an extension?</p>\n\n<pre><code> return dec.decode()\n</code></pre>\n\n<p>What, why? And what are we decoding?</p>\n\n<pre><code>key = b'1234sfsfdsafasdf'\n</code></pre>\n\n<p>Strings are not keys. If you want to create a test key, create one by decoding hexadecimal encoded bytes. And those look like 16 characters which means AES-128 rather than 256. If you want to use a password, you need a password based key derivation function (to perform so called Password Based Encryption, see the PKCS#5 standard).</p>\n\n<hr>\n\n<p>CBC mode is fine for keeping files confidential, but generally cryptographers prefer authenticated modes such as GCM or EAX nowadays. Your files <em>are</em> likely kept confidential, but there is no message integrity or authenticity implemented for the files. Note that CBC mode is entirely unsuitable to send unauthenticated messages over a network.</p>\n\n<p>Files can be large, so generally we try and use an API that provides <code>update</code> and <code>final</code> methods or a streaming API (not to be confused with the <code>update</code> method specified for pycryptodome's AEAD ciphers). That way you can encrypt files piecemeal.</p>\n\n<p>Quite often for files it makes sense to use a specific container format such as CMS or PGP. In that case most of your errors are avoided (although, truth to be said, many container formats are starting to show their age).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:21:18.387",
"Id": "464484",
"Score": "0",
"body": "Thank you very much, that was really helphul. Since you mentioned GSM mode, what's your opinion about [this implementation](https://cryptography.io/en/latest/hazmat/primitives/aead/#cryptography.hazmat.primitives.ciphers.aead.AESGCM)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:39:41.577",
"Id": "464488",
"Score": "0",
"body": "**GCM** mode. Uh, it's not really an implementation but a demo. I don't see any particular errors in it. The HazMat guys did seem to know a bit about how to use cryptography - but I don't know if there are any implementation mistakes. Biggest issue with it is that I don't see any way of encrypting chunk-by-chunk through update / final mechanism, which makes it unsuitable at least for big files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:05:38.510",
"Id": "236938",
"ParentId": "236935",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236938",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T18:59:03.267",
"Id": "236935",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"aes",
"base64"
],
"Title": "AES-256-CBC encrypt and decrypt files in Python"
}
|
236935
|
<p>Can someone help me how to speed up this scraping process getting all the usernames from the # 'cats' on instagram. My goal is to make this as fast as possible because currently the process is kinda slow. Maybe using multithreading? </p>
<pre><code>from instaloader import Instaloader
HASHTAG = 'cats'
loader = Instaloader(sleep=False)
users = []
for post in loader.get_hashtag_posts(HASHTAG):
if post.owner_username not in users:
users.append(post.owner_username)
print(post.owner_username)
</code></pre>
<hr>
<p>The following is a profiling run, ordered by: cumulative time.</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
331/1 0.002 0.000 18.736 18.736 {built-in method builtins.exec}
1 0.001 0.001 18.736 18.736 GetUsernamesFromHashtags.py:1(<module>)
36 0.001 0.000 18.468 0.513 instaloadercontext.py:354(get_json)
36 0.000 0.000 18.453 0.513 sessions.py:528(get)
36 0.001 0.000 18.452 0.513 sessions.py:457(request)
36 0.001 0.000 18.368 0.510 sessions.py:608(send)
36 0.001 0.000 18.126 0.504 adapters.py:394(send)
36 0.001 0.000 18.009 0.500 connectionpool.py:446(urlopen)
492 0.001 0.000 18.002 0.037 socket.py:575(readinto)
492 0.001 0.000 18.000 0.037 pyopenssl.py:295(recv_into)
492 0.002 0.000 17.999 0.037 SSL.py:1795(recv_into)
492 17.994 0.037 17.994 0.037 {built-in method _openssl.SSL_read}
36 0.001 0.000 17.993 0.500 connectionpool.py:319(_make_request)
36 0.000 0.000 17.912 0.498 client.py:1292(getresponse)
36 0.001 0.000 17.911 0.498 client.py:299(begin)
2521 0.002 0.000 17.872 0.007 {method 'readline' of '_io.BufferedReader' objects}
36 0.001 0.000 17.860 0.496 client.py:266(_read_status)
35 0.000 0.000 17.134 0.490 structures.py:180(owner_username)
35 0.000 0.000 17.134 0.490 structures.py:165(owner_profile)
35 0.000 0.000 17.133 0.490 structures.py:141(_full_metadata)
35 0.001 0.000 17.133 0.490 structures.py:132(_obtain_metadata)
36 0.000 0.000 1.336 0.037 instaloader.py:835(get_hashtag_posts)
</code></pre>
|
[] |
[
{
"body": "<p>You probably won't be able to do much to speed up <code>get_hashtag_posts</code> since that's an API call; if you try to hammer it by running multiple queries in parallel, a well-designed API will interpret that as a DDOS attack and rate-limit you.</p>\n\n<p>As far as your code goes, though, you should be using a set instead of a list, since sets are optimized for the exact thing you're doing:</p>\n\n<pre><code>from typing import Set\n\n\nusers: Set[str] = set()\nfor post in loader.get_hashtag_posts(HASHTAG):\n users.add(post.owner_username)\n</code></pre>\n\n<p>This should be a constant-time operation, whereas a list will take longer to search the longer it is (linear-time).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:32:28.803",
"Id": "464490",
"Score": "1",
"body": "NameError: name 'Set' is not defined. how can I fix that? (sry I'm new to python)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:04:25.157",
"Id": "464494",
"Score": "0",
"body": "`from typing import Set` (at the top of the file)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:11:16.070",
"Id": "236940",
"ParentId": "236937",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236940",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:01:38.807",
"Id": "236937",
"Score": "-1",
"Tags": [
"python",
"performance",
"multithreading",
"web-scraping"
],
"Title": "Instagram Scraper running to slow"
}
|
236937
|
<p>Hey I am in the process of making this game, please could I get any feedback on how to further approach this, as I find it kind of inefficient. </p>
<pre><code>import pygame
import time
pygame.init()
#Creating the Pygame window
X = 500
Y = 500
win = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Last to Pick')
width = 65
height = 80
vel = 10
#Colors to Use
cool_blue = (20, 50, 70)
black = (0,0,0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 128)
bright_red = (255,0,0)
bright_green = (0,255,0)
#1st Row
A1 = pygame.Rect(180, 150, width, height)
A2 = pygame.Rect(260, 150, width, height)
#2nd Row
B1 = pygame.Rect(140, 250, width, height)
B2 = pygame.Rect(220, 250, width, height)
B3 = pygame.Rect(300, 250, width, height)
#3rd Row
C1 = pygame.Rect(60, 350, width, height)
C2 = pygame.Rect(140, 350, width, height)
C3 = pygame.Rect(220, 350, width, height)
C4 = pygame.Rect(300, 350, width, height)
C5 = pygame.Rect(380, 350, width, height)
cards = [ [A1, red], [A2, red], [B1, red], [B2, red], [B3, red], [C1, red], [C2, red], [C3, red], [C4, red], [C5, red] ]
bot_turn_first = False
bot_turn = False
player_turn = False
player_turn_finsihed = False
"GENERAL GAME FUNCTIONS"
def text_objects(text, font, color):
text_surface = font.render(text, True, color)
return text_surface, text_surface.get_rect()
def msg_to_display(text):
largeTEXT = pygame.font.Font('freesansbold.ttf',55)
TextSurf, TextRect = text_objects(text, largeTEXT, black)
TextRect.center = ((X/2),(Y/2))
win.blit(TextSurf, TextRect)
pygame.display.update()
def game_ended():
msg_to_display('Game has Ended, Click Here to Try Again.')
def button(mouse,msg,x,y,w,h,ic,ac,action=None):
click = pygame.mouse.get_pressed()
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(win, ac,(x,y,w,h))
if (click[0] or click[1] or click[2]) == 1 and action != None:
action()
else:
pygame.draw.rect(win, ic,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText, white)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
win.blit(textSurf, textRect)
"GENERAL GAME FUNCTIONS END"
def quit_box():
pygame.quit()
def intro_screen():
run = True
while run:
win.fill(cool_blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse = pygame.mouse.get_pos()
font = pygame.font.Font('freesansbold.ttf', 50)
text = font.render('The Last To Pick', True, green, cool_blue)
textRect = text.get_rect()
textRect.center = (250, 200)
win.blit(text, textRect)
button(mouse,'Start', 110, 350, 90, 50, black, green, start_loop)
button(mouse,'Options', 220, 350, 90, 50, black, blue)
button(mouse,'Quit', 330, 350, 90, 50, black, red, quit_box)
pygame.display.update()
def bot_playing():
msg_to_display('I get the first move')
print('I get the first move')
bot_start_loop()
def player_playing():
msg_to_display('You get the first move')
print('You get the first move')
player_start_loop()
def checking_player_turn():
global player_turn
if player_turn == True:
pass#playerturn()
def start_loop():
run = True
while run:
win.fill(cool_blue)
#when 'x' is clicked game loop will quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse2 = pygame.mouse.get_pos()
button(mouse2, 'Bot can start', 300, 0, 200, 50, black, blue, bot_playing)
button(mouse2, 'I want to start', 300, 60, 200, 50, black, blue, player_playing)
for rect, color in cards:
pygame.draw.rect(win, color, rect)
pygame.display.update()
def bot_start_loop():
cards_bot1 = [
[A1, red],
[A2, red],
#2nd Row
[B1, red],
[B2, red],
[B3, red],
#3rd Row
[C1, red],
]
run = True
while run:
win.fill(cool_blue)
#when 'x' is clicked game loop will quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse3 = pygame.mouse.get_pos()
button(mouse3, 'I finshed my turn', 300, 0, 200, 50, black, blue)
for rect, color, in cards_bot1:
pygame.draw.rect(win, color, rect)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
for rect, color in cards:
if rect.collidepoint(pos):
print('Player has selected card' + str(rect))
selected_cards_turn1 = []
def player_start_loop():
global selected_cards_turn1
run = True
while run:
win.fill(cool_blue)
#when 'x' is clicked game loop will quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse3 = pygame.mouse.get_pos()
button(mouse3, 'I finshed my turn', 300, 0, 200, 50, black, blue, card_remover)
for rect, color in cards:
pygame.draw.rect(win, color, rect)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
for rect, color in cards:
if rect.collidepoint(pos):
print('Player has selected card' + str(rect))
nrect = str(rect)
selected_cards_turn1.append(nrect)
def card_remover():
global selected_cards_turn1
print('Selected cards' + str(selected_cards_turn1))
for element in selected_cards_turn1:
if element == '<rect(180, 150, 65, 80)>':#A1
exterminate(element, 0)
if element == '<rect(260, 150, 65, 80)>':#A2
exterminate(element, 1)
if element == '<rect(140, 250, 65, 80)>':#B1
exterminate(element, 2)
if element == '<rect(220, 250, 65, 80)>':#B2
exterminate(element, 3)
if element == '<rect(300, 250, 65, 80)>':#B3
exterminate(element, 4)
if element == '<rect(60, 350, 65, 80)>':#C1
exterminate(element, 5)
if element == '<rect(140, 350, 65, 80)>':#C2
exterminate(element, 6)
if element == '<rect(220, 350, 65, 80)>':#C3
exterminate(element, 7)
if element == '<rect(300, 350, 65, 80)>':#C4
exterminate(element, 8)
if element == '<rect(380, 350, 65, 80)>':#C5
exterminate(element, 9)
def new_loop(new_card_list):
run = True
while run:
win.fill(cool_blue)
#when 'x' is clicked game loop will quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEMOTION:
mouse4 = pygame.mouse.get_pos()
button(mouse4, 'I finshed my turn', 300, 0, 200, 50, black, blue, card_remover)
for rect, color in new_card_list:
pygame.draw.rect(win, color, rect)
pygame.display.update()
def exterminate(cards1, ele):
cards11 = str(cards1) + ', (255, 0, 0)'
list(cards11)
print("""
""")
new_set_of_cards = cards.copy(); del new_set_of_cards[ele]
#new_set_of_cards = [ments for ments in cards if ments != cards11]
print('Drawing this cards: ' + str(cards11))
print('New Set of Cards' + str(new_set_of_cards))
new_loop(new_set_of_cards)
intro_screen()
pygame.quit()
</code></pre>
<p>Thank you!!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:06:25.333",
"Id": "464879",
"Score": "0",
"body": "Actually I'm stuck on the main screen with the three buttons. Mouse clicks don't trigger anything, and I've got just \"(0, 0, 0)\" spammed in the console."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:18:40.443",
"Id": "464880",
"Score": "0",
"body": "I don't know PyGame library, but I've just understand why I can't click on any buttons: you check for clicks only in the MOUSEMOTION event... So, clicking while moving the mouse works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:29:07.653",
"Id": "464962",
"Score": "0",
"body": "@VincentRG Yes on the start screen for the buttons to 'work' you have to be holding down the mouse click on the button. I don't know why it is this way but it is the closest I got to an actual button..."
}
] |
[
{
"body": "<p>Here are a few things that stand out to me:</p>\n\n<h1>Unused import</h1>\n\n<p>You <code>import time</code> but don't use it in your code. It should be removed</p>\n\n<h1>Style</h1>\n\n<p>You should adhere to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> style guide. This guide may seem a little superfluous, but having a consistent style makes your code easier to work with should you modify it and having your code follow the same style guide as mostly all python code makes it easier to review.</p>\n\n<p>Constants should be in capitals, so your colors should be called <code>COOL_BLUE</code>, <code>BLACK</code>, etc.</p>\n\n<p>Top level functions should be surrounded by 2 blank lines. In your code, they are surrounded with 1 to 3 blank lines.</p>\n\n<p>Also, you use random strings (<code>\"GENERAL GAME FUNCTIONS\"</code>) as... comments? Something else? Don't do that, it makes no sense.</p>\n\n<h1>Documentation</h1>\n\n<p>Your code uses some comments that makes it a bit easier to follow, but doesn't include any docstring. Docstrings should document everything your function does (which should be only one thing), what are the arguments it takes and their purposes, and what it returns, so anyone using it (including yourself in the future) can know what it does without working out the logic of the code. </p>\n\n<h1>Code layout</h1>\n\n<p>Your code has some executed statements, then function definitions with some executed statements between some of them, then some more executed statements. It makes it hard to read and follow the logic. Put every statement shat should be executed together, preferably at the end, preferably behind an <code>if __name__ = '__main__':</code> guard (except for the constants)</p>\n\n<h1>Globals</h1>\n\n<p>You use global variables. This is considered to be bad practice, as it makes your logic harder to follow and error prone (it is quite easy to forget that a global was modified in another part of the code). Instead, pass the relevant values as arguments.</p>\n\n<h1>Separation of concerns</h1>\n\n<p>Your code mixes the game logic and its representation with Pygame. It makes the logic flow hard to follow. Instead, you should ensure your game can run independently, and call it with whatever you use for I/O (Pygame for now, but you may want to switch to something else or debug the game in the terminal).</p>\n\n<p>Encapsulating the game logic in a class is probably the way to go.</p>\n\n<h1>Lack of flexibility</h1>\n\n<p>Your nim game has 3 rows of respectively 2, 3 and 5 items, each stored in its own, hardcoded variable. However, there are a lot of variants for the game. The first picture on the <a href=\"https://en.wikipedia.org/wiki/Nim\" rel=\"nofollow noreferrer\">Wikipedia page</a> shows a game with 4 rows of 1, 3, 5 and 7 items. In fact, you could play the game with any number of rows, containing each any number of item. </p>\n\n<p>A list of list to contain these game objects would be much more flexible, and the number of items per row should be passed as parameters to the game class's <code>__init__()</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:33:44.040",
"Id": "464964",
"Score": "0",
"body": "Thanks a lot for the input, will try and adjust it accordingly. A few things to mention, I use global variable cause I could not find a way to pass the `selected_cards_turn1p` into `card_remover()`. As `card_remover()` is being called within a function itself and doesn't work when I give it a parameter. \n\nYou mention that i should use a class for the cards, how would I make/put this in the code??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:56:16.097",
"Id": "465045",
"Score": "0",
"body": "@RutvikKarupothula I didn't mean you should make a class card. In fact, only the number of cards in each rows is required to represent the game. For graphical representation purposes, you may want to keep track of exactly which cards were removed, in which case a list of booleans would be enough. Either way, a class for cards would be overkill IMO. I meant however that you should encapsulate the game core in its own class, and have the Pygame representation refer to an instance of that class. It also allows you to use attributes in basically the same way as you currently use globals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:58:58.617",
"Id": "465046",
"Score": "0",
"body": "Ahhh that makes sense, I will try to do that. I am quite new to python and stuff so it might not work, i'll let you know when I update it... thx"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:37:54.550",
"Id": "237131",
"ParentId": "236941",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237131",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:15:50.490",
"Id": "236941",
"Score": "0",
"Tags": [
"python",
"pygame"
],
"Title": "Nim in Pygame (Feedback plz)"
}
|
236941
|
<p>I've made an iteration of the text game Hunt The Wumpus. The specification came from the text <em>Programming Principles and Practice Using C++</em> by Bjarne Stroustrup.</p>
<blockquote>
<p>Implement a version of the game "Hunt the Wumpus". Hunt the Wumpus" (or just "Wump") is a simple (non-graphically) computer game originally invented by Gregory Yob. The basic premise is that a rather smelly monster lives in a dark cave consisting of connected rooms. Your job is to slay the wumpus using bow and arrow. In addition to the wumpus, the cave has two hazards: bottomless pits and giant bats. If you enter a room with a bat, the bat picks you up and drops you into another room. If you enter a room with a bottomless pit, its the end of the game for you. If you enter the room with the Wumpus he eats you. When you enter a room you will be told if a hazard is nearby:</p>
<p>"I smell the wumpus": It´s in an adjoining room.
"I feel a breeze": One of the adjoining rooms is a bottomless pit.
"I hear a bat": A giant bat is in an adjoining room.</p>
<p>For your convenience, rooms are numbered. Every room is connected by tunnels to three other rooms. When entering a room, you are told something like " You are in room 12; there are tunnels to rooms 1,13, and 4: move or shoot?" Possible answers are m13 ("Move to room 13") and s13-4-3 ("Shoot an arrow through rooms 13,4, and 3"). The range of an arrow is three rooms. At the start of the game, you have five arrows. The snag about shooting is that it wakes up the wumpus and he moves to a room adjoining the one he was in - that could be your room. Be sure to have a way to produce a debug output of the state of the cave.</p>
</blockquote>
<p>New to using pointers and containers of pointers - would love feedback on my limited use of them to keep track of connections between rooms!</p>
<p>Looking to improve whatever I can - all feedback is welcome!</p>
<pre><code>#include <iostream>
#include <vector>
#include <limits>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ GLOBAL VARIABLES ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
constexpr int max_connections = 3;
constexpr int num_rooms = 16;
constexpr int num_bats = 2;
int num_arrows = 5;
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ROOM ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
struct Room {
// holds an occupant. carries a vector of pointers ("connections") to 3 other rooms.
Room(int rn)
: rn{ rn }, occ{ EMPTY } { }
enum Occupant { EMPTY, BAT, PIT, WUMPUS };
bool needs_connections() { return (connections.size() < max_connections); }
bool is_connected_to(int);
void add_connection(Room* r) { connections.push_back(r); }
bool is_empty() { return (occ == EMPTY); }
void set_occupant(Occupant o) { occ = o; }
Occupant display();
int rn;
Occupant occ;
std::vector<Room*> connections;
};
bool Room::is_connected_to(int i)
// returns whether this room is connected to another one, specified by an int
{
for (Room* connection : connections)
if (connection->rn == i) return true;
return false;
}
bool all_rooms_conneted(std::vector<Room> rooms)
// runs through a vector of rooms and returns whether they're all connected
{
for (int i = 0; i < rooms.size(); ++i)
if (rooms[i].connections.size() < 3) return false;
return true;
}
Room::Occupant Room::display()
{
std::cout << "You are in room " << rn << std::endl;
// Current Occupants
if (occ == BAT) {
std::cout << "There's a bat in here!" << std::endl;
return BAT;
}
else if (occ == PIT) {
std::cout << "There's a pit in here!" << std::endl;
return PIT;
}
else if (occ == WUMPUS) {
std::cout << "There's a wumpus in here!" << std::endl;
return WUMPUS;
}
else if (occ == EMPTY) {
std::cout << "The room is empty." << std::endl;
std::cout << "It is connected to rooms ";
for (Room* connection : connections)
std::cout << connection->rn << " ";
std::cout << std::endl << std::endl;
// Neighboring
for (Room* r : connections)
{
if (r->occ == BAT)
std::cout << "There's a bat nearby!" << std::endl;
if (r->occ == PIT)
std::cout << "There's a pit nearby!" << std::endl;
if (r->occ == WUMPUS)
std::cout << "There's a wumpus nearby!" << std::endl;
}
std::cout << std::endl;
std::cout << "You have " << num_arrows << " arrows." << std::endl;
std::cout << std::endl;
return EMPTY;
}
}
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ CAVE ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
struct Cave {
// holds and connects a group of rooms
Cave(int);
void populate(Room::Occupant, int);
int find_empty_room();
int find_location_of(Room::Occupant);
void move_the_wumpus();
void display_debug();
std::vector<Room> rooms;
};
void Cave::populate(Room::Occupant o, int population)
{
for (int i = 0; i < population; ++i)
{
int room_num;
while (true)
{
room_num = rand() % rooms.size();
if (rooms[room_num].is_empty()) break;
}
rooms[room_num].set_occupant(o);
}
}
Cave::Cave(int number_of_rooms)
// Constructor
{
// Generate rooms
for (int i = 0; i < number_of_rooms; ++i)
{
Room r(i);
rooms.push_back(r);
}
// Connect rooms
while (!all_rooms_conneted(rooms))
{
for (int this_room = 0; this_room < rooms.size(); ++this_room) // cycle through all rooms
{
if (rooms[this_room].needs_connections()) // if this room still needs connections
{
int connection = 0;
while (true) // try until an appropriate room is found
{
connection = rand() % number_of_rooms;
if (this_room == connection) continue;
if (rooms[connection].connections.size() == max_connections) continue;
if (rooms[this_room].is_connected_to(connection)) continue;
break;
}
rooms[this_room].add_connection(&rooms[connection]);
rooms[connection].add_connection(&rooms[this_room]);
}
}
}
// Populate with entities
populate(Room::Occupant::BAT, 2);
populate(Room::Occupant::PIT, 2);
populate(Room::Occupant::WUMPUS, 1);
}
int Cave::find_empty_room()
{
int empty_room = 0;
while (true)
{
empty_room = rand() % num_rooms;
if (rooms[empty_room].occ == Room::Occupant::BAT
|| rooms[empty_room].occ == Room::Occupant::PIT
|| rooms[empty_room].occ == Room::Occupant::WUMPUS) continue;
break;
}
return empty_room;
}
int Cave::find_location_of(Room::Occupant o)
{
int result;
for (int i = 0; i < rooms.size(); ++i)
if (rooms[i].occ == o) return i;
return -1;
}
void Cave::move_the_wumpus()
{
// move the wumpus
int wumpus_location = find_location_of(Room::Occupant::WUMPUS);
int new_room = -1;
while (true)
{
new_room = find_empty_room();
if (new_room != wumpus_location) break;
}
rooms[wumpus_location].set_occupant(Room::Occupant::EMPTY);
rooms[new_room].set_occupant(Room::Occupant::WUMPUS);
}
void Cave::display_debug()
{
for (int i = 0; i < rooms.size(); ++i)
{
std::cout << "Room " << i << ": ";
if (rooms[i].occ == Room::Occupant::WUMPUS) std::cout << "WUMPUS" << std::endl;
else if (rooms[i].occ == Room::Occupant::BAT) std::cout << "BAT" << std::endl;
else if (rooms[i].occ == Room::Occupant::PIT) std::cout << "PIT" << std::endl;
else std::cout << std::endl;
}
}
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ TURN ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
std::string make_lower(std::string str)
// return a lowercase version of a string
{
std::string result;
for (int i = 0; i < str.length(); ++i)
result += tolower(str[i]);
return result;
}
bool compare(std::string input, std::initializer_list<std::string> list)
// compares a string, made lowercase, to other strings. return true if it matches any of them.
{
std::string str = make_lower(input);
bool result = false;
for (std::string s : list)
{
if (str == s) result = true;
}
return result;
}
void putback_string(std::istream& is, std::string s)
// puts a string back into an input stream
{
for (char c : s)
is.putback(c);
}
struct Turn
{
Turn() // Parse Player Input
{
std::string input;
std::getline(std::cin, input);
std::istringstream is{ input };
std::string first_word;
is >> first_word;
if (compare(first_word, { "m", "move", "g", "go", "goto", "t", "travel" })) move = 'm';
if (compare(first_word, { "f", "fire", "s", "shoot", "a", "arrow" })) move = 'f';
if (compare(first_word, { "d", "debug" })) move = 'd';
for (char c; is >> c;)
{
if (c == '-') continue;
if (isdigit(c))
{
is.putback(c);
int i;
is >> i;
targets.push_back(i);
}
}
std::cout << std::endl;
}
char move = ' ';
std::vector<int> targets;
};
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ GAME LOOP ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
int main()
{
srand(time(NULL));
while (true)
{
Cave c(num_rooms);
// pick appropriate starting room
int current_room = c.find_empty_room();
// game loop
bool gameon = true;
while (gameon)
{
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ display ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
Room::Occupant current_occupant = c.rooms[current_room].display();
// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ game logic ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
if (num_arrows == 0)
{
std::cout << "You ran out of arrows! Now you can't defeat the wumpus!" << std::endl;
break;
}
else if (current_occupant == Room::Occupant::EMPTY)
{
Turn player_turn;
// MOVE
if (player_turn.move == 'm')
{
if (c.rooms[current_room].is_connected_to(player_turn.targets[0]))
{
current_room = player_turn.targets[0];
std::cout << "Moving to room " << player_turn.targets[0] << std::endl;
}
else
std::cout << "This room isn't connected to that one." << std::endl;
}
// FIRE ARROW
else if (player_turn.move == 'f')
{
for (int target : player_turn.targets)
{
if (c.rooms[current_room].is_connected_to(target))
{
std::cout << "You fired an arrow into room " << target << std::endl;
if (c.rooms[target].occ == Room::Occupant::WUMPUS)
{
std::cout << "You hit the wumpus! You win!" << std::endl;
std::cout << std::endl;
gameon = false;
break;
}
else
{
std::cout << "The arrow flew off into the dark, hitting nothing." << std::endl;
std::cout << std::endl;
c.move_the_wumpus();
std::cout << "The sound of the arrow stirred the wumpus from its sleep!" << std::endl;
std::cout << "The wumpus has moved to a new room!" << std::endl;
std::cout << std::endl;
--num_arrows;
}
}
else
std::cout << "This room isn't connected to that one." << std::endl;
}
}
// DEBUG
else if (player_turn.move == 'd')
{
c.display_debug();
}
}
// EVENT
else if (current_occupant == Room::Occupant::BAT)
{
std::cout << "You were picked up by the bat!" << std::endl;
current_room = c.find_empty_room();
std::cout << "It picked you up and flew you to room " << current_room << "!" << std::endl;
}
else if (current_occupant == Room::Occupant::WUMPUS)
{
std::cout << "The wumpus ate you!! Ahh!" << std::endl;
gameon = false;
}
else if (current_occupant == Room::Occupant::PIT)
{
std::cout << "You fell into the pit!" << std::endl;
gameon = false;
}
system("PAUSE");
system("CLS");
}
std::cout << "Game Over" << std::endl;
std::cin.get();
std::cout << "Play again? (y/n): ";
char input;
std::cin >> input;
if (input == 'n') break;
system("CLS");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Many of the member functions of <code>Room</code> can be <code>const</code> since they don't modify the object data (e.g., <code>bool needs_connections() const</code>).</p>\n\n<p><code>all_rooms_conneted</code> (which has a typo in the name) should take its parameter by <code>const std::vector<Room> &rooms</code> to avoid making a copy of the vector. Likewise for <code>compare</code> with its <code>list</code> parameter. <code>compare</code> can simply short circuit with <code>return true</code> rather than using <code>result</code>.</p>\n\n<p>In <code>Room::display</code>, you have a series of <code>if () { return; } else if () { return; } else</code> statements that could do without the <code>else</code>. And since the conditions are checking one variable for certain values, you could use a <code>switch</code>. In addition, if <code>occ</code> is not one of the four values you check for, you don't return a value from this function resulting in Undefined Behavior. If you compile with the warning level cranked up you should get a warning from the compiler for this.</p>\n\n<p><code>Cave::population</code> can potentially end up in an infinite loop if the initial value for <code>population</code> is too large and all rooms get populated while still needing to add more.</p>\n\n<p>When initializing <code>rooms</code> in the <code>Cave</code> constructor, you can use <code>rooms.emplace_back(i);</code> instead of creating a temporary room and copying it in.</p>\n\n<p>The loop in <code>Cave::move_the_wumpus</code> can be rewritten using a <code>do</code>/<code>while</code> loop:</p>\n\n<pre><code>do {\n new_room = find_empty_room();\n} while (new_room != wumpus_location);\n</code></pre>\n\n<p><code>putback_string</code> is flawed. You can only put back one character, and the putback will fail on an input-only stream.</p>\n\n<p>In the <code>Turn</code> constructor, you can avoid using <code>is.putback</code> of a single character (known to be a digit) by replacing those four lines with <code>targets.push_back(c - '0');</code>.</p>\n\n<p>There are better random number sources in the <code><random></code> header that you should look in to.</p>\n\n<p>In <code>main</code>, you can again replace a series of <code>if</code>/<code>else</code> with a switch on <code>current_occupant</code>.</p>\n\n<p>You use <code>gameon</code> in some instances to end the game, but in another use a <code>break</code>. You should stick one for consistency. Also, rather than <code>bool gameon = true; while (gameon)</code>, you can use a <code>bool gameon = true; do { ... } while (gameon);</code> loop.</p>\n\n<p>Calling <code>system(\"PAUSE\");</code> is a bit nonportable. You can print a message and get a character, or just ask the player for their next move. The clear screen (again, using a system call) is unnecessary. Text games have a long history of being scrolling windows.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:39:45.707",
"Id": "236948",
"ParentId": "236942",
"Score": "10"
}
},
{
"body": "<h1>Legacy C-style headers</h1>\n\n<p>These:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n</code></pre>\n\n<p>are deprecated. Instead, use the C++-style headers:</p>\n\n<pre><code>#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n</code></pre>\n\n<p>And prefix all the calls to the C functions with <code>std::</code>.</p>\n\n<h1>Possibility for scoped <code>enum</code> usage</h1>\n\n<p>You can use <code>enum class Occupant</code> to scope your <code>enum</code>. This way you can possibly reuse the names of the <code>enum</code>'s members elsewhere (not that you would want to do that). You will be able to access the <code>enum</code> using <code>Room::Occupant::<member></code>, like you already do in a lot of cases.</p>\n\n<h1>Inlining</h1>\n\n<p>You have made a lot of the relatively simple functions that aren't one-liners external. For performance reasons, you may consider defining these inside the <code>class</code>, where they will be inlined into the code.</p>\n\n<h1>Use range-<code>for</code> loops consistently, and with <code>auto</code></h1>\n\n<p>In some places I see you not using range-<code>for</code> loops at all:</p>\n\n<pre><code>for (int i = 0; i < rooms.size(); ++i)\n if (rooms[i].connections.size() < 3) return false;\n</code></pre>\n\n<p>while in others you're not using <code>auto</code> and instead being explicit:</p>\n\n<pre><code>for (Room* connection : connections)\n if (connection->rn == i) return true;\n</code></pre>\n\n<p>Both of these should work great with range-<code>for</code> loops and <code>auto &</code>:</p>\n\n<pre><code>for (auto& r : rooms)\n if (r.connections.size() < 3) return false;\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>for (auto &connection : connections)\n if (connection->rn == i) return true;\n</code></pre>\n\n<h1>Don't use <code>std::endl</code> when you don't need to</h1>\n\n<p>There's no reason for you to explicitly flush the streams. A simple newline (<code>\\n</code>) would do.</p>\n\n<h1>Portability</h1>\n\n<p>These:</p>\n\n<pre><code>system(\"PAUSE\");\nsystem(\"CLS\");\n</code></pre>\n\n<p>are not portable. Instead, you can use this for <code>system(\"PAUSE\")</code>:</p>\n\n<pre><code>std::cout << \"Press any key to continue . . .\\n\";\nstd::cin.get();\n</code></pre>\n\n<p>and just remove <code>system(\"CLS\");</code> altogether. I'd rather not have my screen cleared when playing a game.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:07:18.670",
"Id": "236950",
"ParentId": "236942",
"Score": "10"
}
},
{
"body": "<p>A comment on the actual game logic rather than coding style: It looks like it's possible the cave might not be <a href=\"https://en.wikipedia.org/wiki/Connectivity_(graph_theory)\" rel=\"noreferrer\">connected</a>, meaning there would be no way for the player to ever reach the wumpus.</p>\n\n<p>Generating a random but connected graph is a bit tricky, but there are various things you could try.</p>\n\n<p>I think many traditional implementations always have 12 rooms, with the structure of the rooms and edges matching the corners and edges of a dodecahedron. The room numbers can be shuffled so that exploration is still tricky no matter how well a player knows the game.</p>\n\n<p>You could first add rooms one by one with an initial connection to some previous random room, forming a <a href=\"https://en.wikipedia.org/wiki/Tree_(graph_theory)\" rel=\"noreferrer\">tree</a> graph. Then add more random connections like your current cave-building. This might still cause caves where, for example, two different sections are somewhat easy to get around but only two paths connect between them. But that doesn't sound terrible as long as the total size is reasonable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:19:16.710",
"Id": "237011",
"ParentId": "236942",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:21:01.517",
"Id": "236942",
"Score": "14",
"Tags": [
"c++",
"beginner",
"object-oriented",
"game",
"pointers"
],
"Title": "Hunt the Wumpus"
}
|
236942
|
<p>I built a simple web app to manage my friends and I's six nation prediction league. This is my first go at web development so although it works I am guessing that I am not following all best practices or conventions. Any tips would be much appreciated.</p>
<p>The stack I used is:</p>
<p>Neo4j <-> Py2Neo <-> Flask <-> Html, JS, CSS</p>
<p>I know it would have been simpler to do with just a standard sql database but I wanted to learn a graph database.</p>
<p>App.py - Handles the requests and calls functions that return strings of html</p>
<pre class="lang-py prettyprint-override"><code>from flask import Flask, request, redirect, url_for, session
import yaTemplates as Templates
import NeoInterface as Neo
app = Flask(__name__)
app.secret_key = 'MySecretKey'
def checkpassword(username, password):
actualpassword = Neo.getpassword(username)
if actualpassword == password:
return True
return False
@app.route('/')
def index():
if 'username' in session:
return redirect('/LeagueTable')
return Templates.login()
@app.route('/LeagueTable')
def leaguetable():
if 'username' not in session:
return redirect('/')
return Templates.leaguetable(session["username"])
@app.route('/Predictions')
def predictions():
if 'username' not in session:
return redirect('/')
return Templates.predictions(session["username"])
@app.route('/Results')
def results():
if 'username' not in session:
return redirect('/')
return Templates.results(session["username"])
@app.route('/Spread')
def spread():
if 'username' not in session:
return redirect('/')
return Templates.spread(session["username"])
@app.route('/PredictionSubmit', methods=["POST"])
def predictionsubmit():
if 'username' not in session:
return "Failure"
auser = session["username"]
ateam = request.form['ateam']
afixtureid = request.form['afixtureid']
margin = str(request.form['margin'])
check = Neo.mergeprediction(auser, ateam, afixtureid, margin)
if check == "Cheat":
return "Cheat"
return "Success"
@app.route('/ResultSubmit', methods=["POST"])
def resultsubmit():
if 'username' not in session:
return "Failure"
auser = session["username"]
afixtureid = request.form['afixtureid']
margin = str(request.form['margin'])
check = Neo.mergeresult(auser, afixtureid, margin)
return "Success"
@app.route("/loginsubmit", methods=["POST"])
def loginsubmit():
username = request.form['username']
password = request.form['password']
if checkpassword(username, password):
session.permanent = True
session['username'] = username
return url_for('leaguetable')
else:
return "Error"
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>-- This contains some functions I just used in the console to set things up. The rest are used by the app.</p>
<p>NeoInterface.py -- functions for interacting with Neo4j database using py2neo</p>
<pre class="lang-py prettyprint-override"><code>from py2neo import Graph, Node, Relationship, Subgraph
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom
from DataWarehouse import importcsvlistdicts
import os
from datetime import datetime
uri = "bolt://hobby-opbcljlkjmgggbkeoiobbhel.dbs.graphenedb.com:24787"
user = "Admin"
pwd = "MyPassword"
g = Graph(uri, auth=(user, pwd), secure=True)
class User(GraphObject):
__primarykey__ = "Username"
Username = Property()
Password = Property()
League = Property()
Predicts = RelatedTo("Prediction", "PREDICTS")
class Fixture(GraphObject):
__primarykey__ = "GameID"
GameID = Property()
ResultsEntered = Property()
HomePoints = Property()
Round = Property()
Time = Property()
AwayPoints = Property()
Date = Property()
Name = Property()
In_Fixture = RelatedFrom("Prediction", "IN_FIXTURE")
Home_Team = RelatedTo("Team", "HOME_TEAM")
Away_Team = RelatedTo("Team", "AWAY_TEAM")
class Team(GraphObject):
__primarykey__ = "Name"
Name = Property()
PrimaryColour = Property()
SecondaryColour = Property()
To_Win = RelatedFrom("Prediction", "TO_WIN")
Home_Team = RelatedFrom("Fixture", "HOME_TEAM")
Away_Team = RelatedFrom("Fixture", "AWAY_TEAM")
class Prediction(GraphObject):
__primarykey__ = "ConcCat"
ConcCat = Property()
Margin = Property()
Predicts = RelatedFrom("User", "PREDICTS")
To_Win = RelatedTo("Team", "TO_WIN")
In_Fixture = RelatedTo("Fixture", "IN_FIXTURE")
def createfromcsv(filename):
# list of dicts where Label is reserved for label
# todo use the filename if Label column not present
rows = importcsvlistdicts(os.path.join(os.path.dirname(__file__), filename + '.csv'))
nodelist = list()
for arow in rows:
thisnode = Node(arow["Label"])
for key, value in arow.items():
if key not in ['Label']:
thisnode[key] = value
nodelist.append(thisnode)
for n in nodelist:
g.create(n)
def mergeprediction(auser, ateam, afixtureid, margin, check=True):
# Todo: Learn python string subsitition and swap for below
datenow = datetime.now()
# datenow = datetime.strptime('01/02/2020 14:16', "%d/%m/%Y %H:%M")
cypherstatement = "MATCH (f:Fixture { GameID : '%s'}) " % afixtureid
cypherstatement += " RETURN f.Date, f.Time "
dateandtime = g.run(cypherstatement).data()[0]
fixturedatetime = datetime.strptime(dateandtime["f.Date"] + ' ' + dateandtime["f.Time"], "%d/%m/%Y %H:%M")
if datenow > fixturedatetime and check:
return "Cheat"
tx = g.begin()
ConcCat = auser + afixtureid
cypherstatement = 'MATCH (p:Prediction {ConcCat:"' + ConcCat + '"}) '
cypherstatement += ' DETACH DELETE p'
g.run(cypherstatement)
cypherstatement = 'CREATE (p:Prediction { ConcCat: "' + ConcCat + '", Margin: "' + margin + '"})'
tx.run(cypherstatement)
cypherstatement = 'MATCH (p:Prediction), (t:Team), (f:Fixture), (u:User) '
cypherstatement += ' WHERE p.ConcCat = "' + ConcCat + '" '
cypherstatement += ' AND t.Name = "' + ateam + '" '
cypherstatement += ' AND f.GameID = "' + afixtureid + '" '
cypherstatement += ' AND u.Username = "' + auser + '" '
cypherstatement += ' CREATE '
cypherstatement += ' (p)-[:TO_WIN]->(t), '
cypherstatement += ' (p)-[:IN_FIXTURE]->(f), '
cypherstatement += ' (u)-[:PREDICTS]->(p)'
tx.run(cypherstatement)
tx.commit()
return "Honest"
def mergeresult(auser, afixtureid, margin):
margin = int(margin)
if margin < 0:
homescore = margin * -1
awayscore = 0
elif margin > 0:
homescore = 0
awayscore = margin
else:
homescore = 0
awayscore = 0
cypherstatement = "MATCH (f:Fixture { GameID : '%s'}) " % afixtureid
cypherstatement += " set f.HomePoints = '%d' , f.AwayPoints = '%d'" % (homescore, awayscore)
g.run(cypherstatement)
return "Honest"
def linkfixturetoteam(fixid, home, away):
fixturenode = Fixture.match(g, fixid).first()
homenode = Team.match(g, home).first()
awaynode = Team.match(g, away).first()
fixturenode.HomeTeam.add(homenode)
fixturenode.AwayTeam.add(awaynode)
g.push(fixturenode)
g.push(homenode)
g.push(awaynode)
def linkfixturestoteams():
rows = importcsvlistdicts(os.path.join(os.path.dirname(__file__), "Fixtures" + '.csv'))
for row in rows:
home = row["Home"]
away = row["Away"]
fixid = row["GameID"]
linkfixturetoteam(fixid, home, away)
def getpassword(auser):
usernode = User.match(g, auser).first()
return usernode.Password
def setpassword(auser, password):
usernode = User.match(g, auser).first()
usernode.Password = password
g.push(usernode)
def setcolour(ateam, colour, seccolour):
ateam = Team.match(g, ateam).first()
ateam.PrimaryColour = colour
ateam.SecondaryColour = seccolour
g.push(ateam)
def generateficturetable(username):
cypherstatement = "match (f:Fixture)-[:HOME_TEAM]->(h:Team), (f)-[:AWAY_TEAM]->(a:Team) "
cypherstatement += "optional match (f)<-[:IN_FIXTURE]-(p:Prediction)<-[:PREDICTS]-(u:User {Username: '" + username + "'}) "
cypherstatement += ", (p:Prediction)-[:TO_WIN]->(w:Team) "
cypherstatement += " return f, h, a, p, u, w "
returndata = g.run(cypherstatement).data()
return returndata
def generateresultstable():
cypherstatement = "match (f:Fixture)-[:HOME_TEAM]->(h:Team), (f)-[:AWAY_TEAM]->(a:Team) "
cypherstatement += " return f, h, a"
returndata = g.run(cypherstatement).data()
return returndata
def getspreadfixture(userleague):
datenow = datetime.now()
# datenow = datetime.strptime('01/02/2020 14:16', "%d/%m/%Y %H:%M")
cypherstatement = "MATCH (f:Fixture)-[:HOME_TEAM]->(h:Team), "
cypherstatement += " (f:Fixture)-[:AWAY_TEAM]->(a:Team) "
cypherstatement += " return f, h, a"
returndata = g.run(cypherstatement).data()
mindiff = 24 * 30
minfixture = None
for afixture in returndata:
fixturedate = datetime.strptime(afixture['f']["Date"] + ' ' + afixture['f']["Time"], "%d/%m/%Y %H:%M")
datediff = (datenow - fixturedate).total_seconds() / 3600
if 0 < datediff < mindiff:
minfixture = afixture
mindiff = datediff
if minfixture is None:
return None, None
cypherstatement = " MATCH (f:Fixture {GameID : '" + minfixture['f']["GameID"] + "'})"
cypherstatement += "<-[:IN_FIXTURE]-(p:Prediction)-[:TO_WIN]->(t:Team), "
cypherstatement += "(p:Prediction)<-[:PREDICTS]-(u:User) "
cypherstatement += ' where u.League = "' + userleague + '"'
cypherstatement += " return p, t, u"
predictions = g.run(cypherstatement).data()
return minfixture, predictions
def getleaguedata(userleague):
cypherstatement = "MATCH (f:Fixture)-[:HOME_TEAM]->(h:Team), "
cypherstatement += " (f:Fixture)-[:AWAY_TEAM]->(a:Team) "
cypherstatement += " return f, h, a"
fixtures = g.run(cypherstatement).data()
cypherstatement = " MATCH (f:Fixture)"
cypherstatement += "<-[:IN_FIXTURE]-(p:Prediction)-[:TO_WIN]->(t:Team), "
cypherstatement += "(p:Prediction)<-[:PREDICTS]-(u:User) "
cypherstatement += ' where u.League = "' + userleague + '"'
cypherstatement += " return f, p, t, u"
predictions = g.run(cypherstatement).data()
return fixtures, predictions
def getusers(userleague):
cypherstatement = "MATCH (u:User)"
cypherstatement += ' where u.League = "' + userleague + '"'
cypherstatement += " return u"
users = g.run(cypherstatement).data()
return users
def getuserleague(auser):
cypherstatement = 'MATCH (u:User) where u.Username = "' + auser + '" return u.League'
return g.run(cypherstatement).data()[0]['u.League']
</code></pre>
<p>YaTemplates.py -- Uses Yattag library to generate html </p>
<pre class="lang-py prettyprint-override"><code>from yattag import Doc, indent
import os
import NeoInterface as Neo
from datetime import datetime
from GameLogic import *
def padstrings(astring, padtonum, alignment):
astringlength = len(astring)
numspacestoadd = padtonum - astringlength
left = False
if alignment == "Left":
left = True
for x in range(0, numspacestoadd):
if left:
astring = astring + ' '
else:
astring = ' ' + astring
if alignment == "Center":
left = not left
return astring
def gettextfromfile(afilename):
afilename = os.path.join(os.path.dirname(__file__), afilename)
with open(afilename) as f:
return f.read()
def materialize(innerHTML, headeradditions=''):
doc, tag, text = Doc().tagtext()
doc.asis("<!DOCTYPE html>")
with tag('head'):
doc.stag('link', href='https://fonts.googleapis.com/icon?family=Material+Icons', rel='stylesheet')
doc.stag('link', rel='stylesheet',
href='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css')
doc.stag('meta', name='viewport', content='width=device-width, initial-scale=1.0')
with tag('script'):
doc.attr(src='https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js')
doc.asis(indent(headeradditions, indent_text=True))
with tag('html'):
with tag('body'):
doc.asis(indent(innerHTML, indent_text=True))
return indent(doc.getvalue(), indent_text=True)
def addmenu(innerhtml):
doc, tag, text = Doc().tagtext()
with tag('div', klass='row'):
text('')
with tag("center"):
with tag('div', klass='row'):
with tag('a', klass='waves-effect waves-light btn', href='LeagueTable'):
text("Table")
with tag('a', klass='waves-effect waves-light btn', href='Predictions'):
text("Predictions")
with tag('a', klass='waves-effect waves-light btn', href='Results'):
text("Results")
with tag('a', klass='wave-effect waves-light btn', href='Spread'):
text('Spread')
doc.asis(indent(innerhtml, indent_text=True))
return indent(doc.getvalue(), indent_text=True)
def leaguetable(username):
usersleague = Neo.getuserleague(username)
users = Neo.getusers(usersleague)
scoresdict = dict()
for user in users:
scoresdict[user["u"]["Username"]] = 0
fixtures, predictions2 = Neo.getleaguedata(usersleague)
fixturepredictions = dict()
for f in fixtures:
fixturepredictions[f["f"]["GameID"]] = []
for x in predictions2:
pred = [x['u']['Username'], x['t']['Name'], x['p']['Margin']]
gameid = x["f"]["GameID"]
fixturepredictions[gameid].append(pred)
for f in fixtures:
winningmargin = int(f["f"]["AwayPoints"]) - int(f["f"]["HomePoints"])
preds = fixturepredictions[f["f"]["GameID"]]
hometeam = f['h']['Name']
awayteam = f['a']['Name']
scoresdict = getpoints(scoresdict, preds, hometeam, awayteam, winningmargin)
doc, tag, text = Doc().tagtext()
# todo; Can all of the logic be done in cypher??
with tag('div', klass='row'):
with tag('div', klass='container col s12 offset-m2 m8 offset-l2 l4'):
with tag("table", klass='centred', style="margin-top:10px; margin-left:10px;"):
with tag("thead"):
with tag("th"):
text("Name")
with tag("th"):
text("Score")
with tag("tbody"):
scoreslist = []
for name, score in scoresdict.items():
scoreslist.append([name, score])
scoreslist.sort(key=lambda pair: pair[1], reverse=True)
for apair in scoreslist:
with tag("tr"):
if apair[0] == username:
doc.attr(klass="lime lighten-5")
with tag("td"):
text(apair[0])
with tag("td"):
text(apair[1])
innerhtml = indent(doc.getvalue(), indent_text=True)
return materialize(addmenu(innerhtml))
def spread(username):
# todo: Home and away sections should be done via a function as is duplicating a lot of code there
doc, tag, text = Doc().tagtext()
usersleague = Neo.getuserleague(username)
fixture, spreadpredictions = Neo.getspreadfixture(usersleague)
if fixture is None:
return materialize(addmenu("<center>No games have kicked off yet"), "")
spreadpredictions = [[x['u']['Username'], x['t']['Name'], x['p']['Margin']] for x in spreadpredictions]
hometeam = fixture['h']['Name']
awayteam = fixture['a']['Name']
maxhome = max([int(x[2]) for x in spreadpredictions if x[1] == hometeam] + [1])
maxaway = max([int(x[2]) for x in spreadpredictions if x[1] == awayteam] + [1])
with tag("center"):
first = True
for x in range(maxhome, 0, -1):
with tag("div", klass="row reducemargin"):
winners = getclosest(spreadpredictions, hometeam, awayteam, x * -1)
if not winners:
winners = "No Winners"
else:
winners = ', '.join(winners)
if first:
addtext = "+"
first = False
else:
addtext = ""
text(hometeam + ' by ' + str(x) + addtext + ' : ' + winners)
with tag("div", klass="row reducemargin"):
text("Draw then nobody wins")
first = True
for x in range(1, maxaway + 1, 1):
with tag("div", klass="row reducemargin"):
winners = getclosest(spreadpredictions, hometeam, awayteam, x)
if not winners:
winners = "No Winners"
else:
winners = ', '.join(winners)
if first:
addtext = "+"
first = False
else:
addtext = ""
text(awayteam + ' by ' + str(x) + addtext + ' : ' + winners)
innerhtml = indent(doc.getvalue(), indent_text=True)
doc, tag, text = Doc().tagtext()
with tag('style'):
doc.asis("div.reducemargin {margin-bottom: 2px;} ")
css = indent(doc.getvalue(), indent_text=True)
return materialize(addmenu(innerhtml), css)
def predictions(username):
doc, tag, text = Doc().tagtext()
datenow = datetime.now()
# datenow = datetime.strptime('01/02/2020 14:16', "%d/%m/%Y %H:%M")
allfixtures = Neo.generateficturetable(username)
allfixtures.sort(key=lambda x: datetime.strptime(x["f"]["Date"] + ' ' + x["f"]["Time"], "%d/%m/%Y %H:%M"))
allfixtures = (x for x in allfixtures
if datetime.strptime(x["f"]["Date"] + ' ' + x["f"]["Time"], "%d/%m/%Y %H:%M") > datenow)
valueadjustorjs = []
for thisfictureinfo in allfixtures:
fixtureid = thisfictureinfo["f"]["GameID"]
hometeam = thisfictureinfo["h"]["Name"]
awayteam = thisfictureinfo["a"]["Name"]
homecolour = thisfictureinfo["h"]["PrimaryColour"]
awaycolour = thisfictureinfo["a"]["PrimaryColour"]
hometext = thisfictureinfo["h"]["SecondaryColour"] + '-text'
awaytext = thisfictureinfo["a"]["SecondaryColour"] + "-text"
gamedate = thisfictureinfo["f"]["Date"]
gametime = thisfictureinfo["f"]["Time"]
gamedate = datetime.strptime(gamedate, "%d/%m/%Y")
gametimeformatted = gamedate.strftime("%A %d %B")
if thisfictureinfo["p"] is None:
predictiontext = "No Prediction"
margin = 0
else:
margin = thisfictureinfo["p"]["Margin"]
predictedteam = thisfictureinfo["w"]["Name"]
predictiontext = predictedteam + " to win by " + margin + ' points'
if predictedteam == hometeam:
margin = int(margin) * -1
js = '$("#' + "Fixture-" + fixtureid + '-Slider").value = ' + str(margin) + "; "
valueadjustorjs.append(js)
with tag('center'):
with tag('div', klass='row'):
text("")
with tag('div', klass='row'):
text(gametimeformatted + ' ' + gametime)
with tag('div', klass='row'):
klasstext = 'waves-effect waves-light btn team ' + homecolour.lower() + ' ' + hometext.lower()
with tag('a', klass=klasstext, id="Home-" + fixtureid):
text(hometeam)
with tag('a', klass='waves-effect waves-light btn grey'):
text("V")
klasstext = 'waves-effect waves-light btn team ' + awaycolour.lower() + ' ' + awaytext.lower()
with tag('a', klass=klasstext, id="Away-" + fixtureid):
text(awayteam)
with tag('div', klass='row biggertext', id="PredictionText-" + fixtureid):
text(predictiontext)
with tag('div', klass='row reducemargin'):
# with tag('div'):
with tag('form', action="#", klass='col s10 offset-s1 offset-m3 m6 offset-l4 l4 myslider'):
with tag('p', klass="range-field adjustup"):
doc.stag('input', type="range", id="Fixture-" + fixtureid + "-Slider", min="-60", max="60",
value=margin)
with tag('script'):
doc.asis(gettextfromfile('debounce.js'))
doc.asis(gettextfromfile('predictions.js'))
for js in valueadjustorjs:
doc.asis(js)
innerhtml = indent(doc.getvalue(), indent_text=True)
doc, tag, text = Doc().tagtext()
with tag('style'):
doc.asis("p.adjustup { position: relative; top: -28px;} ")
doc.asis("a.team { width: 100px;} ")
doc.asis("div.biggertext {font-size: large;} ")
doc.asis("form.myslider {height: 17px;} ")
doc.asis("div.reducemargin {margin-bottom: 14px;} ")
css = indent(doc.getvalue(), indent_text=True)
return materialize(addmenu(innerhtml), css)
def results(username):
doc, tag, text = Doc().tagtext()
usersleague = Neo.getuserleague(username)
datenow = datetime.now()
# datenow = datetime.strptime('01/02/2020 14:16', "%d/%m/%Y %H:%M")
allfixtures = Neo.generateresultstable()
allfixtures.sort(key=lambda x: datetime.strptime(x["f"]["Date"] + ' ' + x["f"]["Time"], "%d/%m/%Y %H:%M"))
allfixtures = (x for x in allfixtures
if datetime.strptime(x["f"]["Date"] + ' ' + x["f"]["Time"], "%d/%m/%Y %H:%M") < datenow)
valueadjustorjs = []
for thisfictureinfo in allfixtures:
fixtureid = thisfictureinfo["f"]["GameID"]
hometeam = thisfictureinfo["h"]["Name"]
awayteam = thisfictureinfo["a"]["Name"]
homecolour = thisfictureinfo["h"]["PrimaryColour"]
awaycolour = thisfictureinfo["a"]["PrimaryColour"]
hometext = thisfictureinfo["h"]["SecondaryColour"] + '-text'
awaytext = thisfictureinfo["a"]["SecondaryColour"] + "-text"
homepoints = thisfictureinfo["f"]["HomePoints"]
awaypoints = thisfictureinfo["f"]["AwayPoints"]
margin = int(awaypoints) - int(homepoints)
gamedate = thisfictureinfo["f"]["Date"]
gametime = thisfictureinfo["f"]["Time"]
gamedate = datetime.strptime(gamedate, "%d/%m/%Y")
gametimeformatted = gamedate.strftime("%A %d %B")
if margin < 0:
winningteam = hometeam
elif margin > 0:
winningteam = awayteam
else:
winningteam = "Match ended in a draw"
if margin != 0:
predictiontext = winningteam + " won by " + str(abs(margin)) + " points"
else:
predictiontext = winningteam
js = '$("#' + "Fixture-" + fixtureid + '-Slider").value = ' + str(margin) + "; "
valueadjustorjs.append(js)
with tag('center'):
with tag('div', klass='row'):
text("")
with tag('div', klass='row'):
text(gametimeformatted + ' ' + gametime)
with tag('div', klass='row'):
klasstext = 'waves-effect waves-light btn team ' + homecolour.lower() + ' ' + hometext.lower()
with tag('a', klass=klasstext, id="Home-" + fixtureid):
text(hometeam)
with tag('a', klass='waves-effect waves-light btn grey'):
text("V")
klasstext = 'waves-effect waves-light btn team ' + awaycolour.lower() + ' ' + awaytext.lower()
with tag('a', klass=klasstext, id="Away-" + fixtureid):
text(awayteam)
with tag('div', klass='row biggertext', id="PredictionText-" + fixtureid):
text(predictiontext)
with tag('div', klass='row reducemargin'):
# with tag('div'):
with tag('form', action="#", klass='col s10 offset-s1 offset-m3 m6 offset-l4 l4 myslider'):
with tag('p', klass="range-field adjustup"):
doc.stag('input', type="range", id="Fixture-" + fixtureid + "-Slider", min="-60", max="60",
value=margin)
with tag('script'):
doc.asis(gettextfromfile('results.js'))
for js in valueadjustorjs:
doc.asis(js)
text(" ")
if usersleague != 'Anytime':
doc.asis(gettextfromfile('hideallsliders.js'))
innerhtml = indent(doc.getvalue(), indent_text=True)
doc, tag, text = Doc().tagtext()
with tag('style'):
doc.asis("p.adjustup { position: relative; top: -28px;} ")
doc.asis("a.team { width: 100px;} ")
doc.asis("div.biggertext {font-size: large;} ")
doc.asis("form.myslider {height: 17px;} ")
doc.asis("div.reducemargin {margin-bottom: 14px;} ")
css = indent(doc.getvalue(), indent_text=True)
return materialize(addmenu(innerhtml), css)
def login():
doc, tag, text = Doc().tagtext()
with tag('center'):
with tag('div', klass='row'):
text('')
with tag('h2'):
text("McGarr's Six Nations Table Generator")
with tag('div', klass='row'):
with tag('div', klass='input-field col s6 offset-m2 offset-l4 m4 l2'):
doc.stag('input', placeholder='Username', id='username', type='text')
with tag('div', klass='input-field col s6 m4 l2'):
doc.stag('input', placeholder='Password', id='password', type='password')
with tag('div', klass='row'):
with tag('a', klass='waves-effect waves-light btn', id='loginbutton'):
text('Login')
with tag('div', id='warningModal', klass='modal'):
with tag('div', klass='modal-content'):
with tag('h4', id='errorMessage'):
text('This is an error message')
with tag('div', klass='modal-footer'):
with tag('a', hred='#!', klass='modal-close'):
text("Close")
with tag('script', src='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js'):
text('')
with tag('script'):
doc.asis(gettextfromfile('login.js'))
innerHTML = indent(doc.getvalue(), indent_text=True)
return materialize(innerHTML)
</code></pre>
<p>GameLogic.py -- contains logic for working out which users get points</p>
<pre class="lang-py prettyprint-override"><code>def getclosest(spreadpredictions, hometeam, awayteam, x):
mindiff = 1000
closest = []
for pred in spreadpredictions:
user = pred[0]
team = pred[1]
margin = pred[2]
testmargin = x
if x < 0:
winningteam = hometeam
testmargin *= -1
elif x > 0:
winningteam = awayteam
else:
return []
diff = abs(testmargin - int(margin))
if team == winningteam and diff < mindiff:
mindiff = diff
texttoadd = user
if diff == 0:
texttoadd += '***'
closest = [texttoadd]
elif team == winningteam and diff == mindiff:
texttoadd = user
if diff == 0:
texttoadd += '***'
closest.append(texttoadd)
return closest
def getpoints(scoresdict, spreadpredictions, hometeam, awayteam, winningmargin):
mindiff = 1000
closest = []
exact = []
for pred in spreadpredictions:
user = pred[0]
team = pred[1]
margin = pred[2]
testmargin = winningmargin
if winningmargin < 0:
winningteam = hometeam
testmargin *= -1
elif winningmargin > 0:
winningteam = awayteam
else:
return scoresdict
diff = abs(testmargin - int(margin))
if team == winningteam and diff < mindiff:
mindiff = diff
texttoadd = user
if diff == 0:
exact = [user]
closest = [texttoadd]
elif team == winningteam and diff == mindiff:
texttoadd = user
if diff == 0:
exact.append(user)
closest.append(texttoadd)
if team == winningteam:
scoresdict[user] += 2
for c in closest:
scoresdict[c] += 3
for e in exact:
scoresdict[e] += 5
return scoresdict
</code></pre>
<p>debouncer.js -- prevents a function from firing too many times in a short space of time</p>
<pre><code>// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
</code></pre>
<p>login.js -- login script</p>
<pre><code>$(document).ready(function(){
$('#warningModal').modal();
});
$("#loginbutton").click(function(){
usernameform = $("#username").val();
passwordform = $("#password").val();
if(!usernameform || !passwordform)
{
$('#errorMessage').text('How do you expect to login without entering both a username and a password? you dumb ass')
$('#warningModal').modal('open');
}
else
{
$.ajax(
{
type: 'POST',
url: "/loginsubmit",
data : {'username': usernameform, 'password': passwordform},
success: function(url){
if(url != "Error")
{
window.location = url;
}
else {
$('#errorMessage').text('Concentrate, you feeble minded fool and try again')
$('#warningModal').modal('open');
}
}
}
)
}
});
</code></pre>
<p>prediction.js -- creates sliders and events for predictions</p>
<pre><code>
function addmouseup(fixtureid){
sliderid = "Fixture-" + fixtureid + "-Slider"
$('#' + sliderid).on('mouseup touchend' , debounce(function(){
relfixtureid = $(this).attr('id').split('-')[1]
homeid = "Home-" + relfixtureid
awayid = "Away-" + relfixtureid
predtextid = "PredictionText-" + relfixtureid
hometeam = $('#' + homeid).html().trim()
awayteam = $('#' + awayid).html().trim()
margin = $(this).val()
if(margin <= 0){
teamprediction = hometeam
margin = margin * -1
}
else {
teamprediction = awayteam
}
$.ajax(
{
type: 'POST',
url: "/PredictionSubmit",
data : {'ateam': teamprediction, 'afixtureid': relfixtureid, 'margin': margin},
error: function(){
alert("Prediction Submission Error - Please tell McGarr");
},
success: function(msg){
if(msg=="Cheat"){
alert("Nice try! You cheating!")
location.reload();
}
if(msg=="Failure"){
alert("You are not logged in correctly")
location.reload();
}
}
}
)
}, 429));
$('#' + sliderid).on('input' , function(){
relfixtureid = $(this).attr('id').split('-')[1]
homeid = "Home-" + relfixtureid
awayid = "Away-" + relfixtureid
predtextid = "PredictionText-" + relfixtureid
hometeam = $('#' + homeid).html().trim()
awayteam = $('#' + awayid).html().trim()
margin = $(this).val()
if(margin <= 0){
teamprediction = hometeam
margin = margin * -1
}
else {
teamprediction = awayteam
}
$('#' + predtextid).text(teamprediction + ' to win by ' + margin + ' points')
})
}
for (i=1;i < 16; i++){
addmouseup(i.toString());
}
</code></pre>
<p>results.js</p>
<pre><code>function addmouseup(fixtureid){
sliderid = "Fixture-" + fixtureid + "-Slider"
$('#' + sliderid).on('mouseup touchend' , function(){
relfixtureid = $(this).attr('id').split('-')[1]
homeid = "Home-" + relfixtureid
awayid = "Away-" + relfixtureid
hometeam = $('#' + homeid).html().trim()
awayteam = $('#' + awayid).html().trim()
margin = $(this).val()
$.ajax(
{
type: 'POST',
url: "/ResultSubmit",
data : {'afixtureid': relfixtureid, 'margin': margin},
error: function(){
alert("Result Submission Error - Please tell McGarr");
},
success: function(msg){
if(msg=="Failure"){
alert("You are not logged in correctly")
location.reload();
}
}
}
)
});
$('#' + sliderid).on('input' , function(){
relfixtureid = $(this).attr('id').split('-')[1]
predtextid = "PredictionText-" + relfixtureid
homeid = "Home-" + relfixtureid
awayid = "Away-" + relfixtureid
hometeam = $('#' + homeid).html().trim()
awayteam = $('#' + awayid).html().trim()
margin = $(this).val()
if(margin < 0){
teamprediction = hometeam
margin = margin * -1
}
else if (margin > 0) {
teamprediction = awayteam
}
else {
}
$('#' + predtextid).text(teamprediction + ' won by ' + margin + ' points')
})
}
for (i=1;i < 16; i++){
addmouseup(i.toString());
}
</code></pre>
<p>hideallsliders.js</p>
<pre><code>var divsToHide = document.getElementsByClassName("range-field"); //divsToHide is an array
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.visibility = "hidden";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:20:17.373",
"Id": "464572",
"Score": "0",
"body": "For the unenlightened people among us (like me): You're talking about [rugby](https://www.sixnationsrugby.com/fixtures-2020/), right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:36:42.667",
"Id": "464575",
"Score": "0",
"body": "I am yes, the tournament is happening now"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:47:53.903",
"Id": "236943",
"Score": "2",
"Tags": [
"python",
"javascript",
"html",
"flask",
"neo4j"
],
"Title": "Six Nations Prediction league Web App"
}
|
236943
|
<p>I have made a simple website and I have tried to reduce load times as much as possible. All the content that is loaded is necessary.</p>
<p>Is there anything thing I can do to my code, such as structurally, to make it load even faster?</p>
<h2>Side Note</h2>
<p>I do not want to minify the HTML, as I want it to remain legible and I am not concerned about the content in the body, I am only concerned about the content in the <code><head></code> and the scripts at the bottom of the <code><body></code>.</p>
<p>The website is hosted at <a href="http://discourse.rf.gd" rel="nofollow noreferrer">http://discourse.rf.gd</a>.</p>
<pre><code><!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, minimum-scale=1">
<link rel="manifest" href="./manifest.webmanifest">
<link rel="stylesheet" href="./src/stylesheet.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Muli:400,400i,700,700i,900,900i&display=swap">
<title>Discourse</title>
</head>
<body>
<fieldset>
<legend>Login</legend>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
<br><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<br><br>
<input type="button" value="login" onclick="login()">
<span id="status"></span>
</fieldset>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous" async></script>
<script src="./src/script.js"></script>
<script src="https://kit.fontawesome.com/17c5f15e6c.js" crossorigin="anonymous" async></script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>While your code is technically review-able, any review won't help you with your request, because the limited example page doesn't provide a realistic use case for your site, mostly because it doesn't have a style sheet and doesn't actually use any of the fonts, so they won't be downloaded.</p>\n\n<p>Why do want to have the HTML \"remain legible\"? (Minifying HTML usually doesn't help much with performance anyway, but it's a strange reason for not wanting to do it).</p>\n\n<p>There are automatized performance tests out there, which should be your first stop. For example, Google Chrome's Lighthouse: <a href=\"https://googlechrome.github.io/lighthouse/viewer/?psiurl=http%3A%2F%2Fdiscourse.rf.gd%2F%3Fi%3D1&strategy=mobile&category=performance&category=accessibility&category=best-practices&category=seo&category=pwa&utm_source=lh-chrome-ext\" rel=\"nofollow noreferrer\">https://googlechrome.github.io/lighthouse/viewer/?psiurl=http%3A%2F%2Fdiscourse.rf.gd%2F%3Fi%3D1&strategy=mobile&category=performance&category=accessibility&category=best-practices&category=seo&category=pwa&utm_source=lh-chrome-ext</a></p>\n\n<p>One big resource hog is jQuery. Unless you are using every single feature it provides multiple times, you shouldn't be using it, if performance is important to you.</p>\n\n<p>Make sure you are actually using the fonts and corresponding style sheets.</p>\n\n<hr>\n\n<p>Some remarks to the HTML:</p>\n\n<ul>\n<li>Don't use <code>on*</code> attributes to add JavaScript event listeners. You generally want to keep HTML, CSS and JavaScript separate. Event handlers are part of the JavaScript and don't belong in the HTML, just like you don't use <code>style</code> attributes to assign CSS in the HTML. See <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_dont_use_these\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_dont_use_these</a></li>\n<li>Don't (only) use JavaScript to handle the login. Use a normal HTTP POST from the form.</li>\n<li>Don't use <code><br></code>s for line breaks or spacing. They are for logical line breaks such as lines in a postal address or in the stanzas of poems. To separate the input fields of a form wrap each label/field pair in a block element, such as a div, or put the input inside the label and give the label <code>display: block</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T15:44:22.917",
"Id": "465376",
"Score": "0",
"body": "Why can I not use `on-` attributes to add JavaScript event listeners? And why should I not use `<br>` for line breaks? According to [this](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) Stack Overflow post, the only disadvantage of `onclick` is that it can only assign one event listener, which I am not bothered about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T17:05:27.523",
"Id": "465385",
"Score": "0",
"body": "@zera I've edited my answer to add some details to those points."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:49:30.067",
"Id": "236993",
"ParentId": "236944",
"Score": "3"
}
},
{
"body": "<p>I have few suggestion. I am hoping it may help you.</p>\n\n<ol>\n<li>Always try to use CDN path for 3rd party library whenever is possible. </li>\n<li>You can put <code>google font api</code> in the bottom of the code</li>\n</ol>\n\n<p>All The Best!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T08:09:57.737",
"Id": "242732",
"ParentId": "236944",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236993",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T21:59:20.490",
"Id": "236944",
"Score": "2",
"Tags": [
"javascript",
"performance",
"css",
"html5"
],
"Title": "Loading the stylesheets and scripts on my website"
}
|
236944
|
<p>While rewriting <code>Array</code> so I can practice my javascript, I looked at my implementation of <a href="https://vegibit.com/most-useful-javascript-array-functions/#Array.prototype.join" rel="nofollow noreferrer"><code>.join()</code></a>. It seems a little clunky to me.</p>
<p>I've tried to cover all the edges, like making sure <code>separator</code> isn't null before joining, not adding the separator at the end of the string, and writing some documentation.</p>
<p>What I'm looking for is a smoother way to write this function. Any recommendations about this function are appreciated and considered.</p>
<pre><code>/**
* Converts each element of the array to string then concats them.
*
* @param separator Value to separate the elements by.
*
* @return String of joined elements.
*/
ArrayRewrite.prototype.join = function(separator) {
separator = separator || "";
let string = "";
for (let i = 0; i < this.content.length; i++) {
string += (i !== this.content.length - 1)
? this.content[i] + separator
: this.content[i]
;
}
return string;
}
</code></pre>
<p>A test case is below</p>
<pre><code>// This is the main function that other functions are built onto //
function ArrayRewrite(...elements) {
this.content = elements || [];
}
myArray = new ArrayRewrite("Hello", "Testing", "Testing Again");
console.log(myArray.join(", "))
// Output:
// Hello, Testing, Testing Again
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:57:12.540",
"Id": "464597",
"Score": "0",
"body": "`separator = separator || \"\";` What's the purpose of this?\n\n(Please forgive me if this is a basic question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:57:24.247",
"Id": "464607",
"Score": "0",
"body": "@Srivaths If separator is not passed into the function, that line sets it to `\"\"`. The line says \"separator = (separator if passed) (or if not passed) (set separator to \"\");"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:04:03.190",
"Id": "464609",
"Score": "0",
"body": "Ohh, I believe that's only possible in JavaScript! Thanks a lot!"
}
] |
[
{
"body": "<p>A short review;</p>\n\n<ul>\n<li>You probably want to cache <code>this.content.length</code></li>\n<li>That check for the end of array is clunky</li>\n<li>separator will change from <code>0</code> to <code>\"\"</code>, an unlikely edge case, but it could happen</li>\n<li>Why are array elements in <code>this.content</code> ? I would have gone for <code>this[i]</code> instead</li>\n<li><code>string</code> is not very evocative, I went with <code>out</code></li>\n</ul>\n\n<p>Obligatory rewrite;</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Array.prototype.myJoin = function stringMyJoin(separator) {\n separator = separator || \"\";\n let out = this[0];\n const length = this.length;\n for (let i = 1; i < length; i++) {\n out += separator + this[i];\n }\n return out || \"\";\n}\n\nconsole.log([].myJoin(\",\"), [].myJoin(\",\") === \"\");\nconsole.log([\"apple\"].myJoin(\",\"));\nconsole.log([\"apple\",\"bear\",\"bananers\"].myJoin(\",\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:15:04.800",
"Id": "464792",
"Score": "0",
"body": "\"_separator will change from `0` to `\"\"`_\" - when will this happen? e.g. if the parameter is undefined, per first line of the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:00:45.203",
"Id": "464898",
"Score": "0",
"body": "`console.log([\"a\",\"b\"].myJoin(0))` will return `ab`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:08:54.723",
"Id": "237005",
"ParentId": "236947",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237005",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:24:41.233",
"Id": "236947",
"Score": "2",
"Tags": [
"javascript",
"array",
"ecmascript-6"
],
"Title": "Rewrite of Array.join"
}
|
236947
|
<p>Introduction:</p>
<p>The following script contains code that performs what I would usually do when staring a new scene (add lights, camera, objects). The script will serve as a starting point for most of my future scripts.</p>
<p>In the future, I might use more complex materials, create animations, or use the built-in physics simulator (for example, rigid body, fluid, smoke).</p>
<p>This is what the script below renders:</p>
<p><a href="https://i.stack.imgur.com/y9nPa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y9nPa.png" alt="monkey"></a></p>
<hr>
<p>The command to run the code is <code>blender --background --python-exit-code 1 --python monkey.py</code>. The code has been tested on Blender 2.81a (released December 5, 2019).</p>
<p>Here are some of my concerns:</p>
<ul>
<li>There are quite a few lines which use <code>bpy.ops</code>. <a href="https://blender.stackexchange.com/a/2850"><code>bpy.ops</code> should be avoided</a>.</li>
<li>Clearing all objects in the beginning with <code>select_all</code> and then <code>delete</code> looks like a workaround to me. There might be a way to start a scene without the default cube, light, and camera.</li>
</ul>
<p><code>monkey.py</code></p>
<pre><code>import bpy
import shutil
import os
import time
def add_light(location, light_type='POINT', color=(1.00, 1.00, 1.00), energy=1000.00):
bpy.ops.object.add(type='LIGHT', location=location)
obj = bpy.context.object
obj.data.type = light_type
obj.data.color = color
obj.data.energy = energy
def set_smooth(obj, level=None, smooth=True):
if level:
modifier = obj.modifiers.new('Subsurf', 'SUBSURF')
modifier.levels = level
modifier.render_levels = level
mesh = obj.data
for p in mesh.polygons:
p.use_smooth = smooth
def create_focal_point(location=(0.00, 0.00, 0.00)):
bpy.ops.mesh.primitive_uv_sphere_add(radius=0.10, location=location)
focal_point = bpy.context.object
focal_point.hide_render = True
return focal_point
def set_focal_point(camera, focal_point):
bpy.context.view_layer.objects.active = camera
bpy.ops.object.constraint_add(type='TRACK_TO')
camera.constraints['Track To'].target = focal_point
camera.constraints['Track To'].track_axis = 'TRACK_NEGATIVE_Z'
camera.constraints['Track To'].up_axis = 'UP_Y'
def create_monkey(origin=(0.00, 0.00, 0.00)):
bpy.ops.mesh.primitive_monkey_add(location=origin)
obj = bpy.context.object
return obj
if __name__ == '__main__':
# Delete all objects
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
main_object = create_monkey()
yellow_rgba = (1.00, 1.00, 0.00, 1.00)
mat = bpy.data.materials.new(name='yellow')
mat.use_nodes = True
mat.diffuse_color = yellow_rgba
nodes = mat.node_tree.nodes
nodes.clear()
node_material_output = nodes.new(type='ShaderNodeOutputMaterial')
node_diffuse = nodes.new(type='ShaderNodeBsdfDiffuse')
node_diffuse.name = 'Yellow Diffuse'
node_diffuse.inputs['Color'].default_value = yellow_rgba
input = node_material_output.inputs['Surface']
output = node_diffuse.outputs['BSDF']
mat.node_tree.links.new(input, output)
main_object = bpy.context.active_object
main_object.active_material = mat
set_smooth(main_object, level=5)
add_light(location=(5.00, -7.50, 5.00))
bpy.ops.object.camera_add(location=(0.00, -5.00, 0.00))
main_camera = bpy.context.object
bpy.context.scene.camera = main_camera
focal_point = create_focal_point(main_object.location)
set_focal_point(main_camera, focal_point)
bpy.context.scene.render.engine = 'CYCLES'
bpy.context.scene.cycles.samples = 50
bpy.context.scene.render.tile_x = 256
bpy.context.scene.render.tile_y = 256
bpy.context.scene.render.resolution_x = 600
bpy.context.scene.render.resolution_y = 600
bpy.context.scene.render.resolution_percentage = 100
bpy.context.scene.render.image_settings.compression = 100
base_filename = time.strftime('%Y %m %d - %H %M %S - ') + os.path.basename(__file__)
base_filename_no_extension = os.path.splitext(base_filename)[0]
shutil.copy(__file__, base_filename)
bpy.ops.wm.save_as_mainfile(filepath=base_filename_no_extension+'.blend')
bpy.context.scene.render.filepath = base_filename_no_extension+'.png'
bpy.ops.render.render(write_still=True)
</code></pre>
|
[] |
[
{
"body": "<p>Use alphabetical order for imports</p>\n\n<pre><code>import bpy\nimport os\nimport shutil\nimport time\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T06:49:08.273",
"Id": "465008",
"Score": "2",
"body": "Welcome to Code Review and thank you for supplying an answer. Is there a reason you suggest alphabetical order (e.g. a style guide like [PEP8](https://www.python.org/dev/peps/pep-0008/#imports))? If so, please [edit] your post to add this explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T07:24:26.817",
"Id": "465013",
"Score": "0",
"body": "This is the start of a good review, but it's a bit small don't you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T07:27:11.850",
"Id": "465018",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ As Pythonist I can confirm it's simply good practice to keep them ordered alphabetically and on import type (keep the `import os` separated from the `from os import sleep` from the `import os as o` statements). Oddly enough the latter isn't part of the PEP8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:44:19.443",
"Id": "465037",
"Score": "0",
"body": "[isort](https://pypi.org/project/isort/) sorts `__futures__`, `builtin`, `3rd part`, `own code`. I prefer that to all alphabetically. Since there are tools to do this for me, and IDE's who make using these tools very simple, I haven't manually ordered my imports"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T03:32:38.090",
"Id": "237200",
"ParentId": "236951",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:07:57.713",
"Id": "236951",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Create 3D monkey head"
}
|
236951
|
<p>I'm a beginner in PHP.</p>
<p>Here my script</p>
<pre><code>$url1 = $chemin.'include/aaa/url1.php?param='.$param.'&page='.$p;
$url2 = $chemin.'include/aaa/url1.php?param='.$param.'&page='.$total_pages;
//url2.php
$url3 = $chemin.'include/aaa/url2.php?page='.$p;
$url4 = $chemin.'include/aaa/url2.php?page='.$total_pages;
//url3.php
$url5 = $chemin.'include/aaa/url3.php?page='.$p;
$url6 = $chemin.'include/aaa/url3.php?page='.$total_pages;
</code></pre>
<p>I have to write 10 more lines on the same way.</p>
<p>Is there a way to improve my script?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:54:59.070",
"Id": "464497",
"Score": "3",
"body": "Welcome to CodeReview@SE. Hard to tell: Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) regarding *context*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:32:14.717",
"Id": "464884",
"Score": "1",
"body": "You seem to speak French, hence the `$chemin` variable. However, other variables in your code are written in English. Anyone who has to read your code must therefore be able to understand these two languages. Think about this before you continue. I write all my code in English only. And no, I am not a native English speaker, I just find it easier for working with other people to stick to one common language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:37:28.377",
"Id": "465158",
"Score": "3",
"body": "Can we see how you are using the urls, as it seems unusual to store them as $url1, $url2, instead of in an array of $urls[]. If we can see how you are using them, we may be able to offer better suggestions."
}
] |
[
{
"body": "<p>you can simply use the for loop for such things,</p>\n\n<pre><code>$totalUrl = 16;// change this number as your requirement\nfor($i=0;$<$totalUrl;$i++){\n\n $url = $chemin.'include/aaa/url.'$i'.php?param='.$param.'&page='.$p; \n // and here your code -include this or do whatever you want \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T17:50:03.257",
"Id": "465147",
"Score": "0",
"body": "Can you show how that assigns to `$url1`, `$url2`, etc? It's not clear how that occurs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T03:28:28.370",
"Id": "465190",
"Score": "1",
"body": "I see a `for` loop problem and a concatenation problem. Furthermore, this is not a good Code Review (\"you can do it like this\" is not educational\")."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T17:06:39.163",
"Id": "237250",
"ParentId": "236953",
"Score": "-1"
}
},
{
"body": "<p>The way you currently doing it would require all the websites to be written manually. A possible alternative would be to implement recursion (loops).</p>\n\n<p>The for loop:</p>\n\n<p>For loops are a good way of repeating a section of code/similar code a number of times.\nThe number of times to repeat this code can be known explicitly, or you can determine it through a simple calculation.</p>\n\n<p>Syntax:</p>\n\n<pre><code>for($i = 0; $i < 10; $i++) {\n echo \"I at at iteration: \" . $i . \"\\r\\n\";\n}\n</code></pre>\n\n<p>Meaning:</p>\n\n<pre><code>for(initialisation; condition; increment) {\n Code to Execute\n}\n</code></pre>\n\n<p>Implementation</p>\n\n<p>As Hardy Mathew provided, a possible implementation could be: <a href=\"https://codereview.stackexchange.com/a/237250/218422\">https://codereview.stackexchange.com/a/237250/218422</a></p>\n\n<p>Other</p>\n\n<p>Your urls look like php classes. If you are trying to include them with other classes, perhaps auto loading is what you're looking for: <a href=\"https://www.php.net/manual/en/language.oop5.autoload.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.oop5.autoload.php</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T09:15:38.067",
"Id": "237282",
"ParentId": "236953",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:32:30.387",
"Id": "236953",
"Score": "-1",
"Tags": [
"beginner",
"php"
],
"Title": "Constructing URLs"
}
|
236953
|
<p>I need to learn bash at some point in the near future, so I decided to start playing around with it. This is really the first actual script that I've written and would like feedback.</p>
<p>This finds and prints all the prime numbers up to the argument provided to the script:</p>
<pre><code>./primes.sh 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
</code></pre>
<p>Honestly, this is proving to be a challenging language with very finicky syntax and a lot of ways to do things half-incorrectly. This code works, but I'm sure it's <em>far</em> from optimal. I'd like any and all recommendations.</p>
<p>I intentionally included the mostly-unnecessary <code>hasFactor</code> function just to force use of functions. I wanted to see what complications it caused. The main issue with it is needing to return a number representing a boolean that indicates if the number has a factor or not, and cleanly handling that returned exit code at the "call-site". Needing to check against <code>1</code> seems poor. Any suggestions regarding use of functions would be appreciated.</p>
<p>And I know better algorithms exist, but I wanted to keep it simple.</p>
<pre><code>#!/usr/bin/env bash
maxNumber=$1
# Returns if a number has factors other than 1 and itself
# Params: n - number to check
function hasFactor {
n=$1
for ((factor=2; factor<n; factor++)); do
if [ $((n % factor)) -eq 0 ]; then
true
return
fi
done
false
return
}
for ((n=2; n<maxNumber; n++)); do
hasFactor $n
if [ $? = 1 ]; then
echo $n
fi
done
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, the algorithm is poor. Repeated trial division is one of the worst ways to generate primes. Prefer a sieve of some sort (you can use an array to store the primes).</p>\n\n<p>Instead of <code>true; return</code> we can <code>return 0</code>; similarly, <code>return 1</code> can replace <code>false; return</code>.</p>\n\n<p>Testing <code>$?</code> is usually a sign that you simply need to move the tested command:</p>\n\n<pre><code>if ! hasFactor $n\nthen\n echo $n\nfi\n</code></pre>\n\n<p>Or simply:</p>\n\n<pre><code>hasFactor $n || echo $n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T08:22:58.443",
"Id": "236972",
"ParentId": "236956",
"Score": "3"
}
},
{
"body": "<p>You say: <em>\"This code works, but I'm sure it's far from optimal. I'd like any and all recommendations.\"</em> AND <em>\"And I know better algorithms exist, but I wanted to keep it simple.\"</em> </p>\n\n<p>Unfortunately, these two are very hard to combine. If you want a piece of code to be efficient, a good algorithm is always the most important thing.</p>\n\n<p>In general, my advice is to avoid doing logic in Bash. It is VERY clunky and it's extremely easy to make small mistakes that show up when you least expect it, and it can be years from now. I only use Bash for extremely simple logic. Basically, I treat it as a way of avoiding having to type commands manually in the command prompt. If you would not use the command prompt for a single instance of your problem, then Bash is probably the wrong language. </p>\n\n<p>Your particular example is a case where I would use Python instead.</p>\n\n<p>If you want to learn Bash, I STRONGLY recommend studying this link: <a href=\"https://mywiki.wooledge.org/BashPitfalls\" rel=\"nofollow noreferrer\">https://mywiki.wooledge.org/BashPitfalls</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T08:49:20.140",
"Id": "236973",
"ParentId": "236956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T01:16:51.543",
"Id": "236956",
"Score": "0",
"Tags": [
"beginner",
"primes",
"bash"
],
"Title": "Prime number finder in bash"
}
|
236956
|
<p>I'm looking for combinations, not permutations, and have found some really great examples ranging from using <code>flatMap</code> such as <a href="https://stackoverflow.com/a/54329187/669843">https://stackoverflow.com/a/54329187/669843</a></p>
<p>The result of <code>['a', 'b', 'c']</code> would be an array of arrays of 3 (a, b, and c). The result I'm looking for would also contain arrays of length 1 and 2.</p>
<p>Example:</p>
<pre><code>['a']
['b']
['c']
['a', 'b']
['a', 'b', 'c']
['a', 'c']
...
</code></pre>
<p>I'm accomplishing the results with something like this but this seems extraordinarily awful and requires de-duplication.</p>
<pre><code>for(let i = 0; tci < combo.length; tci++) {
let newcombo = [allitems[item]].concat(combo.slice(tci, combo.length));
...
push newcombo;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:59:27.683",
"Id": "465163",
"Score": "0",
"body": "Wonder why this off topic? It has running code and wonders how to make it better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T08:51:29.553",
"Id": "465223",
"Score": "0",
"body": "@charles, because the code shown for review is a couple of lines with absolutely no context (there's stuff obviously missing in the mysterious `...` region, and variables `combo`, `item` and `tci` appear out of nowhere). There's clearly quite a bit that's missing before this function is reviewable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T20:57:14.613",
"Id": "465322",
"Score": "0",
"body": "I understand! Thanks. I was trying to be brief but I'm going to give it a few passes and resubmit later, @TobySpeight"
}
] |
[
{
"body": "<p>You can write this better. The best way to explain it is to see the code example in <a href=\"https://docs.python.org/3.8/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\">Python's itertools module</a>:</p>\n\n<pre><code>def combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD\n # combinations(range(4), 3) --> 012 013 023 123\n pool = tuple(iterable)\n n = len(pool)\n if r > n:\n return\n indices = list(range(r))\n yield tuple(pool[i] for i in indices)\n while True:\n for i in reversed(range(r)):\n if indices[i] != i + n - r:\n break\n else:\n return\n indices[i] += 1\n for j in range(i+1, r):\n indices[j] = indices[j-1] + 1\n yield tuple(pool[i] for i in indices)\n</code></pre>\n\n<p>This generates the combinations of length 'r' efficiently using counting. You can create all combinations by either adding length-1 'nulls' to the pool or just iterating over the lengths.</p>\n\n<p>Combination generation is a bit hard to grok, and really you should step through this example until you get it. It's a variation on the idea of manually counting used throughout many algorithms. </p>\n\n<p>The base idea for combinations('ABCD', 2) is to start with 'AB' (first <code>yield</code>), increment the last letter 'AC' then 'AD' with the <code>for j</code> loop doing nothing, on the next loop i will be the index 0, so 'A' -> 'B' and the second resets to one more than the first character and you yield 'BC'.</p>\n\n<p>Trace the code. Keep hacking! Keep notes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T03:47:55.063",
"Id": "464503",
"Score": "0",
"body": "That's a pretty good example. It definitely can be better, but one of the points I was trying to make was a more graceful way of doing it. In the itertools example you have a very nice generator. Is a JavaScript generator a suggestion? I really want to avoid the while with a for, etc, which is where I am now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T08:48:12.927",
"Id": "464527",
"Score": "1",
"body": "A simpler way to iterate all combinations of all lengths is to see that each element may be either absent or present. There's a natural mapping to binary numbers of length `n` (start from 0 or 1 depending on whether you want to include the empty set as a result)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T23:17:02.420",
"Id": "464636",
"Score": "2",
"body": "The question is tagged [tag:Javascript]. The consensus is that [answers should use the same language as the code in the question](https://codereview.meta.stackexchange.com/a/2631/120114). Also Please note, questions involving stub code are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are many on-topic questions to answer; you'll make more reputation faster if you review code in on-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:57:56.500",
"Id": "465162",
"Score": "0",
"body": "Sigh. Everytime I write an answer the 'this how we should do it here' folks come out. I only rarely write answers now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T03:50:39.177",
"Id": "465191",
"Score": "0",
"body": "@TobySpeight Very nice insight! So just mapping the range of numbers `pow(2, combo.length)` through `string(2)` for binary and tuples of matching number. Very slick."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T03:09:43.577",
"Id": "236958",
"ParentId": "236957",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T01:35:18.417",
"Id": "236957",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Graceful way to find combinations in JavaScript"
}
|
236957
|
<p>I have developed the program to rotate the array in java request you to please check it and let me know if there are any flaws in it or where further it can be improved</p>
<pre><code> package com.dataStructures.Arrays;
// Java program for reversal algorithm of array rotation
//Let the array be arr[] = [1, 2, 3, 4, 5, 6, 7], d =2 and n = 7
// A = [1, 2] and B = [3, 4, 5, 6, 7]
//
// Reverse A, we get ArB = [2, 1, 3, 4, 5, 6, 7]
// Reverse B, we get ArBr = [2, 1, 7, 6, 5, 4, 3]
// Reverse all, we get (ArBr)r = [3, 4, 5, 6, 7, 1, 2]
import java.util.Arrays;
class ArrayRotate {
static void leftRotate(int[] arr, int d) {
if (d == 0)
return;
int n = arr.length;
reveresArray(arr, 0, d - 1);
reveresArray(arr, d, n - 1);
reveresArray(arr, 0, n - 1);
}
static void reveresArray(int[] arr, int start, int end) {
int temp;
while (start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
static void printArray(int[] arr) {
Arrays.stream(arr).mapToObj(item -> item + " ").forEach(System.out::print);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
int n = arr.length;
int d = 2;
leftRotate(arr, d); // Rotate array by d
printArray(arr);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>while the solution is functional. it is overly complex. rotation is a simple algorithm of index arithmetic: start with the first cell, with each iteration, you determine the source and destination indexes of one value, move that value into place, take the evicted value and set the next iteration to determine its new place. </p>\n\n<p>so we start with idx <code>0</code> and determine its place is at idx <code>5</code>. in the next iteration we start with idx <code>5</code> and determine its new place and so on.</p>\n\n<pre><code>static void leftRotate(int[] arr, int d) {\n int srcIdx, dstIdx;\n srcIdx = 0;\n int val = arr[srcIdx];\n // loop only used to count (i not used as index)\n for (int i = 0; i < arr.length ; i++) {\n dstIdx = srcIdx - d;\n if (dstIdx < 0) dstIdx = arr.length + dstIdx; // rotate dst idx from start to end of arr\n int temp = arr[dstIdx];\n arr[dstIdx] = val;\n val = temp; // set next iteration value to move\n srcIdx = dstIdx; // set next iteration srcIdx\n }\n}\n</code></pre>\n\n<p>also, <code>printArray</code> is redundant. use <code>Arrays.tostring()</code></p>\n\n<h2>EDIT</h2>\n\n<p>thanks to @Imus, there is a nasty bug in my \"simple\" algorithm described above.\nThe bug occurs when the array is divisible by <code>d</code>. in this case, following src-dst-src-dst chain results in processing the same indexes in a loop, while missing other indexes. The solution (that I found) is to detect such cases of \"closed-loop\" and advance the pointers one cell ahead. admittedly, it does make the solution more complex.</p>\n\n<p>below is a fixed solution.</p>\n\n<pre><code>static void leftRotate(int[] arr, int d) {\n int srcIdx, dstIdx, loopDetectIdx;\n srcIdx = 0;\n loopDetectIdx = 0; // detects processing in \"closed loop\" \n int val = arr[srcIdx];\n for (int i = 0; i < arr.length ; i++) {\n dstIdx = srcIdx - d;\n // rotate dst idx from start to end of arr\n if (dstIdx < 0) dstIdx = arr.length + dstIdx;\n int temp = arr[dstIdx];\n arr[dstIdx] = val;\n System.out.println(srcIdx + \"-\" + dstIdx + \" \" + Arrays.toString(arr));\n val = temp;\n srcIdx = dstIdx;\n // if we already processed srcIdx, move all pointers one cell forward \n if (srcIdx == loopDetectIdx) {\n srcIdx++;\n loopDetectIdx++;\n val = arr[srcIdx];\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T08:44:12.387",
"Id": "464525",
"Score": "0",
"body": "You should align `d` to the length of `arr`: `d %= arr.length;`. Else your algorithm fails - and you also optimize the swapping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:24:09.053",
"Id": "464529",
"Score": "1",
"body": "@HenrikHansen, good comment. OP should take notice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:30:17.873",
"Id": "464562",
"Score": "0",
"body": "Your solution fails if `d` is a divisor of arr.length. For example, using `arr= new int[]{0, 1, 2, 3}` and `d=2` it outputs `[0, 1, 0, 3]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T14:14:49.670",
"Id": "464564",
"Score": "0",
"body": "@Imus, thanks. that was a nasty bug indeed. I fixed the proposed solution, however, now it doesn't look as clean and simple as intended (yeah, thanks a lot! :))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T14:27:29.013",
"Id": "464565",
"Score": "0",
"body": "Interesting solution. I prefer OP's solution for readability though. Without benchmarking I can't say which one would be more efficient though (given that the java compiler will optimise certain things better than others)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T08:00:53.027",
"Id": "236971",
"ParentId": "236959",
"Score": "3"
}
},
{
"body": "<p>Your implementation looks good. It's an in memory algorithm so space wise you can't do better. Timewise you're looping over each element swapping it twice so that's perfectly fine.</p>\n\n<p>The only remark left to give is the typo in rever<strong>es</strong>Array -> rever<strong>se</strong>Array.</p>\n\n<p>It's also possible to print the array using <code>System.out.println(Arrays.toString(arr));</code> so you don't really need your own method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:39:49.230",
"Id": "236992",
"ParentId": "236959",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T03:11:52.873",
"Id": "236959",
"Score": "4",
"Tags": [
"java"
],
"Title": "Rotating an array by mentioned digit to rotate"
}
|
236959
|
<p>I'm developing a Go application that has lots of packages.<br>
Many of the packages use the same type from a 3rd party library.<br>
Should an interface be defined for the type in each package, and let the interfaces only contain the methods that are used by the package?<br>
Or, we should define a single interface for the whole application, and let the interface contain the union of all the methods that are used throughout the application?<br>
At <a href="https://github.com/golang/go/wiki/CodeReviewComments#interfaces" rel="nofollow noreferrer">official Golang wiki</a>, there's a statement</p>
<blockquote>
<blockquote>
<p>Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values.</p>
</blockquote>
</blockquote>
<p>But does <strong>the package</strong> means the one that actually uses the type or the root package of the project?<br>
Here's a simplified example:</p>
<pre><code>package subnet
type netOpsClient interface {
Subnets(ctx context.Context, options map[string]string) ([]string, error)
}
type PrimaryNetFinder struct {
netOpsClient netOpsClient
}
func (p *PrimaryNetFinder) Find(ctx context.Context) ([]string, error) {
subnets, err := p.netOpsClient.Subnets(ctx, map[string]string{
"level": "50",
})
//...
}
</code></pre>
<pre><code>package loader
type netOpsClient interface {
Subnets(ctx context.Context, options map[string]string) ([]string, error)
SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
}
type RulesLoader struct {
netOpsClient netOpsClient
policyStore policyStore
}
func (r *RulesLoader) LoadRules(ctx context.Context) error {
//...
subnets, err := r.netOpsClient.Subnets(ctx, map[string]string{
"level": level,
"site": "ne",
})
//...
subnet, err := r.netOpsClient.SubnetGet(ctx, subnetId)
//...
policies, err := policyStore.Policies(subnet.cidr)
//...
}
</code></pre>
<p>You can see both <code>PrimaryNetFinder</code> and <code>RulesLoader</code> store a field of type <code>netOpsClient</code>, which is an interface defined in the package. And a type from a 3-party <code>NetOpsClient</code> implements the interface.<br>
If many packages in the project have a reference to the type, should each package define a similar interface like above? Or, should I define a single interface, and let all the packages share the same interface like below?</p>
<pre><code>package netops
type NetOpsClient interface {
Subnets(ctx context.Context, options map[string]string) ([]string, error)
SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
// ...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T07:29:32.383",
"Id": "464516",
"Score": "2",
"body": "Welcome to CodeReview@SE. `Here's a simplified example` The guideline is [Real code that is yours to change, with enough context to give Good Advice](https://codereview.stackexchange.com/help/on-topic). (I think this might include one each snippet *defining* and *using* the same interface.)"
}
] |
[
{
"body": "<p>Personally I would define it in each package that uses it. It would only be a small amount of duplication but has many advantages:</p>\n\n<ol>\n<li>It keeps the package self contained.</li>\n<li>You mentioned that not all packages use the same method so it stops the interface getting very large.</li>\n<li>If not every package uses each method it makes it explicit which method a package does use.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T07:01:33.373",
"Id": "236966",
"ParentId": "236960",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236966",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T03:18:19.797",
"Id": "236960",
"Score": "0",
"Tags": [
"go",
"interface"
],
"Title": "Should Golang interface be shared among different packages of an application?"
}
|
236960
|
<p>I have a set of products(e.g. P0006, P0009, etc.) and a set of production lines (eg. L1H175, L2H175). A product can be produced on a subset of the lines set (and not necessarily all of them).</p>
<p>If we decide to produce a product on a production line(assuming that the line can actually produce it), we need to buy the appropriate raw materials (e.g. If we decide to produce P0009 on L1h175 we need to buy the set of the selected raw materials in the image). Each raw material has a price and a property(S or NS). </p>
<p>What I want the code to do: </p>
<ol>
<li><p>For each product, return where it can be produced. For example, to see where P0009 can be produced, I need to look at all the rows of the fist columns and whenever I find it, I add the appropriate line id to the set of lines that produce that product. </p></li>
<li><p>Reversely, for each line, what are the products that it can produce.</p></li>
<li><p>For each <code>(p,l)</code> couple store the set of all need raw materials, to produce product <code>p</code> on <code>l</code>, the property of each raw material(coded as 1 if it's S and 0 otherwise) and the total price (I don't need individual prices).</p></li>
</ol>
<p>Here is how I am doing it now: </p>
<pre class="lang-py prettyprint-override"><code>def process(x, y, recipes_df):
raw_materials = {}
total_cost = 0
for product, line, rm, rm_type, rm_price in \
recipes_df[['product','line', 'rm','rm_type','rm_price']].values:
if (x,y) == (product,line):
total_cost += float(rm_price)
raw_materials[rm] = 1 if rm_type == 'S' else 0
return (raw_materials, total_cost)
lines_set = set(recipes_df['line'])
lines = []
rm_data = {}
products_set = set()
for line in lines_set:
for row in recipes_df.itertuples(index=False):
# if the line_id in this row correspond to line in the outer loop
if row[1] == line:
# extract the raw material information by using the process function.
rm_data[row[0]] = process(row[0],row[1], recipes_df)
# add the product to the set of products that can be manufactured on the line
products_set.add(row[0])
# add the informations to lines list
lines.append((rm_data, products_set))
</code></pre>
<p>The file has more than 3000 lines, my approach takes a lot of time.</p>
<p><strong>Observations:</strong>
0. There is no assumption about how the file is sorted, meaning that, I can find P0009 in line 1 and in line 3000, for example, with a lot of other products in between. Same remark for the lines.
1. The process function search in all the file every time it's cold for a couple <code>(p,l)</code>, which may be inefficient
2. For every <code>line</code> in <code>lines_set</code> we browse all the file. </p>
<p><a href="https://i.stack.imgur.com/rpY1Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rpY1Z.png" alt="enter image description here"></a></p>
<p><strong>Question: How to do all of this more efficiently?</strong></p>
<p>Edit : I did only 2. and 3., the 1. is very similar to 2.</p>
<p>Edit2: recipes_df is a pandas data frame</p>
<p>Edit3: <a href="https://drive.google.com/file/d/1HyvaOQShfWhLH8-GUMJmmCib6E5si9ym/view?usp=sharing" rel="nofollow noreferrer">The link to the data</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T06:19:46.790",
"Id": "464511",
"Score": "5",
"body": "Please provide a copy of the Dataframe as text, or parseable format (csv), not an image. Not very many people are going to type it in to test their code."
}
] |
[
{
"body": "<p>In general if you have relational data in a list-like data structure, you want to convert it into a more appropriate data structure before you do anything tricky with it. I'm not sure what the type of <code>recipes_df</code> so I'm just going to copy your code that iterates over it and go from there.</p>\n\n<pre><code>from collections import defaultdict\nfrom typing import Dict, List, Set, Tuple\n\n# For each product, return where it can be produced.\nproduct_lines: Dict[str, Set[str]] = defaultdict(set)\n\n# For each line, what are the products that it can produce.\nline_products: Dict[str, Set[str]] = defaultdict(set)\n\n# For each (p,l) couple store the set of all need raw materials \n# to produce product p on l, the property of each raw material\n# (coded as 1 if it's S and 0 otherwise), and the total price\nclass Recipe:\n def __init__(self):\n self.raw_materials: List[Tuple[str, int]] = []\n self.total_price = 0.0\nrecipes: Dict[Tuple[str, str], Recipe] = defaultdict(Recipe)\n\n# Loop over recipes_df and populate all these structures.\nfor product, line, rm, rm_type, rm_price in \\\n recipes_df[['product','line', 'rm','rm_type','rm_price']].values:\n product_lines[product].add(line)\n line_products[line].add(product)\n recipes[(product, line)].raw_materials.append((rm, 1 if rm_type == 'S' else 0))\n recipes[(product, line)].total_price += rm_price\n</code></pre>\n\n<p>At this point you've done a single pass through the entirety of <code>recipes_df</code> and you've completely populated the dictionaries that will let you find all the information you're looking for in constant time. From here you can convert those dictionaries into whatever other output format you need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T05:56:04.773",
"Id": "464507",
"Score": "0",
"body": "Thanks for your answer! recipes_df is a pandas data frame"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T06:01:40.800",
"Id": "464508",
"Score": "0",
"body": "Why did you used a class for the recipe? What is the \"intuition\" behind, i.e what makes you think of using a class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T06:18:57.763",
"Id": "464510",
"Score": "0",
"body": "I want it to be a collection so I can have it as the value in a single dict, I want it to be well-typed (so a list is out, since all of a list's items are typed the same), and I want it to be mutable so I can build it as I iterate through the DF (so a tuple is out). That leaves a standard class as the easiest choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T06:21:48.660",
"Id": "464512",
"Score": "0",
"body": "It's also convenient to be able to define a constructor that sets up both the empty list and the 0.0 value, and then pass that constructor to `defaultdict`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T05:52:06.467",
"Id": "236964",
"ParentId": "236961",
"Score": "6"
}
},
{
"body": "<p>Pass through the data just once, building up the desired data as you go:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nfrom collections import defaultdict\n\nrecipies_df = pd.read_csv('/home/mike/Downloads/recipes.csv', sep=';')\n\n# maps products to the lines that can make it \nlines_by_product = defaultdict(set)\n\n# maps lines to the products it can make\nproducts_by_line = defaultdict(set)\n\n# maps (product, line) to raw materials and cost\nrms_by_product_line = defaultdict(lambda:[defaultdict(int),0])\n\n\nfor row in recipies_df.itertuples(index=False):\n lines_by_product[row.product].add(row.line)\n\n products_by_line[row.line].add(row.product)\n\n rms,cost = rms_by_product_line[row.product, row.line]\n rms[row.rm] = 1 if row.rm_type == 'S' else 0\n cost += float(row.rm_price_per_ton)\n rms_by_product_line[row.product, row.line] = rms,cost\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T07:32:08.237",
"Id": "236970",
"ParentId": "236961",
"Score": "1"
}
},
{
"body": "<p>Python is rather slow for iterations. If your data is in a pandas Dataframe, try to do things as vectorised as possible. You even iterate over the complete dataset for each row of your dataset, for each separate line. This is very inefficient.</p>\n\n<p>If you need to iterate over all unique values of a column, and do operations on all relevant row, <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html\" rel=\"nofollow noreferrer\"><code>groupby</code></a> is your friend. You can even group by 2 columns at the same time</p>\n\n<pre><code>from collections import defaultdict\n\nlines2 = defaultdict(dict)\nproduct_lines = defaultdict(set)\nline_products = defaultdict(set)\n\nfor (product, line), data in recipes_df.groupby([\"product\", \"line\"]):\n</code></pre>\n\n<p>This sets up our data holders and starts iterating over the product, line combinations. A dict containing the lines as keys and the products that can be made on the line in a set, and vice versa. The <code>lines2</code> is a dict with the line as key, and a seconds dict as value. This second dict has the product as key, and the extra info as values</p>\n\n<pre><code> product_lines[product].add(line)\n line_products[line].add(product)\n</code></pre>\n\n<p>This second is now filled with the data in the group, so no need to iterate over the complete dataset for each row, but only the limited, relevant rows.</p>\n\n<pre><code> lines2[line][product] = {\n \"raw_materials\": {\n row.rm: row.rm_type == \"S\" for row in data.itertuples()\n },\n \"cost\": data[\"rm_price_per_ton\"].sum(),\n }\n</code></pre>\n\n<blockquote>\n<pre><code>{'L2H175': {'P00004': {'raw_materials': {'RM00071': True,\n 'RM00055': True,\n 'RM00058': True,\n 'RM00054': True,\n 'RM00175': False,\n 'RM00149': False,\n 'RM00029': False,\n 'RM00148': False,\n 'RM00152': False,\n 'RM00088': False,\n 'RM00065': False,\n 'RM00097': False},\n 'cost': 62.02},\n 'P00005': {'raw_materials': {'RM00030': True,\n 'RM00055': True,\n 'RM00058': True,\n 'RM00054': True,\n 'RM00175': False,\n 'RM00029': False,\n 'RM00149': False,\n 'RM00152': False,\n 'RM00088': False,\n 'RM00064': False,\n 'RM00097': False},\n 'cost': 75.07},\n ...\n</code></pre>\n</blockquote>\n\n<p>Instead of 1 and 0, I use True and False as flag here, since that better expresses the boolean nature. If you need 1 and 0, you can surround the <code>row.rm_type == 'S'</code> with <code>int(...)</code></p>\n\n<p>Or you can work with some dict comprehensions:</p>\n\n<pre><code>product_lines = {\n line: set(data[\"product\"].unique())\n for line, data in recipes_df.groupby([\"line\"])\n}\nline_products = {\n product: set(data[\"line\"].unique())\n for product, data in recipes_df.groupby([\"product\"])\n}\n</code></pre>\n\n<p>If you want a tuple as key, you can do:</p>\n\n<pre><code>lines3 = {\n (product, line): {\n \"raw_materials\": {\n row.rm: row.rm_type == \"S\" for row in data.itertuples()\n },\n \"cost\": data[\"rm_price_per_ton\"].sum(),\n }\n for (product, line), data in recipes_df.groupby([\"product\", \"line\"])\n}\n</code></pre>\n\n<p>If you want it nested, like <code>lines2</code> you can do 2 nested <code>groupby</code>s</p>\n\n<pre><code>lines4 = {\n line: {\n product: {\n \"raw_materials\": {\n row.rm: row.rm_type == \"S\" for row in data.itertuples()\n },\n \"cost\": data[\"rm_price_per_ton\"].sum(),\n }\n for product, data in line_data.groupby([\"product\"])\n }\n for line, line_data in recipes_df.groupby([\"line\"])\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:45:52.290",
"Id": "464620",
"Score": "0",
"body": "Could you explain a little bit more on when to use goupby, If I am getting you right, it's useful when we have repetitions. Am I right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:43:46.437",
"Id": "236979",
"ParentId": "236961",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T05:19:03.150",
"Id": "236961",
"Score": "4",
"Tags": [
"python",
"performance",
"complexity"
],
"Title": "How to do these extraction/computations efficiently?"
}
|
236961
|
<p>I have implemented a very simple but robust implementation of <a href="https://en.wikipedia.org/wiki/Golomb_coding" rel="noreferrer">the Golomb-Rice coding</a>.
To understand my motivation, see <a href="https://github.com/xbarin02/x-compressor" rel="noreferrer">the minimalist data compressor</a> that is based on this.
At the moment, the implementation works well.
However, I intend to make it more elegant, concise, and possibly faster.
Any suggestions for improvement or constructive criticism are welcome.</p>
<h2>Prerequisites</h2>
<ul>
<li>The <code>typedef</code> name <code>uint32</code> designates an unsigned integer type with width exactly 32 bits.</li>
<li>The <code>uchar</code> name is an alias for <code>unsigned char</code>.</li>
<li>Function <code>size_t minsize(size_t a, size_t b)</code> returns the minimum of <code>a</code> and <code>b</code>.</li>
<li>Function <code>size_t ctzu32(uint32 n)</code> returns the number of trailing 0-bits in <code>n</code>, starting at the least significant bit position. If <code>n</code> is 0, the result is 32.</li>
</ul>
<h2>Code</h2>
<p>The implementation uses the following data structure:</p>
<pre><code>enum {
BIO_MODE_READ,
BIO_MODE_WRITE
};
struct bio {
int mode; /* reading or writing? */
uchar *ptr; /* pointer to memory */
uint32 b; /* bit buffer */
size_t c; /* bit counter */
};
</code></pre>
<p>Furthermore, I use several auxiliary functions (it is a bit long):</p>
<pre><code>static void bio_reset_after_flush(struct bio *bio)
{
assert(bio != NULL);
bio->b = 0;
bio->c = 0;
}
static void bio_open(struct bio *bio, uchar *ptr, int mode)
{
assert(bio != NULL);
assert(ptr != NULL);
bio->mode = mode;
bio->ptr = ptr;
switch (mode) {
case BIO_MODE_READ:
bio->c = 32;
break;
case BIO_MODE_WRITE:
bio_reset_after_flush(bio);
break;
}
}
static void bio_flush_buffer(struct bio *bio)
{
assert(bio != NULL);
assert(bio->ptr != NULL);
assert(sizeof(uint32) * CHAR_BIT == 32);
*((uint32 *)bio->ptr) = bio->b;
bio->ptr += 4;
}
static void bio_reload_buffer(struct bio *bio)
{
assert(bio != NULL);
assert(bio->ptr != NULL);
bio->b = *(uint32 *)bio->ptr;
bio->ptr += 4;
}
static void bio_put_nonzero_bit(struct bio *bio)
{
assert(bio != NULL);
assert(bio->c < 32);
bio->b |= (uint32)1 << bio->c;
bio->c++;
if (bio->c == 32) {
bio_flush_buffer(bio);
bio_reset_after_flush(bio);
}
}
static void bio_write_bits(struct bio *bio, uint32 b, size_t n)
{
assert(n <= 32);
while (n > 0) {
size_t m;
assert(bio->c < 32);
m = minsize(32 - bio->c, n);
assert(32 >= bio->c + m);
bio->b |= (uint32)((b & (((uint32)1 << m) - 1)) << bio->c);
bio->c += m;
if (bio->c == 32) {
bio_flush_buffer(bio);
bio_reset_after_flush(bio);
}
b >>= m;
n -= m;
}
}
static void bio_write_zero_bits(struct bio *bio, size_t n)
{
assert(n <= 32);
while (n > 0) {
size_t m;
assert(bio->c < 32);
m = minsize(32 - bio->c, n);
assert(32 >= bio->c + m);
bio->c += m;
if (bio->c == 32) {
bio_flush_buffer(bio);
bio_reset_after_flush(bio);
}
n -= m;
}
}
static uint32 bio_read_bits(struct bio *bio, size_t n)
{
uint32 w;
size_t s;
/* reload? */
if (bio->c == 32) {
bio_reload_buffer(bio);
bio->c = 0;
}
/* get the avail. least-significant bits */
s = minsize(32 - bio->c, n);
w = bio->b & (((uint32)1 << s) - 1);
bio->b >>= s;
bio->c += s;
n -= s;
/* need more bits? reload & get the most-significant bits */
if (n > 0) {
assert(bio->c == 32);
bio_reload_buffer(bio);
bio->c = 0;
w |= (bio->b & (((uint32)1 << n) - 1)) << s;
bio->b >>= n;
bio->c += n;
}
return w;
}
static void bio_close(struct bio *bio)
{
assert(bio != NULL);
if (bio->mode == BIO_MODE_WRITE && bio->c > 0) {
bio_flush_buffer(bio);
}
}
static void bio_write_unary(struct bio *bio, uint32 N)
{
while (N > 32) {
bio_write_zero_bits(bio, 32);
N -= 32;
}
bio_write_zero_bits(bio, N);
bio_put_nonzero_bit(bio);
}
static uint32 bio_read_unary(struct bio *bio)
{
/* get zeros... */
uint32 total_zeros = 0;
assert(bio != NULL);
do {
size_t s;
/* reload? */
if (bio->c == 32) {
bio_reload_buffer(bio);
bio->c = 0;
}
/* get trailing zeros */
s = minsize(32 - bio->c, ctzu32(bio->b));
bio->b >>= s;
bio->c += s;
total_zeros += s;
} while (bio->c == 32);
/* ...and drop non-zero bit */
assert(bio->c < 32);
bio->b >>= 1;
bio->c++;
return total_zeros;
}
</code></pre>
<p>Finally, the main entry functions (that encode/decode non-negative integer <code>N</code> using parameter <code>2^k</code>) are defined as follows:</p>
<pre><code>void bio_write_gr(struct bio *bio, size_t k, uint32 N)
{
uint32 Q = N >> k;
bio_write_unary(bio, Q);
assert(k <= 32);
bio_write_bits(bio, N, k);
}
uint32 bio_read_gr(struct bio *bio, size_t k)
{
uint32 Q;
uint32 N;
Q = bio_read_unary(bio);
N = Q << k;
assert(k <= 32);
N |= bio_read_bits(bio, k);
return N;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:53:50.500",
"Id": "464658",
"Score": "0",
"body": "OT: the function: `assert()` should not be in production code and does not display the information needed when debugging"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:11:03.967",
"Id": "464788",
"Score": "2",
"body": "@user3629249 Quoting from the corresponding man page: _If the macro `NDEBUG` is defined at the moment `<assert.h>` was last included, the macro `assert()` generates no code, and hence does nothing at all._ And further: _The error message includes the name of the file and function containing the `assert()` call, the source code line number of the call, and the text of the argument_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T18:22:27.607",
"Id": "465311",
"Score": "0",
"body": "Not shown here, but aside [the parameter N in bio_write_gr](https://github.com/xbarin02/x-compressor/blob/76870ce81a059710aa30635ee4d5b15eacb9ce25/libx.c#L234) and [the local variable N in bio_read_gr](https://github.com/xbarin02/x-compressor/blob/76870ce81a059710aa30635ee4d5b15eacb9ce25/libx.c#L246) your current implementation also contains [a global variable named N](https://github.com/xbarin02/x-compressor/blob/76870ce81a059710aa30635ee4d5b15eacb9ce25/libx.c#L24). This makes it harder to read."
}
] |
[
{
"body": "<h1>Give the mode enum a name</h1>\n\n<p>While <code>enum</code>s are not strongly typed in C, it is more elegant to pretend they are. Give the <code>enum</code> you are declaring a type, and use it in <code>struct bio</code>, like so:</p>\n\n<pre><code>enum bio_mode {\n BIO_MODE_READ,\n BIO_MODE_WRITE,\n};\n\nstruct bio {\n enum bio_mode mode;\n ...\n};\n</code></pre>\n\n<p>Compilers can use this information, for example if you write a <code>switch (mode) {...}</code> statement and you forget to handle all possible modes, the compiler will warn about this.</p>\n\n<p>Also change functions that take <code>int mode</code> as a parameter to <code>enum bio_mode mode</code>.</p>\n\n<h1>Use standard types where possible</h1>\n\n<p>Use the standard fixed width integer types from <a href=\"https://en.cppreference.com/w/c/types/integer\" rel=\"nofollow noreferrer\"><code><stdint.h></code></a> instead of inventing your own names. So instead of <code>uint32</code>, use <code>uint32_t</code>, and instead of <code>uchar</code>, use <code>uint8_t</code>.</p>\n\n<p>There is no need to <code>assert()</code> that the size of <code>uint32_t</code> is 32 bits.</p>\n\n<h1>Reorder <code>struct bio</code> to be more compact</h1>\n\n<p>On most 64-bit architectures, the layout of <code>struct bio</code> is suboptimal, because pointers and <code>size_t</code> have a 64-bit alignment, while <code>int</code>s have 32-bit alignment. I suggest the following:</p>\n\n<pre><code>struct bio {\n enum bio_mode mode;\n uint32_t b;\n uint8_t *ptr;\n size_t c; \n};\n</code></pre>\n\n<h1>Make <code>ptr</code> <code>uint32_t *</code></h1>\n\n<p>Since you are casting <code>ptr</code> to <code>uint32_t *</code> in many places, it makes more sense to store it directly as that type, and only cast it once in <code>bio_open()</code>. I also recommend you take a <code>void *</code> in <code>bio_open()</code>, so there is no need for the caller to do any casting.</p>\n\n<pre><code>struct bio {\n enum bio_mode mode;\n uint32_t b;\n uint32_t *ptr;\n size_t c; \n};\n\nstatic void bio_open(struct bio *bio, void *ptr, int mode)\n{\n ...\n bio->ptr = ptr;\n ...\n}\n</code></pre>\n\n<p>Remember to also change all occurrences of <code>bio->ptr += 4</code> to <code>bio->ptr++</code>.</p>\n\n<h1>Assert that <code>ptr</code> is 32-bit aligned</h1>\n\n<p>Casting a pointer to an <code>uint32_t *</code> is only valid if the pointer is 32-bit aligned. On some architectures, accessing memory through a pointer that is not properly aligned is not allowed. On those that do, it might be less efficient than having the pointer properly aligned. To assert this write:</p>\n\n<pre><code>assert(((uintptr_t)ptr & 3) == 0);\n</code></pre>\n\n<p>Another option would be to allow <code>ptr</code> to be non-aligned in the call to <code>bio_open()</code>, but then to initialize <code>bio->b</code> such that it contains the first few bytes up to the first 32-bit aligned address, and of course set <code>bio->c</code> accordingly.</p>\n\n<h1>Assert the right mode is set in <code>bio_read_*()</code> and <code>bio_write_*()</code></h1>\n\n<p>To avoid accidental reuse of a <code>struct bio</code>, or mixing read and write calls on the same <code>bio</code>, <code>assert(bio->mode == BIO_MODE_READ)</code> in read functions, and so on.</p>\n\n<h1>Optimizing <code>bio_write_bits()</code></h1>\n\n<p>There's a lot of things in <code>bio_write_bits()</code> that can be optimized. First, there is a lot of unnecessary casting going. While it doesn't change the actual binary, it cleans up the source code to remove them, and makes it easier to see the actual equations. For example, you can just write:</p>\n\n<pre><code>bio->b |= (b & ((1 << m) - 1)) << bio->c;\n</code></pre>\n\n<p>In the above, you are masking the lower bits of <code>b</code> before shifting it by <code>bio->c</code>. However, this is completely unnecessary, as either those high bits were zero to begin with, or they will be shifted out anyway. So you can write:</p>\n\n<pre><code>bio->b |= b << bio->c;\n</code></pre>\n\n<p>More importantly, you have written this function as a loop, but you would only ever have at most two iterations of the loop: either all <code>n</code> bits fit in <code>bio->b</code>, or you have to flush once and put the rest of the bits in. You can rewrite the code as follows:</p>\n\n<pre><code>static void bio_write_bits(struct bio *bio, uint32_t b, size_t n)\n{\n assert(n <= 32);\n assert((b >> n) == 0);\n assert(bio->c < 32);\n\n\n bio->b |= b << bio->c;\n bio->c += n;\n\n /* Exit early if we didn't fill bio->b yet */\n if (bio->c < 32)\n return;\n\n bio_flush_buffer(bio);\n\n /* Store the remaining bits */\n bio->c -= 32;\n bio->b = b >> (n - bio->c);\n}\n</code></pre>\n\n<p>A similar optimization is possible for <code>bio_write_zero_bits()</code>.</p>\n\n<h1>Reset <code>ptr</code> in <code>bio_close()</code></h1>\n\n<p>To catch potential use of a <code>struct bio</code> after calling <code>bio_close()</code>, set <code>bio->ptr = NULL</code> in <code>bio_close()</code>.</p>\n\n<h1>Validate your input</h1>\n\n<p>In <code>bio_read_unary()</code>, you have a loop reading zero bits. What if the input is malformed and just contains zero bits? After consuming the whole input, <code>bio_read_unary()</code> would continue reading past the end of the input.</p>\n\n<p>First, you can get rid of the loop by just assuming you have to do at most two iterations, just like in <code>bio_write_bits()</code>. Second, it would be good to have an extra field in <code>struct bio</code> that is either the remaining size in the buffer, or the end pointer, and keep track of how much you have read and written. Don't use <code>assert()</code> to check that you don't go past the end, but use an actual <code>if</code>-statement, and return an error or at least call <code>abort()</code> if the input is invalid.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T08:31:03.853",
"Id": "465427",
"Score": "1",
"body": "This is exactly what I needed. I have switched from C89 to C99, so now don't need to define my own type a can use the `uint32_t`. (This also greatly shortened the entire code.) Unfortunately, reordering the `struct bio` didn't improve the performance. Similarly, the masking the lower bits of `b` before shifting it by `bio->c` seems to be necessary, otherwise the more significant bits of `b` screw up the most significant bits of `bio->b` (which are intended to be filled by future calls of the function). Anyhow, excellent answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T10:58:43.807",
"Id": "465436",
"Score": "0",
"body": "The masking should not be necessary if the input to `bio_write_bits()` satisfies `(b >> n) == 0`. Either all bits fit in the first step, or they don't in which the ones that did not fit are shifted out. In the second step, `b` is shifted right so only those bits that didn't fit in the first step are left. Note that in the second step the result is directly assigned to `bio->b`, we don't OR it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T19:49:02.123",
"Id": "237180",
"ParentId": "236965",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237180",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T05:55:38.280",
"Id": "236965",
"Score": "5",
"Tags": [
"performance",
"c",
"compression"
],
"Title": "Minimalist Golomb-Rice coder"
}
|
236965
|
<p>I've implemented <code>atoi</code> function as described in leetcode problem <a href="https://leetcode.com/problems/string-to-integer-atoi/" rel="nofollow noreferrer">string-to-integer-atoi</a>.</p>
<p>I am looking for some feedback on writing this in a more scala native way and being able to include the requirement that:</p>
<blockquote>
<p>If the numerical value is out of the range of representable values,
INT_MAX (231 − 1) or INT_MIN (−231) is returned.</p>
</blockquote>
<pre><code> object Solution {
def myAtoi(str: String): Int = {
val charMap = Map('1'->1, '2'->2, '3'->3, '4'->4, '5'->5, '6'->6, '7'->7, '8'->8, '9'->9, '0'-> 0)
val keySet = charMap.keySet
var num = 0
var firstChar = -1
var negFlag = false
var zeroFlag = false
var cleanStr = str.reverse.dropWhile(c => !charMap.contains(c) || c == '-' || c == ' ').trim
for((c, i) <- cleanStr.view.zipWithIndex) {
var summand = c match {
case c if keySet.contains(c) => {
if(firstChar == -1) firstChar = i
charMap(c) * math.pow(10, i - firstChar).toInt
}
case '-' if(firstChar != -1) => {
negFlag = true
0
}
case _ => {
zeroFlag = true
0
}
}
num += summand
}
if(zeroFlag) 0 else if(negFlag) num * -1 else num
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few observations about your code.</p>\n\n<p><strong>incomplete</strong> - As you've noted, it doesn't handle <code>Int</code> overflow. It also doesn't handle the optional leading <code>+</code> character.</p>\n\n<p><strong>digit characters</strong> - The variables <code>charMap</code> and <code>keyMap</code> are unnecessary. The <code>.isDigit</code> and <code>.asDigit</code> methods in the standard library provide the same functionality.</p>\n\n<p><strong>Boolean logic</strong> - Consider this Boolean test: <code>!charMap.contains(c) || c == '-' || c == ' '</code> It translates to \"if c is not a digit OR if c is a dash OR if c is a space.\" But if c is a dash or space then it is already not a digit. The dash and space tests serve no purpose because no dash or space character would get beyond the digit test.</p>\n\n<p><strong>unneeded vars</strong> - There's no reason to make <code>cleanStr</code> or <code>summand</code> a <code>var</code>. Their initial values are never changed. In fact, you could just drop <code>summand</code> altogether and increment <code>num</code> directly.</p>\n\n<pre><code>num += (c match { ...//rest of code block\n</code></pre>\n\n<p><strong>excess braces</strong> - In a <code>match{...}</code> every <code>case</code> statement ends the previous code block and starts a new one. Therefore wrapping the code block in <code>{</code> braces <code>}</code> is redundant and just adds visual clutter. In other words, this...</p>\n\n<pre><code>case x =>\n //code\n //here\n</code></pre>\n\n<p>...is cleaner than this...</p>\n\n<pre><code>case x => {\n //code\n //here\n}\n</code></pre>\n\n<p><strong>style</strong> - The use of so much mutation (i.e. <code>var</code>s instead of <code>val</code>s) makes it pretty clear that you are using the Scala language to write C code. This will change as you become more familiar with the Scala standard library, the tenants of Functional Programming, and the study of other Scala code.</p>\n\n<p>Here, for example, is a Scala solution for the <strong>atoi</strong> challenge.</p>\n\n<pre><code>val numRE = \"\\\\s*([+-]?)0*(\\\\d+).*\".r\n\ndef myAtoi(str :String) :Int = str match {\n case numRE(signStr, numStr) =>\n val sign = if (Option(signStr).contains(\"-\")) -1 else 1\n val bailOut = if (sign < 0) Int.MinValue else Int.MaxValue\n if (numStr.length > 10) bailOut //too many digits\n else if (numStr.length < 10 || numStr < \"2147483648\")\n sign * numStr.foldLeft(0)(_*10 + _.asDigit) //calculate return Int\n else bailOut\n case _ => 0 //input doesn't match the pattern\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T04:33:38.323",
"Id": "466397",
"Score": "0",
"body": "Thanks for taking time to explain and also for your elegant solution :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T05:16:51.940",
"Id": "237203",
"ParentId": "236974",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:06:10.100",
"Id": "236974",
"Score": "0",
"Tags": [
"scala"
],
"Title": "implementation of atoi in scala"
}
|
236974
|
<p>I've wrote a C++ program to calculate the determinant of a matrix:</p>
<pre><code>#include <iostream>
#include <string>
double getDeterminant(double arr[], int dimension);
int main() {
//First, the user has to enter the dimension of the matrix
int dimension;
std::cout << "Please enter dimension of Matrix: ";
std::cin >> dimension;
std::cout << std::endl;
double matrix[dimension][dimension];
//Now, the user has to enter the matrix line by line, seperated by commas
std::string str;
for(int i = 1; i <= dimension; i++) {
std::cout << "Enter line " << i << " only seperated by commas: ";
std::cin >> str;
std::cout << std::endl;
str = str + ',';
std::string number;
int count = 0;
for(int k = 0; k < str.length(); k++) {
if(str[k] != ',') {
number = number + str[k];
}
else {
matrix[i - 1][count] = std::stod(number);
number = "";
count++;
}
}
}
//Conversion to a onedimensional matrix to be able to give it over as a parameter
double array[dimension * dimension];
int k = 0;
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
array[k] = matrix[i][j];
k++;
}
}
//Output
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Determinant of the matrix is : " << getDeterminant(array, dimension) << std::endl;
return 0;
}
double getDeterminant(double array[], int dimension) {
//Formula for 2x2-matrix
if(dimension == 2) {
return array[0] * array[3] - array[1] * array[2];
}
//Conversion back to 2D-array
double matrix[dimension][dimension];
int k = 0;
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
matrix[i][j] = array[k];
k++;
}
}
double result = 0;
int sign = 1;
for(int i = 0; i < dimension; i++) {
//Submatrix
double subMatrix[dimension - 1][dimension -1];
for(int m = 1; m < dimension; m++) {
int z = 0;
for(int n = 0; n < dimension; n++) {
if(n != i) {
subMatrix[m-1][z] = matrix[m][n];
z++;
}
}
}
//Conversion of the submatrix to 1D-array
double array2[(dimension - 1) * (dimension - 1)];
int k = 0;
for(int x = 0; x < dimension - 1; x++) {
for(int y = 0; y < dimension - 1; y++) {
array2[k] = subMatrix[x][y];
k++;
}
}
//recursive call
result = result + sign * matrix[0][i] * getDeterminant(array2, dimension -1);
sign = -sign;
}
return result;
}
</code></pre>
<p>I would appreciate any suggestions on improving the code!</p>
<hr>
<p>You can find the follow-up question <a href="https://codereview.stackexchange.com/questions/236986/c-determinant-calculator-follow-up">here</a>.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>double matrix[dimension][dimension];\n</code></pre>\n \n \n\n<pre><code>double array[dimension * dimension];\n</code></pre>\n \n \n\n<pre><code>double matrix[dimension][dimension];\n</code></pre>\n \n \n\n<pre><code> double subMatrix[dimension - 1][dimension -1];\n</code></pre>\n \n \n\n<pre><code> double array2[(dimension - 1) * (dimension - 1)];\n</code></pre>\n</blockquote>\n\n<p>None of those are legal C++, because <code>dimension</code> isn't a constant-expression.</p>\n\n<hr>\n\n<p>We have a signed/unsigned comparison here:</p>\n\n<blockquote>\n<pre><code> for(int k = 0; k < str.length(); k++) {\n</code></pre>\n</blockquote>\n\n<p>We can easily eliminate the compiler warning by using a more appropriate type:</p>\n\n<pre><code> for (std::size_t k = 0; k < str.length(); ++k) {\n</code></pre>\n\n<p>But a better fix, given we only use <code>k</code> to index <code>str</code>, is to use a range-based loop:</p>\n\n<pre><code> for (auto const c: str) {\n</code></pre>\n\n<hr>\n\n<p>When using <code>operator>></code> on a stream, we must always check that it succeeded, before we depend on the result:</p>\n\n<pre><code>std::size_t dimension;\nstd::cin >> dimension;\nif (!std::cin) {\n std::cerr << \"Input failed\\n\";\n return EXIT_FAILURE; // needs <cstdlib>\n}\nif (dimension == 0) {\n std::cout << \"1\\n\"; // empty matrix determinant\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T10:15:20.747",
"Id": "464538",
"Score": "0",
"body": "Should I use vectors instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T10:26:08.727",
"Id": "464539",
"Score": "0",
"body": "That would be a good choice, as that handles memory management etc. Do note that vector-of-vector doesn't have the good locality properties of array-of-array, so consider using or making a matrix class that's more efficient. You could use OpenCV `cv::Mat`, or look at the [Matrix class I recently reviewed](/a/236729)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:20:36.567",
"Id": "464547",
"Score": "0",
"body": "I would use `const auto&` in the range-`for` loop, not that the type of a string will ever change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:53:05.517",
"Id": "464555",
"Score": "0",
"body": "*“empty matrix has zero determinant”* – Actually not: https://codereview.stackexchange.com/a/236988/35991 :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:21:41.077",
"Id": "464560",
"Score": "0",
"body": "Thanks @Martin. That makes more sense for an empty product."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:23:39.680",
"Id": "464561",
"Score": "1",
"body": "@S.S.Anne, that might make sense (I'm guessing that most compilers are smart enough to copy characters rather than blindly using references as coded)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:48:33.273",
"Id": "236980",
"ParentId": "236977",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236980",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T09:26:47.310",
"Id": "236977",
"Score": "1",
"Tags": [
"c++",
"mathematics"
],
"Title": "C++ determinant calculator"
}
|
236977
|
<p>This is my implementation of Dijkstra's algorithm. It solves any order square mazes.</p>
<pre><code>from copy import deepcopy
from math import inf
import maze_builderV2 as mb
def dijkstra(maze, order, pos, finalpos):
mazemap = {}
def scan(): # Converts raw map/maze into a suitable datastructure.
for x in range(1, order+1):
for y in range(1, order+1):
mazemap[(x, y)] = {}
t = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
for z in t:
# print(z[0], z[1], maze[z[0]][z[1]])
if maze[z[0]][z[1]] == 'X':
pass
else:
mazemap[(x, y)][z] = 1
scan()
unvisited = deepcopy(mazemap)
distances = {} # Stores shortest possible distance of each node
paths = {} # Stores last node through which shortest path was acheived for each node
for node in unvisited: # Initialisation of distance information for each node
if node == pos:
distances[node] = 0 # Starting location...
else:
distances[node] = inf
while unvisited != {}:
curnode = None
for node in unvisited:
if curnode == None:
curnode = node
elif distances[node] < distances[curnode]:
curnode = node
else:
pass
# cannot use unvisited map is it will keep changing in the loop
for childnode, length in mazemap[curnode].items():
if length + distances[curnode] < distances[childnode]:
distances[childnode] = distances[curnode] + length
paths[childnode] = curnode
unvisited.pop(curnode)
def shortestroute(paths, start, end):
shortestpath = []
try:
def rec(start, end):
if end == start:
shortestpath.append(end)
return shortestpath[::-1]
else:
shortestpath.append(end)
return rec(start, paths[end])
return rec(start, end)
except KeyError:
return False
finalpath = shortestroute(paths, pos, finalpos)
if finalpath:
for x in finalpath:
if x == pos or x == finalpos:
pass
else:
maze[x[0]][x[1]] = 'W'
else:
pass
</code></pre>
<p>Problem is that it is quite slow, even compared to other implementations I have seen online. Now I could just copy those, but I wrote this from scratch with minimal help online and by just reading descriptions about the algorithm, all for the purpose of learning. So just copying better code would not serve my purpose.</p>
<p>So can someone tell me where and how I can squeeze some more performance out of this?</p>
<p>Note: If there is a need for my custom maze generating code, here it is:</p>
<pre><code>def mazebuilder(maze, order=10, s=(1, 1), e=(10, 10)):
from copy import deepcopy
from random import randint, choice
maze[s[0]][s[1]] = 'S' # Initializing a start position
maze[e[1]][e[1]] = 'O' # Initializing a end position
finalpos = e
pos = s
blocks = []
freespaces = [(x, y) for x in range(1, order+1) for y in range(1, order+1)]
def blockbuilder(kind):
param1 = param2 = 0
double = randint(0, 1)
if kind == 0:
param2 = randint(3, 5)
if double:
param1 = 2
else:
param1 = 1
else:
param1 = randint(3, 5)
if double:
param2 = 2
else:
param2 = 1
for a in range(blockstarter[0], blockstarter[0]+param2):
for b in range(blockstarter[1], blockstarter[1]+param1):
if (a+1, b) in blocks or (a-1, b) in blocks or (a, b+1) in blocks or (a, b-1) in blocks or (a, b) in blocks or (a+1, b+1) in blocks or (a-1, b+1) in blocks or (a+1, b-1) in blocks or (a-1, b-1) in blocks:
pass
else:
if a > order+1 or b > order+1:
pass
else:
if maze[a][b] == 'X':
blocks.append((a, b))
else:
spaces = [(a+1, b), (a-1, b), (a, b+1), (a, b-1)]
for c in spaces:
if maze[c[0]][c[1]] == 'X':
break
else:
maze[a][b] = 'X'
blocks.append((a, b))
for x in range(1, order+1):
for y in range(1, order+1):
if (x, y) in freespaces:
t = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
i = 0
while i < len(t):
if maze[t[i][0]][t[i][1]] == 'X' or (t[i][0], t[i][1]) == pos or (t[i][0], t[i][1]) == finalpos:
del t[i]
else:
i += 1
if len(t) > 2:
blockstarter = t[randint(0, len(t)-1)]
kind = randint(0, 1) # 0 - vertical, 1 - horizontal
blockbuilder(kind)
else:
pass
b = 0
while b < len(blocks):
block = blocks[b]
t = {'d':(block[0]+2, block[1]), 'u':(block[0]-2, block[1]), 'r':(block[0], block[1]+2), 'l':(block[0], block[1]-2)}
rch = choice(['d', 'u', 'r', 'l'])
z = t[rch]
if z[0] > order-2 or z[1] > order-2 or z[0] < 2+2 or z[1] < 2+2: # Decreased chance of having non solvable maze being generated...
pass
else:
if maze[z[0]][z[1]] == 'X':
if randint(0, 1):
set = None
if rch == 'u':
set = (z[0]+1, z[1])
elif rch == 'd':
set = (z[0]-1, z[1])
elif rch == 'r':
set = (z[0], z[1]-1)
elif rch == 'l':
set = (z[0], z[1]+1)
else:
pass
if maze[set[0]][set[1]] == '_':
# Checks so that no walls that block the entire way are formed
# Makes sure maze is solvable
sets, count = [(set[0]+1, set[1]), (set[0]-1, set[1]), (set[0], set[1]+1), (set[0], set[1]-1)], 0
for blyat in sets:
while blyat[0] != 0 and blyat[1] != 0 and blyat[0] != order+1 and blyat[1] != order+1:
ch = [(blyat[0]+1, blyat[1]), (blyat[0]-1, blyat[1]), (blyat[0], blyat[1]+1), (blyat[0], blyat[1]-1)]
suka = []
for i in ch:
if ch not in suka:
if maze[i[0]][i[1]] == 'X':
blyat = i
break
else:
pass
suka.append(ch)
else:
pass
else:
blyat = None
if blyat == None:
break
else:
pass
else:
count += 1
if count < 1:
maze[set[0]][set[1]] = 'X'
blocks.append(set)
else:
pass
else:
pass
else:
pass
b += 1
</code></pre>
|
[] |
[
{
"body": "<p>I believe the code is slow because you are using normal Dijkstra, which takes <code>O(V^2)</code> where <code>V</code> is the number of vertices (Here, <code>V</code> would be <code>N*M</code>).</p>\n\n<p>This is because you are searching for the minimum by iterating through all the unvisited elements, which takes <code>O(V)</code> time. Repeat this for <code>V</code> times and it becomes <code>O(V^2)</code>.</p>\n\n<p>You can reduce this to <code>O(V * log V)</code> by using a heap, which would increase your code's performance dramatically.</p>\n\n<p>This is a trick most competitive programmers use ;-)</p>\n\n<p>You can refer on how to use the heaps here:<br>\n<a href=\"https://courses.cs.washington.edu/courses/cse326/07au/lectures/lect22.pdf\" rel=\"nofollow noreferrer\">https://courses.cs.washington.edu/courses/cse326/07au/lectures/lect22.pdf</a></p>\n\n<p>(This one is for graphs, but you can incorporate it for mazes as well)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:17:47.867",
"Id": "237010",
"ParentId": "236981",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T10:14:33.833",
"Id": "236981",
"Score": "6",
"Tags": [
"python",
"performance",
"algorithm"
],
"Title": "I have a working Dijkstra algorithm code for solving mazes but I am looking for more performance"
}
|
236981
|
<p>After following some suggestions you can find <a href="https://codereview.stackexchange.com/questions/236977/c-determinant-calculator">here</a>, I'd like to show you the result:</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
double getDeterminant(std::vector<std::vector<double>> vect, int dimension);
int main() {
//First, the user has to enter the dimension of the matrix
int dimension;
std::cout << "Please enter dimension of Matrix: ";
std::cin >> dimension;
std::cout << std::endl;
if(dimension < 0) {
std::cout << "ERROR: Dimension cannot be < 0." << std::endl;
return -1;
}
//Now, the user has to enter the matrix line by line, seperated by commas
std::vector<std::vector<double>> vect(dimension, std::vector<double> (dimension));
std::string str;
for(int i = 1; i <= dimension; i++) {
std::cout << "Enter line " << i << " only seperated by commas: ";
std::cin >> str;
std::cout << std::endl;
str = str + ',';
std::string number;
int count = 0;
for(int k = 0; k < str.length(); k++) {
if(str[k] != ',') {
number = number + str[k];
}
else if(count < dimension) {
if(number.find_first_not_of("0123456789.-") != std::string::npos) {
std::cout << "ERROR: Not only numbers entered." << std::endl;
return -1;
}
vect[i - 1][count] = std::stod(number);
number = "";
count++;
}
else {
std::cout << "ERROR: Too many numbers entered." << std::endl;
return -1;
}
}
}
//Output
for(int i = 0; i < dimension; i++) {
for(int j = 0; j < dimension; j++) {
std::cout << vect[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << "Determinant of the matrix is : " << getDeterminant(vect, dimension) << std::endl;
return 0;
}
double getDeterminant(std::vector<std::vector<double>> vect, int dimension) {
if(dimension == 0) {
return 0;
}
if(dimension == 1) {
return vect[0][0];
}
//Formula for 2x2-matrix
if(dimension == 2) {
return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0];
}
double result = 0;
int sign = 1;
for(int i = 0; i < dimension; i++) {
//Submatrix
std::vector<std::vector<double>> subVect(dimension - 1, std::vector<double> (dimension - 1));
for(int m = 1; m < dimension; m++) {
int z = 0;
for(int n = 0; n < dimension; n++) {
if(n != i) {
subVect[m-1][z] = vect[m][n];
z++;
}
}
}
//recursive call
result = result + sign * vect[0][i] * getDeterminant(subVect, dimension - 1);
sign = -sign;
}
return result;
}
</code></pre>
<p>Do you have any more suggestions to improve the code?</p>
<hr>
<p>You can find the follow-up question <a href="https://codereview.stackexchange.com/questions/237153/c-determinant-calculator-2nd-follow-up">here</a>.</p>
|
[] |
[
{
"body": "<pre><code>if(dimension == 0) {\n return 0;\n}\n</code></pre>\n\n<p>Mathematically, that is not correct. The determinant of an empty (i.e. zero-dimensional) matrix is <em>one,</em> see for example <a href=\"https://math.stackexchange.com/q/1762537/42969\">What is the determinant of []?</a> on Mathematics Stack Exchange.</p>\n\n<hr>\n\n<p>With respect to <em>efficiency:</em> Your program computes the determinant recursively using the <a href=\"https://en.wikipedia.org/wiki/Determinant#Laplace's_formula_and_the_adjugate_matrix\" rel=\"noreferrer\">Laplace formula</a>, which requires <span class=\"math-container\">\\$ O(n!) \\$</span> arithmetic operations, and the creation of many temporary “submatrices”.</p>\n\n<p>A better method (at least for larger matrices) is <a href=\"https://en.wikipedia.org/wiki/Gaussian_elimination#Computing_determinants\" rel=\"noreferrer\">Gaussian elimination</a> which requires <span class=\"math-container\">\\$ O(n^3) \\$</span> arithmetic operations, and can operate on a single copy of the original matrix.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:42:56.620",
"Id": "236988",
"ParentId": "236986",
"Score": "14"
}
},
{
"body": "<pre><code>double getDeterminant(std::vector<std::vector<double>> vect, int dimension);\n</code></pre>\n\n<p>This will create a copy of the <code>std::vector</code>. For small <code>std::vector</code> this is not a problem, but it's good to make it a habit to pass complex data structures as <code>const&</code>, so the copy will not be created:</p>\n\n<pre><code>double getDeterminant(const std::vector<std::vector<double>>& vect, int dimension);\n</code></pre>\n\n<p>To make your code more readable, you can use an alias for the long vector name:</p>\n\n<pre><code>using Matrix = std::vector<std::vector<double>>;\ndouble getDeterminant(const Matrix& vect, int dimension);\n</code></pre>\n\n<p>Lastly it is not necessary to pass the dimension, as it is accessible from the vector class:</p>\n\n<pre><code>double getDeterminant(const Matrix& vect); \n// instead dimension = vect.size();\n</code></pre>\n\n<p><code>std::endl</code> will flush the output buffer. Only use it, if you want the buffer to be flushed. Writing to the screen takes a fair amount of time (compared to other instructions). Instead just use <code>\\n</code>, it is cross-platform compatible</p>\n\n<pre><code>std::cin >> dimension;\nstd::cout << '\\n';\n</code></pre>\n\n<p>This terminates the program. A better way of handling the erroneous input would be to allow the user to repeat the line</p>\n\n<pre><code>if(number.find_first_not_of(\"0123456789.-\") != std::string::npos) {\n std::cout << \"ERROR: Not only numbers entered.\" << std::endl;\n return -1;\n}\n</code></pre>\n\n<p>Furthermore, this still allows for invalid numbers, I could input something like <code>.-.-.-.</code> for example. </p>\n\n<p>This </p>\n\n<pre><code>number = number + str[k];\n</code></pre>\n\n<p>Can be replaced by the shorter version </p>\n\n<pre><code>number += str[k];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:47:33.240",
"Id": "236989",
"ParentId": "236986",
"Score": "10"
}
},
{
"body": "<p>A vector of vectors can be an inefficient representation, because the storage may be scattered across many pages of memory. We can keep the data close together by using a single vector, and linearising the rows within it, perhaps like this:</p>\n\n<pre><code>#include <cstddef>\n#include <vector>\n\nclass Matrix\n{\n std::size_t width;\n std::size_t height;\n std::vector<double> content;\n\npublic:\n Matrix(std::size_t width, std::size_t height)\n : width{width},\n height{height},\n content(width * height)\n {}\n\n double& operator()(std::size_t row, std::size_t col) {\n return content[row * width + col];\n }\n\n double const& operator()(std::size_t row, std::size_t col) const {\n return content[row * width + col];\n }\n};\n</code></pre>\n\n<hr>\n\n<p>Repeating from the original review:</p>\n\n<ul>\n<li>always check the result of stream input operations</li>\n<li>avoid comparing signed and unsigned types; or better, avoid the comparison by using range-based <code>for</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:30:39.317",
"Id": "464671",
"Score": "0",
"body": "You should add a mechanism to initialize the `Matrix`. Right now the official way is to assign the elements one by one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:08:23.147",
"Id": "464713",
"Score": "0",
"body": "Left as an excercise; it's not hard to add a `std::initializer_list<double>` to the arguments. That's a distraction from the main point, which is to linearise the array of elements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:55:51.593",
"Id": "236994",
"ParentId": "236986",
"Score": "8"
}
},
{
"body": "<p>Though there is already an accepted answer, I would add that usually, you would want to only return values between 0 and 127 in <code>main</code> -- just replace <code>return -1;</code> with <code>return 1;</code>, following the convention that non-zero exit codes represent errors or exceptions. (<a href=\"https://stackoverflow.com/a/8083027/9870592\">https://stackoverflow.com/a/8083027/9870592</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T16:31:24.997",
"Id": "237090",
"ParentId": "236986",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T12:26:50.570",
"Id": "236986",
"Score": "4",
"Tags": [
"c++",
"mathematics"
],
"Title": "C++ determinant calculator - follow-up"
}
|
236986
|
<p>I'm working on a Slack bot for service desk which sends direct message to user on a Slack when their ticket will be on <code>user_action_needed</code> status. I'm using AWS Lambda to handle Jira incoming webhooks. Everything works well but I think I've got an issue with whole architecture of the app - I quess the code is not so readable, name of the class probably doesn't match what they do.</p>
<p>First of all I've got the <code>handler</code> on AWS lambda:</p>
<pre><code> module JiraHandler
extend self
def handle(event:, _context:)
Parsers::JiraParser.new(event).call
{ statusCode: 200 }
end
end
</code></pre>
<p><code>Parsers::JiraParser</code> is responsible not only for parsing events but it calls another class which grabs <code>userId</code> from Slack, and then inside of <code>GetUserId</code> I've got another class which sends message to user. So at the end if you call <code>Parsers::JiraParser</code> class you will receive slack message instead of parsed data.</p>
<p>Details of what I wrote about each class below:</p>
<p><code>Parsers::JiraParser</code></p>
<pre><code>module Parsers
class JiraParser
def initialize(event)
payload = event['body']
@event = JSON.parse(payload)
end
def call
::Slack::GetUserId.new(reporter_email, reporter_name, ticket_number).call
end
# reporter_email, reporter_name, ticket_number are methods to pull data by .dig from event hash
</code></pre>
<p><code>GetUserId</code></p>
<pre><code> class GetUserId
SLACK_LOOKUP_BY_EMAIL = 'https://slack.com/api/users.lookupByEmail'
def initialize(email, name, ticket_number)
@email = email
@name = name
@ticket_number = ticket_number
end
def call
user_id = set_slack_user.dig('user', 'id')
::Slack::SlackMessenger.new(user_id, name, ticket_number).call
end
def set_slack_user
HTTParty.get(SLACK_LOOKUP_BY_EMAIL, options)
end
</code></pre>
<p><code>SlackMessanger</code></p>
<pre><code>module Slack
class SlackMessenger
SLACK_API_ENDPOINT = 'https://slack.com/api/chat.postMessage'
def initialize(user_id, name, ticket_number)
@user_id = user_id
@name = name
@ticket_number = ticket_number
end
def call
HTTParty.post(SLACK_API_ENDPOINT, body: params, headers: headers)
end
</code></pre>
<p>I don't think this is a good approach, should I create an extra class where all those classes will be called? or maybe I should use monads?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T17:41:54.193",
"Id": "465307",
"Score": "0",
"body": "Personally I find the `call` pattern a little opaque, you could easily replace the name `call` with something like `deliver_message_to_slack` and the behavior is more obvious"
}
] |
[
{
"body": "<p>Your code is not very clear indeed, as you said the name of the classes don't reflect what they do.</p>\n\n<p><code>GetUserId</code> sends the message to the user, I can't infer that just by the name of the class.</p>\n\n<p>You know the steps of your program, which is good, but you haven't separated them in your program, so, the first step would be to create each of these steps in an independent way and then create a class that coordinates what has to be called. I think the <code>handle</code> method can do this coordination, it doesn't need to be as clean as you did.</p>\n\n<p>Also, try to create classes that have states and operations, this way it is more object-oriented IMO. In terms of DDD, you are creating Service classes, you can try to create Entity classes.</p>\n\n<p>For example (just a draft):</p>\n\n<pre><code>slack_api = SlackAPI.new\n\nuser = ::Slack::User.new(reporter_email, reporter_name, ticket_number, slack_api.user_id)\nmessage = ::Slack::Message.new(user)\n\nslack_api.send_message!(message)\n</code></pre>\n\n<p>(I've introduced here a class that will handle the communication with the Slack API.)</p>\n\n<p>User:</p>\n\n<pre><code>class Slack::User\n def initialize(email, name, ticket_number, id)\n @id = id\n @email = email\n @name = name\n @ticket_number = ticket_number\n end\nend\n</code></pre>\n\n<p>Message:</p>\n\n<pre><code>class Slack::Message\n def initialize(user_id, name, ticket_number)\n @user_id = user_id\n @name = name\n @ticket_number = ticket_number\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-15T21:57:41.313",
"Id": "240596",
"ParentId": "237000",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T15:18:34.420",
"Id": "237000",
"Score": "2",
"Tags": [
"object-oriented",
"ruby"
],
"Title": "Change architecture of Ruby app to be more object oriented, readable"
}
|
237000
|
<p>I am writing a function to have insert a list of strings into a MySQL database and C#.</p>
<p>The process of creating the list of Components:</p>
<p>User has to scan multiple barcodes and have them stored in a list.
The goal is to take that list and insert it into a MySQL database on the click of a submit button. </p>
<p>Is the function below the best way to insert a list of strings into MySQL?</p>
<pre><code>public static void insert_db(List components, int id, string product)
{
string sql = "INSERT INTO table (id, Product, Component) VALUES ";
for(int i = 0; i < components.Count(); i++))
{
sql += "(" + id +"," + product + "," + component + ")";
if(i+1 != components.Count()) // Make sure its not the last value in the list
{
sql = sql + ",";
}
}
sqlCommand InsertDataCmd = new SqlCommand(sql, dbConn);
try
{
InsertDataCmd.ExecuteNonQuery();
}
catch (SqlException sq)
{
MessageBox.Show(sq.Message);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:35:43.270",
"Id": "464589",
"Score": "0",
"body": "https://www.w3schools.com/sql/sql_injection.asp + https://stackoverflow.com/a/23186013/648075 + https://docs.microsoft.com/en-us/dotnet/api/system.string.join . Your code looks ancient, you should really look at modern code to use the proper ways to do this. It also mixes business logic (data manipulation) with UI code (MessageBox), which is also really bad."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:50:08.593",
"Id": "237003",
"Score": "1",
"Tags": [
"c#",
"mysql"
],
"Title": "C# MySQL Database insert list of components"
}
|
237003
|
<p>I've been making a simple "game engine" for fun and I had a lot of trouble designing a decent asset management system. Currently I got it working but it uses a lot of downcasting which is usually bad practise.
The whole code wouldn't really fit here so I'm putting here the relevant parts and linking the whole thing on GitHub (<a href="https://github.com/ekardnam/Newtonic" rel="nofollow noreferrer">https://github.com/ekardnam/Newtonic</a>)</p>
<p>The design idea is this:</p>
<ul>
<li>I have an <code>AssetManager</code> class that is a singleton to which you can register specific instances of <code>IAssetCache</code> for caching assets and to which you register assets themselves (you assign an id and tell the manager how to load them, more on this later)</li>
<li>I have an <code>AssetLoader</code> singleton to which you register different providers for different type of assets (which derive from <code>IAssetProvider</code>)</li>
</ul>
<p>Here I'll post interfaces of such code</p>
<pre><code>namespace Newtonic
{
class IAssetCache
{
public:
virtual AssetType GetCachedType() = 0;
virtual void CollectGarbage() = 0;
};
template<typename T>
class AssetCache : public IAssetCache
{
public:
AssetType GetCachedType() override
{
return T::GetAssetType();
}
void CacheAsset(const std::string & id, std::shared_ptr<T> asset)
{
m_cache[id] = asset;
}
bool IsAssetCached(const std::string & id)
{
return (m_cache.find(id) != m_cache.end() && m_cache[id]);
}
std::shared_ptr<T> GetAsset(const std::string & id)
{
return m_cache[id];
}
void CollectGarbage() override
{
for (auto & kv : m_cache)
{
if (kv.second.use_count() == 1)
{
// in this case the only reference left is the cache reference
// we can free the asset from the cache
NW_WRAP_DEBUG(Core::GetCoreLogger().Debug(FormatString("Collecting asset %s of type %i", kv.first.c_str(), T::GetAssetType())));
kv.second.reset();
}
}
}
private:
std::unordered_map<std::string, std::shared_ptr<T>> m_cache;
};
}
</code></pre>
<p>I feel that <code>IAssetCache</code> is a consequence of bad code design but I need it to store different instances of caches into a map in <code>AssetManager</code>.</p>
<p>Here asset manager</p>
<pre><code>namespace Newtonic
{
class AssetManager
{
public:
static void RegisterCache(std::unique_ptr<IAssetCache> cache);
static void RegisterAsset(const std::string & id, std::unique_ptr<AssetLoadingInformation> information);
template<typename T>
static std::shared_ptr<T> GetAsset(const std::string & id)
{
AssetType type = T::GetAssetType();
if (s_caches.find(type) != s_caches.end())
{
ASSERT_TRUE(s_caches[type]->GetCachedType() == type);
AssetCache<T> *cache = dynamic_cast<AssetCache<T>*>(s_caches[type].get());
ASSERT_TRUE(cache != nullptr);
if (cache->IsAssetCached(id))
{
return cache->GetAsset(id);
}
ASSERT_TRUE(s_loadingInformation.find(id) != s_loadingInformation.end());
ASSERT_TRUE(s_loadingInformation[id]->type == type);
std::shared_ptr<T> asset = AssetLoader::LoadAsset<T>(s_loadingInformation[id].get());
cache->CacheAsset(id, asset);
return asset;
}
NW_WRAP_DEBUG(Core::GetCoreLogger().Debug(FormatString("Cache for type %d not registered", type)));
ASSERT_TRUE(s_loadingInformation.find(id) != s_loadingInformation.end());
return AssetLoader::LoadAsset<T>(s_loadingInformation[id].get());
}
static void CollectGarbage();
private:
static std::unordered_map<AssetType, std::unique_ptr<IAssetCache>> s_caches;
static std::unordered_map<std::string, std::unique_ptr<AssetLoadingInformation>> s_loadingInformation;
};
}
</code></pre>
<p>Here <code>AssetLoadingInformation</code> is a class that stores information on how to load an asset, this is what I meant by "registering assets" before (whether you want to load from a file system path or maybe in other ways, I guess it might be useful to have such feature in case I wanted to add more ways in the future). <code>AssetLoadingInformation</code> uses again polymorphism with downcasting but again I don't have any better ideas.</p>
<p>I think that posting also <code>AssetLoader</code> and <code>IAssetProvider</code> here would make the post untidy. The problem is actually the same that you have with the asset cache and manager, but I would be glad if you took a look at those files from the github repository.
The relevant files in the repo are the ones starting with asset in <code>newtonic/include</code> for headers and <code>newtonic/src</code> for implementation.</p>
<p>My main concerns are about downcasting and anyway the code feels a bit messy to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:57:32.603",
"Id": "464617",
"Score": "0",
"body": "How many different asset types do you have? Is this supposed to be thread-safe in any way? BTW: Globals (and singletons are no different!) are usually considered a bad idea. Makes code hard to test. Prefer using dependency injection instead."
}
] |
[
{
"body": "<p>I just notice that you are making two lookups that impact the performance of your operation <em>IsAssetCached</em></p>\n\n<pre><code>bool IsAssetCached(const std::string & id)\n{\n return (m_cache.find(id) != m_cache.end() && m_cache[id]);\n}\n</code></pre>\n\n<p>You don't need to do the m_cache[id]</p>\n\n<pre><code>bool IsAssetCached(const std::string & id)\n{\n return (m_cache.find(id) != m_cache.end());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:02:17.660",
"Id": "464624",
"Score": "0",
"body": "This breaks the code. If an id is in the cache but the value associated with it is a nullptr, your version will return `true` when it should return `false`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:07:28.123",
"Id": "464625",
"Score": "0",
"body": "I don't think is a good design having containers that have shared_ptrs that could be nullptr. On a container, you have objects, but you don't have entries that could be nullptr, or may be im missing something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:22:51.027",
"Id": "464628",
"Score": "0",
"body": "Good design or not, the original code allows for the possibility that a cached value can be null, and your proposed rewrite does not, which changes the behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:51:52.693",
"Id": "464679",
"Score": "0",
"body": "An empty shared_ptr (ie points to nullptr) is created when an asset is freed by CollectGarbage. As user673679 stated in his answer I should probably just remove those from the map"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:17:21.177",
"Id": "464718",
"Score": "0",
"body": "An actually if for any reason the user code calls reset on an asset shared_ptr you would have nullptr in there no?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:41:49.017",
"Id": "237021",
"ParentId": "237006",
"Score": "1"
}
},
{
"body": "<p>Design:</p>\n\n<p>It would be possible to use a single <code>AssetCache</code> for different types of asset by storing assets as <code>std::shared_ptr<void></code> and casting back to the appropriate type using <code>std::static_pointer_cast</code>. They could be stored like:</p>\n\n<pre><code> struct TypeID\n {\n std::type_index TypeIndex;\n std::string ID;\n };\n\n std::unordered_map<TypeID, std::shared_ptr<void>> m_assets; // (with appropriate hash and equality for TypeID)\n</code></pre>\n\n<p>The extra <code>std::type_index</code> per asset is probably not a concern if we're using <code>std::string</code> for asset IDs.</p>\n\n<hr>\n\n<p>Code:</p>\n\n<pre><code>void CacheAsset(const std::string & id, std::shared_ptr<T> asset)\n{\n m_cache[id] = asset;\n}\n</code></pre>\n\n<p>We can move the asset into place: <code>m_cache[id] = std::move(asset);</code>. I'd question whether it's a good idea to allow an existing asset to be overwritten without explicitly removing the old asset from the cache first.</p>\n\n<p>In addition to what <em>camp0</em> said about <code>bool IsAssetCached(const std::string & id)</code>, it should then be made <code>const</code>.</p>\n\n<pre><code>std::shared_ptr<T> GetAsset(const std::string & id)\n{\n return m_cache[id];\n}\n</code></pre>\n\n<p>This can also be <code>const</code> if we use <code>find</code> instead of <code>operator[]</code>.</p>\n\n<pre><code>void CollectGarbage() override\n{\n for (auto & kv : m_cache)\n {\n if (kv.second.use_count() == 1)\n {\n // in this case the only reference left is the cache reference\n // we can free the asset from the cache\n NW_WRAP_DEBUG(Core::GetCoreLogger().Debug(FormatString(\"Collecting asset %s of type %i\", kv.first.c_str(), T::GetAssetType())));\n kv.second.reset();\n }\n }\n}\n</code></pre>\n\n<p>We could perhaps remove the empty map entries too.</p>\n\n<pre><code>template<typename T>\nstatic std::shared_ptr<T> GetAsset(const std::string & id)\n{\n ...\n\n ASSERT_TRUE(s_caches[type]->GetCachedType() == type);\n AssetCache<T> *cache = dynamic_cast<AssetCache<T>*>(s_caches[type].get());\n</code></pre>\n\n<p>Since we've just checked that the type is the same, we don't need <code>dynamic_cast</code>, and can use <code>static_cast</code> instead.</p>\n\n<pre><code> if (cache->IsAssetCached(id))\n {\n return cache->GetAsset(id);\n }\n</code></pre>\n\n<p>We're doing two lookups here: once in <code>IsAssetCached</code>, and once in <code>GetAsset</code>. We could instead return an empty <code>std::shared_ptr<T></code> from <code>GetAsset</code> if the asset is missing.</p>\n\n<pre><code> class AssetManager\n {\n public:\n static ...\n static ...\n</code></pre>\n\n<p>Perhaps we could have an <code>AssetManager</code> instance somewhere, instead of one global one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:43:12.450",
"Id": "464672",
"Score": "0",
"body": "First about string ids, I probably may want to turn them into integer ids, I used strings because in the previous implementation I had I used strings and I wanted to avoid changing to much of other working code to test this. I should probably map string ids to integer ids and use integer ids instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:44:21.447",
"Id": "464673",
"Score": "0",
"body": "Second, probably about existsting asset being overwritten there should be an assertion as anyway id should be unique and one asset shouldn't be overwritten by a different asset"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:45:20.800",
"Id": "464675",
"Score": "0",
"body": "I thought I couldn't use static_cast when downcasting but if I actually can in there it would be great"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:46:01.817",
"Id": "464676",
"Score": "0",
"body": "Yeah doing on lookup there would be better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:50:27.920",
"Id": "464677",
"Score": "0",
"body": "I know singletons are bad design, but in the end I feel like using a singleton here isn't that much of an issue, there actually shouldn't be more than one instanced and if using a non global instance I would have to pass a reference to it around to such many other stuff that I'm unsure it would actually be better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:15:34.763",
"Id": "464716",
"Score": "0",
"body": "Could you take a look at this commit if you have time https://github.com/ekardnam/Newtonic/commit/b7f92675666c6e43e4119573b21ab39fb25df799 I still didn't make AssetManager non-global tho'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:10:49.793",
"Id": "464730",
"Score": "0",
"body": "Note that in `CollectGarbage()` when calling `m_cache.erase(iter)`, the erased iterator is invalidated and can't be used to get the next item in the container. `erase` returns the next valid iterator itself. For an example see: https://en.cppreference.com/w/cpp/container/unordered_map/erase"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:13:39.333",
"Id": "464756",
"Score": "0",
"body": "Yep indeed. That was caused because I was writing in a hurry and didn't double check"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:00:58.577",
"Id": "237022",
"ParentId": "237006",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:32:44.870",
"Id": "237006",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Asset management in C++ for games"
}
|
237006
|
<p>I'm creating mazes, and have a Cell class (only relevant code shown)...</p>
<pre><code>public class Cell {
public int Row { get; }
public int Col { get; }
public List<Cell> Links { get; }
public Cell North { get; set; }
public Cell South { get; set; }
public Cell East { get; set; }
public Cell West { get; set; }
public Cell(int row, int col) {
Row = row;
Col = col;
Links = new List<Cell>();
}
public bool Linked(Cell cell) =>
Links.Contains(cell);
public bool DeadEnd =>
Links.Count == 1;
public IEnumerable<Cell> Neighbours =>
new List<Cell> { North, South, East, West }.Where(c => c != null);
}
</code></pre>
<p>The mazes are all (currently) rectangular, so a <code>Cell</code> starts off with 2, 3 or 4 neighbours (depending on where it is in the maze, eg corner cells only have two neighbours, other edge cells have three, internal cells have four). These are set during the maze initialisation code (In <code>Maze</code> class which is not shown as it's not relevant here), and the <code>Neighbours</code> property gives the resulting neighbouring cells.</p>
<p>Given a grid of cells, the maze-generation algorithm links cells together using <code>Link()</code> and <code>Unlink()</code> methods (not shown as they aren't relevant here).</p>
<p>The <code>Linked</code> method then allows you to check if a cell is linked to the current one.</p>
<p>As I often need to pick a random cell from a collection, I have the following extension method defined...</p>
<pre><code>public static Cell Rand<Cell>(this IEnumerable<Cell> items, Random r) =>
items.OrderBy(n => r.Next()).First();
</code></pre>
<p>I create one <code>Random</code> object at the start, and pass it around, hence the second parameter.</p>
<p>Some of the maze-generation algorithms work by taking a random walk around the grid. When on a cell, they pick a neighbouring cell to be the next in the walk.</p>
<p>One specific algorithm will try and avoid previously visited cells. This means that if there are any neighbours that don't yet have any links, then it will pick one of those. If all neighbouring cells have links, it picks one of those instead.</p>
<p>My current code for this is shown below. This is on the maze-generating class, and <code>current</code> is the cell we're currently visiting in our random walk. We pick the next by...</p>
<pre><code>Cell next = current.Neighbours.Any(c => c.Links.Count == 0)
? current.Neighbours.Where(c => c.Links.Count == 0).Rand(r)
: current.Neighbours.Rand(r);
</code></pre>
<p>This works fine, but I can't help feeling that there is a way to combine this into one Linq query instead of the three required for the <code>?:</code> operator.</p>
<p>Any suggestions? Thanks.</p>
|
[] |
[
{
"body": "<p>Using straight linq you could get to two iterations over Neighbours, assuming Neighbours is a class and not a struct. </p>\n\n<pre><code>var neighbour = current.Neighbours.FirstOrDefault(n => n.DeadEnd) ?? current.Neighbours.Where(n => !current.Linked(n)).First();\n</code></pre>\n\n<p>Pretty similar to yours except we using FirstOrDefault to return null if not found and using the ?? to execute the 2nd iteration if it's null. </p>\n\n<p>If it is a struct then you would need to compare the FirstOrDefault to default. At that point I would just do the FirstOrDefault and write an If statement on next line comparing it to default.</p>\n\n<p>If you want to do it in one iteration then will need to break out into a foreach loop. The downside is it will be calling the Linked() method even if it will never be used. As needs to store the value just in case it can't find DeadEnd. </p>\n\n<pre><code>Neighbour defaultValue == null;\nforeach (var neighbour in current.Neighbours)\n{\n if (neighbour.DeadEnd)\n {\n return neighbour;\n } else if (defaultValue == null && !current.Linked(neighbour))\n {\n defaultValue = neighbour;\n }\n}\n\nreturn defaultValue;\n</code></pre>\n\n<p>Without knowing what Linked does - aka does it have side effects or performance issues. This might not be the best answer.</p>\n\n<p>As you can see from my review there are questions: Neighbours a class or struct? Should post the source code for Neighbours. What does Linked method do? Because of this the code can't fully be reviewed and is not complete. I would suggest you update your question to get better answers. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:58:26.833",
"Id": "464622",
"Score": "0",
"body": "Thanks for the reply. I have updated my question, which should hopefully answer your questions. I'm trying not to swamp the question with a load of irrelevant code, so I hope I added enough. Please let me know if you want to see anything more. If you're interested in the full source code (which is quite fun, generating mazes), the `Cell` class can be seen here... https://github.com/MrYossu/MazesForProgrammers/blob/master/Mazes.Models/Models/Cell.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:59:25.797",
"Id": "464623",
"Score": "0",
"body": "Also, the code shown in my question was taken from this class... https://github.com/MrYossu/MazesForProgrammers/blob/master/Mazes.Models/MazeMakers/AldousBroderAvoidLinks.cs"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:14:00.580",
"Id": "237014",
"ParentId": "237007",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T17:40:28.140",
"Id": "237007",
"Score": "6",
"Tags": [
"c#",
"linq"
],
"Title": "Picking a random neighbouring cell, but only picking previously-visited ones if there aren't any unvisited"
}
|
237007
|
<p>I'm working on implementing a goal-based pathfinding.
first step is to set a goal and calculate the shortest walkable distance between the goal and all points in the grid, using a brushfire algorithm.</p>
<p>I'm worried about two things here, readability and efficiency, since this is for an RTS game.</p>
<pre><code> int[] GenerateHeatMap(IGrid grid, GridPoint goal)
{
var heatMap = new int[grid.Cells.Length];
var unexploredPoints = new List<GridPoint>();
var openPoints = new List<GridPoint>();
for (int i = 0; i < grid.Width; i++)
{
for (int j = 0; j < grid.Height; j++)
{
unexploredPoints.Add(new GridPoint(i, j));
}
}
var currentDistance = 0;
heatMap[grid.IndexOf(goal)] = currentDistance;
openPoints.Add(goal);
unexploredPoints.Remove(goal);
while (openPoints.Count > 0)
{
currentDistance++;
var newOpenPoints = new List<GridPoint>();
foreach (var currentPoint in openPoints)
{
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
var point = new GridPoint(currentPoint.x + i, currentPoint.y + j);
if ((i == 0 && j == 0) || !unexploredPoints.Contains(point) || newOpenPoints.Contains(point) || !grid.PointToCell(point).CanCross) continue;
heatMap[grid.IndexOf(point)] = currentDistance;
newOpenPoints.Add(point);
unexploredPoints.Remove(point);
}
}
}
openPoints.Clear();
openPoints.AddRange(newOpenPoints);
}
return heatMap;
}
</code></pre>
<p>For clarity here the definition of GridPoint</p>
<pre><code>public struct GridPoint
{
public GridPoint(int x, int y)
{
this.x = x;
this.y = y;
}
public readonly int x;
public readonly int y;
}
</code></pre>
<p>What can I do to improve this?</p>
|
[] |
[
{
"body": "<p>I would suggest to implement a <code>HeatMapGridPoints</code> class and inside this class, create two separate methods for <code>GetUnexploredPoints</code> and <code>GetOpenPoints</code> which will return list of <code>GridPoint</code>. This way, you can expand and also reuse the <code>HeatMap</code>. Also, it would be more readable than just gathering them into one method. </p>\n\n<p>Example : </p>\n\n<pre><code>public class HeatMapGridPoints\n{\n\n public IList<GridPoint> GetUnexploredPoints(IGrid grid)\n {\n var points = new List<GridPoint>();\n\n for (int i = 0; i < grid.Width; i++)\n {\n for (int j = 0; j < grid.Height; j++)\n {\n points.Add(new GridPoint(i, j));\n }\n }\n\n return points;\n\n }\n\n\n public IList<GridPoint> GetOpenPoints(IGrid grid, GridPoint goal)\n {\n // rest of the code \n }\n\n\n}\n</code></pre>\n\n<p>you can also do something like this : </p>\n\n<pre><code>public class HeatMapGridPoints\n{\n private readonly IGrid _grid;\n\n private readonly GridPoint _gridPoint;\n\n public IList<GridPoint> OpenPoints { get; private set; }\n\n public IList<GridPoint> UnexploredPoints { get; private set; }\n\n\n\n public HeatMap(IGrid grid, GridPoint goal)\n {\n _grid = grid;\n\n _gridPoint = goal;\n\n OpenPoints = GetOpenPoints(); \n\n UnexploredPoints = GetUnexploredPoints();\n }\n\n\n private IList<GridPoint> GetUnexploredPoints()\n {\n ...\n }\n\n\n private IList<GridPoint> GetOpenPoints()\n {\n ...\n }\n\n\n}\n</code></pre>\n\n<p>usage : </p>\n\n<pre><code>var heatMap = new HeatMapGridPoints(grid, goal);\n\nforeach(var point in heatMap.OpenPoints)\n{\n ....\n}\n</code></pre>\n\n<p>this would make it much easier to maintain and also more readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T08:09:47.073",
"Id": "464663",
"Score": "0",
"body": "I think you didn't understand my code. I'll edit my initial post to explain the brusfire algorithm.\n\nHow it works is: set the goal as my start point in my grid, and give it a distance of 0 in my distance map (it's called heatmap but I think distance map is better)\nthen I set that point as an \"open\" point.\nThen for each point in my open points I get all its neighbours, check if they're walkable and unexplored, set their distance in the heat map, and add them to the list of open points. Then I remove the open points I just treated, and repeat until there are no new open points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:01:46.617",
"Id": "464708",
"Score": "0",
"body": "@user1747281 I understood your code, but don't know the brushfire algorithm except what you have in your code. What I was suggesting is expanding your code (as I suggested) would give you a better management. The idea is an easier way to access both functionalities, and a way to store the points instead of regenerating them every time you call `GenerateHeatMap`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:30:40.483",
"Id": "237030",
"ParentId": "237008",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:00:18.010",
"Id": "237008",
"Score": "3",
"Tags": [
"c#",
"pathfinding"
],
"Title": "A Brushfire algorithm to generate a distance map in a grid"
}
|
237008
|
<p>Before I begin showing code, I have two main questions which I feel could help me.</p>
<ol>
<li>What is a service or factory, I've heard of them but why use them?</li>
<li>Should I use one shared instance of ILogger throughout my whole application, I only plan on persisting errors and I can get the reporter from the stacktrace.</li>
</ol>
<p>So,</p>
<p>I decided to write a simple logger for my dotnet core application. This logger will write messages to the console, and optionally save them to a file. I intend on only saving errors to a file.</p>
<p>For every class that needs a logger, I implement ILogger like so</p>
<pre><code>var typeOfClass = typeof(myClass);
var myClass = new MyClass(
new HybridLogger(
new ConsoleLogger(typeOfClass),
new FileLogger(typeOfClass)
)
)
</code></pre>
<p>I thought that was too much, so I simplified it</p>
<pre><code>public static class LogProvider
{
public static ILogger CreateLogger(Type type)
{
return new HybridLogger(new ConsoleLogger(type), new FileLogger(type));
}
}
</code></pre>
<p>This feels much better</p>
<pre><code>var myClass = new MyClass(LogProvider.GetLogger(typeof(MyClass));
</code></pre>
<p>I have an interface, ILogger which all implementations implement. This ensures all implementations have the correct methods and I can use ILogger to encapsulate the concrete implementation</p>
<pre><code>public interface ILogger
{
void Trace(string message, bool logToFile = false);
void Warning(string message, bool logToFile = false);
void Debug(string message, bool logToFile = false);
void Success(string message, bool logToFile = false);
void Error(string message, bool logToFile = false);
void Exception(Exception e, bool logToFile = true);
}
</code></pre>
<p>Let's start with the first out of the 3 implementations, ConsoleLogger. This one <code>Console.WriteLine</code>'s messages to the console. </p>
<p>The implementation has different methods for different LogLevel's and will use different <code>ConsoleColor</code>'s depending on the LogLevel chosen.</p>
<p>You can think of my LogType enum as LogLevel when reading the code below.</p>
<pre><code>public class ConsoleLogger : ILogger
{
private readonly Type _owner;
public ConsoleLogger(Type owner)
{
_owner = owner;
}
private readonly Dictionary<LogType, ConsoleColor> _colorsForLogType = new Dictionary<LogType, ConsoleColor>() {
{LogType.Trace , ConsoleColor.White},
{LogType.Success , ConsoleColor.Green},
{LogType.Warning , ConsoleColor.Yellow},
{LogType.Debug , ConsoleColor.Cyan},
{LogType.Error , ConsoleColor.Red},
};
public void Trace(string message, bool logToFile = false)
{
Log(message, LogType.Trace, logToFile);
}
public void Warning(string message, bool logToFile = false)
{
Log(message, LogType.Warning, logToFile);
}
public void Debug(string message, bool logToFile = false)
{
Log(message, LogType.Debug, logToFile);
}
public void Success(string message, bool logToFile = false)
{
Log(message, LogType.Success, logToFile);
}
public void Error(string message, bool logToFile = false)
{
Log(message, LogType.Error, logToFile);
}
public void Exception(Exception e, bool logToFile = true)
{
Log("An error occurred: " + Environment.NewLine + e, LogType.Error, logToFile);
}
private void Log(string message, LogType type, bool logToFile = false)
{
var oldColor = Console.ForegroundColor;
var newColor = _colorsForLogType[type];
Console.ForegroundColor = newColor;
Console.WriteLine($"[{DateTime.Now:MM/dd HH:mm:ss}] " + message);
Console.ForegroundColor = oldColor;
}
}
</code></pre>
<p>Now here is the FileLogger - this is used to persist errors logs so that I can read them later, I use this library in a server so its unwatched for most of its lifetime.</p>
<pre><code>public class FileLogger : ILogger
{
private readonly Type _owner;
public FileLogger(Type owner)
{
_owner = owner;
}
private readonly Dictionary<LogType, string> _fileNameForLogType = new Dictionary<LogType, string>() {
{LogType.Trace , "trace.log"},
{LogType.Success , "success.log"},
{LogType.Warning , "warn.log"},
{LogType.Debug , "debug.log"},
{LogType.Error , "error.log"},
};
public void Trace(string message, bool logToFile = false)
{
// Should only need the Log method in this class but
// I need to comply to ILogger, I'll keep them until
// I come up with a solution, an ideal one would be
// I just call Log(message, type) from the HybridLogger
// But thinking, is extra methods better? Encapsulation for LogType...
LogToFile(message, LogType.Trace);
}
public void Warning(string message, bool logToFile = false)
{
LogToFile(message, LogType.Warning);
}
public void Debug(string message, bool logToFile = false)
{
LogToFile(message, LogType.Debug);
}
public void Success(string message, bool logToFile = false)
{
LogToFile(message, LogType.Success);
}
public void Error(string message, bool logToFile = false)
{
LogToFile(message, LogType.Error);
}
public void Exception(Exception e, bool logToFile = true)
{
LogToFile(e.ToString(), LogType.Exception);
}
private void LogToFile(string message, LogType type)
{
FileUtilities.WriteToFile(
Path.GetFullPath(FileUtilities.GetStoragePath(), "/logging/" + _fileNameForLogType[type]),
$"Occurred at [{DateTime.Now:MM/dd HH:mm:ss}] in [{_owner.FullName}]: " + Environment.NewLine + message + Environment.NewLine
);
}
}
</code></pre>
<p>Lastly, I thought maybe I want to write to the console AND persist it to a file, so maybe an implementation that does two in one? I feel like there could be a better way to merge implementations, so if anyone has any bright ideas you can let me know.</p>
<pre><code>public class HybridLogger : ILogger
{
private readonly ILogger _consoleLogger;
private readonly ILogger _fileLogger;
public HybridLogger(ILogger consoleLogger, ILogger fileLogger)
{
_consoleLogger = consoleLogger;
_fileLogger = fileLogger;
}
public void Trace(string message, bool logToFile = false)
{
_consoleLogger.Trace(message, logToFile);
if (logToFile)
{
_fileLogger.Success(message);
}
}
public void Warning(string message, bool logToFile = false)
{
_consoleLogger.Warning(message, logToFile);
if (logToFile)
{
_fileLogger.Success(message);
}
}
public void Debug(string message, bool logToFile = false)
{
_consoleLogger.Debug(message, logToFile);
if (logToFile)
{
_fileLogger.Success(message);
}
}
public void Success(string message, bool logToFile = false)
{
_consoleLogger.Success(message, logToFile);
if (logToFile)
{
_fileLogger.Success(message);
}
}
public void Error(string message, bool logToFile = false)
{
_consoleLogger.Error(message, logToFile);
if (logToFile)
{
_fileLogger.Success(message);
}
}
public void Exception(Exception e, bool logToFile = true)
{
_consoleLogger.Exception(e, logToFile);
if (logToFile)
{
_fileLogger.Success(e.ToString());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:43:17.057",
"Id": "464601",
"Score": "1",
"body": "Please change the title So that it fits the standard on this site. That Is to state what the code Is about rather then your concerns about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:44:19.877",
"Id": "464603",
"Score": "0",
"body": "I have updated the title - thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:59:52.123",
"Id": "464659",
"Score": "0",
"body": "Your HybridLogger logs Sucess for all file logs. Doesn't look right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:20:09.833",
"Id": "464734",
"Score": "0",
"body": "you're trying to do what is already implemented in `NLog`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:09:53.937",
"Id": "464819",
"Score": "0",
"body": "@iSR5 NLog is fairly heavy - even though I've already stated this is for educational purposes and not to reinvent the wheel."
}
] |
[
{
"body": "<h1>What is a service?</h1>\n<p>There are mupltiple definitions. Probably the most generic one is that it is any object that provides some useful functionality. Sometimes it may be a synonym for a singleton.</p>\n<h1>What is a factory?</h1>\n<p>Factory is basically a service that instantiates other objects. A class constructor can be considered a factory in a way that is not polymorhic (in runtime). More complex factories should often stand aside from the class being instantiated as it involves more dependencies needed only for the instantiation but not by the instantiated object once it exists (like in your case HybridLogger does not need to know which loggers it is given but your factory combines the two concrete implementations). Factory method generally helps separate concerns and maintain single responsibility principle. One class should either create objects, or act on them when they already exist, but not both. If they need new objects for their acting, they delegate to factories.</p>\n<h1>One generic method vs specific method for each level</h1>\n<blockquote>\n<p>Should only need the Log method in this class but\nI need to comply to ILogger, I'll keep them until\nI come up with a solution, an ideal one would be\nI just call Log(message, type) from the HybridLogger</p>\n<p>But thinking, is extra methods better? Encapsulation for LogType..</p>\n</blockquote>\n<p>You might want to design the interface so that it only has that one method.</p>\n<pre><code>public interface ILogger\n{\n void Log(LogType type, string message);\n}\n\nlogger->Log(LogType.Success, "message");\n// instead of\nlogger->Success("message");\n</code></pre>\n<p>Now if you stil want those individual methods, you can define a wrapper.</p>\n<pre><code>public interface ILoggerFacade\n{\n void Success(string message);\n void Warning(string message);\n // etc.\n}\n\npublic class LoggerFacade : ILoggerFacade\n{\n private ILogger Logger;\n public LoggerFacade(ILogger logger) {Logger = logger;}\n public void Success(string message) {Logger.Log(LogType.Success, message);}\n public void Warning(string message) {Logger.Log(LogType.Warning, message);}\n}\n\nvar facade = new LoggerFacade(logger);\nfacade.Success("message");\n</code></pre>\n<h1>Log to file or not log to file?</h1>\n<p>Notice I omitted the <code>bool logToFile</code> parameter, thats because whether file logging occurs is implementation detail of the logger. If you want that control from outside for some reason, you should probably merge console logger and file logger together avoiding the hybrid logger. But it makes very little sense to me.</p>\n<p>It might make sense to decide whether file logging should occur based on the log type, you can have a configurable Ilogger implementation that follows the decorator pattern and allows to turn on/off specific log types (refered to as SwitchableLogger in the last code snippet).</p>\n<h1>"Merging" Implementations</h1>\n<blockquote>\n<p>I feel like there could be a better way to merge implementations</p>\n</blockquote>\n<p>It is absolutely fine to combine them this way, although it could be generalized to an Enumerable to be able to log to any amount of ILogger implementations, not just two.</p>\n<pre><code>public class MultiLogger : ILogger\n{\n private IEnumerable<ILogger> Loggers;\n public MultiLogger(IEnumerable<ILogger> loggers) {Loggers = loggers;}\n public void Log(LogType type, string message) {\n foreach (var logger in Loggers) logger.Log(type, message);\n }\n}\n</code></pre>\n<p>Further we have made sure that every logger is called with the correct type, unlike your HybridLogger which calls <code>Success</code> on the second logger regardless of the type requested.</p>\n<h1>Logger aware of the class using it</h1>\n<p>This is actualy almost a circular reference. The loggers dont depend on the class who owns the logger, but they depend on its class type. It means you need at least one logger for each distinct class that uses a logger. You could shift this to only have one logger service in your application by having the type passed to the Log method.</p>\n<pre><code>public interface ILogger\n{\n public void Log(LogType type, string message, Type callerType);\n //or even as template\n public void Log<T>(LogType type, string message);\n}\n</code></pre>\n<p>But honestly, your ConsoleLogger does not even use that value. And secondly if the logger consumer wishes, he can add the class name to the message.</p>\n<h1>Dependency Injection</h1>\n<p>You should be explicit about where the FileLogger puts the logs. Let it get the file path mapper in constructor.</p>\n<h1>Final result</h1>\n<pre><code>var logger = new SwitchableLogger(new FileLogger(errorLogPaths));\nlogger.AllOff();\nlogger.ErrorOn();\nvar facade = new LoggerFacade(new MultiLogger([new ConsoleLogger(), logger]));\n// the facade is output of the factory method, im putting it here to simplify...\n\nfacade.Error("whoops"); //logs both\nfacade.Success("success"); // logs only to console\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T06:20:16.960",
"Id": "465007",
"Score": "0",
"body": "Thanks for your answer I'm gradually reading through it. When you say that I'm not even using type yes that's correct, usually only for exceptions but that's in the stack trace anyway. How bad is class-based logging compared to one logger for the entire application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T10:47:04.080",
"Id": "465071",
"Score": "0",
"body": "@AshKetchum well it Is not bad per se. But it may get annoying to have to instantiate new logger everytime you instantiate an object which may want to log something. You should at least again follow the decorator pattern to create a logger that knows another logger And a type And Will prepend the type name to every message that Is to be logged before delegating the message to the inner logger. The same goes for prepending the message with a timestamp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T10:48:54.217",
"Id": "465073",
"Score": "0",
"body": "It Is btw a very nice example of decorator pattern because it literally decorates the message before saving it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T11:05:06.070",
"Id": "465081",
"Score": "0",
"body": "Another option might be to not use the generic logger facade And instead define class specific facades with methods encapsulating not only log type but also the log message together with params used to build the message. MyClassLoggerFacade.ThisSucceeded(input) or MyClassLoggerFacade.ThatFailed(error), etc. Although it May be wise to use domain And not the class. I.e. HttpClientLogger And the actual http client implementation using it Is not that important."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T21:16:58.993",
"Id": "237188",
"ParentId": "237012",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237188",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:26:18.387",
"Id": "237012",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Simple C# logger with multiple implementations"
}
|
237012
|
<p>I have a set of unique strings, I want to create a unique integer identifier for each string. </p>
<p><strong>Usage</strong> I want a function to move back and forth, if I give it an integer it returns the corresponding string and vice versa.</p>
<p>Here is how I am doing it</p>
<pre class="lang-py prettyprint-override"><code>def str_to_int(S):
integers = list(range(len(S)))
my_dict = dict(zip(S,integers))
rev_dict = dict(zip(integers,S))
return my_dict, rev_dict
</code></pre>
<p>If I need to get the integer identifier of an item of <code>S</code>, I need to call the function and then the appropriate returned dictionary. </p>
<p>I want something simpler, given an integer or a string, it knows, somehow automatically if it's an int or str and return the other identifier (i.e. if I give an int it returns the str identifier and vice versa). Is it possible to do it in a single function ? (if possible without being obliged to recreate dictionaries for each call)</p>
<p>Edit: I thought of doing to functions <code>str_to_int(S:set, string:str)->int</code> and <code>int_to_str(S:set ,integer:int)->str</code> but the problem is 1) that's two functions, 2) each time two dictionaries are created.</p>
|
[] |
[
{
"body": "<p>I'm not sure why you insist on doing this only with a single function, but we surely can. Also, just pass in the prebuilt dictionaries so that you don't need to build them on every call.</p>\n\n<pre><code>def build_mapping(S):\n integers = list(range(len(S)))\n return dict(zip(S, integers)), dict(zip(integers, S))\n\ndef get_value(key, conv, rev_conv):\n return conv[key] if isinstance(key, str) else rev_conv[key]\n\nS = ['foo', 'bar', 'baz', 'hello', 'world']\nconv, rev_conv = build_mapping(S)\n\nkey = 'hello'\nkey2 = 3\n\n# print \"3 hello\"\nprint(get_value(key, conv, rev_conv), get_value(key2, conv, rev_conv))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:57:22.643",
"Id": "464614",
"Score": "0",
"body": "I thought it's more readable using a single function and it's less lines of code. But, I guess, you don't recommend it. Am I right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:54:53.057",
"Id": "237017",
"ParentId": "237015",
"Score": "1"
}
},
{
"body": "<p>Since what you want is something a little more complicated than what a normal dictionary can do, I think you want to encapsulate all of this in a class that behaves the way you want the dict to behave. You can make it \"look like\" a dict by implementing <code>__getitem__</code>, something like:</p>\n\n<pre><code>from typing import Dict, List, Set, Union, overload\n\n\nclass StringTable:\n \"\"\"Associate strings with unique integer IDs.\"\"\"\n\n def __init__(self, strings: Set[str]):\n \"\"\"Initialize the string table with the given set of strings.\"\"\"\n self._keys: List[str] = []\n self._ids: Dict[str, int] = {}\n for key in strings:\n self._ids[key] = len(self._keys)\n self._keys.append(key)\n\n @overload\n def __getitem__(self, o: int) -> str: ...\n\n @overload\n def __getitem__(self, o: str) -> int: ...\n\n def __getitem__(self, o: Union[int, str]) -> Union[str, int]:\n \"\"\"Accepts either a string or int and returns its counterpart.\"\"\"\n if isinstance(o, int):\n return self._keys[o]\n elif isinstance(o, str):\n return self._ids[o]\n else:\n raise TypeError(\"Bad argument!\")\n\n def __len__(self) -> int:\n return len(self._keys)\n</code></pre>\n\n<p>Now you can use it like:</p>\n\n<pre><code>strings = {\"foo\", \"bar\", \"baz\"}\nbijection = StringTable(strings)\nfor s in strings:\n print(s, bijection[s])\n assert bijection[bijection[s]] == s\n</code></pre>\n\n<p>etc. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T08:45:05.863",
"Id": "464665",
"Score": "0",
"body": "Didn't know about `overload` and that usage of `Ellipsis`, nice!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:20:37.327",
"Id": "237018",
"ParentId": "237015",
"Score": "4"
}
},
{
"body": "<p>If the keys are strings and ints, they can't collide, so they can go in the same dict.</p>\n\n<pre><code>strings = ['one', 'alpha', 'blue']\n\n# mapping from strings to ints and ints to strings\ntwo_way_dict = {}\nfor i,s in enumerate(strings):\n two_way_dict.update([(s,i), (i,s)])\n\nbijection = two_way_dict.get\n\n#example\nbijection('alpha') -> 1\nbijection(1) -> 'alpha'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T07:15:44.920",
"Id": "237045",
"ParentId": "237015",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:28:30.763",
"Id": "237015",
"Score": "1",
"Tags": [
"python"
],
"Title": "Creating a bijection between integers and a set of strings"
}
|
237015
|
<p>I got this from a practice problem set, and looking for feedback on my approach.</p>
<blockquote>
<p>Suppose you're given a binary tree represented as an array. Write a function that determines whether the left or right branch of the tree is larger. The size of each branch is the sum of the node values. The function should return the string "Right" if the right side is larger and "Left" if the left side is larger. If the tree has 0 nodes or if the size of the branches are equal, return the empty string.</p>
</blockquote>
<p>My logic is that each "breadth" of the tree is <code>2^depth</code> wide, and we start the work on the second "depth". I can use that to establish how to slice the array to get each "breadth" out of the array (ie, first round is <code>arr[1:3]</code>, second is <code>arr[3:7]</code>, etc). From there I sum the left/right slices of that slice.</p>
<p>I think my solution uses <span class="math-container">\$O(n)\$</span> time and <span class="math-container">\$O(1)\$</span> space and should handle unbalanced trees, but parsing trees as arrays is new to me, so wondering about edge cases I should be considering.</p>
<pre><code>def solution(arr):
breadth = 2
floor = 1
left = 0
right = 0
while floor < len(arr):
level = arr[floor:(floor+breadth)]
pivot = breadth / 2
left += sum(level[:pivot])
right += sum(level[pivot:])
floor += breadth
breadth *=2
if left < right:
return 'Right'
elif right < left:
return 'Left'
else:
return ''
import unittest
class Test(unittest.TestCase):
def test_function(self):
self.assertEqual(solution([3,6,2,9,-1,10]), 'Left')
self.assertEqual(solution([1,4,100,5]), 'Right')
self.assertEqual(solution([1,10,5,1,0,6]), '')
self.assertEqual(solution([]), '')
self.assertEqual(solution([1]), '')
t = Test()
t.test_function()
</code></pre>
<p>One alternate I can think of is evaluating each value. Could this be better than my current solution?</p>
<pre><code>for i in range(len(level)):
if i < pivot:
left += level[i]
else:
right += level[i]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:36:00.357",
"Id": "464618",
"Score": "0",
"body": "Not sure why you got a downvote. Looks like you included everything, and even have some unittests."
}
] |
[
{
"body": "<p>I think the solution you have is likely to be optimal (or close enough) in terms of runtime, and I think your approach of summing over the slice is much better than doing a <code>for</code> loop. </p>\n\n<p>The only downside of this approach is that it's a little hard to grok, and consequently difficult to extend or maintain, because the approach you're taking is so specific to the implementation of the tree and to the particular task you're doing. In other words, this code would probably not be reusable for a different task that involved traversing the same tree, or for applying the same task to a different tree representation. </p>\n\n<p>If efficiency is of paramount importance, there's a place for tightly optimized code, but in that case I'd recommend having some explanatory comments to speed the reader's comprehension. Something with a diagram of the tree layout, say:</p>\n\n<pre><code># Our tree:\n# arr[0] <- breadth 1, floor 0\n# arr[1] arr[2] <- breadth 2, floor 1\n# arr[3] arr[4] arr[5] arr[6] <- breadth 4, floor 3\n\n# Begin at the second level (top of the left and right subtrees).\nbreadth = 2 # number of nodes on the current level\nfloor = 1 # index of the first node on the current level\nleft = 0 # sum of the left subtree up to this point\nright = 0 # sum of the right subtree up to this point\n</code></pre>\n\n<p>This is the diagram I built in my head when I was reading the code; having it in front of me already would have saved me a couple of minutes. With that diagram and the explanations of the different values, it's a lot easier to read through the code and visualize what the slices correspond to.</p>\n\n<hr>\n\n<p>An entirely different direction to go in for this problem would be to build an abstraction that lets you traverse the tree in a more tree-like way:</p>\n\n<pre><code>from typing import List, NewType, Optional\n\ndef solution(arr: List[int]) -> str:\n \"\"\"Takes a binary tree packed into an array root-first.\n Returns 'Right' or 'Left' to indicate which subtree is larger.\"\"\"\n\n # Helpers to read and traverse nodes in the tree.\n # The internal representation of our Node is simply an array index, but\n # these helper functions expose derived \"properties\" as if it were an object.\n Node = NewType('Node', int)\n\n def make_node(index: int) -> Optional[Node]:\n return Node(index) if index < len(arr) else None\n\n def left_child(node: Node) -> Optional[Node]:\n return make_node(node * 2 + 1)\n\n def right_child(node: Node) -> Optional[Node]:\n return make_node(node * 2 + 2)\n\n def root_node() -> Optional[Node]:\n return make_node(0)\n\n def value(node: Node) -> int:\n return arr[node]\n\n # Recursive function to sum the subtree under a node.\n def sum_subtree(node: Optional[Node]) -> int:\n if node is None:\n return 0\n return (\n value(node) \n + sum_subtree(left_child(node)) \n + sum_subtree(right_child(node))\n )\n\n # Get sums of left and right subtrees.\n root = root_node()\n if root is None:\n return ''\n left_sum = sum_subtree(left_child(root))\n right_sum = sum_subtree(right_child(root))\n\n if right_sum > left_sum:\n return 'Right'\n elif left_sum > right_sum:\n return 'Left'\n else:\n return ''\n</code></pre>\n\n<p>This approach breaks the logic into layers. The foundational layer is the five functions that define the <code>Node</code> abstraction, which gives us a way to read the tree that's completely decoupled from the array. The details of how the tree is stored in the array (e.g. the magic <code>2 * index + 1</code> logic) are completely contained inside these functions. You could also implement this collection of functions as a class (storing a reference to the array as an instance attribute), which would make it easy to use outside this function and unit-test on its own; I've used a <code>NewType</code> wrapper because it makes it easy to see (and typecheck) the abstraction while still giving us the low overhead of a single int at runtime.</p>\n\n<p>This tree abstraction lets us build a <code>sum_subtree</code> helper that recursively sums up everything under a node. Even if the reader didn't understand the way the tree is packed into an array (or care to), they could read this function and understand how it's navigating the tree to arrive at a sum, and if they wanted to write a similar function they'd be able to do so without having to understand the array representation.</p>\n\n<p>Finally, we have the top-level logic that gets the two top-level subtrees, compares their sums, and returns a result in the expected format.</p>\n\n<p>This solution is a bit less efficient than yours (the recursive call is going to use log(N) space, and the fact that we're iterating through each node one by one will add a few more clock cycles), but in many real world applications \"slow and obvious\" is preferable over \"fast and clever\". :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:47:34.853",
"Id": "237044",
"ParentId": "237019",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:37:34.340",
"Id": "237019",
"Score": "4",
"Tags": [
"python",
"tree"
],
"Title": "Parsing Binary Tree Array in Python"
}
|
237019
|
<p>Which of these three methods is the most efficient?</p>
<p>Also, what is the time & space complexity of each?</p>
<pre><code>public class Palindrome {
public static boolean isStringBased(String word) {
if (word == null || "".equals(word)) {
return false;
}
String lowerCasedWord = word.toLowerCase();
int i = 0;
int j = lowerCasedWord.length() - 1;
while (i < j) {
if (lowerCasedWord.charAt(i) != lowerCasedWord.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static boolean isPalindromeRecursive(String input) {
if(input.length() == 0 || input.length() == 1) {
return true;
}
if(input.charAt(0) == input.charAt(input.length()-1)) {
return isPalindromeRecursive(input.substring(1, input.length()-1));
}
return false;
}
public static boolean isPalindromeIterative(String input) {
boolean retValue = false;
int length = input.length();
for( int i = 0; i < length/2; i++ ) {
if (input.charAt(i) == input.charAt(length-i-1)) {
retValue = true;
}
}
return retValue;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:46:17.140",
"Id": "464634",
"Score": "1",
"body": "`isPalindromeIterative(\"override\")`: true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T21:36:21.020",
"Id": "465401",
"Score": "0",
"body": "What terrible programming practices are these? The functions are not named similarly, the checks on the input / word are different for each, unexplained and incorrectly implemented algorithms. Yuk."
}
] |
[
{
"body": "<p>First solution requires O(1) space and O(n) complexity.</p>\n\n<p>The last one looks to be less than 100% efficient, because you could directly return false when you find out it is not a palindrome, but it continues until the loop ends. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:29:59.227",
"Id": "464630",
"Score": "0",
"body": "Why did someone put a downvote (and its not -1)? I thought the purpose of the code review is to help people."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:39:58.477",
"Id": "464631",
"Score": "0",
"body": "(@PacificNW_Lover Up to this comment, nobody downvoted this answer. Your question has been down-voted once, with no up-vote. By rights, somebody found it *not useful* (**as it was at the time of the vote**).)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:28:17.520",
"Id": "237024",
"ParentId": "237020",
"Score": "2"
}
},
{
"body": "<p>You present undocumented code<br>\n(yours, truly? <code>StringBased</code> looks <em>different</em>). </p>\n\n<p>let me try and just code it more tersely, correcting the iterative variety:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>/** check a <code>CharSequence</code> to be a <em>palindrome</em> */\nstatic interface Palindrome {\n /** @return <code>true</code> if <code>word</code>\n * is a <em>palindrome</em> else <code>false</code> */\n boolean isPalindrome(CharSequence word);\n\n static class StringBased implements Palindrome {\n public boolean isPalindrome(CharSequence word) {\n if (word == null || 0 == word.length())\n return false;\n String lowerCasedWord = word.toString().toLowerCase();\n for (int i = 0, j = word.length() - 1; i < j; i++, j--)\n if (lowerCasedWord.charAt(i) != lowerCasedWord.charAt(j))\n return false;\n return true;\n }\n }\n static class Recursive implements Palindrome {\n public boolean isPalindrome(CharSequence input) {\n int last;\n return input.length() <= 1\n || input.charAt(0) == input.charAt(last = input.length()-1)\n && isPalindrome(input.substring(1, last));\n }\n }\n static class Iterative implements Palindrome {\n public boolean isPalindrome(CharSequence input) {\n int length = input.length();\n for( int i = 0; i < length/2; i++ )\n if (input.charAt(i) != input.charAt(length-i-1))\n return false;\n return true;\n }\n }\n public static void main(String[] args) {\n Palindrome[]checkers = {\n new StringBased(),\n new Recursive(),\n new Iterative()\n };\n String [] checks = { \"\", \"a\", \"aa\", \"ab\", \"Aba\", \"abc\", \"aaba\", };\n System.out.print('\\t');\n for (String check: checks)\n System.out.print(\"\\t\\\"\" + check + '\"');\n for (Palindrome checker: checkers) {\n System.out.print('\\n' + checker.getClass().getSimpleName() + \":\\t\");\n for (String check: checks)\n System.out.print(checker.isPalindrome(check) + \"\\t\");\n }\n }\n}\n</code></pre>\n\n<p><code>StringBased</code> still is different (<code>Evitareti</code> is <code>isPalindromeIterative()</code>):</p>\n\n<blockquote>\n<pre><code> \"\" \"a\" \"aa\" \"ab\" \"Aba\" \"abc\" \"aaba\"\nStringBased: false true true false true false false \nRecursive: true true true false false false false \nIterative: true true true false false false false \nEvitareti: false false true false false false true \n</code></pre>\n</blockquote>\n\n<p><code>StringBased</code> and <code>Recursive</code> use O(n) additional space.<br>\nWith respect to time, </p>\n\n<ol>\n<li><strong>DON'T assume</strong>: model & <strong>measure</strong><br>\n(using a framework, microbenchmarking where appropriate (e.g. here))</li>\n<li>your mileage <strong>will</strong> vary</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:18:46.273",
"Id": "464641",
"Score": "0",
"body": "\"production strength\" implementations *without instance data* should be *singletons*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:41:28.137",
"Id": "464763",
"Score": "0",
"body": "Nice rewrite. What I'm missing here is the fact that `Palindrome` is not a **verb**. It should really be `PalindromeChecker` or something similar. Terse is fine, but removing the braces is not (this is subjective, but I guess if > 90% of devs agree on it, that you need to make it explicit in your answer that most don't agree)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T18:11:30.730",
"Id": "464810",
"Score": "0",
"body": "(I learned coding with each line adding 2.5 grams to the program, and the quality of rubber bands important to the mental balance of a coder. PalindromeChecker was the name of the abstract class when I first typed this… (I tried renaming the predicate to `is()` when I shortened the interface name - didn't work for me.))"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:14:18.120",
"Id": "237035",
"ParentId": "237020",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T20:40:05.283",
"Id": "237020",
"Score": "0",
"Tags": [
"java",
"performance",
"algorithm",
"complexity"
],
"Title": "Java Palindrome - Time & Space Complexity"
}
|
237020
|
<p>Here's my algorithm / approach for transposing a 2D Matrix on the main diagonal.</p>
<p>Before: </p>
<pre><code>a L M d
b G c N
H K e F
I J O P
</code></pre>
<p>After: </p>
<pre><code>a b H I
L G K J
M c e O
d N F P
</code></pre>
<hr>
<p>My code:</p>
<pre><code>public class Matrix {
static String[][] matrix = {
{"a", "L", "M", "d"},
{"b", "G", "c", "N"},
{"H", "K", "e", "F"},
{"I", "J", "O", "P"}
};
public void transpose(String[][] matrix) {
String[][] transposedArray = new String [4][4];
for (int row =0; row < 4; row ++) {
for (int col = 0; col < 4; col++) {
transposedArray[row][col] = matrix[col][row];
}
}
}
}
</code></pre>
<p>What is the time & space complexity of this approach? </p>
<p>Is there a better optimal solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:39:01.263",
"Id": "464619",
"Score": "0",
"body": "May I ask *why* you are asking for the time and space complexity of this approach? Is this for a school assignment? Are you trying to learn time and space complexities yourself? I'm not saying there's anything wrong with your question, I'm just curious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T23:34:14.973",
"Id": "464640",
"Score": "0",
"body": "Not school assignment, just learning Big O Notation. Thanks for asking."
}
] |
[
{
"body": "<p>I have three suggestions for you.</p>\n\n<ol>\n<li>Instead of <code>String</code>, you can use <code>char</code>, less memory footprint than a <code>String</code>.</li>\n<li>In the <code>transpose</code> method, I suggest that you return the array, since the method does nothing at the moment.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>static char[][] matrix = {\n {'a', 'L', 'M', 'd'},\n {'b', 'G', 'c', 'N'},\n {'H', 'K', 'e', 'F'},\n {'I', 'J', 'O', 'P'}\n};\n\npublic char[][] transpose(char[][] matrix) {\n char[][] transposedArray = new char [4][4];\n\n for (int row = 0; row < 4; row ++) {\n for (int col = 0; col < 4; col++) {\n transposedArray[row][col] = matrix[col][row];\n }\n }\n\n return transposedArray;\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>Since the <code>matrix</code> variable is static, I suggest that you also put the method static.</li>\n</ol>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n System.out.println(Arrays.deepToString(transpose(matrix)));\n}\n\nstatic char[][] matrix = {\n {'a', 'L', 'M', 'd'},\n {'b', 'G', 'c', 'N'},\n {'H', 'K', 'e', 'F'},\n {'I', 'J', 'O', 'P'}\n};\n\npublic static char[][] transpose(char[][] matrix) {\n char[][] transposedArray = new char [4][4];\n\n for (int row = 0; row < 4; row ++) {\n for (int col = 0; col < 4; col++) {\n transposedArray[row][col] = matrix[col][row];\n }\n }\n\n return transposedArray;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:14:22.773",
"Id": "464732",
"Score": "0",
"body": "About note 3. Note that there are two different `matrix` variables. One local to the `transpose` method and one static in the class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:52:25.193",
"Id": "237031",
"ParentId": "237023",
"Score": "2"
}
},
{
"body": "<p>Regarding time complexity, since your algorithm traverses the entire matrix once, it is working at <em>O(n)</em>. this means the performance is affected in direct proportion to the size of the input (the matrix in this case). it is expected that a matrix with double the size (meaning four times the cell count) will perform 4 times worse than the original, and so forth.</p>\n\n<p>Regarding space complexity, the algorithm allocates a new matrix the same size as the original. this also means that space requirements relate in direct proportion to the size of input. Here I have an improvement suggestion: the transformation can easily be done \"in place\" by iterating over half the matrix (triangular half, bordered by the diagonal) and swapping values of two cells. it also bares a small performance improvement - you need not touch the cells on the diagonal itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:16:41.737",
"Id": "464733",
"Score": "0",
"body": "O(n) if you consider the number of elements in the matrix as `n`. O(n^2) if you consider just the width of the matrix as `n` (as I assume matrix is always square)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T07:26:50.993",
"Id": "237046",
"ParentId": "237023",
"Score": "1"
}
},
{
"body": "<p>In addition to previous answers, which address valid points, I'd like to point out that your code is not scalable. If a matrix always has exactly 16 elements, time and space complexity are not really an issue, as they describe how the algorithm behaves at different scales.</p>\n\n<p>You should figure out the row and column count of the matrix beforehand, and use these values when creating <code>transposedArray</code> and in your <code>for</code> loops.</p>\n\n<p>As for time and space complexity, they both can be improved, as noted by Sharon Ben Asher in his answer. To go in further details, your algorithm performs <code>n*m</code> operations, or <code>n²</code> operations if <code>m = n</code>. Iterating on the upper half triangle reduces the number of operations to <code>n * (n-1) / 2</code>, which is a sizeable improvement by a factor 2. However, this would fail on a non-square matrix see the example below:</p>\n\n<pre><code> input | expected | iteration on\n | output | upper triangle\n-------------------------------------------\na b c d | a e i | a e i d\ne f g h | b f j | b f j h\ni j k l | c g k | c g k l\n | d h l |\n</code></pre>\n\n<p>As you state that you are currently learning big O notation, note that the time complexity is still <code>O(n²)</code>, as it is still the dominant term in the number of operations performed. The improvement is far from negligible, but it isn't represented in big O notation.</p>\n\n<p>As of space complexity, swapping elements in place doesn't require allocating another <code>n*m</code> array to store the results of the operation. This means an improvement in terms of space complexity from <code>O(n²)</code> to <code>O(1)</code>. This is great, especially with larger inputs. However, this also fails for non-square inputs, and means the input is mutated. If you happen to need the input in its original state, you'd have to transpose the matrix again.</p>\n\n<p>Depending on the exact behavior you need, iterating on the full matrix or the upper triangle, and transposing in place or returning a transposed array can both be justified.</p>\n\n<p>Finally, for integration purposes, your class could use some refactoring, most importantly to allow processing a matrix of any size.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:07:40.403",
"Id": "237068",
"ParentId": "237023",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:19:10.583",
"Id": "237023",
"Score": "1",
"Tags": [
"java",
"performance",
"complexity"
],
"Title": "Transpose 2D Matrix in Java - Time & Space Complexity?"
}
|
237023
|
<p>Currently trying to migrate two fields of information into one field. We have many, many objects to go through and it takes roughly 12 minutes to loop through all the objects. That would mean the website would be down for 12 minutes and we do not want that. Is there any way to speed up this migration? It works, it's just slow. </p>
<pre class="lang-py prettyprint-override"><code>from __future__ import unicode_literals
from django.db import migrations, models
def set_people(apps, schema_editor):
ParticipationCount = apps.get_model('partcount', 'ParticipationCount')
for row in ParticipationCount.objects.all():
row.people = row.male + row.female
row.save()
class Migration(migrations.Migration):
dependencies = [
('partcount', '0002_participationcount_people'),
]
operations = [
migrations.RunPython(set_people),
]
</code></pre>
<p>No is an acceptable answer in this case, I am just curious if there is a different way to do this, as loops can be slow. I am using Django 1.8 and python 2.</p>
|
[] |
[
{
"body": "<p>Unfortunately you're using django<2.2, since from 2.2 onwards you can use <a href=\"https://docs.djangoproject.com/en/2.2/ref/models/querysets/#bulk-update\" rel=\"nofollow noreferrer\">bulk_update</a> , but you can still use something like</p>\n\n<pre><code>ParticipationCount.objects.all().update(\n people=F(\"male\") + F(\"female\")\n)\n</code></pre>\n\n<p>Which will do it in one query to save time. This will fail for certain fields in Postgres however as it requires some specific type casting, but this can be done within the query</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:41:34.723",
"Id": "466714",
"Score": "1",
"body": "Works swimmingly! Thank you so much! Just had to import F from `django.db.models` to get it to work"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:38:32.890",
"Id": "237082",
"ParentId": "237026",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:31:36.020",
"Id": "237026",
"Score": "2",
"Tags": [
"python",
"database",
"django"
],
"Title": "Speed up Django migration that adds two fields into one"
}
|
237026
|
<p>I have a single image of shape img.shape = (500, 439, 3)</p>
<p>The convolution function is</p>
<pre><code>def convolution(image, kernel, stride=1, pad=0):
n_h, n_w, _ = image.shape
f = kernel.shape[0]
kernel = np.repeat(kernel[None,:], 3, axis=0)
kernel = kernel.transpose()
n_H = int(((n_h + (2*pad) - f) / stride) + 1)
n_W = int(((n_w + (2*pad) - f) / stride) + 1)
n_C = 1
out = np.zeros((n_H, n_W, n_C))
for h in range(n_H):
vert_start = h*stride
vert_end = h*stride + f
for w in range(n_W):
horiz_start = w*stride
horiz_end = w*stride + f
for c in range(n_C):
a_slice_prev = image[vert_start:vert_end,
horiz_start:horiz_end, :]
s = np.multiply(a_slice_prev, kernel)
out[h, w, c] = np.sum(s, dtype=float)
return out
</code></pre>
<p>The code for plotting is</p>
<pre><code>img = plt.imread('cat.png')
kernel = np.arange(25).reshape((5, 5))
out2 = convolution(img, kernel)
plt.imshow(np.squeeze(out2))
plt.show()
</code></pre>
<p>The output seems to get a CYAN cover, is the logic of the code correct ?</p>
<p><a href="https://i.stack.imgur.com/TVJFJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TVJFJ.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:51:49.007",
"Id": "464725",
"Score": "0",
"body": "The \"CYAN cover\" is likely because of the data type of `out`. ndarrays with `float64` dtype, not in range `[0, 1]` are considered as \"general data\" and matplotlib falls back to its [default colormap](https://matplotlib.org/users/dflt_style_changes.html#colormap)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:16:48.700",
"Id": "464742",
"Score": "0",
"body": "@AlexV is it possible to have a colored output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:29:36.490",
"Id": "464746",
"Score": "0",
"body": "You will have to normalize your data before plotting, either to `[0, 255]` and using `np.uint8` as dtype or `[0, 1]` for `np.float64`/`np.float32`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:54:05.997",
"Id": "464751",
"Score": "0",
"body": "@AlexV I normalize it using the following `out2 -= out2.min()` `out2 /= out2.max()` and then `plt.imshow(np.squeeze(out2), vmin=out2.min(), vmax=out2.max())`, when I print out `print('Min: %.3f, Max: %.3f' % (out2.min(), out2.max()))` I get my range from 0 to 1, my datatype is still though `Data Type: float64` and the image is still CYAN, Using cmap=`gray` gives a grey output. But still not the coloured one I am hoping for. Is it actually possible to have a coloured image with only 1 channel ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:13:29.843",
"Id": "464755",
"Score": "1",
"body": "Sorry, my bad! It's not possible to have a color image with just one channel. Grayscale is as \"natural\" as it gets."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:38:04.053",
"Id": "237027",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Convoluting 3D image with 2D"
}
|
237027
|
<p>I have an Access macro that runs <code>AfterUpdate</code> of a form. It opens an Excel workbook and edits a few cells. I have It working the way I want, but the problem is that the code takes about 25 seconds to run. This is way too long for the users of this database to have to wait. After adding some timing messages, I found that 98% of that time is just spent opening and saving Excel.</p>
<p>I have a few ideas on how to fix this problem. I'm hoping someone out there can tell which are possible/which is the best way to approach the problem:</p>
<ol>
<li><p>Create a CSV file next to the workbook. Access adds the 5 values to the CSV file each time the macro runs. Then I add <code>Workbook_Open</code> macro to the Workbook that reads the CSV file and makes the changes, then clears the CSV.</p>
</li>
<li><p>Add a new table to my access file that keeps track of the form updates that have been made. Then, when the access file is closed or saved, another macro opens the Excel workbook, makes the changes and clears the new table.</p>
</li>
<li><p>(pie in sky idea, not sure how to do this) Somehow open the workbook in the background and pass the 5 values to it, so that an Excel macro makes the changes without causing Access to freeze while the code runs.</p>
</li>
<li><p>(last resort idea, really don't want to do this) Import the workbook into the Access file so the changes can be made without involving Excel.</p>
</li>
</ol>
<p>Here's the current code:</p>
<pre class="lang-vb prettyprint-override"><code>Option Compare Database
Const xlToRight As Long = -4161
Const xlToLeft As Long = -4159
Const xlUp As Long = -4162
Const xlDown As Long = -4121
Private Sub Form_AfterUpdate()
'This macro will update the Excel WO Tracker for a project each time an NCR is closed or resolved
Dim xl As Object 'Excel
Dim tracker As Object 'Book
Dim sn As Object 'Sheet
Dim wo As Object, scrap As Object, wos As Object, cell As Object 'Range
Dim connect(1) As Variant 'WO and NCR#
Dim assy() As Variant 'Part and associated WO's
Dim partName As String, NCR As String
Dim starttime As Double
'Exit if required fields are blank
starttime = Timer
If (Title.Value = "") Or (status.Value = "") Or (Program.Value = "") Or _
(Disposition.Value = "") Or ([Work Order Number].Value = "") Then
Exit Sub
End If
On Error GoTo Handler
If (status.Value = "Closed") Or (status.Value = "Resolved") Then
Set xl = CreateObject("Excel.Application")
xl.ScreenUpdating = False
Select Case Program.Value
Case "SE07"
Set tracker = xl.Workbooks.Open("Z:\Operations\Projects\Sierra\SE07\" & Year(Now()) & " SE07 WO Tracker.xlsm")
Case "VS02"
Set tracker = xl.Workbooks.Open("Z:\Operations\Projects\ViaSat\VS01\" & Year(Now()) & " VS02 WO Tracker.xlsm")
Case Else 'Program does not have a WO Tracker
xl.ScreenUpdating = True
Set xl = Nothing
Exit Sub
End Select
Set sn = tracker.Sheets("SN")
'Record NCR connection
connect(0) = [Work Order Number].Value
connect(1) = Title.Value
xl.Intersect(sn.Range("NCRConnect"), sn.Columns(xl.Intersect(sn.Range("FirstCol"), sn.Range("NCRConnect")).End(xlToRight).Column + 1)) = xl.Transpose(connect)
Set wo = sn.UsedRange.Find([Work Order Number].Value)
If Not wo Is Nothing Then
If (Disposition.Value = "Scrap-Destroy") Or (Disposition.Value = "Scrap-Repurpose") Then 'Move WO to scrap graveyard
If xl.Intersect(wo, sn.Range("ScrapYard")) Is Nothing Then
If xl.Intersect(wo, sn.Range("Layup")) Is Nothing Then
partName = sn.Cells(wo.Row, 1).End(xlUp).Value
'Copy From
If xl.Intersect(wo.Offset(-1, 0), sn.Range("EmptyRows")) Is Nothing Then
If xl.Intersect(wo.Offset(1, 0), sn.Range("EmptyRows")) Is Nothing Then
Set wo = sn.Range(sn.Cells(sn.Cells(wo.Row, 1).End(xlUp).Row, wo.Column), sn.Cells(sn.Cells(wo.Row, 1).End(xlDown).Row, wo.Column))
Else 'wo is at bottom of range
Set wo = sn.Range(sn.Cells(sn.Cells(wo.Row, 1).End(xlUp).Row, wo.Column), wo)
End If
Else 'wo is at top of range
Set wo = sn.Range(wo, sn.Cells(sn.Cells(wo.Row, 1).End(xlDown).Row, wo.Column))
End If
assy = wo
'Copy To
Set scrap = sn.Cells(sn.Range("ScrapYard").Find(partName).Row, sn.Range("ScrapYard").Find("NCRs").End(xlToRight).Column + 1).Resize(wo.Rows.Count, 1)
scrap = assy
wo.Delete Shift:=xlToLeft
'Record NCR#
Set wo = sn.Cells(xl.Max(sn.Cells(sn.Range("NCRConnect").Row, scrap.Column).End(xlUp).Offset(1, 0).Row, sn.Range("ScrapYard").Find("NCRs").Row), scrap.Column)
wo.Value = Title.Value
Set wos = xl.Intersect(sn.Range("ScrapYard"), sn.Columns(wo.Column))
For Each cell In wos
Set scrap = sn.Rows(sn.Range("NCRConnect").Row).Find(cell.Value)
If (Not scrap Is Nothing) And (InStr(cell.Value, Program.Value) <> 0) Then
NCR = scrap.Offset(1, 0).Value
Set scrap = wos.Find(NCR)
If scrap Is Nothing Then
Set wo = wo.Offset(1, 0)
wo.Value = NCR
End If
End If
Next cell
Else
partName = sn.Cells(wo.Row, 1).Value
Set scrap = sn.Cells(sn.Range("ScrapYard").Find(partName).Row, sn.Range("ScrapYard").Find("NCRs").End(xlToRight).Column + 1)
scrap = wo.Value
wo.Delete Shift:=xlToLeft
Set wo = sn.Cells(xl.Max(sn.Cells(sn.Range("NCRConnect").Row, scrap.Column).End(xlUp).Offset(1, 0).Row, sn.Range("ScrapYard").Find("NCRs").Row), scrap.Column)
wo.Value = Title.Value
End If
End If
End If
End If
End If
tracker.Save
tracker.Close
Set tracker = Nothing
Set sn = Nothing
xl.ScreenUpdating = True
Set xl = Nothing
Debug.Print Round(Timer - starttime, 2) & " seconds"
Exit Sub
Handler:
tracker.Save
tracker.Close
Set tracker = Nothing
Set sn = Nothing
xl.ScreenUpdating = True
Set xl = Nothing
End Sub
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:37:55.057",
"Id": "464642",
"Score": "0",
"body": "I/O is going to be hopelessly slow indeed, with little to no opportunity to improve... is `Z:` a mapped network drive? Is there a way the Access database / backend could be on the same server? Curious how much of that 25 seconds gets shaved when the file is local.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:39:59.267",
"Id": "464643",
"Score": "0",
"body": "Does the form's `AfterUpdate` method need to run more than once per form instance? Your point/idea #2 seems to mean the answer is \"yes\" - consider opening the workbook (hidden so user can't accidentally close it) with the form, and only closing it *with the form*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:43:53.593",
"Id": "464645",
"Score": "3",
"body": "Lastly... any reason why the workbook can't just *query* the Access db to get what it needs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:47:49.280",
"Id": "464749",
"Score": "0",
"body": "@ Mathieu Guindon Both files are on the same network drive, I can't move them to my computer because other employees use the database. I dont need it to happen `AfterUpdate`, but that was the easiest way I could figure out when I started writing this macro. I've considered having Excel look into the database, I just don't know a lot about Access so that would take a lot of research"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:38:33.590",
"Id": "464762",
"Score": "0",
"body": "If the db and the xlsx are on the same machine, try accessing the xlsx with a local path instead of a mapped network drive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T18:09:01.767",
"Id": "464809",
"Score": "0",
"body": "Assigning value to `Object` `scrap` (at two points) without `Set` is a bit suspicious. Doesn't it take you to the error handler? BTW right after assigning value to it with `Set`. I'd further refine time analysis by more measurements. You could keep reducing run time by disabling event handling and a few more time comsuming services for the course of processing. Take a look at this: https://codereview.stackexchange.com/questions/234904/changing-the-formatting-of-sheets/235074?noredirect=1#comment459911_235074 . You needn't even waste time with restoring the settings if you close Excel anyway."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T22:54:26.107",
"Id": "237032",
"Score": "4",
"Tags": [
"performance",
"vba",
"excel",
"ms-access"
],
"Title": "Edit Excel through MS Access"
}
|
237032
|
<p>Is this a good way of removing all the nodes that contains a value x?
This function takes as input the head of a list and has to delete all the nodes that contain a given value taken. If there is any better way of doing this can you please show them to me?</p>
<pre><code>node_t *funzione(node_t *head){
int x;
node_t *temp = head;
node_t *curr = head;
temp = (node_t *)malloc(sizeof(node_t));
curr = (node_t *)malloc(sizeof(node_t));
printf("Inserisci il valore che vuoi eliminare: \n");
scanf("%d", &x);
if (head == NULL)
exit(0);
while(head->val == x){
head = head->next;
free(temp);
temp = head;
}
curr = head;
temp = curr->next;
while (temp != NULL){
if (temp->val == x){
if(temp->next != NULL){
curr->next = temp->next;
free (temp);
temp = curr->next;
}
else {
curr->next = NULL;
}
}
else {
curr = temp;
temp = temp->next;
}
}
return head;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T23:20:02.180",
"Id": "464637",
"Score": "0",
"body": "Your first malloc calls look a little odd to me... You aren't using the memory anywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T01:04:02.657",
"Id": "464646",
"Score": "1",
"body": "Your question would be more complete if you showed the definition for `node_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:58:21.337",
"Id": "464752",
"Score": "0",
"body": "Please don't modify your question to reflect changes based on answers, it creates confusion and mismatched Q & A. If you want changes reviewed, please ask another question."
}
] |
[
{
"body": "<p>The input asking for which value to delete can/should be placed in a separate function. Then the function to remove the nodes can take that value as a parameter.</p>\n\n<p>The two <code>malloc</code> calls for <code>temp</code> and <code>curr</code> near the top are completely unnecessary and just leak memory. You want to remove nodes, so you shouldn't have to allocate any memory.</p>\n\n<p>If your list consists of a single node where <code>val == x</code> (or, more generally, all nodes in the list have that value), your program will crash.</p>\n\n<p>If the last node in the list matches the value (and there are other nodes that don't), you'd be leaking that node except that you will be stuck in an infinite loop. You shouldn't need to handle the last node any differently than removing any other node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T01:03:40.737",
"Id": "237038",
"ParentId": "237033",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>node_t *funzione(node_t *head){\n</code></pre>\n</blockquote>\n\n<p>This is a weird name for a function to remove a node. The naming should reflect what the operation does, not what it is. </p>\n\n<blockquote>\n<pre><code> int x;\n node_t *temp = head;\n node_t *curr = head;\n</code></pre>\n</blockquote>\n\n<p>The way the rest of your function works, it assumes that <code>temp</code> points to the node after <code>curr</code> in the list, assigning them to the same node is asking for trouble.</p>\n\n<blockquote>\n<pre><code> temp = (node_t *)malloc(sizeof(node_t));\n curr = (node_t *)malloc(sizeof(node_t));\n</code></pre>\n</blockquote>\n\n<p>You don't need to <code>malloc</code> anything here, you're not doing anything with the memory. Since <code>malloc</code> returns <code>void *</code>, casting it to <code>node_t*</code> would be unnecessary.</p>\n\n<blockquote>\n<pre><code> printf(\"Inserisci il valore che vuoi eliminare: \\n\");\n scanf(\"%d\", &x);\n</code></pre>\n</blockquote>\n\n<p>This would be better done in another method, with the value being passed in as a parameter to this method, to indicate what to remove.</p>\n\n<blockquote>\n<pre><code> if (head == NULL)\n exit(0);\n</code></pre>\n</blockquote>\n\n<p>This is pretty drastic. If you're going to just abort the app like this, then it would be a good idea to print something to <code>stderr</code> to give an indication what happened. Generally, consider wrapping if clauses in <code>{}</code>, even when they're single line. I think it would be ok in this situation to return <code>head</code>, i.e. <code>NULL</code> in this situation, rather than exiting the program. If the caller passed in a <code>head</code> of <code>NULL</code>, they're probably ok handling it coming back from the method.</p>\n\n<blockquote>\n<pre><code> while(head->val == x){\n head = head->next;\n free(temp);\n temp = head;\n }\n</code></pre>\n</blockquote>\n\n<p>This <code>free</code>s the memory allocated for <code>temp</code> above, however it doesn't free the actual node pointed to by <code>head</code> on the first pass.</p>\n\n<blockquote>\n<pre><code> curr = head;\n temp = curr->next;\n\n while (temp != NULL){\n if (temp->val == x){\n if(temp->next != NULL){\n curr->next = temp->next;\n free (temp);\n temp = curr->next; \n }\n else {\n curr->next = NULL;\n</code></pre>\n</blockquote>\n\n<p>You stop pointing at <code>temp</code>, but never <code>free</code> it, or break out of the loop, so you'll just keep revisiting this assignment over and over again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:35:19.177",
"Id": "464747",
"Score": "0",
"body": "Hi thanks a lot for your reply I have modified the code applying some of the things you have said. I haven't understood your last commend about stop pointing at temp but never free it, how should I modify it to make it work? cause when i exe it it works. About your second to last comment, do I have modified it correctly? Thanks in advance man, really apprecciate your help :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:57:24.073",
"Id": "237054",
"ParentId": "237033",
"Score": "3"
}
},
{
"body": "<p>A function that asks its parameter is not really usable, but let's assume it is for the code review question.</p>\n\n<p>The main error is starting right away to declare and create variables. Allocation certainly is not needed when deleting nodes.</p>\n\n<p>Try postpone creating variables until one needs them. Thus reducing the effort to read the code, and being sure one needs them in that way.</p>\n\n<p>C/C++ can use <em>aliasing</em>: keeping a variable pointing to either <code>head</code> or some <code>node_t->next</code> field. This really is a special feature of these languages. The usage here would be:</p>\n\n<pre><code>node_t *funzione(node_t *head) {\n\n printf(\"Inserisci il valore che vuoi eliminare: \\n\");\n\n int x;\n scanf(\"%d\", &x);\n\n node_t **curr = &head;\n while (*curr != NULL) {\n if ((*curr)->val == x) {\n node_t *removed = *curr;\n *curr = (*curr)-> next;\n free(removed);\n } else {\n curr = &(*curr)->next;\n }\n }\n return head;\n}\n</code></pre>\n\n<p>As you see: the code is more straight forward. The alternative you applied: first handle head, and then in the loop remember the previous node, so its next field may be corrected.</p>\n\n<p>Declaring the <code>removed</code> inside the loop is not more inefficient, neither costs more time or space.</p>\n\n<hr>\n\n<p><strong><em>Sketchy</em></strong></p>\n\n<pre><code>curr ---> head or next field ---> node with data sought\n insidde the preceding node\n</code></pre>\n\n<ul>\n<li><code>*curr = xxx;</code> will change head or next fields value</li>\n<li><code>curr = &(*curr)->next;</code> will remove the node</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code> head node1 node2 node3\n+-------+ +---------+ +-------+ +-------+\n| node1 |--->| +-----+ | | node3 |--->| null |---|\n+-------+ | |node2| |--->| val2 | | val3 |\n | + -^--+ | +-------+ +-------+\n +----|----+\n |\n curr\n has the address of the next field containing node2\n</code></pre>\n\n<ul>\n<li>*curr == node2</li>\n<li>(*curr).val == val2</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:16:58.317",
"Id": "464794",
"Score": "0",
"body": "so you are creating a **curr variable instead of creating a new variable and you use it to go through the list. So this short function has the same result of the one I should have had?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:18:48.167",
"Id": "464796",
"Score": "0",
"body": "Yes, curr points to head, then nodes' next field, being able to change those variable/fields."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:45:05.263",
"Id": "464822",
"Score": "0",
"body": "Thanks very much for your help man it really means a lot for me, could you just explain the last thing? What is the meaning of &head, I mean when you are assigning to **curr = &head what's really happening, what's &head, I know & is used to dereference but you are dereferencing a pointer am I wrong? And last but not least, could you explain why there is the need to do this: \"curr = &(*curr)->next;\" Thanks a lot in advance :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:27:21.730",
"Id": "464883",
"Score": "0",
"body": "Inverse, `&` takes the address/reference of the variable. So `*curr = xxx;` is the same as `head = xxx;`. Then `curr = &(*curr)->next` takes the address of the `node_t*`next field. So then `*curr = xxx;` is the same as `(*curr)->next == xxx;`. A pointer to pointer. The effect is addressing the next node from the current (head or next field)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T13:15:51.433",
"Id": "465261",
"Score": "0",
"body": "Hi Joop, sorry if I bother you too much but there is still something that I cannot get about the code you wrote. I know it works perfectly cause I have tested it, but you don't have a reference to the precedente element, so you can not delete current element. Am I wrong? If there is the reference could you please show it to me? Many thanks and sorry again if bothered you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T13:29:08.563",
"Id": "465266",
"Score": "0",
"body": "Scenario: `curr` hold the address of a next field (= of the preceding node). If the next field contains a pointer to a node with the sought data, you change the next field to the sought node's next, removing it. _A thing for sketching on paper/whiteboard._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T13:51:14.637",
"Id": "465269",
"Score": "0",
"body": "Tried some ascii art, as explanation, but I am afraid you need pen and paper."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T18:33:00.353",
"Id": "465314",
"Score": "0",
"body": "You might want to introduce separation of concerns. `funzione` does two things, and at least the latter deserves its own separate function."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T16:57:12.480",
"Id": "237093",
"ParentId": "237033",
"Score": "3"
}
},
{
"body": "<p>Whenever you perform input like this, don't discard the result of <code>scanf()</code>:</p>\n\n<blockquote>\n<pre><code>int x;\nscanf(\"%d\", &x);\n</code></pre>\n</blockquote>\n\n<p>At the very least, bail out if invalid input is provided:</p>\n\n<pre><code>int x;\nif (scanf(\"%d\", &x) != 1) {\n fputs(\"Input failed!\\n\", stderr);\n return NULL;\n}\n</code></pre>\n\n<p>A more sophisticated approach would consume the rest of the line (<code>scanf(\"%*[^\\n]\")</code>) and re-try the input, until either it succeeds or the stream reaches an irrecoverable state (<code>feof(stdin)</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:31:21.777",
"Id": "237095",
"ParentId": "237033",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237093",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T23:12:28.930",
"Id": "237033",
"Score": "2",
"Tags": [
"c",
"linked-list",
"c99"
],
"Title": "Removing nodes with a given value from a linked list"
}
|
237033
|
<p>So I ported a lexer I wrote in C++ over to rust, as I'm starting to learn rust. Since I'm very new though, I don't know any Idioms and good practices in rust. So if anyone could point out some (probably obvious) issues I'd be very thankful.</p>
<p>This is my code:</p>
<pre><code>use std::cmp::PartialEq;
use std::fmt::Debug;
#[derive(Debug, PartialEq)]
pub enum Token {
EOF,
Ident(String),
Str(String),
FNum(f64),
INum(u64),
Assign,
BLsh,
BRsh,
BURsh,
If,
Else,
Elif,
Loop,
Stop,
Skip,
Yes,
No,
Nope,
Fun,
Ret,
And,
Not,
Or,
LBrack,
LBrace,
LPar,
RBrack,
RBrace,
RPar,
Semi,
Comma,
Get,
Concat,
IDiv,
FDiv,
Add,
Minus,
Mul,
Mod,
BXOr,
BAnd,
BOr,
IE,
EQ,
NE,
LT,
LE,
GT,
GE,
}
macro_rules! peek_char {
($e:expr) => {
match $e.peek().cloned() {
Some(c) => c,
None => {
return Token::EOF;
}
}
};
}
pub fn get_token(iterator: &mut std::iter::Peekable<std::str::Chars>) -> Token {
let mut next: char = peek_char!(iterator);
let mut current_token: String = String::new();
if next.is_whitespace() {
loop {
next = peek_char!(iterator);
if !next.is_whitespace() {
break;
}
iterator.next();
}
get_token(iterator)
} else if next == '#' {
loop {
next = peek_char!(iterator);
if next == '\n' {
break;
}
iterator.next();
}
get_token(iterator)
} else if next.is_alphabetic() {
loop {
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
break;
}
};
if !(next.is_alphanumeric() || next == '_') {
break;
}
iterator.next();
current_token.push(next);
}
match current_token.as_str() {
"if" => Token::If,
"else" => Token::Else,
"elif" => Token::Elif,
"loop" => Token::Loop,
"stop" => Token::Stop,
"skip" => Token::Skip,
"yes" => Token::Yes,
"no" => Token::No,
"nope" => Token::Nope,
"fun" => Token::Fun,
"return" => Token::Ret,
"and" => Token::And,
"not" => Token::Not,
"or" => Token::Or,
_ => Token::Ident(current_token),
}
} else if next == '"' {
iterator.next();
loop {
next = peek_char!(iterator);
let to_add: char = if next == '\\' {
iterator.next();
next = peek_char!(iterator);
match next {
't' => '\t',
'b' => '\x08',
'n' => '\n',
'r' => '\r',
'f' => '\x0c',
'"' => '"',
'\\' => '\\',
_ => panic!("unknown escaped character"),
}
} else if next == '"' {
iterator.next();
break;
} else {
next
};
iterator.next();
current_token.push(to_add);
}
Token::Str(current_token)
} else if next.is_digit(10) {
loop {
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
break;
}
};
if !(next.is_digit(10) || next == '.') {
break;
}
iterator.next();
if next == '.' && current_token.contains('.') {
panic!("multiple decimal points in number");
}
current_token.push(next);
}
if current_token.contains('.') {
Token::FNum(
current_token
.parse::<f64>()
.expect("error reading float literal"),
)
} else {
Token::INum(
u64::from_str_radix(&current_token, 10).expect("error reading integer literal"),
)
}
} else if next == '/' {
iterator.next();
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
return Token::FDiv;
}
};
if next == '/' {
iterator.next();
Token::IDiv
} else {
Token::FDiv
}
} else if next == '?' {
iterator.next();
next = peek_char!(iterator);
iterator.next();
if next == '=' {
Token::IE
} else {
panic!("unknown character");
}
} else if next == '!' {
iterator.next();
next = peek_char!(iterator);
iterator.next();
if next == '=' {
Token::NE
} else {
panic!("unknown character");
}
} else if next == '=' {
iterator.next();
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
return Token::Assign;
}
};
if next == '=' {
iterator.next();
Token::EQ
} else {
Token::Assign
}
} else if next == '<' {
iterator.next();
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
return Token::LT;
}
};
if next == '=' {
iterator.next();
Token::LE
} else if next == '<' {
iterator.next();
Token::BLsh
} else {
Token::LT
}
} else if next == '>' {
iterator.next();
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
return Token::GT;
}
};
if next == '=' {
iterator.next();
Token::GE
} else if next == '>' {
iterator.next();
next = match iterator.peek().cloned() {
Some(c) => c,
None => {
return Token::BRsh;
}
};
if next == '>' {
iterator.next();
Token::BURsh
} else {
Token::BRsh
}
} else {
Token::GT
}
} else {
iterator.next();
match next {
'[' => Token::LBrack,
'{' => Token::LBrace,
'(' => Token::LPar,
']' => Token::RBrack,
'}' => Token::RBrace,
')' => Token::RPar,
';' => Token::Semi,
'.' => Token::Get,
',' => Token::Comma,
'+' => Token::Add,
'-' => Token::Minus,
'*' => Token::Mul,
'%' => Token::Mod,
'$' => Token::Concat,
'^' => Token::BXOr,
'&' => Token::BAnd,
'|' => Token::BOr,
_ => panic!("unknown character"),
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple of general notes:</p>\n\n<ul>\n<li>I’m not sure why you used a macro for <code>peek_char!</code>. I’m relatively certain this could have been a standard function. </li>\n<li>Take some time to learn about slices. </li>\n<li>You have a single, several hundred line function there. It’s hard to read and follow. Extract lots of well named functions to improve readability. </li>\n<li>If you <code>panic</code> inside your function, there’s not really any way for the person calling your function to handle it. This should return a <code>Result<Token, ParseError></code>. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:12:55.320",
"Id": "237135",
"ParentId": "237034",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237135",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T23:36:05.263",
"Id": "237034",
"Score": "4",
"Tags": [
"beginner",
"parsing",
"rust",
"lexer"
],
"Title": "Lexer written in Rust"
}
|
237034
|
<p>I've been learning more about PHP Objects and Classes, and my immediate reaction was to create a Database Object for handling the MySQLi Connection, Statements and Results. Its not meant to be an ultimate do-all object, but help with WET code. Obviously this has been done before... at least a hundred times. </p>
<p>There's no question lingering on whether I <em>should</em> be doing this, my question is more along the lines of <em>am I doing this right?</em>.</p>
<p>Basically I don't want to write out 10+ lines of code each time I make an SQL statement, let alone deal with the other functions that take place. So I made an object that can do the SQL connection, statement, and get results. The goal was to make the interaction as simple as possible and I like to think I achieved that. Thoughts?</p>
<h3>Usage:</h3>
<p>Create the Object</p>
<p><code>$db = new Sqli();</code></p>
<p>Execute a Statement</p>
<p><code>$db->statement($sql, $param)</code></p>
<p><code>$db->statement("SELECT column_name FROM table WHERE = ?", "bind_me")</code></p>
<p><code>$db->statement("INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)", [$foo, $bar, $baz]);</code></p>
<p>Print Results</p>
<p><code>print_r($db->result());</code></p>
<p>JSON Result</p>
<p><code>print json_encode($db->result());</code></p>
<h3>PHP Code:</h3>
<pre><code>class Sqli
{
const DBHOST = "localhost";
const DBUSER = "";
const DBPASS = "";
const DBNAME = "";
protected $conn;
protected $stmt;
function __construct()
{
$this->setConnection();
}
private function setConnection()
{
mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ERROR);
try
{
$conn = new mysqli(
self::DBHOST,
self::DBUSER,
self::DBPASS,
self::DBNAME
);
}
catch(MySQLi_sql_exception $e)
{
throw new \MySQLi_sql_exception(
$e->getMessage(),
$e->getCode()
);
}
$this->conn = $conn;
}
public function statement($sql, $param)
{
$stmt = $this->conn->prepare($sql);
if($param !== FALSE)
{
if(!is_array($param))
{
$param = [$param];
}
$types = str_repeat("s", count($param));
$stmt->bind_param($types, ...$param);
}
$stmt->execute();
$stmt->store_result();
$this->stmt = $stmt;
}
public function result()
{
$stmt = $this->stmt;
$meta = $stmt->result_metadata();
while($field = $meta->fetch_field())
{
$param[] = &$row[$field->name];
}
call_user_func_array([$stmt, "bind_result"], $param);
while($stmt->fetch())
{
foreach($row as $key => $val)
{
$r[$key] = filter_var($val, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW|FILTER_FLAG_ENCODE_AMP);
}
$result[] = $r;
}
return $result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:05:02.430",
"Id": "464656",
"Score": "0",
"body": "Member access operator surrounded with spaces is a real rarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T00:51:38.360",
"Id": "464848",
"Score": "0",
"body": "@slepic My code view wasn't helping, it *looked better* with spaces... And I noticed that you're right, none of the code I've read surrounds them with spaces I guess it is rare. So I changed it and now code hinting works a lot better lol. Thank you for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:42:58.857",
"Id": "464887",
"Score": "0",
"body": "Does this code work? I don't see where `$row` is coming from in `result()`. I didn't test the code myself, but it seems weird to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T02:12:54.637",
"Id": "465000",
"Score": "0",
"body": "Yes, I would not post if it did not work, it will work on any prepared query. If you have no params to bind then call `$db->statement($sql, FALSE)`. For the `$row` variable you need to understand how references work https://www.php.net/manual/en/language.references.pass.php it is created in the first `while` loop and references the field name from `$meta->fetch_field()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T11:54:03.617",
"Id": "465085",
"Score": "0",
"body": "I tested your code, and indeed it does work. I just find it difficult to understand. I know how references work, I just don't like (to use) them. I *prefer* the \"normal\" way, illustrated in the examples of [execute()](https://www.php.net/manual/en/mysqli-stmt.execute.php). What I'm missing from your class is a way to bind parameters. I hope you don't do stuff like `SELECT * FROM table WHERE col1 = '$inputValue'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T23:46:53.527",
"Id": "465181",
"Score": "0",
"body": "No, its not possible to use a `SELECT *` statement with prepared queries. The params are bound in `->statement` . The code I use is almost directly copied from php delusions helper function https://phpdelusions.net/mysqli/simple . And no one *likes* to use references, but sometimes you have to. In this case there is no other way I can think of. To be fair my usage example is not very good, you would pass any variables as an array to `statement` as the second parameter to be bound. Or pass false if you have no params to be bound."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T00:06:44.507",
"Id": "465183",
"Score": "0",
"body": "@KIKO Software I have updated the documentation on usage in the question if it helps you understand the question."
}
] |
[
{
"body": "<p>Dont call private methods in constructor, put the code into the constructor directly (well unless you have reason to call the same piece of code from elsewhere too, not your case tho).</p>\n\n<p>Don't put your db credentials into the class's constants. This way you are unable to use the class to connect to any other database. Well you can change their values, but that means change the code, or you can extend the class and override the constants. But that's also not very convenient.</p>\n\n<p>You might want to prefer PDO instead of the mysqli extension. The PDO contains mysql adapter in it (maybe you need pdo_mysql extension i think). But you will have the freedom to change the underlying database transparently anytime (well unless you are using some specific sql dialect features).</p>\n\n<p>PDO basically offers the same as your class does, except it has no hardcoded credentials, which, as I already mentioned, is bad.</p>\n\n<p>So learn to use PDO and you may find out that you need no such wrapper at all, you just need a place where you pass the right credentials to its contructor. This place could be described as database connection factory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T23:58:04.450",
"Id": "465182",
"Score": "0",
"body": "I realise the credentials being defined directly in the object isn't ideal. For my particular use case it is not an issue since there is no plan to connect to any other DB. But I can completely get behind *why* you wouldn't do it this way. I will seriously consider changing it. I kind of figured out the private method was completely redundant (useless) and moved the code into the constructor on my local files after I posted the question. None-the-less I still wanted an answer on *which* way is correct. Thank you for the answer +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:18:11.340",
"Id": "237237",
"ParentId": "237036",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "237237",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T00:42:59.387",
"Id": "237036",
"Score": "1",
"Tags": [
"php",
"mysqli"
],
"Title": "PHP MySQLi database object"
}
|
237036
|
<p>I have a json field in a table that I want to select certain fields from into a new json field. So far I have this, which works, but I feel may not be optimal:</p>
<pre><code>select to_json(new_obj) from (
select big_json_field->'json_property_1' as json_property_1,
big_json_field->'json_property_2' as json_property_2
from table_with_big_json_field
) as new_obj
</code></pre>
<p>Is there a function or method I'm missing to optimize this?</p>
|
[] |
[
{
"body": "<p>I'd recommend (if it isn't already) converting to the type from json to jsonb and adding a GIN index. The documentation below lays it out pretty clear. Good luck!\n <a href=\"https://www.postgresql.org/docs/9.4/datatype-json.html\" rel=\"nofollow noreferrer\">https://www.postgresql.org/docs/9.4/datatype-json.html</a></p>\n\n<p>For my recommendation, reason for using jsonb as opposed to vanilla json is that regular json is stored as an exact copy in postgres and you cannot add an index to that column. Whereas jsonb has a smaller footprint and allows for indexing the specific column. I'd prefer to store it in a format that could be indexed to allow for queries to be more performant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:12:39.750",
"Id": "464830",
"Score": "0",
"body": "Yea sure thing. One caveat is looking at the poster's response below, I think he was looking more for advice on how to build a json object as opposed to looking for a performance gain. For my recommendation, reason for using jsonb as opposed to vanilla json is that regular json is stored as an exact copy in postgres and you cannot add an index to that column. Whereas jsonb has a smaller footprint and allows for indexing the specific column. I'd prefer to store it in a format that could be indexed to allow for queries to be more performant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T16:25:07.247",
"Id": "237089",
"ParentId": "237043",
"Score": "5"
}
},
{
"body": "<p>I ended up using <code>jsonb_build_object</code> (also available as <code>json_build_object</code>):</p>\n\n<pre><code>select jsonb_build_object (\n 'json_property_1', big_json_field->'json_property_1', \n 'json_property_2', big_json_field->'json_property_2' \n) from table_with_big_json_field\n</code></pre>\n\n<p>This eliminated the sub-select, and felt a bit cleaner than <code>as</code>-ing every field.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:07:05.607",
"Id": "237099",
"ParentId": "237043",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T06:04:24.437",
"Id": "237043",
"Score": "2",
"Tags": [
"json",
"postgresql"
],
"Title": "Postgres query to extract a JSON sub-object from a JSON field"
}
|
237043
|
<p>How can I get the date of the next occurrence of <a href="https://en.wikipedia.org/wiki/Friday_the_13th" rel="noreferrer">Friday the 13th</a>?</p>
<p>Below is my attempt. It returns the correct results. I think there must be a better way of writing this without checking <code>thirteenth > start_date</code> for every month. It might also be possible to exploit the fact that every calendar year has a Friday 13th.</p>
<pre><code>import itertools
from datetime import date
def next_fri_13(start_date):
'''Get the next Friday 13th after the specified start_date.
Args:
start_date (datetime.date)
Returns:
datetime.date: The first Friday 13th after the start_date.
'''
for year in itertools.count(start_date.year):
for month in range(1, 13):
thirteenth = date(year, month, 13)
# Ensure that the 13th is after the start date, and is a Friday.
if thirteenth > start_date and thirteenth.weekday() == 4:
return thirteenth
r = next_fri_13(date(2020, 2, 11))
print(r) # Prints: 2020-03-13
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T18:35:26.970",
"Id": "464812",
"Score": "0",
"body": "There may be a way to solve Zeller's Congruence for the months if you put in the year, but keep in mind that because it uses mod 7 there can be multiple solutions (which you can account for by knowing that there are 12 months in a year). You would have to plug in the day of the month (13th) and day of the week (6, Friday)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:27:36.130",
"Id": "464917",
"Score": "0",
"body": "https://codegolf.stackexchange.com/q/976/9516 There's some perfectly \"good\" examples to reference here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:04:00.113",
"Id": "464929",
"Score": "0",
"body": "You could find every Friday the 13th for as long as you care about in the future and store those static dates someplace (database, XML, static class, etc). One time calculation and all subsequent calls are reads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T17:36:23.730",
"Id": "464948",
"Score": "0",
"body": "If you have an easier way to get the first day of each month, then checking if that it is a Sunday should be better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:04:31.297",
"Id": "464952",
"Score": "0",
"body": "Note also that there are only 14 variations on the calendar -- January 1st can be one of seven days, and the year can be a leap year or not a leap year, so that's 14. You can list all the Friday the 13ths in each of those 14 variations, and then all you need to do to find the next one is (1) know which of the 14 variations we're in now, and (2) search the appropriate list for the first one following the current date."
}
] |
[
{
"body": "<p>This is already very nice looking code. The documentation is good and the algorithm used is clear. The points I would do different are really minor, and also depend on preference</p>\n\n<ul>\n<li>Instead of <code>from datetime import date</code>, I would just <code>import datetime</code>, and use <code>datetime.date</code>. This makes it more clear where <code>date</code> comes from, and I find <code>date</code> a very useful variable name, so I would like to keep the option open to use that</li>\n<li>function name: the 3 characters save by not spelling out friday completely are not worth it</li>\n<li>the comment <code># Ensure that the 13th is after the start date, and is a Friday.</code> is superfluous. The code itself expresses that exactly. Inline comments should explain why something is coded the way it is, not what the code does. If that is not clear, then you should rather choose a different code path</li>\n<li>type annotate your function <code>def next_friday_13(start_date: datetime.date) -> datetime.date:</code></li>\n<li>main guard: Put the code that actually executes something behine aan <code>if __name__ == \"__main__:</code>. That way you can later import this code as a module</li>\n</ul>\n\n<h1>test</h1>\n\n<p>Write a simple test routine that you can use:</p>\n\n<pre><code>def test_friday_13th():\n tests = {\n datetime.date(2020, 3, 12): datetime.date(2020, 3, 13),\n datetime.date(2020, 3, 13): datetime.date(2020, 11, 13),\n datetime.date(2020, 1, 1): datetime.date(2020, 3, 13),\n datetime.date(2020, 12, 13): datetime.date(2021, 8, 13)\n # TODO: add more test cases\n }\n for startdate, thirtheenth in tests.items():\n assert next_friday_13(startdate) == thirtheenth\n</code></pre>\n\n<p>or use <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctest</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:44:05.350",
"Id": "237052",
"ParentId": "237049",
"Score": "7"
}
},
{
"body": "<p>I think this can be slightly simplified by using <a href=\"https://dateutil.readthedocs.io/en/latest/relativedelta.html\" rel=\"noreferrer\"><code>dateutils.relativedelta</code></a> (since <code>datetime.timedelta</code> does not support months, unfortunately). This way you don't need to manually keep track of the year and month and if you ever need to implement something for e.g. next end of a month that is on a Sunday, it is way easier, because it takes care of the peculiarities for you, like months ending on different days of the month.</p>\n\n<p>I would also make the magic constant <code>4</code> into a global constant called <code>FRIDAY</code>.</p>\n\n<pre><code>from datetime import date\nfrom dateutil.relativedelta import relativedelta\n\nFRIDAY = 4 # Monday is 0\n\ndef next_fri_13(start_date):\n '''Get the next Friday 13th after the specified start_date.\n\n Args:\n start_date (datetime.date)\n\n Returns:\n datetime.date: The first Friday 13th after the start_date.\n '''\n thirteenth = date(start_date.year, start_date.month, 13)\n if start_date.day >= 13:\n thirteenth += relativedelta(months=1)\n\n while thirteenth.weekday() != FRIDAY:\n thirteenth += relativedelta(months=1)\n return thirteenth\n</code></pre>\n\n<p>Alternatively, you could make a generator of thirteenths days and drop all that are not a Friday using <code>filter</code> and use the fact that <code>relativedelta</code> does not only take offsets, but can also replace attributes at the same time (using the keywords without a trailing \"s\"):</p>\n\n<pre><code>from itertools import count\n\ndef next_fri_13(start_date):\n '''Get the next Friday 13th after the specified start_date.\n\n Args:\n start_date (datetime.date)\n\n Returns:\n datetime.date: The first Friday 13th after the start_date.\n '''\n thirteenths = (start_date + relativedelta(months=n, day=13)\n for n in count(start_date.day >= 13))\n return next(filter(lambda d: d.weekday() == FRIDAY, thirteenths))\n</code></pre>\n\n<p>IMO the first is easier to read, though, while this one is slightly easier to convert into a generator yielding all Friday the 13ths after <code>start_date</code> (just replace <code>return next(...)</code> with <code>yield from ...</code>).</p>\n\n<p>In any case, there is a bit of a philosophical debate about doing</p>\n\n<pre><code>import itertools\n\nitertools.count()\n</code></pre>\n\n<p>or</p>\n\n<pre><code>from itertools import count\n\ncount()\n</code></pre>\n\n<p>I personally tend to favor the latter, as long as it is still somewhat easy to figure out which module a function comes from, and there is no shadowing. This makes the lines a bit shorter and easier to read, especially if you use one particular module quite heavily (which the <code>itertools</code> module is a bit predestined for). It is also slightly faster, because you only need to do a global lookup instead of a global lookup and an attribute lookup, but that is negligible most of the time (and if it is not, you should make it a local variable anyway). But in the end the choice is yours.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:59:23.360",
"Id": "464680",
"Score": "0",
"body": "What format are your docstring's arguments and returns?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:00:48.777",
"Id": "464681",
"Score": "1",
"body": "@Peilonrayz: I copied the docstring from the OP. It looks like the [Google docstring conventions](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html), as far as I can tell."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:47:25.293",
"Id": "237053",
"ParentId": "237049",
"Score": "12"
}
},
{
"body": "<p>While working on my answer, <a href=\"https://codereview.stackexchange.com/users/98493/\">@Graipher</a> already introduced the idea of a generator.</p>\n\n<p>This generator variant does not rely on an external library, but should still be robust enough:</p>\n\n<pre><code>import itertools\nimport datetime\nfrom typing import Iterator\n\n\nFRIDAY = 4\n\ndef friday_13_generator(start_date: datetime.date) -> datetime.date:\n year = start_date.year\n month = start_date.month\n\n def increment_month(year, month):\n \"\"\"Helper function to increase the year on month 'overflow'\"\"\"\n month += 1\n if month > 12:\n month = 1\n year += 1\n return year, month\n\n if start_date.day >= 13:\n year, month = increment_month(year, month)\n\n while True:\n candidate = datetime.date(year, month, 13)\n if candidate.weekday() == FRIDAY:\n yield candidate\n\n year, month = increment_month(year, month)\n\n\ndef next_friday_13(start_date: datetime.date) -> datetime.date:\n '''Get the next Friday 13th after the specified start_date.\n\n Args:\n start_date (datetime.date)\n\n Returns:\n datetime.date: The first Friday 13th after the start_date.\n '''\n return next(friday_13_generator(start_date))\n</code></pre>\n\n<p><code>if candidate.weekday() == FRIDAY:</code> could also be moved out of <code>candidate_generator</code> using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.dropwhile\" rel=\"nofollow noreferrer\"><code>itertools.dropwhile</code></a> as presented by @Graipher.</p>\n\n<p>Edit: Thanks to <a href=\"https://codereview.stackexchange.com/users/123200/\">Maarten Fabré</a> for spotting an error when <code>start_date</code> was after or on Dec 13.</p>\n\n<p>You can check the correctness of this implementation using the tests provided by <a href=\"https://codereview.stackexchange.com/users/123200/\">Maarten Fabré</a> in his <a href=\"https://codereview.stackexchange.com/a/237052/\">answer</a>. <s><a href=\"https://codereview.stackexchange.com/users/171983/\">gazoh</a> also outlined an additional test case in his <a href=\"https://codereview.stackexchange.com/a/237059/\">answer</a> that you should take care of.</s></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:11:41.593",
"Id": "464683",
"Score": "1",
"body": "I like the idea of `friday_13_generator` and then using `next` in `next_friday_13`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:12:40.003",
"Id": "464684",
"Score": "0",
"body": "Thanks for fixing the type hint :-) I'm still getting used to them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:14:06.843",
"Id": "464685",
"Score": "1",
"body": "No problem, it could be changed to `Generator[datetime.date, None, None]`, but since you're not using it as a coroutine and instead as an `Iterator` it makes more sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:00:58.783",
"Id": "464729",
"Score": "0",
"body": "Don't forget to increment the year when getting a start date after December 13"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:15:32.133",
"Id": "464741",
"Score": "0",
"body": "@MaartenFabré: Hopefully fixed now :-) I think `datetime.date(2020, 12, 13): datetime.date(2021, 8, 13)` could be added as test case for `# TODO: add more test cases` in your answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:10:30.977",
"Id": "237057",
"ParentId": "237049",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T08:49:49.263",
"Id": "237049",
"Score": "14",
"Tags": [
"python",
"python-3.x",
"datetime"
],
"Title": "Compute the next occurrence of Friday the 13th"
}
|
237049
|
<p>I am still a beginner and I would love to hear some feedback on a small wrapper I wrote for the TMDb API (<a href="https://developers.themoviedb.org/3/getting-started/introduction" rel="nofollow noreferrer">https://developers.themoviedb.org/3/getting-started/introduction</a>). It is used for queries on a movie database. I tried to make it as simple as possible so all that is needed to get relevant information is the title of the movie or tv-show. It is quite basic at the moment since it is not yet finished. </p>
<p>There is only one constructor and it expects the movie title as a String object.
This is what a search looks like. I wasn't quite sure what to return if the movie does not exist so it returns empty fields in that case.</p>
<pre><code>MovieDataRetriever someMovie = new MovieDataRetriever("movie title here")
someMovie.getTitle() //returns the title of the movie
someMovie.getReleaseDate() //returns the release date of the movie
</code></pre>
<p>I also wrote a static factory method that returns an array of movie objects based on the user query. This is what it looks like in practice</p>
<pre><code>MovieDataRetriever[] movies = getMoviesByQuery("query string here")
</code></pre>
<p>The data is obtained as a JSON field from the TMDb servers using HTTP requests. Since movie requests return different fields than tv-show requests, I wrote two seperate classes. I also wrote another abstract superclass where I implemented the behavior that is shared by the other classes (Movieretriever and Tvshowretriever).</p>
<p>This is the abstract superclass MediaDataRetriever</p>
<pre><code>public abstract class MediaDataRetriever
{
private static final String API_KEY = "<<APIKEY>>";
/*
* guarantees to return a valid JsonObject containing data about the specified movie/tv-show
* returns null if the movie/tv-show does not exist on the TMdb servers or an error occurs while
* retrieving the JsonObject
*
* @param mediaType Media type as a string ("movie" or "tv-show" )
* @param mediaTitle Title of the movie/tv-show as a string
* @returns mediaData a valid JsonObject containing all relevant information about the specified movie/tv-show
*/
protected final JsonObject validateMediaData(final String mediaType, final String mediaTitle)
{
try {
JsonObject mediaData = getMediaDataAsJson(mediaType, mediaTitle);
return mediaData;
} catch (IOException e) {
return null;
}
}
/*
* private helper method that returns a JSON file that contains complete information about a movie/tv-show
* as a JsonObject
*
* @params mediaType Media type as a string ("movie" or "tv-show")
* @param mediaTitle Title of the movie/tv-show as a string
* @returns rootObject a JsonObject containing all relevant information about the searched for movie/tv-show
* @throws IOException if an error occurs while decoding the URL's
*/
private final JsonObject getMediaDataAsJson(final String mediaType, final String mediaTitle) throws IOException
{
if(!mediaType.equals("movie") && !mediaType.equals("tv"))
{
throw new IllegalArgumentException("Possible values for mediaType are \"movie\" and \"tv\" only");
}
JsonParser mediaParser;
JsonElement rootElement;
JsonObject rootObject;
/* the data is obtained with a simple HTTP request.
* To get detailed movie/tv show information,
* it is neccessary to do a standard search with limited return values first
* to obtain the ID of the movie/tv show. The ID is needed to start a detailed search
* for additional information like the runtime, vote count, vote score, budget ...
*/
String standardQuery = "https://api.themoviedb.org/3/search/" + mediaType + "?api_key=" + API_KEY + "&query=" + mediaTitle;
URL standardSearchUrl = new URL(standardQuery);
HttpURLConnection requestStandardData = (HttpURLConnection) standardSearchUrl.openConnection();
requestStandardData.connect();
try(InputStreamReader standardQueryStream = new InputStreamReader((InputStream) requestStandardData.getContent()))
{
mediaParser = new JsonParser(); //create a new JsonParser instance
rootElement = mediaParser.parse(standardQueryStream); //convert the input stream to a json element
rootObject = rootElement.getAsJsonObject(); //get the element as a json object
}
/* The http request returns several fields, the field that contains the movie information is called
* "results". This field will have a size of zero if the searched for movie does not exist
*/
if(rootObject.get("results").getAsJsonArray().size() == 0) return null;
//the movie data is contained in the first sub-field of the results field
//in this case, we only obtain the movie ID to start a detailed query
String mediaId = rootObject
.get("results")
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("id")
.getAsString();
//URL format for the detailed query
String detailedQuery = "https://api.themoviedb.org/3/" + mediaType + "/" + mediaId + "?api_key=" + API_KEY;
URL detailedQueryUrl = new URL(detailedQuery);
HttpURLConnection requestDetailed = (HttpURLConnection) detailedQueryUrl.openConnection();
requestDetailed.connect();
try(InputStreamReader detailedQueryStream = new InputStreamReader((InputStream) requestDetailed.getContent()))
{
rootElement = mediaParser.parse(detailedQueryStream); //convert the input stream to a json element
rootObject = rootElement.getAsJsonObject(); //get the json element as a json object
}
return rootObject;
}
/*
* returns a gson JsonObject that contains several JSON fields with information required to start a detailed search
* for a collection of movies/tv-shows based on the user submitted query
*
* @param mediaType string representing the media type (movie or tv-show)
* @param query user submitted query string
* @returns rootObject a gson JsonObject containing several JSON fields with name and ID fields
* @throws IOException if an error occurs while decoding the URL
*/
protected static JsonObject getMediaBasedOnQueryAsJson(final String mediaType, final String query) throws IOException
{
if(!mediaType.equals("movie") && !mediaType.equals("tv"))
{
throw new IllegalArgumentException("Possible values for mediaType are \"movie\" and \"tv\" only");
}
String queryString = "https://api.themoviedb.org/3/search/" + mediaType + "?api_key=" + API_KEY + "&query=" + query.replace(" ", "+");
URL searchUrl = new URL(queryString);
HttpURLConnection searchRequest = (HttpURLConnection) searchUrl.openConnection();
JsonParser mediaParser;
JsonElement rootElement;
JsonObject rootObject;
try(InputStreamReader standardQueryStream = new InputStreamReader((InputStream) searchRequest.getContent()))
{
mediaParser = new JsonParser(); //create a new JsonParser instance
rootElement = mediaParser.parse(standardQueryStream); //convert the input stream to a json element
rootObject = rootElement.getAsJsonObject(); //get the element as a json object
}
return rootObject;
}
/*
* returns the poster of the movie
*
* @param posterPath filepath of the poster as described in the TMdb API
* @returns poster BufferedImage object representing the poster of the movie/tv-show
* @throws IOException if an error occurs while decoding the URL
*/
protected BufferedImage getPoster(final String posterPath) throws IOException
{
//The poster_path field contains the file path as a String that looks like this: /xxxxxxxxxx.png
if(posterPath == null) return null;
//The file path of the poster has to be appended to the base url
String posterUrl = "https://image.tmdb.org/t/p/w185/" + posterPath;
URL posterQuery = new URL(posterUrl);
BufferedImage poster = ImageIO.read(posterQuery);
return poster;
}
}
</code></pre>
<p>The HTTP requests for movie and tv-shows are similar so I implemented the method that requests the JSON data inside the abstract superclass. The returned JSON data has different fields for movie and tv-shows so the actual parsing is done inside the specific classes (TvDataRetriever, MovieDataRetriever).
This is the MovieDataRetriever class described above. I omitted the getter methods since they are very basic. I also omitted the TvDataRetriever class that is used to get information on TV-shows since the actual implementations of movie and tv-show classes are quite similar-</p>
<pre><code>/* Retrieves information about the specified movie as JSON fields using the TMdb API (Version 3)
* and converts the JSON data into Java objects for easy access
* Returned values correspond to movie data from the US
* To get data for other regions, check the TMdb API
*/
public class MovieDataRetriever extends MediaDataRetriever
{
private final String MOVIE_TITLE_FOR_QUERY;
private final String MOVIE_TITLE;
private final String MOVIE_STATUS;
private final long BUDGET;
private final long REVENUE;
private final String[] GENRES;
private final String RELEASE_DATE;
private final int RUNTIME;
private final double VOTE_AVERAGE;
private final long VOTE_COUNT;
private final String POSTER_PATH;
private boolean validityFlag = true;
public MovieDataRetriever(String movieTitle)
{
if(movieTitle == null)
{
throw new IllegalArgumentException("Movie title can't be null");
}
this.MOVIE_TITLE_FOR_QUERY = movieTitle.replace(" ", "+");
JsonObject movieData = validateMediaData("movie", MOVIE_TITLE_FOR_QUERY);
if(movieData == null)
{
this.MOVIE_TITLE = "No data";
this.MOVIE_STATUS = "No data";
this.BUDGET = 0;
this.GENRES = new String[0];
this.RELEASE_DATE = "No data";
this.REVENUE = 0;
this.RUNTIME = 0;
this.VOTE_AVERAGE = 0;
this.VOTE_COUNT = 0;
this.POSTER_PATH = "No data";
validityFlag = false;
}
else
{
this.MOVIE_STATUS = movieData.get("status").getAsString();
this.BUDGET = movieData.get("budget").getAsLong();
this.GENRES = setGenres(movieData);
this.MOVIE_TITLE = movieData.get("title").getAsString();
if(movieData.get("release_date") == JsonNull.INSTANCE)
this.RELEASE_DATE = "Unavailable";
else
this.RELEASE_DATE = movieData.get("release_date").getAsString();
this.REVENUE = movieData.get("revenue").getAsLong();
if(movieData.get("runtime") == JsonNull.INSTANCE)
this.RUNTIME = -1;
else
this.RUNTIME = movieData.get("runtime").getAsInt();
this.VOTE_AVERAGE = movieData.get("vote_average").getAsDouble();
this.VOTE_COUNT = movieData.get("vote_count").getAsLong();
if(movieData.get("poster_path") == JsonNull.INSTANCE)
this.POSTER_PATH = null;
else
this.POSTER_PATH = movieData.get("poster_path").getAsString();
}
}
@SuppressWarnings("unused")
private MovieDataRetriever()
{
this.MOVIE_TITLE = null;
this.MOVIE_TITLE_FOR_QUERY = null;
this.MOVIE_STATUS = null;
this.BUDGET = 0;
this.GENRES = null;
this.RELEASE_DATE = null;
this.REVENUE = 0;
this.RUNTIME = 0;
this.VOTE_AVERAGE = 0;
this.VOTE_COUNT = 0;
this.POSTER_PATH = null;
}
/* static factory method that returns an array of movie objects
* based on the query string
*
* @params keyword the query string
* @returns an array of MovieDataRetriever objects (returns a maximum of 20 movies)
*/
public static MovieDataRetriever[] getMoviesByQuery(String query) throws IOException
{
JsonObject rootObject = getMediaBasedOnQueryAsJson("movie", query);
int searchResultSize = rootObject.get("results")
.getAsJsonArray()
.size();
if(searchResultSize == 0) return new MovieDataRetriever[0];
MovieDataRetriever[] searchResults = new MovieDataRetriever[searchResultSize];
for(int i = 0; i < searchResultSize; i++)
{
String movieTitle = rootObject
.get("results")
.getAsJsonArray()
.get(i)
.getAsJsonObject()
.get("title")
.getAsString();
searchResults[i] = new MovieDataRetriever(movieTitle);
}
return searchResults;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:51:42.173",
"Id": "464678",
"Score": "0",
"body": "Hi Karl, welcome on codreview. I did not (yet) reviewed the whole code. But there is one thing that disrupts me. Usually, we do not want to execute something without telling it explicitly, and based on the name of your classes (_\"..Retriever\"_) I would expect one method to execute the query: `Media result = new MovieRetriever(\"title\").execute()`."
}
] |
[
{
"body": "<p>As said in my comment, we do not want to execute something without telling it explicitly. Most of the time such programs are built with one class that execute the request and another to model the result. </p>\n\n<p>But let's start by reviewing your code. </p>\n\n<p>The main issue that I see is that you cannot test it without mocking the underlying API. One solution is to introduce an extra, low level, layer that manage the communication and that you can easily mock. </p>\n\n<pre><code>interface MovieDatabase {\n Map<String, Object> search(String mediaType) throws IOException;\n\n Map<String, Object> get(String mediaType, String mediaId) throws IOException;\n\n BufferedImage getPoster(String path) throws IOException;\n}\n</code></pre>\n\n<p>I have replaced your <code>JsonObject</code> by a <code>Map<String, Object></code> so that I can really try to refactor your code without having to manage all the dependencies. But this can also be a pattern if you want to abstract a bit more on the underlying api (It can be an Xml api, or a SQL database) </p>\n\n<p>While we are on that class, you can also replace the <code>String mediaType</code> by one enumeration, so that it will be impossible to ask something else than a <em>movie</em> or a <em>tv</em> show. </p>\n\n<p>When implementing that interface for \"The movie db\" you will discover that its own responsibility is to execute a query and parse the result. So internally, the public methods will just create a valid url and send it to a private method.</p>\n\n<p>Please not also that URL encoding is more complex than <code>query.replace(\" \", \"+\")</code>, there is one <code>URLEncoder</code> utility class to deal with that. </p>\n\n<pre><code>public Map<String, Object> search(MediaType mediaType, String query) throws IOException {\n return get(\"search/\" + mediaTypeAsString(mediaType) + \"&query=\" + URLEncoder.encode(query, \"UTF-8\"));\n}\n\n// ...\n\nprivate Map<String, Object> get(String path) throws IOException {\n URL url = new URL(url+path+\"?api_key=\" + apiKey);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n\n try (InputStreamReader standardQueryStream = new InputStreamReader((InputStream) conn.getContent())) {\n return parse(standardQueryStream);\n }\n}\n\nprivate Map<String, Object> parse(InputStreamReader input) {\n // ...\n}\n</code></pre>\n\n<p>At this time you have a low level service to query the api. It can easily be mocked or replaced by another implementation. Let's use it in your <code>MediaDataRetriever</code>, basically you have to add one constructor that expect one <code>MovieDatabase</code>. You can then replace all of the low level calls by a call to the corresponding method on the database. By doing that you will notice that there was a duplication of code in <code>getMediaBasedOnQueryAsJson</code> and <code>validateMediaData</code>, there where both executing a search request. </p>\n\n<p>We can then start to review the <code>MovieDataRetriever</code>. This one use the wrong naming convention for the fields, _UPPER_SNAKE_CASE_ is used for constants and <em>lowerCamelCase</em> must be used for class members. There is also some unused fields. </p>\n\n<p>But since that one inherit from the <code>MediaDataRetriever</code> it wont compile because it doesnt use the super constructor. And this is where the discussion start. </p>\n\n<p>As already said, most of the time, we do not want to execute something without asking for. Usually you ask provide a service that will produce a Media who can be a movie or a tv show.\nThere are some advantages of doing that. </p>\n\n<pre><code>Media media = new MediaService(..).search(\"..\");\n</code></pre>\n\n<p>In some cases it is interesting to receive a common type. It is also useful in case there is no result because you can either throw one exception or use the \"null object pattern\".</p>\n\n<p>But, please, note that while the polymorphism is a powerful pattern it may also introduce complexity. If you always know that you want a <code>Movie</code> or a <code>TvShow</code>, receiving one abstract <code>Media</code> can be boring and will introduce many code smells and useless type casts. On that subject you may consider the usage of composition instead of inheritance if your system (business side) never consider that there is a common ancestor to <code>Movie</code> and <code>TvShow</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:26:39.277",
"Id": "237129",
"ParentId": "237051",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237129",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:36:39.493",
"Id": "237051",
"Score": "1",
"Tags": [
"java",
"json",
"wrapper"
],
"Title": "Java wrapper for a movie database API"
}
|
237051
|
<p>I am making an user class which I could inherit and use in the future.<br>
(recently started learning Python and OOP)</p>
<pre><code>import mysql.connector as mycon
class user:
host = "localhost"
user = "root"
password = "pass"
database = "USERS"
table = "UserData"
def __init__(self,firstName,lastName,userName,email):
self.firstName = firstName
self.lastName = lastName
self.userName = userName
self.fullName = firstName + " " + lastName
self.email = email
@classmethod
def login(cls,userName,password):
db = mycon.connect(host = cls.host,user = cls.user,password = cls.password,database = cls.database)
cursor = db.cursor()
r=cursor.execute("SELECT * FROM {} WHERE UserName = '{}';".format(cls.table,userName))
userInfo = cursor.fetchone()
if(userInfo!=None):
if(userInfo[2]==password):
print("Login Successful")
return cls(userInfo[0],userInfo[1],userInfo[3],userInfo[4])
else:
print("INVALID PASSWORD",password,userInfo[2])
else:
print("USER DOES NOT EXIST")
db.close()
@classmethod
def register(cls,firstName,lastName,password,userName,email):
db = mycon.connect(host = cls.host,user = cls.user,password = cls.password,database = cls.database)
cursor = db.cursor()
r=cursor.execute("Insert into {} values('{}','{}','{}','{}','{}');".format(cls.table,firstName,lastName,password,userName,email))
db.commit()
db.close()
</code></pre>
<p>with a table UserData with description</p>
<p><a href="https://i.stack.imgur.com/FUZkK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FUZkK.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:23:35.077",
"Id": "464689",
"Score": "0",
"body": "Welcome to CodeReview@SE. Not claiming being new to DB programming, better don your asbestos. (Nah. [Everything *should* be meant constructive](https://codereview.stackexchange.com/conduct), even if not praise.)"
}
] |
[
{
"body": "<p>One of the most important things to take care of when writing a database application is to prevent unwanted access. This means that you always want to make sure that there is no user (and the programmer, i.e. you should be included in that) can supply an input that can escape the query and e.g. delete your whole database. This attack vector is called SQL injection and is very common. <a href=\"https://www.w3schools.com/python/python_mysql_where.asp\" rel=\"nofollow noreferrer\">Avoiding it is relatively easy, thankfully</a>, although you cannot do it for the table name:</p>\n\n<pre><code>@classmethod\ndef login(cls, user_name, password):\n db = mycon.connect(host=cls.host, user=cls.user, password=cls.password,\n database=cls.database)\n cursor = db.cursor()\n query = f\"SELECT firstName, lastName, password, UserName, email FROM {cls.table} WHERE UserName = %s;\"\n r = cursor.execute(query, (user_name,))\n user_info = cursor.fetchone()\n if user_info is not None:\n if user_info[2] == password:\n print(\"Login Successful\")\n return cls(user_info[0],user_info[1],user_info[3],user_info[4])\n else:\n print(f\"INVALID PASSWORD {password} {user_info[2]}\")\n else:\n print(\"USER DOES NOT EXIST\")\n db.close()\n</code></pre>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for variables and functions, spaces after commas and around <code>=</code> when using it as an assignment, but no space around the <code>=</code> when using it for keyword arguments.</p>\n\n<p>Comparisons to <code>None</code> should always be done with <code>is</code> or <code>is not</code> and <code>if</code> conditions don't require parenthesis, since it is a keyword.</p>\n\n<p>I also explicitly named the column names (they might be called differently, judging by <code>UserName</code>, so you would have to fix that), to ensure that you can change the table structure, as long as these names stay the same.</p>\n\n<p>And I used an <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> for easy formatting in case of an invalid password. Note that in this case you do reveal the actual password (I guess this is just for testing, just make sure you don't forget to remove that information later). In a similar vein, you should not store passwords in plaintext. Hash them with a good hashing algorithm and ideally add a salt.</p>\n\n<p>You could also use the <a href=\"https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursornamedtuple.html\" rel=\"nofollow noreferrer\"><code>mysql.cursor.MySQLCursorNamedTuple</code></a> cursor, so you can say <code>user_info.password</code> instead of <code>user_info[2]</code>. Just use <code>cursor = db.cursor(named_tuple=True)</code>.</p>\n\n<p>You should do yourself a favor and add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to every method you write, to explain what the method does, what its arguments are and what it returns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:52:28.407",
"Id": "464726",
"Score": "0",
"body": "How to prevent revealing the password"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:23:32.857",
"Id": "464735",
"Score": "0",
"body": "@VISHALAGRAWAL Just don't print the password that was input and the real password, `print(\"INVALID PASSWORD\")`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:37:17.720",
"Id": "464761",
"Score": "0",
"body": "Oh forgot to remove those thanks for help man"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:33:31.547",
"Id": "237058",
"ParentId": "237055",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "237058",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T09:59:54.603",
"Id": "237055",
"Score": "1",
"Tags": [
"python",
"beginner",
"object-oriented"
],
"Title": "User class for future inheritance in other programs involving user activity"
}
|
237055
|
<p>I have a function that constructs a path based on a function of inputs and creates the parent directory. </p>
<p>When writing a unit test for this function, I want to mock the I/O part of the function, namely the <code>.exists()</code> and <code>.mkdir()</code> methods of the <code>pathlib.Path</code> objects. However, since both are not called until the path has been constructed, I find myself reconstructing the implementation using a long chain of <code>return_value.__truediv__</code> accesses, such as below:</p>
<pre class="lang-py prettyprint-override"><code>import pathlib
import unittest.mock
import datetime
def get(base, timestamp, channel):
base = pathlib.Path(base)
path = base / "tofu" / timestamp.strftime("%Y%m%d") / f"{channel:>02d}" / "quinoa.txt"
if path.exists():
print(path, "exists")
else:
path.parent.mkdir(exist_ok=True, parents=True)
return path
@unittest.mock.patch("pathlib.Path", autospec=True)
def test_get(pP):
pP.return_value.__truediv__.return_value.__truediv__.return_value.\
__truediv__.return_value.__truediv__.return_value.\
exists.return_value = False
get("quorn", datetime.datetime.now(), 42)
pP.return_value.__truediv__.return_value.__truediv__.return_value.\
__truediv__.return_value.__truediv__.return_value.\
parent.mkdir.assert_called_once()
</code></pre>
<p>This test passes, but I have several concerns:</p>
<ul>
<li>It is testing implementation rather than functionality. If I were to rewrite the second line in <code>get</code> to read <code>path = base / timestamp.strftime("tofu%Y%m%d") / f{channel:>02d}</code> / <code>"quinoa.txt"</code>, the functionality would be identical, but the test would fail as I wouldn't be mocking the right value anymore.</li>
<li>It is hard to read and easy to miscount the depth of <code>__truediv__.return_value</code> chain.</li>
</ul>
<p>Apart from moving the I/O out of <code>get</code>, can I mock this in another way, that does not share those limitations? Or does the difficulty of writing a good test (with mock) telling me my function is too complex, despite it's small size?</p>
|
[] |
[
{
"body": "<p>Mocking system calls, especially those with side effects (<code>mkdir()</code>), is difficult and error prone.</p>\n\n<p>I would rather use a temporary directory for test purposes. This approach has the added advantage of <em>really</em> testing your FS manipluation code.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import datetime\nimport os\nimport pathlib\n\nfrom contextlib import contextmanager\nfrom tempfile import TemporaryDirectory\n\n\n@contextmanager\ndef temporary_test_dir():\n oldpwd = os.getcwd()\n with TemporaryDirectory(\"test-path\") as td:\n try:\n os.chdir(td)\n yield\n finally:\n os.chdir(oldpwd)\n\n\ndef get(base, timestamp, channel):\n base = pathlib.Path(base)\n path = base / \"tofu\" / timestamp.strftime(\"%Y%m%d\") / f\"{channel:>02d}\" / \"quinoa.txt\"\n if path.exists():\n print(path, \"exists\")\n else:\n path.parent.mkdir(exist_ok=True, parents=True)\n return path\n\n\n@temporary_test_dir()\ndef test_get():\n # All relative FS operations will be made in a temporary directory\n result = get(\"quorn\", datetime.datetime.now(), 42)\n assert result.parent.exists()\n\n</code></pre>\n\n<p>I'm not sure what is the point of the tested function, but it doesn't matter for this example's sake.</p>\n\n<p>If you <em>really</em> need to mock the filesystem part, I would suggest using an existing library such as <a href=\"https://pypi.org/project/pyfakefs/\" rel=\"nofollow noreferrer\">pyfakefs</a>, although I have never had such a need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:43:52.393",
"Id": "464724",
"Score": "0",
"body": "Thank you for posting this as an answer. With added details to boot! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:41:34.510",
"Id": "237063",
"ParentId": "237060",
"Score": "5"
}
},
{
"body": "<p>I'm no professional when it comes to testing. But it looks like your code is a perfect example on non-test friendly code. And is why SRP, <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a> is such a big thing.</p>\n\n<p>From my perspective, your function is doing two things:</p>\n\n<ol>\n<li>Making <code>path</code>.</li>\n<li>Ensuring <code>path</code> exists.</li>\n</ol>\n\n<p>If you change your code so that those are two distinct functions than you can test more easily. And finally have <code>get</code> as a helper function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def generate_path(base, timestamp, channel):\n return (\n pathlib.Path(base)\n / \"tofu\"\n / timestamp.strftime(\"%Y%m%d\")\n / f\"{channel:>02d}\"\n / \"quinoa.txt\"\n )\n\n\ndef ensure_exists(path):\n if path.exists():\n print(path, \"exists\")\n else:\n path.parent.mkdir(exist_ok=True, parents=True)\n\n\ndef get(base, timestamp, channel):\n path = generate_path()\n ensure_exists(path)\n return path\n\n</code></pre>\n\n<p>I believe someone more versed in testing would be able to say something more enlightening about what you should unittest and what you should mock. But from my POV I don't see why the implementation details of <code>generate_path</code> should matter, all that matters is you get the correct result. The implementation details of <code>ensure_exists</code>, however, do matter, as it can be hard to test file interactions. But with <a href=\"https://codereview.stackexchange.com/a/237063\">etene's</a> changes this statement can suddenly become false.</p>\n\n<p>Overall I agree with etene's answer, but I think my answer should help when designing your code for testing.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\nimport unittest.mock\nimport datetime\n\n\ndef generate_path(base, timestamp, channel):\n return (\n pathlib.Path(base)\n / timestamp.strftime(\"tofu/%Y%m%d\")\n / f\"{channel:>02d}\"\n / \"quinoa.txt\"\n )\n\n\ndef ensure_exists(path):\n if path.exists():\n print(path, \"exists\")\n else:\n path.parent.mkdir(exist_ok=True, parents=True)\n return path\n\n\nclass Tests(unittest.TestCase):\n BASE = \"quorn\"\n TIME = datetime.datetime(2020, 2, 11, 0, 0, 0, 0)\n CHANNEL = 42\n PATH = pathlib.Path(\"quorn/tofu/20200211/42/quinoa.txt\")\n\n def test_generate_path(self):\n self.assertEqual(\n generate_path(self.BASE, self.TIME, self.CHANNEL),\n self.PATH,\n )\n\n @unittest.mock.patch(\"pathlib.Path\", autospec=True)\n def test_ensure_exists(self, pP):\n pP.exists.return_value = False\n ensure_exists(pP)\n pP.parent.mkdir.assert_called_once()\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:36:10.913",
"Id": "464748",
"Score": "0",
"body": "I wholeheartedly agree with your suggestion of refactoring the code to make it more testable. \"Do one thing and do it well\", as goes the saying. I just didn't think of this angle when writing my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:20:25.623",
"Id": "464757",
"Score": "1",
"body": "Don't sweat it @etene I didn't think of your solution either ;P Things like this are what make the site great IMO"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:45:21.633",
"Id": "237071",
"ParentId": "237060",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "237071",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:46:13.667",
"Id": "237060",
"Score": "6",
"Tags": [
"python",
"unit-testing",
"mocks"
],
"Title": "Mocking pathlib.Path I/O methods in a maintainable way which tests functionality not implementation"
}
|
237060
|
<p>I wrote this simple scoped thread to use it as a class member to ensure the the thread running on a class method doesn't continue running after the class has been destructed. Also to spawn threads from the <code>main()</code> function to ensure that I don't forget any running threads upon exit .</p>
<p>This can be achieved by calling <code>join()</code> method of the C++11 <code>std::thread</code> but I wanted a class that will automatically do this.</p>
<p>I didn't implement <code>detach()</code> function because I think this kills the purpose of a scoped thread; is this right?</p>
<p>I'd like to know if there is any bug, memory leak, other errors ...</p>
<pre><code>#include <tuple>
#include <process.h>
extern "C"
{
__declspec(dllimport)
BOOL
__stdcall
CloseHandle(
HANDLE hObject
);
__declspec(dllimport)
DWORD
__stdcall
WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds
);
__declspec(dllimport)
DWORD
__stdcall
GetCurrentThreadId(
void
);
}
template <class T, auto CloseFn>
struct HandleDeleter
{
using pointer = T;
void operator ()(pointer handle) { CloseFn(handle); }
};
using Handle = std::unique_ptr<void, HandleDeleter<HANDLE, CloseHandle>>;
inline std::error_code make_system_error(DWORD val) noexcept
{
return std::error_code{ static_cast<int>(val), std::system_category() };
}
inline std::error_code make_system_error(int val) noexcept
{
return std::error_code{ val, std::system_category() };
}
namespace LIB_NAMESPACE
{
namespace detail
{
template <class Func, class ... Args>
struct ThreadParams
{
public:
ThreadParams(Func&& func, Args && ... args)
: fn{ std::forward<Func>(func) }, args_tuple{ std::forward<Args>(args)... }
{}
void Invoke()
{
std::apply(fn, args_tuple);
}
private:
Func fn;
std::tuple<Args...> args_tuple;
};
template <class ParamsType>
unsigned __stdcall ThreadFunc(void* args)
{
auto params = reinterpret_cast<ParamsType*>(args);
params->Invoke();
delete params;
return 0;
}
}
class scoped_thread
{
public:
using native_handle_type = Handle;
struct thread_id
{
public:
friend class scoped_thread;
thread_id() = default;
thread_id(unsigned int id) : id_{ id } {}
thread_id(const thread_id&) = default;
thread_id(thread_id&& other) noexcept : id_{ other.id_ }
{
other.invalidate();
}
thread_id& operator=(const thread_id&) = default;
thread_id& operator=(thread_id&& other) noexcept
{
id_ = other.id_;
other.invalidate();
return *this;
}
~thread_id()
{
id_ = 0;
}
unsigned int id() const { return id_; }
bool operator==(const thread_id& other) const
{
return id() == other.id();
}
bool operator!=(const thread_id& other) const
{
return id() != other.id();
}
bool operator>(const thread_id& other) const
{
return id() > other.id();
}
bool operator>=(const thread_id& other) const
{
return id() >= other.id();
}
bool operator<(const thread_id& other) const
{
return id() < other.id();
}
bool operator<=(const thread_id& other) const
{
return id() <= other.id();
}
private:
void invalidate() { id_ = 0; }
unsigned int * id_ptr() { return &id_; }
unsigned int id_ = 0;
};
scoped_thread() = default;
template <class Fn, class ... Args>
scoped_thread(Fn&& fn, Args && ... args)
{
using ParamsType = detail::ThreadParams<Fn, Args...>;
ParamsType* params = new ParamsType{ std::forward<Fn>(fn), std::forward<Args>(args)... };
thd_handle.reset(
reinterpret_cast<void*>(_beginthreadex(nullptr, 0,
detail::ThreadFunc<ParamsType>, params, 0, id.id_ptr()))
);
if (!thd_handle)
{
delete params;
throw std::system_error(errno, std::system_category());
}
}
scoped_thread(scoped_thread&&) = default;
scoped_thread& operator=(scoped_thread&& other) noexcept
{
if (joinable())
std::terminate();
this->~scoped_thread();
new (this) scoped_thread{ std::move(other) };
return *this;
}
native_handle_type& native_handle() noexcept { return thd_handle; }
const native_handle_type& native_handle() const noexcept { return thd_handle; }
thread_id get_id() const noexcept { return id; }
bool joinable() const noexcept
{
return get_id() != thread_id{};
}
void join()
{
check_if_valid_join();
WaitForSingleObject(thd_handle.get(), std::numeric_limits<DWORD>::max());
thd_handle.reset();
id.invalidate();
}
~scoped_thread()
{
if (joinable())
join();
}
private:
void check_if_valid_join()
{
if (!thd_handle)
throw std::system_error(std::make_error_code(std::errc::no_such_process));
if (get_id() == GetCurrentThreadId())
throw std::system_error(std::make_error_code(std::errc::resource_deadlock_would_occur));
if (!joinable())
throw std::system_error(std::make_error_code(std::errc::invalid_argument));
}
native_handle_type thd_handle;
thread_id id;
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:51:33.737",
"Id": "464804",
"Score": "0",
"body": "I might be missing something, but why couldn't `scoped_thread` be implemented in terms of `std::thread`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T11:36:04.307",
"Id": "464897",
"Score": "0",
"body": "It could, but I wanted to make use of the new language features and to be more familiar with templates"
}
] |
[
{
"body": "<p>Overall I think the code is pretty good and your use of the more modern features of C++ looks OK.</p>\n\n<p>Still there are some things that could be improved. In no particular order I offer the following suggestions:</p>\n\n<ul>\n<li>The idea of a <code>scoped_thread</code> is good (also discussed in Effective\nModern C++ item 37). Even if you want to implement your own\n<code>std::thread</code> replacement (for learning purposes or otherwise), I'd\nrecommend splitting that part out and implementing <code>scoped_thread</code> in\nterms of it. That way you can re-use both classes in other contexts.</li>\n<li>I'd probably use either the functions from <code>process.h</code> or the raw\nWin32 API (i.e. <code>CreateThread</code>) not mix them.</li>\n<li>Speaking of Win32 API functions: Just include <code>windows.h</code>, don't\ndo the declarations on your own.</li>\n<li>I realize including <code>windows.h</code> in a header file like this is pollutes\nthe global namespace, so I'd create wrapper functions like\n<code>void native_start_thread(void (*)(void*))</code> etc. and place them in an\naccompanying C++ file.</li>\n<li>In modern C++ naked calls to <code>delete</code> are a code smell. You should always\nhave the pointers owned by a <code>std::unique_ptr</code>. Of course you have to\nbe careful in this case to not double delete objects. What I mean is:\nIn <code>ThreadFunc</code> hand ownership to a <code>std::unique_ptr</code> and in the\n<code>scoped_thread</code> constructor store <code>params</code> in a <code>unique_ptr</code>. Use\n<code>get()</code> when creating the thread and then <code>release()</code> when the thread\nhas been constructed (and thus has taken ownership of the memory).</li>\n<li>You should check the return value of <code>WaitForSingleObject</code></li>\n<li>The code could use some more comments. For instance I had to look up\nwhether 0 could be a valid thread id (it can't, but I couldn't\nremember that was the case).</li>\n<li>I can't see anything wrong with the code in this regard, but I'm not\ntoo fond of thread ownership actually being tied to the thread id.</li>\n<li>Again, I don't see any immediate problems, but I'd probably make sure\nto null out the thread handle in the moved from thread (to at least aid\nin debugging). This would mean using a non-defaulted move-constructor,\nand then I'd probably implement it in terms of the move assignment\noperator (which then wouldn't/couldn't use placement new, which again\nI think works fine, but seems \"overkill\" here).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:04:24.230",
"Id": "464951",
"Score": "1",
"body": "\"I'd probably use either the functions from process.h or the raw Win32 API (i.e. `CreateThread`) not mix them\" . the docs recommends to start any thread that uses c runtime library using functions from `process.h` in order to avoid a small memory leak when the thread exits . for the last remark : it's already done because the thread handle is a smart handle (handle in a smart pointer) so the default `unique_ptr` move assignment operator nulls out (invalidates) the handle once moved from to ensure one object manages the handle . thanks for your tips ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:25:39.567",
"Id": "464960",
"Score": "0",
"body": "@dev65: Sorry my bad on both counts. I mistakenly though the need to use `_beginthread` was gone, but it seems like that's not the case when [linking statically to the CRT](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitthread?redirectedfrom=MSDN). And in the heat of battle I'd forgotten that `native_handle_type` was a smart pointer - I'll amend my post later to reflect this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T17:22:30.323",
"Id": "237169",
"ParentId": "237065",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:54:51.023",
"Id": "237065",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"c++17",
"winapi"
],
"Title": "Scoped thread using modern C++"
}
|
237065
|
<p>This program does simple arithmetic calculation (+. -, *, /, %) in <code>masm</code>. I've tested the code.</p>
<pre><code>disp_str macro msg ;print a string
lea dx, msg
mov ah, 09h
int 21h
endm
input macro ;move values to ax & bx for execution
call clear_reg
mov ax, num1
mov bx, num2
endm
output macro msg, num ;display numerical values
disp_str msg
mov ax, num
call write
endm
.model small
.stack
.data
msg1 db 0Ah,0Dh, "Enter the first number > $"
msg2 db 0Ah,0Dh, "Enter the second number > $"
msum db 0Ah,0Dh, "Sum = $"
mdif db 0Ah,0Dh, "Difference = $"
mprd db 0Ah,0Dh, "Product = $"
mquo db 0Ah,0Dh, "Quotient = $"
mrem db 0Ah,0Dh, "Remainder = $"
num1 dw ?
num2 dw ?
temp dw 0
rslt dw 0
.code
mov ax, @data
mov ds, ax
main proc
disp_str msg1
call read
mov num1, ax
disp_str msg2
call read
mov num2, ax
input
add ax, bx
mov rslt, ax
output msum, rslt
input
sub ax, bx
mov rslt, ax
output mdif, rslt
input
mul bx
mov rslt, ax
output mprd, rslt
input
div bx
mov rslt, ax
mov temp, dx
output mquo, rslt
output mrem, temp
mov ah, 4Ch
int 21h
main endp
read proc
mov ax, 00h
mov cx, 04h
L1:
mov dl, 0Ah
mul dx
mov temp, ax
mov ah, 01h
int 21h
sub al, 30h
mov ah, 00h
mov bx, temp
add ax, bx
loop L1
ret
read endp
write proc
mov bx, 0Ah
mov cx, 00h
L2:
mov dx, 00h
inc cx
div bx
push dx
cmp ax, 00h
jne L2
L3:
pop dx
add dl, 30h
mov ah, 02h
int 21h
loop L3
ret
write endp
clear_reg proc ;clears all the registers
xor ax, ax
xor bx, bx
xor cx, cx
xor dx, dx
ret
clear_reg endp
end
</code></pre>
<p>Output:
<a href="https://i.stack.imgur.com/ofugF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ofugF.png" alt="Output"></a></p>
<p>Also how does the procedure <code>read</code> & <code>write</code> work?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:18:21.993",
"Id": "464743",
"Score": "1",
"body": "Your question about how read and write works suggests you didn't write the code yourself. Can you clarify if you're the author?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:19:33.243",
"Id": "464744",
"Score": "1",
"body": "No, I'm not the author, original program was given by the lab instructor, here https://p.ip.fi/LNsP, I tried to optimize it to the extent of my understanding of macros & procedures."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:51:04.240",
"Id": "464750",
"Score": "2",
"body": "Other people's code is off topic. Read and write are essentially just wrapping the DOS api to read and write characters. http://spike.scu.edu.au/~barry/interrupts.html"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:58:21.133",
"Id": "237066",
"Score": "1",
"Tags": [
"assembly"
],
"Title": "Simple arithmetic operations in MASM using dosbox"
}
|
237066
|
<p>Here is problem:<br>
There is string (domain) divided by dots (like <code>www.part1.partN.com</code>)<br>
Need to build reversed by dot string (like <code>com.partN.part1.www</code>)<br>
Both strings are utf-8 encoded </p>
<p>My solution:</p>
<pre><code>std::string reverseHost(const std::string& host)
{
std::string ret;
ret.reserve(host.size());
size_t tail = host.size();
size_t head = host.find_last_of('.');
while (head != std::string::npos)
{
ret.append(host.c_str() + head + 1, tail - head - 1);
ret += '.';
tail = head;
head = host.find_last_of('.', tail - 1);
}
ret.append(host.c_str(), tail);
return ret;
}
</code></pre>
<p>Need to improve speed (or advice how to improve), raw memory and other tricks allowed. ty.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T15:46:58.507",
"Id": "465292",
"Score": "0",
"body": "what if the input string is just a \".\", should you handle such case?"
}
] |
[
{
"body": "<p>You've misspelt <code>std::size_t</code>.</p>\n\n<p>Apart from that, the code seems reasonably straightforward if you always need to return a copy.</p>\n\n<p>A two-pass algorithm (reverse the whole string, then reverse each of the individual components) might be faster, because you can operate in-place, without having to create a new string. Of course, you'll only get the speed benefit if the caller doesn't need to retain the original (pass by value, and use <code>std::move</code> to control copying).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:38:22.590",
"Id": "237070",
"ParentId": "237067",
"Score": "3"
}
},
{
"body": "<p>If you're using Boost, one readable solution is:</p>\n\n<pre><code>#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\nstd::string reverseHost(const std::string& host)\n{\n std::vector<std::string> parts;\n boost::algorithm::split(parts, host, boost::is_any_of(\".\"));\n std::reverse(parts.begin(), parts.end());\n\n return boost::algorithm::join(parts, \".\");\n}\n</code></pre>\n\n<p>In short, we split the input into parts using dot as a delimiter, reverse them, and join in reverse order.</p>\n\n<p>However, this is not designed with performance in mind. A faster alternative is likely the following:</p>\n\n<pre><code>std::string reverseHost(const std::string& str)\n{\n std::string rev(str.crbegin(), str.crend());\n const std::size_t len = rev.size();\n\n for (std::size_t j, i = 0; i < len; ++i)\n {\n j = i;\n\n while ((i < len) && (rev[i] != '.'))\n ++i;\n\n std::reverse(rev.begin() + j, rev.begin() + i);\n }\n\n return rev;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T08:40:50.897",
"Id": "465680",
"Score": "0",
"body": "i've tested your solution 100 launches with 1m iterations each. your solution ~148 ms (per 1m) mine ~95 ms"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T08:43:15.887",
"Id": "465681",
"Score": "0",
"body": "also boost is about ~700ms in same benchmark xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T19:51:02.603",
"Id": "465771",
"Score": "0",
"body": "@goldstar I made a small optimization, but perhaps it won't matter much. A second step could be to try another method instead of `std::reverse`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T20:33:04.730",
"Id": "465946",
"Score": "0",
"body": "@goldstar: Is this function really a hotspot that needs such micro optimization? Unlikely; if not then go with the clearer solution. Which `Juho` has provided (the copy revered, then reverse each word) is the classic implementation. If this is the hot spot (you need the data to prove that), then go with your optimized version and add the extra documentation to make sure maintainers know that it needs to be optimized. But note the cost of this version can be optized in several ways. Do the work in place or making sure the space is pre-allocated (as in your version)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-20T06:24:09.130",
"Id": "465988",
"Score": "0",
"body": "@MartinYork, yep, this function is bottleneck and part of library so i need optimize it as well."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:54:22.997",
"Id": "237258",
"ParentId": "237067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:01:50.440",
"Id": "237067",
"Score": "2",
"Tags": [
"c++",
"strings"
],
"Title": "Reverse string by separator"
}
|
237067
|
<p>I am using the code below to pass filter selections from table A to table B in Spotfire. I am doing this to create a filtering relationship between the tables, but skipping the creation of a traditional Spotfire table relationship, as this is not advisable in this setting.</p>
<p>The code is associated with a document property which itself is driven by a simple data function, following the instructions found <a href="https://support.tibco.com/s/article/Tibco-KnowledgeArticle-Article-45663" rel="noreferrer">here</a>. </p>
<p>After it is triggered, the code finds a specific filter in table A. It reads the content and creates a list. It checks the length of the list, and if greater than zero, it takes the filter object and passes it to the matching filter in table B. If nothing is selected (len = 0), then the matching filter in table B is reset. The process is repeated for multiple filters.</p>
<p>As far as I can tell it works on my machine. But even as a complete beginner, I can tell it is poorly written. I would appreciate suggestions and feedback on how I can make it better.</p>
<pre><code>from Spotfire.Dxp.Application.Filters import *
from Spotfire.Dxp.Application.Visuals import VisualContent
from System import Guid
#Get the active page and filterPanel
page = Application.Document.ActivePageReference
filterPanel = page.FilterPanel
##########################reasons#############################################
#get information for the first filter
theFilter = filterPanel.TableGroups[0].GetFilter("Reason")
lbFilter = theFilter.FilterReference.As[ListBoxFilter]()
#get information for the second filter
theFilter2 = filterPanel.TableGroups[1].GetFilter("Reason")
lb2Filter = theFilter2.FilterReference.As[ListBoxFilter]()
#check if any selections are made in the first filter
n = []
for value in lbFilter.SelectedValues:
n.append(value)
if len(n)>0:
lb2Filter.IncludeAllValues = False
lb2Filter.SetSelection(lbFilter.SelectedValues)
#if no selections are made, reset the second filter
else:
lb2Filter.Reset()
#########################Type#####################################################
theFilterPT = filterPanel.TableGroups[0].GetFilter("Type")
lbFilterPT = theFilterPT.FilterReference.As[ListBoxFilter]()
theFilter2PT = filterPanel.TableGroups[1].GetFilter("Type")
lb2FilterPT = theFilter2PT.FilterReference.As[ListBoxFilter]()
n = []
for value in lbFilterPT.SelectedValues:
n.append(value)
if len(n)>0:
lb2FilterPT.IncludeAllValues = False
lb2FilterPT.SetSelection(lbFilterPT.SelectedValues)
else:
lb2FilterPT.Reset()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:10:47.610",
"Id": "464740",
"Score": "3",
"body": "Hey! Thanks for the ping, I've edited the title to bring it in line with our rules. Since most people need help the title you had wouldn't be any different than other questions. I have also made some minor edits to your description so that it's clear that the question is on-topic. Thank you for the added description and pinging me. If you think I've drastically changed your question feel free to roll back my edit :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:03:47.230",
"Id": "464753",
"Score": "0",
"body": "@Peilonrayz. I appreciate the help, and thanks for creating the tags."
}
] |
[
{
"body": "<ul>\n<li><p><code>from ... import *</code> is discouraged by a large amount of people.</p>\n\n<p>Currently it's easy to see what comes from <code>Filters</code>, as you only have one. But if you have two or more than it just becomes impossible to understand.</p></li>\n<li><p>Your code doesn't look Pythonic, unfortunately this is because <code>Spotfire</code> has violated <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> making anything that uses it look, to my eyes, ugly.</p>\n\n<p>Whilst I'm not a fan of the style you are using, I would like to congratulate you on sticking to one style. Well done.</p></li>\n<li><p>If the comments help you then keep them. However if you wrote them to help us then I would recommend that you remove them.</p></li>\n<li>You have lots of un-needed variables; <code>page</code>, <code>theFilter</code>, <code>theFilterPT</code>.</li>\n<li>Functions are the bread and butter of programming. And your code is in some dire need of functions.</li>\n</ul>\n\n<p>In your code we see that you have the following definitions:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>#get information for the first filter\ntheFilter = filterPanel.TableGroups[0].GetFilter(\"Reason\")\nlbFilter = theFilter.FilterReference.As[ListBoxFilter]()\n#get information for the second filter\ntheFilter2 = filterPanel.TableGroups[1].GetFilter(\"Reason\")\nlb2Filter = theFilter2.FilterReference.As[ListBoxFilter]()\n</code></pre>\n \n <pre class=\"lang-py prettyprint-override\"><code>theFilterPT = filterPanel.TableGroups[0].GetFilter(\"Type\")\nlbFilterPT = theFilterPT.FilterReference.As[ListBoxFilter]()\n\ntheFilter2PT = filterPanel.TableGroups[1].GetFilter(\"Type\")\nlb2FilterPT = theFilter2PT.FilterReference.As[ListBoxFilter]()\n</code></pre>\n</blockquote>\n\n<p>We can see clearly that only two things change between them; <code>[0]</code> and <code>[1]</code>, and \"Reason\" and \"Type\".\nI personally think <code>filterPanel.TableGroups[0]</code> shouldn't be in the function and we can just pass the filter in the function. This can result in:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def getGroup(tableGroup, filter):\n return (\n tableGroup\n .getFilter(filter)\n .FilterReference\n .As[Filters.ListBoxFilter]()\n )\n</code></pre>\n\n<p>After this we can see you've written something else twice too.</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>n = []\nfor value in lbFilter.SelectedValues:\n n.append(value)\nif len(n)>0:\n lb2Filter.IncludeAllValues = False\n lb2Filter.SetSelection(lbFilter.SelectedValues)\n#if no selections are made, reset the second filter\nelse:\n lb2Filter.Reset()\n</code></pre>\n</blockquote>\n\n<p>Firstly creating <code>n</code> can be simplified simply as <code>list(lbFilter.SelectedValues)</code>.\nYou don't need to use <code>len(n)>0</code> as just <code>if n:</code> does that check, with a list, for you.\nFinally I find it easier to have the smaller code block first, and so flipped the if.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def filterGroups(tableGroups, filter):\n group1 = getGroup(tableGroups[0], filter)\n group2 = getGroup(tableGroups[1], filter)\n\n if not list(group1.SelectedValues):\n group2.Reset()\n else:\n group2.IncludeAllValues = False\n group2.SetSelection(group1.SelectedValues)\n</code></pre>\n\n<p>Finally I would wrap everything in a <code>main</code> function and you'd get the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import System\nfrom Spotfire.Dxp.Application import Filters, Visuals\n\n\ndef getGroup(tableGroup, filter):\n return (\n tableGroup\n .getFilter(filter)\n .FilterReference\n .As[Filters.ListBoxFilter]()\n )\n\n\ndef filterGroups(tableGroups, filter):\n group1 = getGroup(tableGroups[0], filter)\n group2 = getGroup(tableGroups[1], filter)\n\n if not list(group1.SelectedValues):\n group2.Reset()\n else:\n group2.IncludeAllValues = False\n group2.SetSelection(group1.SelectedValues)\n\n\ndef main():\n tableGroups = (\n Filters\n .Application\n .Document\n .ActivePageReference\n .FilterPanel\n .TableGroups\n )\n filterGroups(tableGroups, \"Reason\")\n filterGroups(tableGroups, \"Type\")\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:16:18.573",
"Id": "473291",
"Score": "0",
"body": "Thank you so much for this. Now that I wrapped up another project, I can get back to this code. One question: What is the benefit of wrapping it in a main function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:28:17.107",
"Id": "473296",
"Score": "0",
"body": "@KR In short `main()` stops the variables from being in the global scope. They're not needed to be in global scope and for some this causes an unhealthy dependence on global variables. It also causes there to be less name collisions and so you can safely call different but similar variables in two separate functions the same name. This allows you to use shorter and easier to read variable names everywhere."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T15:26:21.387",
"Id": "237330",
"ParentId": "237072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:03:40.700",
"Id": "237072",
"Score": "5",
"Tags": [
"python"
],
"Title": "Spotfire: Creating filtering relationships by passing filters between tables"
}
|
237072
|
<p>In this code I calculate the statistical functions of values from different files and save them into CSV files (one filer for each statistical function).</p>
<pre class="lang-py prettyprint-override"><code>def mean(data):
pass
def standard_deviation(data):
pass
def afd(data):
pass
def norma_afd(data):
pass
def asd(data):
pass
def norma_asd(data):
pass
def calculation(file):
"""
Get the DataFrame and calculate for ever column the different statistical mean
:param file: DataFrame 56x7681
:return: 6 different 56x1 lists for (mean, std, afd, norm_afd, asd, norm_asd)
"""
m, sd, afd_l, nafd, asd_l, nasd = ([] for _ in range(6))
for column in file:
data = file[column].to_numpy()
m.append(mean(data))
sd.append(standard_deviation(data))
afd_l.append(afd(data))
nafd.append(norma_afd(data))
asd_l.append(asd(data))
nasd.append(norma_asd(data))
return m, sd, afd_l, nafd, asd_l, nasd
def run(load_path, save_path):
"""
Get (yield) all the different DataFrame from a folder
and calculate for each file the statistical mean and save it in a csv file
:param load_path: the folder path to load all the different files
:param save_path: the folder save path
:return: none
"""
m, sd, afd_l, nafd, asd_l, nasd = ([] for _ in range(6))
for current_path, file in yield_data(load_path, data_type="data"):
a, b, c, d, e, f = calculation(file)
m.append(a)
sd.append(b)
afd_l.append(c)
nafd.append(d)
asd_l.append(e)
nasd.append(f)
if not os.path.exists(save_path):
os.makedirs(save_path)
pd.DataFrame(m).to_csv(save_path + os.path.sep + "mean.csv", index=False, header=False)
pd.DataFrame(sd).to_csv(save_path + os.path.sep + "std.csv", index=False, header=False)
pd.DataFrame(afd_l).to_csv(save_path + os.path.sep + "afd.csv", index=False, header=False)
pd.DataFrame(nafd).to_csv(save_path + os.path.sep + "norm_afd.csv", index=False, header=False)
pd.DataFrame(asd_l).to_csv(save_path + os.path.sep + "asd.csv", index=False, header=False)
pd.DataFrame(nasd).to_csv(save_path + os.path.sep + "norm_asd.csv", index=False, header=False)
</code></pre>
<p>Is there a better and more efficient way to write this code? This may be a stupid question, but I would be really interested to know if there is a better way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:46:14.273",
"Id": "464776",
"Score": "0",
"body": "Are you missing some `import` statements? Please [edit] to complete the program."
}
] |
[
{
"body": "<p>As the code cannot be run, here is a wild guess on a way to restructure it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def mean(fileResults, data):\n result = 0\n # do computation\n fileResults[\"mean\"].append(result)\n\ndef standard_deviation(fileResults, data):\n pass\n\ndef afd(fileResults, data):\n pass\n\ndef norma_afd(fileResults, data):\n pass\n\ndef asd(fileResults, data):\n pass\n\ndef norma_asd(fileResults, data):\n pass\n\ndef calculation(file):\n \"\"\"\n Get the DataFrame and calculate for ever column the different statistical mean\n :param file: DataFrame 56x7681\n :return: 6 different 56x1 lists for (mean, std, afd, norm_afd, asd, norm_asd)\n \"\"\"\n fileResults = {\n \"mean\": [],\n \"std\": [],\n \"afd\": [],\n \"norm_afd\": [],\n \"asd\": [],\n \"norm_asd\": [],\n }\n\n functionCallList = [\n mean,\n standard_deviation,\n afd,\n norma_afd,\n asd,\n norma_asd,\n ]\n\n for column in file:\n data = file[column].to_numpy()\n\n for functionCall in functionCallList:\n functionCall(fileResults, data)\n\n return fileResults\n\ndef run(load_path, save_path):\n \"\"\"\n Get (yield) all the different DataFrame from a folder\n and calculate for each file the statistical mean and save it in a csv file\n\n :param load_path: the folder path to load all the different files\n :param save_path: the folder save path\n :return: none\n \"\"\"\n results = {}\n\n for current_path, file in yield_data(load_path, data_type=\"data\"):\n fileResults = calculation(file)\n\n for key, value in fileResults.items():\n if key not in results:\n results[key] = []\n\n results[key].append(value)\n\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n for key, value in results.items():\n pd.DataFrame(value).to_csv(save_path + os.path.sep + key + \".csv\", index=False, header=False)\n</code></pre>\n\n<p>So, instead of repeating function call, mostly when function prototypes are the same, you can use a list of function callbacks. Then just iterate it.</p>\n\n<p>You can also use a dictionnary to store your data, instead of n lists. It's a little bit more scalable, and clearer than returning a 6-tuple. It also avoids a lot of copy-paste when you save csv files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T18:01:43.167",
"Id": "464805",
"Score": "0",
"body": "Agree, list of function is way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:06:04.690",
"Id": "464878",
"Score": "1",
"body": "@VincentRG To work correct for my purpose I initial the dictionary `fileResults` in `calculation` with `{\"mean\": [], \"std\": [], \"afd\": [], \"norm_afd\": [], \"asd\": [], \"norm_asd\": []}` and the calculation methods append to the lists. But many thanks for your solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:26:42.873",
"Id": "464882",
"Score": "0",
"body": "Yes you're right, several columns per file are parsed, and for each column you do all computations. Hence the need for appending to each list for each column. I haven't seen that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T17:16:35.973",
"Id": "237094",
"ParentId": "237074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237094",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T13:47:41.173",
"Id": "237074",
"Score": "0",
"Tags": [
"python",
"performance",
"pandas",
"statistics"
],
"Title": "Calculate the statistical mean of different files and save it into a CSV file"
}
|
237074
|
<p>I want to associate an error message to a Validator and not have to in the html check for a specific error. aka *ngIf="controls.name.required". I've seen generic error message helpers that build up an javascript object with an index and a message that goes with that index. What I want is to actually associate the error message with the validation result. </p>
<p>This only works for ReactiveForms but I'm wrapping the Validator Result and tagging in the message into the ValidationErrors result. </p>
<pre><code>import { ValidatorFn, ValidationErrors, AbstractControl, AsyncValidatorFn } from '@angular/forms';
import { map, filter, take } from 'rxjs/operators';
import { Observable } from 'rxjs';
function isObservable(observerable: ValidationErrors | Observable<ValidationErrors>): observerable is Observable<ValidationErrors> {
return observerable.pipe && typeof observerable.pipe === 'function';
}
// @dynamic
export class ValidatorHelpers {
// Validator that wraps another validator and adds a message property to the ValidationErrors payload
static addMessage(innerValidator: ValidatorFn, message: string | ((validationErrors: ValidationErrors) => string)): ValidatorFn {
return (control: AbstractControl) => {
const result = innerValidator(control);
if (result) {
if (typeof message !== 'string') {
const func = message as ((validationErrors: ValidationErrors) => string);
message = func(result);
}
const newObj: ValidationErrors = Object.assign({}, ...Object.keys(result)
.filter((k) => result[k])
.map(k => ({ [k]: { ...result[k], message } })));
return newObj;
}
return null;
};
}
static asyncAddMessage(innerValidator: AsyncValidatorFn, message: string | ((validationErrors: ValidationErrors) => string)): AsyncValidatorFn {
return async (control: AbstractControl) => {
const innerResult = await innerValidator(control);
if (innerResult) {
const getMessage = (errors: ValidationErrors): string => {
if (typeof message !== 'string') {
const func = message as ((validationErrors: ValidationErrors) => string);
return func(errors);
} else {
return message;
}
};
const result = (errors: ValidationErrors): ValidationErrors => {
return Object.assign({}, ...Object.keys(errors)
.filter(x => errors[x])
.map(x => ({ [x]: { ...errors[x], message: getMessage(errors), value: control.value } })));
};
if (isObservable(innerResult)) {
return innerResult.pipe(
filter(x => Boolean(x)),
map(x => result(x)),
take(1)).toPromise();
} else {
return result(innerResult);
}
}
return null;
};
}
}
</code></pre>
<p>Now when validation comes back it has a new property called message to the ValidationErrors. when I build my FormGroup I can add validation message as</p>
<pre><code>ngOnInit() {
this.createFormGroup = this.fb.group({
name: ['', [ValidationHelpers.addMessage(Validators.required, 'Name is required')]]
})
}
</code></pre>
<p>In the html I can get the error for each field as so</p>
<pre><code><div *ngIf="(controls.name.dirty || controls.name.touched) && controls.name.invalid" class="invalid-feedback d-block">
<div data-error-for="name" *ngFor="let error of controls.name.errors | keyvalue">
{{error.value.message}}
</div>
</div>
</code></pre>
<p>This way when validations get changed don't have to update html or a error to message mapping object and the message gets returned back with the error.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:02:33.327",
"Id": "237075",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Angular ReactiveForm Error Association"
}
|
237075
|
<p>How can I re-factorise this circular nesting dictionary function?</p>
<h2>The challenge:</h2>
<blockquote>
<p>I recently received a data extract with a list of folder names and associated subfolders. The challenge was to produce a reusable function that could provide a summary of the unique folder names and all the nested subfolders.</p>
<p>The data source was an excel spreadsheet containing 2 columns:</p>
<p>Parent: Folder name</p>
<p>Child: Subfolder name</p>
<p>Note: I have recreated spreadsheet data using pandas so the code can be easily tested.</p>
</blockquote>
<p><strong>Create table:</strong></p>
<pre><code>import pandas as pd
data = {'Parent': ['A', 'B', 'C', 'D', 'E', 'F', 'C', 'C'],
'Child': ['B', 'C', 'E', 'E', 'Z', 'Z', 'B', 'A']}
df = pd.DataFrame(data)
print(df):
Parent Child
0 A B
1 B C
2 C E
3 D E
4 E Z
5 F Z
6 C B
7 C A
</code></pre>
<h2>My solution:</h2>
<pre><code>def relationship_dictionary(dataframe, key_column_name, values_column_name):
"""
The key_column_name is the primary data source that should be considered the
start of the nested relationship.
The values_column_name is the subfolder
Creates a dictionary of unique relationships to each key.
"""
parent = key_column_name
child = values_column_name
d = {}
for i, row in dataframe.iterrows():
key = row[parent]
value = row[child]
if key in d.keys():
d[key].append(value)
else:
d[key] = [value]
for k, values in d.items():
for v in values:
if v in d.keys():
for each in d[v]:
if (each not in d[k]) and (each != k):
d[k].extend([each])
return d
</code></pre>
<h2>Result:</h2>
<pre><code>relationship_dictionary(df, "Parent", "Child")
{'A': ['B', 'C', 'E', 'Z'],
'B': ['C', 'E', 'A', 'Z'],
'C': ['E', 'B', 'A', 'Z'],
'D': ['E', 'Z'],
'E': ['Z'],
'F': ['Z']}
</code></pre>
<h2>Feedback</h2>
<blockquote>
<p>I'm happy to say it works after mitigating the circular nesting issue but I can't help thinking there is a far simpler way of doing this so I thought I'd put it out there for critique so feedback would be welcome... :)</p>
</blockquote>
|
[] |
[
{
"body": "<p>You could create a graph, and use graph theory algorithms to find all nodes (children) you can visit from your current node (parent). The graph would be a directed, acyclic graph due to the nature of the file system.</p>\n\n<p>In fact, this sounds like a great example of how to use graph theory in practice, so I will implement it given slightly more time.</p>\n\n<p>I am including a simplified version of your code without using graphs (still had to use a nested loop, but only of depth 2!):</p>\n\n<pre><code>def relationship_dictionary(dataframe, key_column_name, values_column_name):\n \"\"\"\n The key_column_name is the primary data source that should be considered the\n start of the nested relationship.\n\n The values_column_name is the subfolder\n\n Creates a dictionary of unique relationships to each key.\n \"\"\"\n # ['A', 'B', 'C', 'D', 'E', 'F', 'C', 'C']\n parents = dataframe[key_column_name].to_list()\n\n # ['B', 'C', 'E', 'E', 'Z', 'Z', 'B', 'A']\n children = dataframe[values_column_name].to_list()\n\n # [('A', 'B'), ('B', 'C'), ('C', 'E'), ('D', 'E'), ('E', 'Z'), ('F', 'Z'), ('C', 'B'), ('C', 'A')]\n queue = tuple(zip(parents, children))\n\n # Create a parent -> empty set mapping to avoid using \"if parent in mapping then ..., else ...\"\n mapping = {parent: set() for parent in parents}\n\n # Iterate over each parent, child pair\n for parent, child in queue:\n\n # Always register a new pair has been processed\n mapping[parent].add(child)\n\n # Need to iterate over current pairs to make sure situations such as\n # 1. Pair A -> {B} added\n # 2. Pair B -> {C} added\n # result in A -> {B, C} instead of A -> {B}\n #\n # This essentially checks that if the parent in the current pair has been a child somewhere, the child in\n # current pair should also be added to wherever the parent was a child (if confusing follow sample above),\n # excluding cases (such as the last C -> {A} pair being included into A -> {'C', 'B', 'E', 'Z'} mapping)\n # in which the child is also the parent\n for current_parent, current_children in mapping.items():\n if parent in current_children and child != current_parent:\n current_children.add(child)\n\n return mapping\n\n\nfor k, v in relationship_dictionary(df, \"Parent\", \"Child\").items():\n print(k, v)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>A {'E', 'B', 'Z', 'C'}\nB {'E', 'A', 'Z', 'C'}\nC {'A', 'B', 'Z', 'E'}\nD {'Z', 'E'}\nE {'Z'}\nF {'Z'}\n</code></pre>\n\n<p>I have only tested it with your example but you might want to verify the code works with some more samples!</p>\n\n<p>Hope it helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T12:29:41.453",
"Id": "465865",
"Score": "0",
"body": "I really like this! This problem was a real life one with basically finding out all the user and computer objects in an Active Directory.I had no idea what graph theory was so I've just spent 4 hours reading up on it and it is awesome!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T00:32:39.307",
"Id": "237469",
"ParentId": "237076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237469",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:10:02.643",
"Id": "237076",
"Score": "3",
"Tags": [
"python"
],
"Title": "Circular nesting dictionary function"
}
|
237076
|
<p>I was doing this exercise on <a href="https://www.codeabbey.com/index/task_view/code-guesser" rel="nofollow noreferrer">codeabbey.</a></p>
<blockquote>
<p>Andrew and Peter play the code-guessing game. Andrew chooses a secret
number consisting of 3 digits. Peter tries to guess it, proposing
several values, one by one.</p>
<p>For each guess Andrew should answer how many digits are correct - i.e.
are the same in the proposed value and in his secret number - and are
placed in the same position. For example, if secret number is 125 and
Peter calls 523, then Andrew answers with 1</p>
<p>You are to write program which reads guesses given by Peter (except
the last) and prints out the secret number choosen by Andrew. It is
guaranteed that exactly one solution exists.</p>
<p>Input data will contain number of guesses in the first line. Then
answers with attempts will follow - each contains the number told by
Peter and the answer given by Andrew. In contrast with examples
numbers will be of 4 digits. Answer should contain the secret number
(also 4 digits).</p>
</blockquote>
<p>There is also a better explanation of the requirements on the site itself.</p>
<p>Below is my code</p>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <vector>
#include <set>
bool isgoodguess (bool flag[], int tempnum, std::set<int> &one, std::set<int> &two, // good guesses are guesses that can show an answer, given the prior information.
std::set<int> &three, std::set<int> &four, int howmany) {
int passnum; // for ease of understanding. "howmany" is the number of correct digits.
switch(howmany) {
case 1:
passnum = 3; // but passnum is used to count if there are enough digits that were already removed so that
break; // we know if this is a good guess or not.
case 2:
passnum = 2; // basically if the guess has 2 correct digits, we need to have 2 numbers that were already proven
break; // to be wrong, so that we know which two digits are correct.
}
int counter = 0; // counter tracks how many digits can be proven to be wrong.
if (one.find(tempnum/1000) == one.end()) { // if this digit can not be found in the current set of possible values (i.e this digit is not correct)
counter++; // increase counter
flag[0] = false; // mark this particular digit as a false one.
}
else {
flag[0] = true; // else if this digit cannot be proven to be wrong yet, mark it as true.
}
if (two.find(tempnum%1000 / 100) == two.end()) { // and so on.
counter++;
flag[1] = false;
}
else {
flag[1] = true;
}
if (three.find(tempnum%100 / 10) == three.end()) {
counter++;
flag[2] = false;
}
else {
flag[2] = true;
}
if (four.find(tempnum%10) == four.end()) {
counter++;
flag[3] = false;
}
else {
flag[3] = true;
}
return (counter == passnum) ? true : false; // if sufficient digits are proven false (a good guess since it helps to narrow down further), return true.
}
void check(std::vector<int> &tocheck, std::set<int> &one, std::set<int> &two, // passing by reference the vectors and sets so that they can be changed from inside the function.
std::set<int> &three, std::set<int> &four, int howmany) { // howmany refers to how many digits are correct.
std::vector<int>::iterator it = tocheck.begin();
while(it != tocheck.end()) { // loop through the whole vector of guesses.
bool flag[4]; // required to check which digits out of the four are correct or wrong.
if (isgoodguess(flag, *it, one, two, three, four, howmany)) { // passing on values to a func which will determine if an answer can be found from that particular guess.
if (flag[0] == true) { // if first digit is correct,
one.clear(); // remove the whole set of first digits
one.insert(*it/1000); // insert the one correct value into the set.
}
if (flag[1] == true) { // repeat for other sets.
two.clear();
two.insert(*it%1000 / 100);
}
if (flag[2] == true) {
three.clear();
three.insert(*it%100 / 10);
}
if (flag[3] == true) {
four.clear();
four.insert(*it%10);
}
tocheck.erase(it); // remove this particular guess from the vector of guesses, not required anymore.
}
else {
it++;
}
}
}
int main() {
int cases;
std::cin >> cases;
int guess, correct;
std::set<int> digit1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // create a set of possible values for first digit.
std::set<int> digit2 = digit1, digit3 = digit1, digit4 = digit1; // create 3 more sets of possible values for the other 3 digits.
std::vector<int> guess1, guess2; // for holding on to values with 1 correct digit and 2 correct digit respectively.
for (int x = 0; x<cases; x++) { // take in the number of guesses.
std::cin >> guess >> correct;
if (correct == 0) { // if that guess has 0 answers, remove all the digits from their respective sets.
digit1.erase(guess/1000);
digit2.erase(guess%1000 / 100);
digit3.erase(guess%100 / 10);
digit4.erase(guess%10);
}
else if (correct == 1) { // if that guess has 1 correct digit, add that value to vector guess1.
guess1.push_back(guess);
}
else if (correct == 2) { // if that guess has 2 correct digits, add that value to vector guess2.
guess2.push_back(guess);
}
}
while (digit1.size() > 1 || digit2.size() > 1 || digit3.size() > 1 || digit4.size() > 1) { // while any position has not been narrowed down to one answer yet, repeat loop.
check(guess1, digit1, digit2, digit3, digit4, 1); // passing vector 1, as well as all the set of possible digits, as well as "1" which means 1 correct.
check(guess2, digit1, digit2, digit3, digit4, 2);
}
std::cout << *digit1.begin() << *digit2.begin() << *digit3.begin() << *digit4.begin(); // answer.
}
</code></pre>
<p>I am wondering if this is considered a good way to do it? What did I do wrongly or are there any other methods to do this?</p>
<p>Also, I have seen another person's code, and that person basically does it starting from number 1000 ( the first possible number ), and comparing if this number will produce the same answers. If it does not, the number increases by 1, until a correct answer is found. The code is below:</p>
<blockquote>
<pre><code>#include <bits/stdc++.h>
using namespace std;
vector <pair < int ,int> > code;
pair <int,int> pp;
int codechecker(int no,int guess)
{
int n[4],g[4],r1,r2,i=0;
while(no>0)
{
r1 = no%10;
n[i] = r1;
no = no/10;
r2 = guess%10;
g[i] = r2;
guess = guess/10;
i++;
}
i=0;
for(int j=0;j<4;j++)
{
if(n[j]==g[j])
i++;
}
return i;
}
bool correct(int no)
{
int size1 = code.size();
for(int i=0;i<size1;i++)
{
pp = code[i];
int m = codechecker(no,pp.first);
if(m!=pp.second)
return 0;
}
return 1;
}
int main()
{
int N,a;
cin>>N;
for(int i=0;i<N;i++)
{
cin>>pp.first>>pp.second;
code.push_back(pp);
}
for(int i=1000;i<=9999;i++)
{
if(correct(i))
{
a = i;
break;
}
}
cout<<" "<<a;
return 0;
}
</code></pre>
</blockquote>
<p>My next question is: Is this person's code preferable to mine? It is much neater and shorter. It does not need many sets and vectors. However, having to test each number from 1000 - 9999 is not considered efficient right? Which method is actually better?</p>
<p>Thanks for taking the time to read through all these code. I am starting out so any feedback is valuable!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:11:16.167",
"Id": "464769",
"Score": "0",
"body": "The limited scope of the windows of SE is a perfect reason why you should not use end-of-line commenting; just put the comment in front of the code. Modern practices may also include refactoring and variable renaming, which may make your statements even longer, moving the end-of-line comment to the right..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:31:32.033",
"Id": "464774",
"Score": "0",
"body": "I guess the first thing you should ask yourself is: is `int` really the best representation if you want to check **individual digits**?"
}
] |
[
{
"body": "<p>Hi and welcome to code review. </p>\n\n<p>Your code is already ok, but there are several ways to improve both from the algorithm as well as the code style:</p>\n\n<ol>\n<li><p>Order includes lexicographically. \nThis will ensure that you neither miss some nor forget some. Even better use clang-format so that it does it for you.</p></li>\n<li><p>Properly indent your code.\nAgain this should be done via clang-format and will greatly improve readability of your code, regardless what codestyle you choose.</p></li>\n<li><p>Chose a readable naming convention\nA rather poor example is <code>isgoodguess</code> vs <code>is_good_guess</code> or <code>isGoodGuess</code> or any of the other naming conventions you choose. That said in most C++ codebases there is CamelCase for classes and camelCase for functions.</p></li>\n<li><p>Beware uninitialized variables.\nThat code here is a ticking time bomb:</p>\n\n<pre><code>int passnum;\nswitch(howmany) {\n case 1:\n passnum = 3;\n break; \n case 2:\n passnum = 2; \n break;\n}\n</code></pre>\n\n<p>Do you guarantee that howmany is eihter 1 or 2? what if it is 0? what if it is 3. You will use an uninitialized variable. Better write code that cannot fail.</p>\n\n<pre><code>const int passnum = howmany == 1 ? 3 : 2;\n</code></pre>\n\n<p>That code is much simpler. As a rule of thumb <em>never</em> leave a variable unitialized. There are very rare cases where it is actually valid, but that usually happens in library implementations.</p></li>\n<li><p>Use the correct data representation\nYou are using int for representation. But that is actualy a poor choice. You want indvidual digits not an integer so I would suggest that you store the inputs in a std::string. You will still be able to compare the individual characters. </p>\n\n<p>Note that there is a std algorithm that you can use <code>std::inner_product</code>. Read it up and think about how you can use it on a range of two <code>std::string</code></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T13:44:09.277",
"Id": "464908",
"Score": "0",
"body": "Thanks for the help, one thing I cannot figure out is how to use clang-format in codeblocks, the editor i am using. Should I be switching to visual studio or something to use clangformat?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:12:24.747",
"Id": "237085",
"ParentId": "237077",
"Score": "4"
}
},
{
"body": "<p>This compiles with no warnings from a fairly pedantic compiler (<code>g++ -std=c++2a -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++</code>) - well done!</p>\n\n<hr>\n\n<p>Your program is closely tied to the number of digits in the secret number. If you wanted to adapt it to work with a five-digit number, you'd need to rework almost every part of it. A maintainable solution should have just one part that might need to change.</p>\n\n<hr>\n\n<p>It's great that you have comments, but some are highly misleading:</p>\n\n<blockquote>\n<pre><code>int passnum; // for ease of understanding. \"howmany\" is\n // the number of correct digits.\n</code></pre>\n</blockquote>\n\n<p>(I wrapped this to a readable length - 70 columns is a well-established choice)</p>\n\n<p>Looking at the code, it seems that <code>howmany</code> is nothing to do with the number of correct digits, but is always 0 or 1. It might be worth encoding that in an enum, and using values that directly correspond to the <code>passnum</code> value we want:</p>\n\n<pre><code>// values correspond to how many matches we're looking for\nenum Pass {\n PASS_1 = 3;\n PASS_2 = 2;\n};\n\n// good guesses are guesses that can show an answer, given the prior information.\nbool isgoodguess (bool flag[],\n int tempnum,\n std::set<int> &one, std::set<int> &two,\n std::set<int> &three, std::set<int> &four,\n Pass passnum)\n{\n int counter = 0;\n ...\n}\n</code></pre>\n\n\n\n<pre><code> while (...) {\n check(guess1, digit1, digit2, digit3, digit4, PASS_1);\n check(guess2, digit1, digit2, digit3, digit4, PASS_2);\n }\n</code></pre>\n\n<hr>\n\n<p>When reading from streams, <em>always</em> check that the stream is in a good state afterwards; if not, you can't rely on the streamed-into variables.</p>\n\n<pre><code> int cases;\n if (!(std::cin >> cases)) {\n std::cerr << \"Input format error!\\n\";\n return EXIT_FAILURE; // needs <cstdlib>\n }\n</code></pre>\n\n<hr>\n\n<p>We have some long-winded boolean identities:</p>\n\n<blockquote>\n<pre><code>return (counter == passnum) ? true : false; \n</code></pre>\n</blockquote>\n\n \n\n<blockquote>\n<pre><code> if (flag[0] == true) {\n</code></pre>\n</blockquote>\n\n<p>These can be simplified:</p>\n\n<pre><code>return counter == passnum; \n</code></pre>\n\n\n\n<pre><code> if (flag[0]) {\n</code></pre>\n\n<hr>\n\n<p>With a little cleverness, we can simplify the <code>if</code>/<code>else</code> chains in <code>isgoodguess()</code>, e.g.:</p>\n\n<blockquote>\n<pre><code>if (four.find(tempnum%10) == four.end()) {\n counter++;\n flag[3] = false;\n}\nelse {\n flag[3] = true;\n}\n</code></pre>\n</blockquote>\n\n<p>We can say <code>flag[3] = (four.find(tempnum%10) != four.end());</code>, and then use the fact that booleans convert to integer 0 or 1 to increment <code>counter</code> only if false:</p>\n\n<pre><code>counter += !(flag[3] = four.find(tempnum%10) != four.end());\n</code></pre>\n\n<p>That's sufficiently non-obvious to be worth an explanatory comment, though.</p>\n\n<hr>\n\n<p>We have an iterator invalidation problem here:</p>\n\n<blockquote>\n<pre><code> tocheck.erase(it);\n</code></pre>\n</blockquote>\n\n<p>We subsequently use <code>it</code> (in the loop condition), but it's no longer valid. I think you meant to write:</p>\n\n<pre><code> it = tocheck.erase(it);\n</code></pre>\n\n<hr>\n\n<p>In <code>main()</code>, it would be more natural to use a <code>switch</code> rather than an <code>else if</code> chain to choose between the different values of <code>correct</code>. Why do we ignore <code>correct</code> values of 3 or more?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T13:55:39.227",
"Id": "464910",
"Score": "0",
"body": "Thanks for the in depth reply. For the iterator, I was assuming that tocheck.erase(it) would remove that particular element in the vector, but since the iterator position didn't change, the iterator is now pointing to the next element in the vector, is that wrong? Also I wrote the code based on the question requirements, hence I didn't consider correct values of 3 or more, my mistake. Also, for the counter += !... example you gave, is there supposed to be another bracket? making it !( flag[3] = ( four.find( tempnum%10 ) != four.end() ) ); ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:25:26.747",
"Id": "464916",
"Score": "0",
"body": "`std::vector::erase()` [Invalidates iterators and references at or after the point of the erase](http://eel.is/c++draft/vector#modifiers-3), so yes, you were taking chances with the iterator. You could add the extra parentheses to the assignment of `flag[3]` if that makes it clearer to you, but they are not necessary because `!=` is higher precedence than `=`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:40:23.580",
"Id": "237088",
"ParentId": "237077",
"Score": "4"
}
},
{
"body": "<p>I'll just do a code review and show you things that a beginning programmer should be aware of.</p>\n\n<p>I won't go into the solution <em>at all</em> as the website already will show other attempts & solutions.</p>\n\n<h2>Generic remarks:</h2>\n\n<p>Don't use end of line comments, as they may become hard to read fast, especially if the line is expanded (for instance by a rename of a variable throughout the scope of the variable).</p>\n\n<p>You are operating on digits. Then you need a sensible representation of a digit. You have chosen <code>int</code> (a character could also be a choice), but you're still doing integer arithmetic in your methods. That's just not necessary and will slow your solution down. What if <code>tempnum</code> - which really should be named <code>guess</code> - would be an <code>int[]</code>, for instance? Would you have to perform all these calculations in the main loop?</p>\n\n<p>What about a <code>getDigit(int v, int off)</code> if you want to convert between numbers and digits?</p>\n\n<h2>Walk-through</h2>\n\n<pre><code> bool isgoodguess (bool flag[], int tempnum, std::set<int> &one, std::set<int> &two, // good guesses are guesses that can show an answer, given the prior information.\n std::set<int> &three, std::set<int> &four, int howmany) {\n</code></pre>\n\n<p>For this kind of method, you really need to write a method comment. It is unclear to the reader what <code>flag</code> means, and certainly what <code>tempnum</code> means.</p>\n\n<p>The other thing here is that there are sets named one, two etc. A good application allows to test for 3 and 4 digits or even five. You you'd use a list or array of sets as input.</p>\n\n<pre><code>int passnum; // for ease of understanding. \"howmany\" is the number of correct digits.\n</code></pre>\n\n<p>If you've already explained \"howmany\" in the method parameter description, this would be a good time to explain <code>passnum</code> instead.</p>\n\n<pre><code>switch(howmany) {\n cases...\n</code></pre>\n\n<p>A switch should be used sparingly, and if it is used on e.g. a number it should have a default (possibly throwing an exception).</p>\n\n<pre><code>int counter = 0; // counter tracks how many digits can be proven to be wrong.\n</code></pre>\n\n<p>You mean a <code>wrongDigitCounter</code>? Prefer longer var names over comments. If that's hard during writing, simply rename after.</p>\n\n<pre><code>if (one.find(tempnum/1000) == one.end()) { // if this digit can not be found in the current set of possible values (i.e this digit is not correct)\n counter++; // increase counter\n flag[0] = false; // mark this particular digit as a false one.\n}\nelse {\n flag[0] = true; // else if this digit cannot be proven to be wrong yet, mark it as true.\n}\nif (two.find(tempnum%1000 / 100) == two.end()) { // and so on.\n counter++;\n flag[1] = false;\n}\nelse {\n flag[1] = true;\n}\nif (three.find(tempnum%100 / 10) == three.end()) {\n counter++;\n flag[2] = false;\n}\nelse {\n flag[2] = true;\n}\nif (four.find(tempnum%10) == four.end()) {\n counter++;\n flag[3] = false;\n}\nelse {\n flag[3] = true;\n}\n</code></pre>\n\n<p>Here the repetitiveness really jumps out. If you had an input array, I'm sure you could very easily do this in a loop, with just one piece of code in the middle. You can see this from the <code>flag[1]</code>, <code>flag[2]</code> etc. If <strong>you are doing the counting</strong> then something is going wrong, basically.</p>\n\n<pre><code>std::set<int> digit1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // create a set of possible values for first digit.\n</code></pre>\n\n<p>A set of digit is called <code>digits</code> maybe. Again, repetition over 4. Where is the array?</p>\n\n<pre><code>std::set<int> digit2 = digit1, digit3 = digit1, digit4 = digit1;\n</code></pre>\n\n<p>Well, a C++ programmer probably would be sure that these are copied instead of referenced, as they are by-value, but don't do that in other languages.</p>\n\n<h2>Conclusion</h2>\n\n<p>In the end, it's a good attempt. But you would be surprised how few numbers would be in an attempt written by an experienced programmer. We may well have no number literals in there <strong>at all</strong> except maybe a zero <code>0</code> value now and then. There would not be any <code>one</code> named variables, or variables names ending with a number behind it either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:03:24.230",
"Id": "464911",
"Score": "0",
"body": "Thank you for the feedback. One thing though that I am still unsure, is it possible to create an array of sets? Like std::set<int> digits[4]; ? Regarding the repetitiveness though, i only did it that way because I wasn't sure how to make a loop that will change the set of digits it is iterating over each time. Because for the first round, it is find in set \"one\", but the second time it needs to look in set \"two\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:13:53.453",
"Id": "464913",
"Score": "0",
"body": "I'm not such a C++ programmer, but yeah, usually you can insert a collection in any other collection. For fun I wrote a different solution in Java using only 0, 1 and 9 as literal values and a variable number of digits. That's the problem with variables like `one`..`four`, you're in trouble if you count to three and ... five is right out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T16:52:28.433",
"Id": "237092",
"ParentId": "237077",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:20:22.047",
"Id": "237077",
"Score": "4",
"Tags": [
"c++",
"number-guessing-game"
],
"Title": "Codeabbey Code Guesser"
}
|
237077
|
<p>I have a question regarding code quality and best practices. My task - to write a feature encoding function that will encode categorical labels, boolean labels as one-hot encoding, timestamps for further usage for ml training.</p>
<p>Input - dictionary of several dataframes, each dataframe consist of several columns of different types.</p>
<p>The function should return a dictionary of correctly encoded dataframes and a dictionary of label encoders for categorical columns.</p>
<p>Here is what I did:</p>
<pre><code># Encode bool values to one hot encoding, change NaN numerical values to single const value, make timestamp be time columns, add categorical encoding
def df_encoder(data_dict) :
#encode all NA values of continuos data as a constant
NA_values = 0.001
# dictionary to save dictionary of label encodings from LabelEncoder
labels_codes = dict()
for names_df in data_dict:
# list, where to save label encodings from LabelEncoder from one dataframe
labels_codes[names_df] = list()
#take iteratively dataframe from the dictionary of dataframes
df_additional = data_dict[names_df]
for col in df_additional:
if is_bool_dtype(df_additional[col]):
loc_col = df_additional.columns.get_loc(col)
df_additional_one_hot = pd.get_dummies(df_additional[col], prefix=col, dummy_na=True)
df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_one_hot, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)
elif is_numeric_dtype(df_additional[col]):
df_additional[col].fillna(NA_values)
elif is_datetime64_any_dtype(df_additional[col]):
loc_col = df_additional.columns.get_loc(col)
date_df = pd.DataFrame()
date_df[col+'_year'] = df_additional[col].dt.year.fillna(0)
date_df[col+'_month'] = df_additional[col].dt.month.fillna(0)
date_df[col+'_day'] = df_additional[col].dt.day.fillna(0)
date_df[col+'_hour'] = df_additional[col].dt.hour.fillna(25)
date_df[col+'_minute'] = df_additional[col].dt.minute.fillna(60)
date_df[col+'_seconds'] = df_additional[col].dt.second.fillna(60)
df_additional = pd.concat([df_additional.iloc[:, :loc_col], date_df, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)
elif is_categorical_dtype(df_additional[col]) and df_additional[col].nunique()== 2:
loc_col = df_additional.columns.get_loc(col)
df_additional_two_val_categ = pd.get_dummies(df_additional[col], prefix=col, dummy_na=True)
df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_two_val_categ, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)
elif is_categorical_dtype(df_additional[col]) and df_additional[col].nunique()>2:
#keep only alphanumeric and space, and ignore non-ASCII
df_additional[col].replace(regex=True,inplace=True,to_replace=r'[^A-Za-z0-9 ]+',value=r'')
label_enc = LabelEncoder()
df_additional[col] = label_enc.fit_transform(df_additional[col].astype(str))
labels_codes[names_df].append({col: label_enc})
data_dict[names_df] = df_additional
return data_dict, labels_codes
</code></pre>
<p>The functions work well, but I'm not happy with its quality. I need some useful advice or examples of how to make this function more efficient, and more "best-coding practises" alike. Will appreciate any insights and critique.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T23:18:45.713",
"Id": "465179",
"Score": "0",
"body": "Can you share the rest of the program? Also, why was this tagged as functional-programming?"
}
] |
[
{
"body": "<p>Just have the time to take a quick view on your code, but one of the first thing you have to learn to do (before using design pattern and such things), is to refactor your code.</p>\n\n<p>By simply scrolling, we can see <code>df_additional[col]</code> more than ten times. For all the places where you just need to read this value, use a local variable to store it. If you need to write it, in that case leave it.</p>\n\n<p>There is also <code>df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_one_hot, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)</code> a couple of time, with just a local variable used as a parameter which changes between those calls. Maybe you can also refactor that?</p>\n\n<p>It's also worth noting that if your <code>if</code> (or whatever loop or control statement) begins to be long (dozen of lines), and even more when you have several <code>if</code> like that, think about isolating each block in a separate function. Or at least all the complete <code>if</code>/<code>elif</code> block in a function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:57:44.907",
"Id": "237102",
"ParentId": "237079",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:34:57.693",
"Id": "237079",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"pandas",
"machine-learning"
],
"Title": "Re-write custom feature encoding function python"
}
|
237079
|
<p>This is my second iteration of a function to remove all nodes containing value 'x'. The previous iteration is <a href="https://codereview.stackexchange.com/q/237033/4203">here</a>.</p>
<p>This function takes as input the head of a list and has to delete all the nodes that contain a given value taken. Is this an improvement on the previous iteration? Is there anything else that can be improved?</p>
<pre><code>typedef struct node {
int val;
struct node *next;
} node_t;
</code></pre>
<pre><code>node_t *rimuovi(node_t *head, int x){
node_t *temp = head;
node_t *curr = head;
if (head == NULL){
printf("Lista vuota, finito!\n");
return head;
}
while(head->val == x){
if (head->next == NULL){
free(head);
printf("La lista adesso e' vuota. Finito\n");
return head;
}
else {
curr = head->next;
free(head);
head = curr;
}
}
temp = head;
curr = temp->next;
while (curr != NULL){
if (curr->val == x){
if(curr->next != NULL){
temp->next = curr->next;
free (curr);
curr = temp->next;
}
else {
temp->next = NULL;
}
}
else {
temp = curr;
curr = curr->next;
}
}
return head;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:20:36.583",
"Id": "464773",
"Score": "0",
"body": "This looks like the code version before you modified it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T16:06:28.270",
"Id": "464780",
"Score": "0",
"body": "yes cause they said me to post a new post not to modify the original one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:03:59.420",
"Id": "464818",
"Score": "1",
"body": "The suggestion was that you ask a new question with the *new* version of your code. That way you can get feedback on the new version, without making the previous question confusing. I've edited your question to reflect a request for a followup review. If it doesn't match what you're looking for, please revert the change."
}
] |
[
{
"body": "<p><strong>Bug: Returning a free'd pointer!</strong></p>\n\n<p>After freeing a pointer, do not use it.</p>\n\n<pre><code> free(head);\n printf(\"La lista adesso e' vuota. Finito\\n\");\n // return head;\n return NULL;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Is there anything else that can be improved?</p>\n</blockquote>\n\n<p>Rather than 2 or 3 cases to handle an empty list, list of only matches or mixed list, consider a code simplification.</p>\n\n<p>Create a temporary pre-head node and assign its next to the head. Only 1 case needed. This approach is reasonable when <code>node_t</code> is not large.</p>\n\n<p>Some untested code.</p>\n\n<pre><code>node_t *rimuovi(node_t *head, int x) {\n node_t pre_head;\n node_t *p = &pre_head;\n pre_head.next = head; // Other members are not used.\n\n while (p->next) {\n if (p->next->val == x) {\n node_t *next = p->next->next;\n free(p->next);\n p->next = next;\n } else {\n p = p->next;\n }\n }\n return pre_head.next;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:14:32.097",
"Id": "237103",
"ParentId": "237080",
"Score": "2"
}
},
{
"body": "<p>Please include the necessary headers:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n\n<p>There's a lot of duplication between these branches:</p>\n\n<blockquote>\n<pre><code>while(head->val == x){\n if (head->next == NULL){\n free(head);\n printf(\"La lista adesso e' vuota. Finito\\n\");\n return head;\n }\n else {\n curr = head->next;\n free(head);\n head = curr;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>We always <code>free(head)</code>, and we probably ought to set <code>head = NULL</code> in the first branch, rather than leaving it pointing to freed memory.<br>\nTherefore:</p>\n\n<pre><code>while (head->val == x) {\n curr = head->next;\n free(head);\n head = curr;\n if (curr == NULL){\n printf(\"La lista adesso e' vuota. Finito\\n\");\n return head;\n }\n}\n</code></pre>\n\n<p>As <a href=\"/a/237103/75307\">chux says</a>, use of a dummy head node can help us merge this with the following (non-head) logic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T13:59:49.037",
"Id": "237150",
"ParentId": "237080",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T14:35:53.343",
"Id": "237080",
"Score": "2",
"Tags": [
"c",
"linked-list",
"c99"
],
"Title": "Removing nodes from a linked list"
}
|
237080
|
<p>This function formats raw buffer output in manner as Wireshark and many others does:</p>
<pre><code>0x00: 68 65 6C 6C 6F 20 77 6F 72 6C 64 02 6B 68 67 61 |hello world.khga|
0x10: 76 73 64 20 0B 20 0A 05 58 61 73 6A 68 6C 61 73 |vsd . ..Xasjhlas|
0x20: 62 64 61 73 20 6A 61 6C 73 6A 64 6E 13 20 20 30 |bdas jalsjdn. 0|
0x30: 31 32 33 34 35 36 37 38 39 |123456789 |
</code></pre>
<p>Please review and assess code quality.
<a href="http://www.cppshell.com/9yfgo" rel="nofollow noreferrer">cppshell</a></p>
<pre><code>#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
static const char line_placeholder[] = "0x00: | |";
size_t format_hex_payload_sizeof_output(const char* payload, size_t payload_len)
{
size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
size_t sizeof_output = sizeof line_placeholder * number_of_lines;
return sizeof_output;
}
size_t format_hex_payload(char* output, const char* payload, size_t payload_len)
{
size_t number_of_lines = payload_len / 16 + (payload_len%16 > 0);
size_t sizeof_output = sizeof line_placeholder * number_of_lines;
// char *output = (char*)alloca(sizeof_output);
char *pout = output;
const char *p = payload;
const char *const end = payload + payload_len;
size_t ascii_offset = strchr(line_placeholder,'|') - line_placeholder + 1; //could be calculated at compile time
unsigned char offset = 0;
for(unsigned l=0; l < number_of_lines; l++, offset+=16)
{
char* pline_begin = pout;
char* pline = pout;
strcpy(pline,line_placeholder);
pline += sprintf(pline, "0x%02X: ", offset);
for(unsigned i=0; i<16 && p < end; ++i, ++p){
pline += sprintf(pline, "%02X ", *p);
*(pline_begin+ascii_offset+i) = isprint(*p) ? *p : '.';
}
*pline=' ';
pout += sizeof line_placeholder; // next line
pout[-1] = '\n';
}
pout[-1] = '\0';
assert(pout == output + sizeof_output); // sanity check
return pout - output;
}
int main()
{
const char input[] = "hello\x02";
char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
format_hex_payload(outbuf, input, sizeof input -1);
printf("%s\n\n", outbuf);
{
const char input[] = "hello world\x02khgavsd \x0B \x0A\x05Xasjhlasbdas jalsjdn\x13xa0";
char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
format_hex_payload(outbuf, input, sizeof input -1);
printf("%s\n\n", outbuf);
}
{
const char input[] = "hello world\x02khgavsd \x0B \x0A\x05Xasjhlasbdas jalsjdn\x13 0123456789";
char outbuf[format_hex_payload_sizeof_output(input, sizeof input -1)];
format_hex_payload(outbuf, input, sizeof input -1);
printf("%s\n\n", outbuf);
}
}
</code></pre>
<p>As an improvement I'd add function that prints to file descriptor and extend current function that has output buffer size limitation, like snprintf().</p>
<hr>
<p><em>This question is an improvement of <a href="https://codereview.stackexchange.com/questions/236851/format-raw-bytes-in-hex-and-ascii-in-manner-like-wireshark-does">Format raw bytes in hex and ascii in manner like Wireshark does</a>, was created according to <a href="https://codereview.stackexchange.com/questions/236851/format-raw-bytes-in-hex-and-ascii-in-manner-like-wireshark-does#comment464738_236851">@MartinR's suggestion</a></em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T18:32:25.440",
"Id": "464811",
"Score": "0",
"body": "You should notice that you can always use c++ implementations to be linked with plain c using simple wrappers. It's probably not necessary that you provide an extra c implementation besides what you've already done in c++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:18:55.547",
"Id": "464902",
"Score": "0",
"body": "Some code is written in pure C to be compliant with Linux kernel. So this code could be used in driver."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T15:21:48.583",
"Id": "237086",
"Score": "0",
"Tags": [
"c"
],
"Title": "Format raw bytes in hex and ascii in manner like Wireshark does in pure C"
}
|
237086
|
<p>Version 1 may be found <a href="https://codereview.stackexchange.com/questions/236787/transforming-nodatime-zoneintervals">here</a>.</p>
<p>I have implemented the suggestions by <a href="https://codereview.stackexchange.com/users/16031/jon-skeet">Jon Skeet</a>, plus some of my own. Key differences between versions:</p>
<ul>
<li>ZonedDateRange class is now immutable.</li>
<li>LocalDate variables no longer are named with "Day".</li>
<li>Some ToString() methods were added.</li>
</ul>
<p><strong>ZonedDateRange.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using NodaTime.TimeZones;
namespace NodaTime_Zoned_Ranges
{
public class ZonedDateRange
{
public enum DayState { Standard, DST, SpringForward, FallBack }
public DateTimeZone Zone { get; }
public DayState State { get; }
public LocalDate StartDate { get; }
public LocalDate EndDateInclusive { get; }
public LocalDate EndDateExclusive => EndDateInclusive.PlusDays(1);
public ZonedDateTime ZoneStart => Zone.AtStartOfDay(StartDate);
public ZonedDateTime ZoneEnd => Zone.AtStartOfDay(EndDateExclusive);
public DateTime UtcStart => ZoneStart.ToDateTimeUtc();
public DateTime UtcEnd => ZoneEnd.ToDateTimeUtc();
public double HoursPerDay => IsTransitionDay ? (UtcEnd - UtcStart).TotalHours : 24;
public int DaysInRange => IsTransitionDay ? 1 : (int)((ZoneStart - ZoneEnd).TotalDays);
// -1 = Falling back DAY, +1 Spring Forward DAY, 0 means no transition occuring (Standard or DST).
public int Transition => (State == DayState.FallBack) ? Backward : (State == DayState.SpringForward) ? Forward : None;
public bool IsTransitionDay => (Transition != None);
public const int Backward = -1;
public const int Forward = 1;
public const int None = 0;
// internal constructor forces using static factory.
internal ZonedDateRange(DateTimeZone zone, LocalDate startDate, LocalDate endDate, DayState state)
{
Zone = zone;
StartDate = startDate;
EndDateInclusive = endDate;
State = state;
}
// A list should be fairly small. Consider U.S. Central Time for an entire calendar year. There will only be 5 items in the list.
// 1) CST from Jan 1 to the day before Spring forward.
// 2) Spring Forward transition day (one day is both start and end)
// 3) CDT from day after Spring Forward and day before Fall Back.
// 4) Fall Back transition day (again, only 1 day in range)
// 5) CST after Fall Back day
// The most important thing is that all days in a range will have the same length.
// That way you can safely average in whatever that length is.
public static IEnumerable<ZonedDateRange> GenerateRanges(DateTimeZone zone, Instant anchorInstant, int days)
{
if (zone == null)
{
throw new ArgumentNullException(nameof(zone));
}
var anchorDate = anchorInstant.InZone(zone).Date;
var inclusiveStartDate = (days < 0) ? anchorDate.PlusDays(days) : anchorDate;
var inclusiveEndDate = (days < 0) ? anchorDate : anchorDate.PlusDays(days);
return GenerateRanges(zone, inclusiveStartDate, inclusiveEndDate);
}
public static IEnumerable<ZonedDateRange> GenerateRanges(DateTimeZone zone, LocalDate inclusiveStartDate, LocalDate inclusiveEndDate)
{
if (zone == null)
{
throw new ArgumentNullException(nameof(zone));
}
// Small adjustment to add an extra day to the inclusive end date.
// When working with LocalDate(s) that are inclusive, we obviously start at the start of the start date
// BUT we want to end at the END of the end date, which is really the start of the next day following the
// end date.
var exclusiveEndDate = inclusiveEndDate.PlusDays(1);
var startInstant = inclusiveStartDate.AtStartOfDayInZone(zone).ToInstant();
var endInstant = exclusiveEndDate.AtStartOfDayInZone(zone).ToInstant();
// Just in case the start or end day occurs on transition day, we pad each endpoint with a few days.
// We will later prune away this padding.
var pad = Duration.FromDays(5);
var padStartInstant = startInstant.Minus(pad);
var padEndInstant = endInstant.Plus(pad);
var intervals = zone.GetZoneIntervals(padStartInstant, padEndInstant).ToList();
// Take care of easy cases.
// Check count returned instead of custom SupportsDaylightSavingsTime method.
// E.g. Argentina supported DST in the past, but since 2010 has been on Standard time only.
if (intervals.Count == 1)
{
yield return new ZonedDateRange(zone, inclusiveStartDate, exclusiveEndDate, DayState.Standard);
yield break;
}
for (var index = 0; index < intervals.Count; index++)
{
var interval = ClampInterval(intervals[index], padStartInstant, padEndInstant);
// Chop off the Start and End dates, since those are transition days.
// That is move Start ahead 1 day, and move End back 1 day.
var currStartDate = interval.Start.InZone(zone).Date.PlusDays(1);
var currEndDate = interval.End.InZone(zone).Date.PlusDays(-1);
var endLength = zone.HoursInDay(interval.End);
var endState = DayState.Standard;
if (endLength > NodaConstants.HoursPerDay)
{
endState = DayState.FallBack;
}
else if (endLength < NodaConstants.HoursPerDay)
{
endState = DayState.SpringForward;
}
var startState = (endState == DayState.FallBack) ? DayState.DST : DayState.Standard;
var range = new ZonedDateRange(zone, LocalDate.Max(inclusiveStartDate, currStartDate), LocalDate.Min(exclusiveEndDate, currEndDate), startState);
if (IsOkayToOutput(range))
{
yield return range;
}
var endTransitionDate = interval.End.InZone(zone).Date;
range = new ZonedDateRange(zone, endTransitionDate, endTransitionDate, endState);
if (IsOkayToOutput(range))
{
yield return range;
}
}
}
private static bool IsOkayToOutput(ZonedDateRange range) => (range.UtcEnd > range.UtcStart);
private static ZoneInterval ClampInterval(ZoneInterval interval, Instant start, Instant end)
{
var outstart = start;
var outend = end;
if (interval.HasStart && outstart < interval.Start)
{
outstart = interval.Start;
}
if (interval.HasEnd && interval.End < outend)
{
outend = interval.End;
}
return new ZoneInterval(interval.Name, outstart, outend, interval.WallOffset, interval.Savings);
}
public override string ToString() => ToString(showZone: true);
public string ToString(bool showZone)
{
var prefix = showZone ? $"{Zone}: " : "";
return $"{prefix}{State,-13} [{UtcStart.ToIsoString()}, {UtcEnd.ToIsoString()}) {HoursPerDay}";
}
}
}
</code></pre>
<p><strong>Extensions.cs</strong>
previous methods are unchanged but FilterRanges was added.</p>
<pre><code>using System;
using System.Collections.Generic;
using NodaTime;
namespace NodaTime_Zoned_Ranges
{
public static class Extensions
{
public static IEnumerable<ZonedDateRange> FilterRanges(this IEnumerable<ZonedDateRange> ranges, LocalDate firstInclusiveDate, LocalDate lastInclusiveDate)
{
if (ranges == null || firstInclusiveDate > lastInclusiveDate)
{
yield break;
}
foreach (var range in ranges)
{
if (range.StartDate > lastInclusiveDate || range.EndDateInclusive < firstInclusiveDate)
{
continue;
}
yield return new ZonedDateRange(range.Zone, LocalDate.Max(range.StartDate, firstInclusiveDate), LocalDate.Min(range.EndDateInclusive, lastInclusiveDate), range.State);
}
}
// For DST Transition days, hours will be less than or greater than 24.
public static double HoursInDay(this DateTimeZone zone, Instant instant)
{
if (zone == null)
{
return NodaConstants.HoursPerDay;
}
var day = instant.InZone(zone).LocalDateTime.Date;
var bod = zone.AtStartOfDay(day);
var eod = zone.AtStartOfDay(day.PlusDays(1));
return (eod.ToInstant() - bod.ToInstant()).TotalHours;
}
/// <summary>
/// Preferred format of ISO 8601 time string.
/// Unlike Round Trip format specifier of "o", this format will suppress decimal seconds
/// if the input time does not have subseconds.
/// </summary>
public const string DateTimeExtendedIsoFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK";
/// <summary>
/// Returns an ISO-8601 compliant time string.
/// If the input Kind is Local and TimeZoneInfo.Local is not "UTC", then the output string will contain a time zone offset.
/// Unlike ToString("o"), if the input time does not contain subseconds, the output string will omit subseconds.
/// </summary>
/// <param name="time">DateTime</param>
/// <returns>String</returns>
public static string ToIsoString(this DateTime time)
{
// TimeZoneInfo MUST use Equals method and not == operator.
// Equals compares values where == compares object references.
if (time.Kind == DateTimeKind.Local && TimeZoneInfo.Local.Equals(TimeZoneInfo.Utc))
{
// Don't use time zone offset if Local time is UTC
time = DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
return time.ToString(DateTimeExtendedIsoFormat);
}
}
}
</code></pre>
<p><strong>Program.cs</strong>
Mostly unchanged except using the new ToString method.</p>
<pre><code>using System;
using NodaTime;
namespace NodaTime_Zoned_Ranges
{
class Program
{
static void Main(string[] args)
{
var zoneIds = new string[] { "Central Brazilian Standard Time", "Singapore Standard Time" };
var startDay = new LocalDate(2018, 1, 1);
var endDay = new LocalDate(2019, 12, 31);
foreach (var zoneId in zoneIds)
{
var zone = DateTimeZoneProviders.Bcl.GetZoneOrNull(zoneId);
ZoneTest(zone, startDay, endDay);
}
Console.WriteLine("\n\nPress ENTER key");
Console.ReadLine();
}
private static void ZoneTest(DateTimeZone zone, LocalDate startDay, LocalDate endDay)
{
Console.WriteLine($"\n\n*** TEST FOR ZONE: {zone.Id} , Start:{startDay} , End:{endDay}\n");
var startInstant = startDay.AtStartOfDayInZone(zone).ToInstant();
var endInstant = endDay.PlusDays(1).AtStartOfDayInZone(zone).ToInstant();
Console.WriteLine("NodaTime DateTimeZone.GetZoneIntervals");
var intervals = zone.GetZoneIntervals(startInstant, endInstant);
var i = 0;
foreach (var interval in intervals)
{
Console.WriteLine($" [{i++}]: {interval}");
}
Console.WriteLine($"\nCustom ZonedDateRange for {zone}");
i = 0;
var ranges = ZonedDateRange.GenerateRanges(zone, startDay, endDay);
foreach (var range in ranges)
{
Console.WriteLine($" [{i++}]: {range.ToString(showZone: false)}");
}
}
}
}
</code></pre>
<p>The <code>ToString</code> method allow you to show or hide the Zone. For the <code>DateTime</code> ranges, I use a trailing ")" to denote an exclusive endpoint, though there is a bug in NodaTime with Brazil and a handful of others zones with times ending in <code>59.999Z</code> that one would think should be inclusive. I am keeping this behavior as-is and will wait for Jon to patch it one day in NodaTime.</p>
<p><strong>Sample Console Output</strong>:</p>
<pre><code>*** TEST FOR ZONE: Central Brazilian Standard Time , Start:Monday, January 1, 2018 , End:Tuesday, December 31, 2019
NodaTime DateTimeZone.GetZoneIntervals
[0]: Central Brazilian Daylight Time: [2017-10-15T03:59:59Z, 2018-02-18T02:59:59Z) -03 (+01)
[1]: Central Brazilian Standard Time: [2018-02-18T02:59:59Z, 2018-11-04T03:59:59Z) -04 (+00)
[2]: Central Brazilian Daylight Time: [2018-11-04T03:59:59Z, 2019-02-17T03:00:00Z) -03 (+01)
[3]: Central Brazilian Standard Time: [2019-02-17T03:00:00Z, EndOfTime) -04 (+00)
Custom ZonedDateRange for Central Brazilian Standard Time
[0]: DST [2018-01-01T03:00:00Z, 2018-02-17T03:00:00Z) 24
[1]: FallBack [2018-02-17T03:00:00Z, 2018-02-18T04:00:00Z) 25
[2]: Standard [2018-02-18T04:00:00Z, 2018-11-04T03:59:59.999Z) 24
[3]: SpringForward [2018-11-04T03:59:59.999Z, 2018-11-05T03:00:00Z) 23.0000002777778
[4]: DST [2018-11-05T03:00:00Z, 2019-02-16T03:00:00Z) 24
[5]: FallBack [2019-02-16T03:00:00Z, 2019-02-17T04:00:00Z) 25
[6]: Standard [2019-02-17T04:00:00Z, 2020-01-02T04:00:00Z) 24
[7]: Standard [2020-01-06T04:00:00Z, 2020-01-07T04:00:00Z) 24
*** TEST FOR ZONE: Singapore Standard Time , Start:Monday, January 1, 2018 , End:Tuesday, December 31, 2019
NodaTime DateTimeZone.GetZoneIntervals
[0]: Malay Peninsula Standard Time: [StartOfTime, EndOfTime) +08 (+00)
Custom ZonedDateRange for Singapore Standard Time
[0]: Standard [2017-12-31T16:00:00Z, 2020-01-01T16:00:00Z) 24
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:21:17.157",
"Id": "237100",
"Score": "1",
"Tags": [
"datetime",
"nodatime"
],
"Title": "Transforming NodaTime ZoneIntervals, version 2"
}
|
237100
|
<p>I am built a program that will give the 7 chords that are found a given major or minor key. My program takes in first a key (C, Ab, F#, etc.) then takes in its mode (Major (input is 'M') and minor (denoted by 'm')). From there the program builds the chords in that key in a specific manner depending on the mode where you take a pattern of whole (W) and half (H) steps.</p>
<p>For major keys, the pattern is to move (from the original position): <code>WWHWWW</code>. The 2nd, and 3rd chords in the key are minor and the 6th is diminished (denoted by '°'). The rest are major chords.</p>
<p>Minor keys is similar to: <code>WHWWHW</code>. The 1st, 4th, and 5th are minor chords, and the 2nd is a diminished. The rest are major.</p>
<p>My code build the chords in a weird way. I have a string array with the name of the chords in them called <code>sChords</code>. When I get a specific key input, a call my function called <code>GetScale</code> which orchestrates the whole program. It returns a string which I add to another string in the main function. The first thing <code>GetScale</code> is it adds the first chord which is very easy. </p>
<p>It then calls <code>FindKey</code> which returns an integer (into <code>keyInt</code>) such that the integer corresponds to the index of that key in the <code>sChords</code> array. I then use a function in a for loop called <code>IndexNumberForChordArray</code> where I send the key index, the mode, and the current iteration in the for loop. Over there the steps are calculated.</p>
<p>[The steps are done such that for a whole step, the pointer for <code>sChords</code> moves 2 over, and for a half, only one over.]</p>
<p>After that, <code>AdditionsToChord</code> is called which adds the 'm' for minor chords and '°' for diminished ones.</p>
<p>I have a couple of weird quirks in my program. </p>
<p>First is the useless bool variable in <code>GetScale</code> called <code>flatted</code>. I have that there because when my program builds a key, it often repeats letters for weird key signatures like C#. The general rule of thumb in music theory is that when describing a scale, each letter should appear only once. I have that there so that I can later make it so that the program can print only one of each letter. How? Well, I am not too sure if it will work, but I was thinking something like: </p>
<blockquote>
<p>If the key is flatted, unless a chord is a natural (i.e. no sharps or flats), it should also be flatted. Otherwise always use natural or sharped chords.</p>
</blockquote>
<p>The other problem that might be evident is that <code>mode</code> is an integer when it can easily be a bool. I have it as an integer because I hope to expand this program to include more than the major and minor scales. There are 7 scales in western music and I hope to add that into this program.</p>
<p>I am uncomfortable with the current method however, and want to see how it can be improved. I especially don't like that fact that I have to use a string array and move a pointer around the array to reach a specific chord. I felt like there might be an easier mathematical way, maybe using ASCII, but I didn't know how to do it because of all the sharps and flats.</p>
<p>Another thing is that I don't like is that I am using a large switch structure to identify the index of a given key. Maybe this can be improved too.</p>
<p>One last thing that is a bad habit for me is using <code>goto</code>. I know it is bad practice, but I thought it might not matter in this specific situation.</p>
<p>Some useful links are:</p>
<ol>
<li><p><a href="http://www.piano-keyboard-guide.com/chords-by-key.html" rel="nofollow noreferrer">http://www.piano-keyboard-guide.com/chords-by-key.html</a></p></li>
<li><p><a href="https://en.wikipedia.org/wiki/Mode_(music)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Mode_(music)</a></p></li>
</ol>
<pre class="lang-cs prettyprint-override"><code>// I am planning on adding different modes + making the scales have one of every letter.
using System;
namespace ChordFinder
{
class Program
{
//This will probably be removed for a more dynamic way of creating the scale.
static string[] sChords = { "Ab", "A", "Bb", "B", "C", "C#", "D", "Eb", "E", "F", "F#", "G" };
static void Main(string[] args)
{
string key, mode;
int[] nChords = new int[7];
//Get key
Start:
Console.Write("Enter key (type 'Exit' to exit): ");
key = Console.ReadLine();
//Check if input is exit
if (key.ToUpper() == "EXIT" || key == null)
Environment.Exit(1);
else if (key[0] > 71 || key[0] < 65)
{
Console.WriteLine("Invalid key, try again.");
goto Start;
}
//Get mode
ModeStart:
Console.Write("Enter mode ('M' for major, 'm' for minor): ");
mode = Console.ReadLine();
//Checks if input is 'M' or 'm'
if (mode[0] != 77 && mode[0] != 109)
{
Console.WriteLine("Invalid mode, try again.");
goto ModeStart;
}
string a = "";
if (mode[0] == 77)
a = GetScale(key, 0, false);
else
a = GetScale(key, 1, false);
Console.WriteLine("The chords are: " + a);
Console.WriteLine();
goto Start;
}
//Gets the scale. Note: flatted not developed yet.
static string GetScale(string key, int mode, bool flatted)
{
string a = string.Empty;
int keyInt;
//Set the first chord.
a += key;
if (mode == 1)
a += "m";
a += " ";
//Set point to sChords array.
keyInt = FindKey(key);
for (int i = 1; i < 7; i++)
a += sChords[IndexNumberForChordArray(ref keyInt, mode, i)] + AdditionsToChord(mode, i) + " ";
return a;
}
//Returns an integer that corresponds to the
//index of the sChords array.
static int FindKey(string key)
{
switch (key)
{
case "G#":
case "Ab":
return 0;
case "A":
return 1;
case "A#":
case "Bb":
return 2;
case "B":
return 3;
case "C":
return 4;
case "C#":
case "Db":
return 5;
case "D":
return 6;
case "D#":
case "Eb":
return 7;
case "E":
return 8;
case "F":
return 9;
case "F#":
case "Gb":
return 10;
default:
return 11;
}
}
//Finds the index for the correct chord
static int IndexNumberForChordArray(ref int start, int mode, int iteration)
{
if (mode == 0)
{
//Major key algorithm
start += 2;
if (iteration == 3)
start -= 1;
start %= 12;
}
else if (mode == 1)
{
//Minor key algorithm
start += 2;
if (iteration == 2 || iteration == 5)
start -= 1;
start %= 12;
}
return start;
}
//Adds extra stuff depending on the mode and position in the scale.
static string AdditionsToChord(int mode, int iteration)
{
string s = string.Empty;
if (mode == 0)
{
//Major key algorithm
if (iteration == 1 || iteration == 2 || iteration == 5)
s = "m";
if (iteration == 6)
s = "°";
}
else if (mode == 1)
{
//Minor key algorithm
if (iteration == 3 || iteration == 4)
s += "m";
if (iteration == 1)
s += "°";
}
return s;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:43:33.013",
"Id": "464906",
"Score": "0",
"body": "You really shouldn't use (some kind of) Hungarian notation: https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:24:10.223",
"Id": "464915",
"Score": "1",
"body": "I don't understand, is my naming convention wrong? I guess ```keyInt``` and ```sChords``` falls into that, but is it bad?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:47:47.807",
"Id": "465039",
"Score": "0",
"body": "I think the steps for the major keys should be: WWHWWWH. And it's the seventh chord that is diminished - not the sixth (The sixth chord of C major is plain A minor (parallel key) and the seventh chord is B diminished (Bm7b5))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T13:20:54.653",
"Id": "465096",
"Score": "0",
"body": "@HenrikHansen the last half step brings you back to C just an octave higher/lower. If you include the dominant, you get 7 chords using what I wrote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:00:05.220",
"Id": "465099",
"Score": "0",
"body": "Yes, but you include seven steps for the minor scale, so I just thought they should contain the same number of steps :-)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T17:09:57.183",
"Id": "465142",
"Score": "0",
"body": "Oh yes that's right, I'll fix that up."
}
] |
[
{
"body": "<p>Its good you recognize that goto is a bad pattern, I would go so far I would reject any code that I reviewed that had it. They can be converted to a loop statement pretty easy.</p>\n\n<p>For Example </p>\n\n<pre><code>var key = string.Empty;\n//Get key\ndo\n{\n Console.Write(\"Enter key (type 'Exit' to exit): \");\n key = Console.ReadLine();\n if (key != \"EXIT\" || key[0] > 'G' || key[0] < 'A')\n {\n Console.WriteLine(\"Invalid key, try again.\");\n key = string.Empty;\n }\n} while (string.IsNullOrWhiteSpace(key));\n\nvar mode = string.Empty; \n//Get mode\nwhile (key != \"EXIT\" && string.IsNullOrWhiteSpace(mode))\n{\n Console.Write(\"Enter mode ('M' for major, 'm' for minor): \");\n mode = Console.ReadLine();\n if (mode[0] != 'M' || mode[0] != 'm')\n {\n Console.WriteLine(\"Invalid mode, try again.\");\n mode = string.Empty;\n }\n}; \n</code></pre>\n\n<p>No need for Environment.Exit and if wanted to keep user in it's just another loop that check for exit that wraps these two. </p>\n\n<p>Instead of comparing the ASCII number you can use the real letter just using a single quote. See above. When looking at code latter someone will need to look up what ASCII 71,65,77,109 where if you replace it, like the example, it's clear what values the program is checking for.</p>\n\n<p>The variable nChords isn't used. To go along with that is pretty standard in C# to declare your variable at time of use and not at the top of the program. </p>\n\n<p>Lets also talk naming. What is a? It's not descriptive variable at all. Variables should have meaning. Could call it scale or even result would be better than a. Naming is one of the harder things in programming but someone or even you coming back later and looking at this code would not know what a means. Don't prefix your variables/properties/fields with their type. I'm assuming sChords starts with s because it's a string array. just name it cords without the prefix. Same would go with nChords but you can just remove that variable all together.</p>\n\n<p>The GetScale call can be inlined </p>\n\n<pre><code>var scale = GetScale(key, mode[0] == 'M' ? 0 : 1, false);\n</code></pre>\n\n<p>Also with GetScale it doesn't use parameter flatted. </p>\n\n<p>I'm also not a fan of ref parameters in general and would suggest to find a way to not be passing it in by reference. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T13:22:58.220",
"Id": "465097",
"Score": "0",
"body": "I addressed the ```flatted``` parameter in my post saying that it is for future development. Other than that, I hadn't noticed the nChords, that must have been early on in my project. I'll remove that. I also will switch to using characters instead of the ASCII counterparts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:13:31.620",
"Id": "465100",
"Score": "0",
"body": "I usually prescribe to YAGNI and don't add stuff to programs until it's needed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T20:04:20.907",
"Id": "237181",
"ParentId": "237101",
"Score": "2"
}
},
{
"body": "<p>Just looking at this one section:</p>\n\n<pre><code>if (key.ToUpper() == \"EXIT\" || key == null)\n Environment.Exit(1);\nelse if (key[0] > 71 || key[0] < 65)\n{\n Console.WriteLine(\"Invalid key, try again.\");\n goto Start;\n}\n</code></pre>\n\n<ul>\n<li>Why <code>Environment.Exit(1)</code> and not simply <code>exit(1)</code>?</li>\n<li>Given that the program has already exited for the true condition, there is no point in having the <code>else</code>.</li>\n<li><p>Where do \"71\" and \"65\" come from?<br>\nOther than \"0\", \"1\", and \"many\", raw numbers should never appear in code.<br>\nIn this case they are actually the ASCII values for \"A\" and \"G\".<br>\nSo why not simply say <code>'A'</code> and <code>'G'</code>?</p></li>\n<li><p>\"<em>Invalid key, try again.</em>\" is a very frustrating error message.<br>\nDon't tell me that it <em>is</em> invalid; tell me <em>why</em> it is invalid.<br>\nAnd why is \"Burble\" considered valid?</p></li>\n<li><p>There are times when <code>goto</code> is appropriate.<br>\nBut such times are few and far between, and definitely not in this program.</p></li>\n</ul>\n\n<p>Similar comments apply to most of the rest of the program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T13:16:46.150",
"Id": "465095",
"Score": "0",
"body": "I really don't know why I used 71 and 65, but I'll make that fix. The \"invalid key\" error was more of a placeholder, but I'll make sure to make it more specified. I also forgot that \"Burble\" shouldn't work. I'll set up a check for that. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T02:40:45.803",
"Id": "237198",
"ParentId": "237101",
"Score": "3"
}
},
{
"body": "<p>I dabble in music so your post caught my eye.</p>\n\n<p>Here are my thoughts: </p>\n\n<ol>\n<li><p>If I had to pick one word to describe the app, it would be “procedural”. You have successfully defined an algorithm, but I'd say that it reads more like FORTRAN than C#. It even includes <code>goto</code>… which I've never seen used before in C#.</p></li>\n<li><p>When working in an object-oriented language, I prefer to let the domain drive the object model. In my experience, modelling what exists in reality goes a long way toward making software maintainable and expandable. </p></li>\n<li><p>Instead of a giant <code>switch</code> statement, you might want to go with a <code>Dictionary<string, int></code></p></li>\n</ol>\n\n<p>In my spare time I whipped up my take on an object-oriented musical scale and chord “generator” app, which I have posted here: <a href=\"https://github.com/lucidobjects/MusicalKeys\" rel=\"nofollow noreferrer\">https://github.com/lucidobjects/MusicalKeys</a></p>\n\n<p>In keeping with my point #2, there are a bunch of objects, and certainly a lot more lines of code. But, I feel the object model gives us the beginnings of a foundation upon which we could build a music theory app of arbitrary size - and remain sane in the process.</p>\n\n<p>My app lacks some of the features that yours has, like interactive input and modes. But, my aim was to show an object-oriented approach to the problem rather than achieve feature parity.</p>\n\n<p>Here’s a screenshot of the class files. While the preferred terminology may vary from musician to musician, various elements of music theory are present and accounted for.<br>\n<a href=\"https://i.stack.imgur.com/fdYpN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fdYpN.jpg\" alt=\"Classes\"></a></p>\n\n<p>To see how the program runs, check out <a href=\"https://github.com/lucidobjects/MusicalKeys/blob/master/MusicalKeys/App.cs\" rel=\"nofollow noreferrer\">App.cs</a>.</p>\n\n<pre><code>public void Run()\n{\n var steps = new Steps();\n var scalePatterns = getScalePatterns(steps).Select(p => p as Pattern).ToList();\n var intervals = new Intervals();\n var chordPatterns = getChordPatterns(intervals).Select(p => p as Pattern).ToList();\n var tones = new Pitches();\n\n ///define the Key of A and output individual elements from it\n var keyOfA = new Key(tones.A, scalePatterns, chordPatterns);\n Console.WriteLine(keyOfA.Scales.Get(\"Major\").ToString());\n Console.WriteLine(keyOfA.Scales.Get(\"Natural Minor\").ToString());\n Console.WriteLine(keyOfA.Scales.Get(\"Melodic Minor\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"M\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"M7\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"7\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"m7\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"m7b5\").ToString());\n Console.WriteLine(keyOfA.Chords.Get(\"dim7\").ToString());\n Console.WriteLine();\n\n ///shortened syntax to define the Key of F# and output all of its scales and chords\n Console.WriteLine(new Key(tones.Fsharp, scalePatterns, chordPatterns).ToString());\n\n ///define and print a single scale\n var scalePattern = new StepPattern(\"Major Scale\", \"WWHWWWH\");\n var scale = new ToneSet(tones.Dsharp, scalePattern);\n Console.WriteLine(scale.ToString());\n\n ///define and print a single chord\n var chordPattern = new IntervalPattern(\"Major 7th\", \"M7\", \"P1 M3 P5 M7\");\n var chord = new ToneSet(tones.C, chordPattern);\n Console.WriteLine(chord.ToString());\n\n ///define and print another single chord\n var chordPattern2 = new IntervalPattern(\"Dominant Seventh\", \"7\", \"P1 M3 P5 m7\");\n var chord2 = new ToneSet(tones.G, chordPattern2);\n Console.WriteLine(chord2.ToString());\n}\n</code></pre>\n\n<p>And here’s the output:<br>\n<a href=\"https://i.stack.imgur.com/KBPuv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KBPuv.jpg\" alt=\"Output\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T17:19:49.330",
"Id": "465738",
"Score": "0",
"body": "I very much appreciate your work. I understand that c# should primarily be used for its object orientation but I was unsure how to use objects. Thanks for the answer, I have a better idea of how to work with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T18:44:17.253",
"Id": "465756",
"Score": "0",
"body": "Thanks, glad to help. Object Oriented Programming is a big topic, which I enjoy studying. If you're going to be using C#, or any OOP language, I encourage you to learn more about OOP. You might find my other C# code review answers interesting..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T02:53:03.160",
"Id": "237471",
"ParentId": "237101",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237471",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:46:14.663",
"Id": "237101",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Program that outputs the chords in a given key"
}
|
237101
|
<p>I'm calculating a score based on whether or not certain colors shape is selected. Some of the shapes are in groups, some are not. For the shapes which are in groups, only one of them will count towards the score. I have figured out how, as you can see below. However, I have 9 more shapes/scores to add to the Sub. I'm still somewhat new at VBA, and I am wondering if there is a better/shorter way to write this formula. Thanks in advance.</p>
<pre><code>Sub Lead_Score()
With Sheet1
Dim Cust As Integer, Vend As Integer, Sus As Integer, Pros As Integer, RelScore As Integer, Qual As Integer, NonQual As Integer, QualScore As Integer, Score As Integer
Cust = .Shapes("CustomerButton").ShapeStyle
Vend = .Shapes("VendorButton").ShapeStyle
Sus = .Shapes("SuspectButton").ShapeStyle
Pros = .Shapes("ProspectButton").ShapeStyle
Qual = .Shapes("QualifiedButton").ShapeStyle
NonQual = .Shapes("NonQualifiedButton").ShapeStyle
Dim Customer As Long, Vendor As Long, Prospect As Long, Suspect As Long, Qfied As Long, NQfied As Long
Customer = 0
Vendor = 0
Prospect = 15
Suspect = 5
Qfied = 15
NQfied = 0
If Cust = 34 Then
RelScore = Customer
End If
If Vend = 34 Then
RelScore = Vendor
End If
If Sus = 34 Then
RelScore = Suspect
End If
If Pros = 34 Then
RelScore = Prospect
End If
If Qual = 34 Then
QualScore = Qfied
End If
If NonQual = 34 Then
QualScore = NQfied
End If
Score = RelScore + QualScore
Debug.Print Score
End With
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>You deleted this before I could answer on SO:</p>\n\n<pre><code>Option Explicit\nSub Lead_Score()\n\n Dim shp As Shape\n Dim RelScore As Long\n Dim QualScore As Long\n For Each shp In ThisWorkbook.Sheets(1).Shapes 'change (1) for your sheet name.\n RelScore = MyRelScore(shp)\n QualScore = MyQualScore(shp)\n Next shp\n Dim Score As Long\n Score = RelScore + QualScore\n Debug.Print Score\n\nEnd Sub\nPrivate Function MyRelScore(shp As Shape) As Long\n\n Select Case shp.Name\n Case \"CustomerButton\", \"VendorButton\"\n If shp.ShapeStyle = 34 Then MyRelScore = 0\n Case \"ProspectButton\"\n If shp.ShapeStyle = 34 Then MyRelScore = 15\n 'Case ...\n End Select\n\nEnd Function\nPrivate Function MyQualScore(shp As Shape) As Long\n\n Select Case shp.Name\n Case \"SuspectButton\"\n If shp.ShapeStyle = 34 Then MyQualScore = 5\n Case \"QualifiedButton\"\n If shp.ShapeStyle = 34 Then MyQualScore = 15\n Case \"NonQualifiedButton\"\n If shp.ShapeStyle = 34 Then MyQualScore = 0\n 'Case ...\n End Select\n\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:25:02.677",
"Id": "237105",
"ParentId": "237104",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:22:55.430",
"Id": "237104",
"Score": "1",
"Tags": [
"vba",
"mathematics"
],
"Title": "Calculating a Score in VBA based on selected ShapeStyle. Is there a better/shorter way to do this?"
}
|
237104
|
<p>I have two functions which I would like to simplify. They have largely the same logic, but one is asynchronous and uses one await in a try block. I'd like to have the logic in one place, but could not figure out a clean way of doing that. Any suggestions?</p>
<pre><code>from requests import get, HTTPError
# Dummy functions for external functionality
def sync_send(url):
return get(url)
async def async_send(url):
return get(url)
def next(url):
if url is None:
return
try:
response = sync_send(url)
return response.json()
except HTTPError as e:
if e.response.status_code == 404:
return
else:
raise
async def async_next(url):
if url is None:
return
try:
response = await async_send(url)
return response.json()
except HTTPError as e:
if e.response.status_code == 404:
return
else:
raise
</code></pre>
<p>So the point of this all is to provide a way of requesting for resources in an API two ways, sync and async. Despite the simple (synchronous) dummy functions, in <code>async_next</code> we use asynchronous IO to retrieve things. Other than that, the situation is exactly as it is here.</p>
<hr>
<p>I have accepted that the <code>if url is None</code> cannot be refactored, and I currently think my only option is to make a more complex exception hierarchy, raising a dedicated 404 error to catch it without logic. Any other ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T11:20:31.973",
"Id": "465546",
"Score": "0",
"body": "What happened with passing the `cond` variable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T11:24:44.307",
"Id": "465548",
"Score": "0",
"body": "@Mast When asking this question I thought without further context it would be weird to assume that someone would pass in an empty URL. But when I thought about it again, it is better to have it as it is in the code."
}
] |
[
{
"body": "<p>Let's have async implementation: </p>\n\n<pre><code>async def async_next(url):\n if url is None:\n return\n\n try:\n response = await async_send(url)\n return response.json()\n except HTTPError as e:\n if e.response.status_code == 404:\n return\n else:\n raise\n</code></pre>\n\n<p>Then you can provide following sync bridge:</p>\n\n<pre><code>def next(url):\n return asyncio.run(async_next(url))\n\n</code></pre>\n\n<p>Or the following if the event loop is available and running:</p>\n\n<pre><code>def next(url):\n return loop.run_until_complete(async_next(url))\n\n</code></pre>\n\n<p>Note: <a href=\"https://docs.python.org/3/library/asyncio-api-index.html\" rel=\"nofollow noreferrer\">check asyncio high level commands</a> for more details</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T07:04:23.797",
"Id": "465654",
"Score": "0",
"body": "Thanks for the suggestion, though I'm not a fan of running the loop every time a synchronous call should be made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T00:08:59.383",
"Id": "237466",
"ParentId": "237106",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:36:32.140",
"Id": "237106",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"async-await"
],
"Title": "Refactoring try blocks with async/await"
}
|
237106
|
<p>TL;DR: The algorithm receives a string as input, allocate another string to be the final digest, and start working on them. For each char on the digest (a null character on a first moment), it XORs it with every character from the original string, also XORing it with a set of "random bytes" that are specified in the beginning of the code.</p>
<p>Here are some results:</p>
<blockquote>
<p>"000" = qpktluvsqpktluvs; "001" = bcygoiwnccxfohxn;</p>
<p>"abc" = ayedeufryzdfftds; "cba" = cqgleoxlarrnfnvm;</p>
<p>"aaaaa" = hingixcphingixcp; "aabaa" = aprndovlapgneovk;</p>
</blockquote>
<p>Am I mathematically getting the full potential of the performance I'm using? How good would you say it is compared to other hashing algorithms? Thanks a lot for reading!
This is my first hashing algorithm. My goal is to be simple and performatic. How can I improve it?</p>
<pre><code>#define HASH_LENGTH 16
char *hash(char *input){
// Alphabet and length
const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const int alphabetLen = sizeof(alphabet)/sizeof(char) - 1;
// Randomization variables and length
const char vars[] = {
0xA6,
0xC1,
0x5E,
0x31,
0xF5,
0x88,
0xA1,
0xE2
};
const int varsLen = sizeof(vars)/sizeof(char);
// Digest (where the hash is made)
char *digest = (char*)malloc(sizeof(char) * (HASH_LENGTH + 1));
// Input length calculation
int inputLen = 0;
while(input[inputLen] != '\0') inputLen++;
// Digest cleaning
int i;
for(i = 0; i < HASH_LENGTH; i++){
digest[i] = 0;
}
// Hashing process
int j;
for(i = 0; i < HASH_LENGTH; i++){
// XORs digest[i] with vars[input[j]]
for(j = 0; j < HASH_LENGTH; j++){
digest[i] ^= vars[input[j % inputLen] % varsLen];
}
// XORs digest[i] with input[i] + vars[i]
digest[i] ^= input[i % inputLen] + vars[i % varsLen];
}
// Translates digest to desired alphabet
for(i = 0; i < HASH_LENGTH; i++){
j = digest[i] > 0 ? 1 : -1;
digest[i] = alphabet[digest[i] * j % alphabetLen];
}
// Finalizes digest string
*(digest + HASH_LENGTH) = '\0';
return digest;
}
</code></pre>
<p>This is how the function is called:</p>
<pre><code>printf("%s", hash("foo"));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:50:42.627",
"Id": "464825",
"Score": "2",
"body": "Please add some description of your hashing algorithm. You will loose a lot of potential reviewers if they have to infer that knowledge from the code. Also please edit the title to not ask for improvements because that applies basically to every question on this site. Just state what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:00:21.607",
"Id": "464826",
"Score": "0",
"body": "Thanks for the advice. I've edited the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:04:01.923",
"Id": "464828",
"Score": "0",
"body": "Is it possible for you to add some test code to demonstrate how the function is used? It would also help if the definition of HASH_LENGTH was shown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:11:24.373",
"Id": "464829",
"Score": "0",
"body": "Edited it! Thanks for the patience!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:29:41.350",
"Id": "464834",
"Score": "4",
"body": "What is the purpose of this hash function? Is it for data structures like a hash map? Is it for cryptography? Is it for something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T22:32:39.730",
"Id": "464835",
"Score": "0",
"body": "It is intended for hash mapping but it's more a test than anything else"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:21:52.047",
"Id": "464874",
"Score": "0",
"body": "If you call the function like you propose, the memory allocated inside the function is leaked, making that a very bad example."
}
] |
[
{
"body": "<p>I'm not particularly familiar with C, but I have a few observations that may be helpful.</p>\n\n<p>I like the attention to zeroing out your digest before you start. Using uninitialised memory is the sort of bug that can go unnoticed for a while, and it's good that you've caught it. </p>\n\n<p>At the same time, I'm slightly alarmed that you're doing everything with raw loops, instead of using standard library functionality that does the same job. For example your loop to find <code>inputLen</code> could be replaced by a call to something like <code>strlen</code> and your loop to zero the array with a call to <code>memset</code>. As well as generally being more confident that you're using a tested and optimised routine, using library functions makes it easier to read and reason about your code.</p>\n\n<p>I also quite like your use of comments. They're well placed, complementing the code and explaining some of the whys where the code explains the hows. </p>\n\n<hr>\n\n<p>As for the hashing itself, I'm sure that the output looks fairly random, but it's actually doing a lot of work for the level of hashing that it supplies. </p>\n\n<p>My top concerns:</p>\n\n<ol>\n<li>If the input is longer than <code>HASH_LENGTH</code>, the latter part of the input is completely ignored.</li>\n<li>XOR is a standard building block for this sort of low level stuff, but one of the key properties of XOR is that it undoes its own work. That is to say, because your <code>for</code> loop with <code>j</code> is <em>only</em> doing XOR it will confuse rather less than you'd expect for the work that goes into a nested loop. </li>\n<li>The space allocated to <code>digest</code> at the end is underused. For example, because it's restricted to that alphabet, the first three bits of every byte will be \"011\". That has implications for use with, say, hash maps because the hash map will allocate 87.5% of its slots to values this hash function can never fill for any possible input. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:40:46.607",
"Id": "464845",
"Score": "1",
"body": "I kinda tried to do everything from scratch, without many external libraries, just for studying. Thanks a lot for the helpful review. Now about your concerns, the \"longer than HASH_LENGTH\" was actually a bug I didn't notice. The inner loop is supposed to do `inputLen` iterations. Thanks for pointing that out. About the alphabet, what would you suggest to solve this problem? And do you have any suggestions on the XOR thing? Would mixing other operations in be of any help? Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:07:53.660",
"Id": "464871",
"Score": "0",
"body": "Yes, mixing in other operations would help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:21:06.830",
"Id": "464873",
"Score": "0",
"body": "As for the alphabet thing, the standard option is to separate out the hash calculation (which should be a nice even spread across all bits) from the conversion to something visible for debugging. When you do the visible thing, standard is to use something like Hex that can represent all the bits of the hash. But when you use the hash internally, you keep it raw."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T11:27:24.400",
"Id": "464896",
"Score": "1",
"body": "If you're wondering which operations to mix in, it's worth noting that \"Add-Rotate-Xor\" is a common design for hash functions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:11:37.247",
"Id": "237113",
"ParentId": "237107",
"Score": "11"
}
},
{
"body": "<p>We really need to start by defining the kind of hash function we've created - this doesn't appear to be a useful cryptographic (one-way) hash function, yet creating strings as output seems to be a poor choice for hashes used for performance purposes (as keys in unordered maps and sets, for example). What is the intended problem domain here?</p>\n\n<p>We have a very low density of outputs. On a system with 8-bit <code>char</code>, we use only .000000000000013% (significantly less than one quadrillionth) of the available 16-byte results. That's very inefficient use of storage.</p>\n\n<hr>\n\n<p>Should the function be allowed to modify the contents of <code>input</code>? If not, then it should be declared as <code>char const*</code>.</p>\n\n<hr>\n\n<p>Since we return a pointer to allocated memory, the documentation needs to be much more clear that it's the caller's responsibility to call <code>free()</code> when it's no longer required.</p>\n\n<hr>\n\n<p><code>alphabet</code> and <code>vars</code> can be shared across all invocations, so should be declared <code>static</code>.</p>\n\n<hr>\n\n<p>All these values are potentially out of range of <code>char</code>, as <code>CHAR_MAX</code> may be as low as 127:</p>\n\n<blockquote>\n<pre><code>const char vars[] = {\n 0xA6,\n 0xC1,\n 0x5E,\n 0x31,\n 0xF5,\n 0x88,\n 0xA1,\n 0xE2\n};\n</code></pre>\n</blockquote>\n\n<p>Use a type with a guaranteed large enough range, such as <code>int</code> or <code>unsigned char</code>. How were these constants generated? It's worth a comment explaining how these improve the algorithm, because it's not obvious to a casual reader.</p>\n\n<hr>\n\n<p>If we declare <code>malloc()</code> before we use it, we won't need to cast its result:</p>\n\n<pre><code>#include <stdlib.h>\n\nchar *digest = malloc(HASH_LENGTH + 1));\n</code></pre>\n\n<p>Note that <code>sizeof (char)</code> cannot be other than 1, since <code>sizeof</code> works in units of <code>char</code>.</p>\n\n<hr>\n\n<p><code>malloc()</code> will return a null pointer when it fails - we mustn't dereference the result until we know it's a valid pointer.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// Input length calculation\nint inputLen = 0;\nwhile(input[inputLen] != '\\0') inputLen++;\n</code></pre>\n</blockquote>\n\n<p>This is exactly what <code>strlen()</code> (in <code><string.h></code>) is for:</p>\n\n<pre><code>size_t const inputLen = strlen(input);\n</code></pre>\n\n<p>BTW, it's probably worth using <code>size_t</code> (or at least unsigned types) for <code>HASH_LENGTH</code> and <code>varLen</code>, too, and for the indexing iterators <code>i</code> and <code>j</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int i;\nfor(i = 0; i < HASH_LENGTH; i++){\n digest[i] = 0; \n}\n</code></pre>\n</blockquote>\n\n<p><code><string.h></code> also contains <code>memset()</code> - don't reimplement it yourself. Your compiler <em>may</em> be smart enough to spot the pattern and convert it to more efficient form (e.g. writing in units of your processor's word size), but even if it does, you've obscured what's happening here, and programmer time is much more expensive than CPU time.</p>\n\n<hr>\n\n<p>The XOR loops don't seem to consider any of the input string after the first <code>HASH_LENGTH</code> characters. That means you'll get lots of collisions for strings sharing a common prefix.</p>\n\n<p>The nested loops mean we're doing much more work than traditional hash functions, which examine each input character just once (and are O(<em>n</em>) in the length of input).</p>\n\n<hr>\n\n<p>Hashing the empty string gives undefined behaviour, because <code>inputLen</code> is then zero, and <code>% 0</code> is undefined. That's a serious bug.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>digest[i] > 0\n</code></pre>\n</blockquote>\n\n<p>On systems where <code>char</code> is an unsigned type, this may be true much more often than on those where it's signed - that looks like a bug. Reading on, it appears that you're just using this to implement your own <code>abs()</code>; don't do that - include <code><math.h></code> instead.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> digest[i] = alphabet[digest[i] * j % alphabetLen];\n</code></pre>\n</blockquote>\n\n<p>That will give you a non-uniform distribution, unless you can somehow arrange for <code>alphabetLen</code> to be an exact factor of <code>UCHAR_MAX</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>*(digest + HASH_LENGTH)\n</code></pre>\n</blockquote>\n\n<p>That's a convoluted way to write <code>digest[HASH_LENGTH]</code> - why are you going to such lengths to make the code hard to read?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:36:24.187",
"Id": "464843",
"Score": "0",
"body": "I read somewhere that casting `malloc()`s to pointer types was a good practice, I'm not sure why, though. Thanks a lot for the helpful review. Just one question: why did you say I was reimplementing `memset()` less efficiently? How'd you reimplement it in a better way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:39:21.340",
"Id": "464844",
"Score": "1",
"body": "You don't reimplement `memset()` - trust your compiler to have much better knowledge of the target architecture than we C programmers ever can. Each compiler can provide an implementation carefully targeted at its platform; portable code will not (and should not) do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:43:27.413",
"Id": "464846",
"Score": "0",
"body": "But doesn't `memset()` belong to `<string.h>`? Do these libraries vary from compiler to compiler? I thought they were components of the language itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:20:35.360",
"Id": "464866",
"Score": "1",
"body": "Yes, `<string.h>` is part of the Standard Library, and therefore supplied as part of your compiler. That means that it's provided as part of your development platform, and implementations do indeed vary. In particular, compilers are allowed to recognise Standard Library functions and handle them specially - for instance, see the [so] question, _[Can `printf` get replaced by `puts` automatically in a C program?](//stackoverflow.com/q/25816659/4850040)_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:05:42.160",
"Id": "464930",
"Score": "0",
"body": "Minor: \"This is exactly what strlen() (in <string.h>) is for: `int const inputLen = strlen(input);`\" --> except `strlen()` returns `size_t`. OP's code should be adjusted for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:10:38.577",
"Id": "464933",
"Score": "0",
"body": "@chux, I realised that just after I went to bed; forgot to come back and fix it. Thanks for prodding me!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T23:19:07.330",
"Id": "237114",
"ParentId": "237107",
"Score": "10"
}
},
{
"body": "<p>Review of OP's post and <a href=\"https://codereview.stackexchange.com/a/237115/29485\">answer</a>.</p>\n\n<p><strong>Bug</strong></p>\n\n<p><code>digest[i] ^= vars[input[j] % varsLen];</code> is <em>undefined behavior</em>, UB, when <code>input[j] < 0</code>.</p>\n\n<p><strong>Bug</strong></p>\n\n<p><code>hash(\"\")</code> attempts <code>% 0</code> with<code>digest[i] ^= input[i % inputLen] + vars[i % varsLen];</code></p>\n\n<p><strong>Failure on long strings</strong></p>\n\n<p><code>strlen(input);</code> can exceed <code>INT_MAX</code>. <code>size_t const inputLen = strlen(input); size_t i, j;</code> is better.</p>\n\n<p><strong><code>abs()</code> not really needed</strong></p>\n\n<p><code>char *digest</code> as <code>unsigned char *digest</code> would negate the need for <code>abs()</code> in <code>abs(digest[i])</code></p>\n\n<p><strong>Fundamental issues as code uses <code>char</code> rather than <code>unsigned char</code></strong></p>\n\n<p>Using <code>unsigned char</code> rather than <code>char</code> would improve hash quality and maybe speed over when <code>char</code> is signed. </p>\n\n<p><code>char vars[] = { 0xA6, ...</code> remains problematic as when <code>char</code> is signed, conversion of an out-of-range value to char is implementation defined and may not perform as desired. Simplify all this potential signed hashing with <code>unsigned char</code>. The return type can remain <code>char *</code>.</p>\n\n<p>Note that the C library functions perform internally as if <code>char</code> was <code>unsigned char</code> even when <code>char</code> is signed.</p>\n\n<p><strong>Simplification</strong></p>\n\n<p><code>char *digest = malloc(HASH_LENGTH + 1); memset(digest, 0, HASH_LENGTH); ...digest[HASH_LENGTH] = '\\0';</code> can be replaced with <code>char *digest = calloc(HASH_LENGTH + 1, sizeof *digest);</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:35:51.773",
"Id": "237162",
"ParentId": "237107",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237113",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T21:42:35.133",
"Id": "237107",
"Score": "9",
"Tags": [
"c",
"hashcode"
],
"Title": "Simple hashing algorithm"
}
|
237107
|
<p>I've written a basic event messenger broadcasting service. This is meant to allow for broadcasting events between loosely coupled areas of code where you may not have or care about a direct reference to the specific broadcast source (as you might if using Signals/Slots for example), and the broadcaster does not know who might care about that event.</p>
<p>The shared concept for events must be a common broadcast argument, or string key (or both). There was a desire not to need to inherit from some kind of "EventData" object when deciding what message to pass. I have two methods of observing. Either connection via lambdas or having an observer class derive from MessengerObserver depending on your needs. There are data locality vs size of observer logic tradeoffs that I leave up to the developer by providing these interfaces.</p>
<p>I have a single header file dependency on typestring which is visible here: <a href="https://github.com/irrequietus/typestring" rel="nofollow noreferrer">https://github.com/irrequietus/typestring</a> due to limiting this code to C++17 (C++20 will resolve this dependency by introducing template type strings.)</p>
<p>I'm looking for any feedback/thoughts. Issues/errors, and general thoughts on style and usability of the API. Thank you! This will be published on my github after review: <a href="https://github.com/M2tM" rel="nofollow noreferrer">https://github.com/M2tM</a></p>
<blockquote>
<p>messenger.hpp</p>
</blockquote>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <mutex>
#include <algorithm>
#include <typeindex>
#include "typestring.hpp"
#define MV_KEY(x) typestring_is(x)
namespace MV {
struct MessageHandle {
virtual ~MessageHandle() {}
};
class MessageCallerNoArgCastable : public MessageHandle {
public:
typedef void type;
virtual bool operator()() = 0;
};
template<typename F>
class MessageCallerNoArg : public MessageCallerNoArgCastable {
public:
MessageCallerNoArg(F&& a_f) : f(a_f) {}
bool operator()() override {
if constexpr (std::is_pointer<F>::value){
if constexpr (std::is_same<decltype((*f)()), bool>::value){
return (*f)();
} else {
(*f)();
return true; //never self kill
}
}else{
if constexpr (std::is_same<decltype(f()), bool>::value){
return f();
} else {
f();
return true; //never self kill
}
}
}
private:
F f;
};
template<typename T>
class MessageCallerCastable : public MessageHandle {
public:
typedef T type;
virtual bool operator()(const T&) = 0;
};
template<typename F, typename T>
class MessageCaller : public MessageCallerCastable<T> {
public:
MessageCaller(F&& a_f) :f(a_f){}
bool operator()(const T &a_value) override {
if constexpr (std::is_pointer<F>::value){
if constexpr (std::is_same<decltype((*f)(a_value)), bool>::value){
return (*f)(a_value);
} else {
(*f)(a_value);
return true; //never self kill
}
}else{
if constexpr (std::is_same<decltype(f(a_value)), bool>::value){
return f(a_value);
} else {
f(a_value);
return true; //never self kill
}
}
}
private:
F f;
};
template<typename F>
std::shared_ptr<MessageHandle> make_message_caller(F&& a_f) {
return std::static_pointer_cast<MessageHandle>(std::make_shared<MessageCallerNoArg<typename std::decay<F>::type>>(std::forward<F>(a_f)));
}
template<typename T, typename F>
std::shared_ptr<MessageHandle> make_message_caller(F&& a_f) {
if constexpr (std::is_same<T, void>::value){
return make_message_caller(std::forward<F>(a_f));
}else{
return std::static_pointer_cast<MessageHandle>(std::make_shared<MessageCaller<typename std::decay<F>::type, T>>(std::forward<F>(a_f)));
}
}
namespace detail {
template<typename T>
struct is_string : public std::disjunction<
std::is_same<char *, typename std::decay<T>::type>,
std::is_same<const char *, typename std::decay<T>::type>,
std::is_same<std::string, typename std::decay<T>::type>> {
};
}
class Messenger {
private:
struct EventKey {
std::string key;
std::type_index valueType;
bool operator<(const EventKey &a_rhs) const{
return std::tie(valueType, key) < std::tie(a_rhs.valueType, a_rhs.key);
}
};
template <typename T>
static EventKey makeKey(const std::string &a_key) {
return {a_key, typeid(T)};
}
public:
template <typename T>
void broadcast(const std::string &a_key, const T &a_value) {
if constexpr(detail::is_string<T>::value){ //force const char * -> std::string to enable m.broadcast("Key", "Value");
broadcastCommon<MessageCallerCastable<std::string>>(a_key, [&](auto&& callable) -> bool{ return (*callable)(a_value); });
}else{
broadcastCommon<MessageCallerCastable<T>>(a_key, [&](auto&& callable) -> bool{ return (*callable)(a_value); });
}
}
template <typename ValueType>
void broadcast(const ValueType& a_value) {
static_assert(!detail::is_string<ValueType>::value, "Disambiguate broadcast of a string by using either broadcastKey or broadcastValue to clarify intent.");
broadcast(std::string(), a_value);
}
//Zero Argument broadcast of a specific event key.
void broadcastKey(const std::string& a_key) {
broadcastCommon<MessageCallerNoArgCastable>(a_key, [&](auto&& callable) -> bool{ return (*callable)(); });
}
//One Argument broadcast of a string value to any unkeyed observers.
void broadcastValue(const std::string& a_value){
broadcast(std::string(), a_value);
}
template <typename T, typename F>
[[nodiscard]] std::shared_ptr<MessageHandle> observe(const std::string &a_key, F&& a_method) {
std::lock_guard<std::recursive_mutex> guard(mutex);
auto observer = make_message_caller<T>(std::forward<F>(a_method));
auto key = makeKey<T>(a_key);
if (activeKeys[key] > 0) {
pendingObservers[key].push_back(observer);
} else {
observers[key].push_back(observer);
}
return observer;
}
template <typename F>
[[nodiscard]] std::shared_ptr<MessageHandle> observe(const std::string &a_key, F&& a_method) {
return observe<void, F>(a_key, std::forward<F>(a_method));
}
template <typename T, typename F>
[[nodiscard]] std::shared_ptr<MessageHandle> observe(F&& a_method) {
return observe<T, F>(std::string(), std::forward<F>(a_method));
}
private:
template <typename T>
struct ScopedKeyLock {
ScopedKeyLock(const std::string &a_key, Messenger& a_owner) :
key(makeKey<T>(a_key)),
owner(a_owner),
guard(a_owner.mutex),
observerCollection(a_owner.observers[key]){
++owner.activeKeys[key];
}
~ScopedKeyLock() {
if (--owner.activeKeys[key] == 0) {
auto& pendingOserversRef = owner.pendingObservers[key];
for (auto&& pendingObserver : pendingOserversRef) {
if (!pendingObserver.expired()) {
observerCollection.push_back(pendingObserver);
}
}
pendingOserversRef.clear();
}
}
EventKey key;
Messenger& owner;
std::lock_guard<std::recursive_mutex> guard;
std::vector<std::weak_ptr<MessageHandle>>& observerCollection;
};
template <typename T>
friend class ScopedKeyLock;
template <typename T, typename F>
void broadcastCommon(const std::string& a_key, F&& a_invokeCaller) {
ScopedKeyLock<typename T::type> scopedLock(a_key, *this);
scopedLock.observerCollection.erase(std::remove_if(scopedLock.observerCollection.begin(), scopedLock.observerCollection.end(), [&](auto weakObserver) {
if (auto observer = weakObserver.lock()) {
return !a_invokeCaller(std::static_pointer_cast<T>(observer));
} else {
return true;
}
}), scopedLock.observerCollection.end());
}
std::recursive_mutex mutex;
std::map<EventKey, int> activeKeys;
std::map<EventKey, std::vector<std::weak_ptr<MessageHandle>>> observers;
std::map<EventKey, std::vector<std::weak_ptr<MessageHandle>>> pendingObservers;
};
struct KeyPairComparer {};
template <typename KeyParam, typename T = void>
struct KeyPair : public KeyPairComparer {
static const char * key() noexcept {return KeyParam::data();}
typedef T type;
};
template <typename DerivedType, typename ... ObservableTypes>
class MessengerObserver {
public:
MessengerObserver(MV::Messenger &a_m){
autoObserve<ObservableTypes...>(a_m);
}
virtual ~MessengerObserver(){}
protected:
//Allow manual connection
void addHandle(const std::shared_ptr<MV::MessageHandle> &a_handle){
handles.push_back(a_handle);
}
private:
template <int = 0>
void autoObserve(MV::Messenger &a_m) {
}
template <typename T, typename... Ts>
void autoObserve(MV::Messenger &a_m) {
if constexpr (std::is_base_of<KeyPairComparer, T>::value){
if constexpr (std::is_same<typename T::type, void>::value){
handles.push_back(a_m.observe(T::key(),static_cast<DerivedType*>(this)));
}else{
handles.push_back(a_m.observe<typename T::type>(T::key(),static_cast<DerivedType*>(this)));
}
autoObserve<Ts...>(a_m);
}else{
handles.push_back(a_m.observe<T>(static_cast<DerivedType*>(this)));
autoObserve<Ts...>(a_m);
}
}
std::vector<std::shared_ptr<MV::MessageHandle>> handles;
};
}
</code></pre>
<blockquote>
<p>main.cpp</p>
</blockquote>
<pre class="lang-cpp prettyprint-override"><code>#include "messenger.hpp"
struct MyEventData {
int a;
std::string b;
};
//This serves as an example of creating a type which manages its own connection and implicitly connects to a messenger through the derived MessengerObserver interface.
struct MyMultiObserver : public MV::MessengerObserver<MyMultiObserver, MV::KeyPair<MV_KEY("NoDataEvent")>, MV::KeyPair<MV_KEY("KeyedEvent"), int>, double, std::string> {
MyMultiObserver(MV::Messenger &a_m):
MessengerObserver(a_m){
addHandle(a_m.observe<bool>(this)); //allow manual hookup/ownership too.
}
void operator()(int v){
std::cout << "MultiObserver [KeyedEvent|int]: " << v << std::endl;
}
bool operator()(double v){
std::cout << "MultiObserver Self Disconnect [double]: " << v << std::endl;
return false; //only listen once.
}
void operator()(){
std::cout << "MultiObserver [NoData]" << std::endl;
}
//hooked up manually
void operator()(bool v){
std::cout << "MultiObserver [bool]: " << v << std::endl;
}
void operator()(const std::string &a_message){
std::cout << "MultiObserver [string]: " << a_message << std::endl;
}
};
void broadcastTest(MV::Messenger& m);
int main() {
MV::Messenger m;
std::shared_ptr<MV::MessageHandle> disconnectableHandle;
std::cout << "\nBegin Test: Manual Disconnect\n";
{
disconnectableHandle = m.observe<int>([](int value) {
std::cout << "Manual Disconnect [int]: " << value << std::endl;
});
m.broadcast(2);
disconnectableHandle.reset();
m.broadcast(2); // no output.
}
std::cout << "\nBegin Test: Lambda\n";
{
std::vector<std::shared_ptr<MV::MessageHandle>> handles;
handles.push_back(m.observe<int>([&](int value) {
std::cout << "Lambda Self Disconnect [int]: " << value << std::endl;
//example of adding an observer from within a callback.
handles.push_back(m.observe<int>([](int value) {
std::cout << "Lambda Nested [int]: " << value << std::endl;
}));
return false; //return false to remove this, the return value is optional.
}));
handles.push_back(m.observe<double>([](double value) {
std::cout << "Lambda [double]: " << value << std::endl;
}));
handles.push_back(m.observe<MyEventData>([](const MyEventData& value) {
std::cout << "Lambda [MyEventData]: " << value.a << ", " << value.b << std::endl;
}));
handles.push_back(m.observe("NoDataEvent", []() {
std::cout << "Lambda [NoData]" << std::endl;
}));
handles.push_back(m.observe<int>("KeyedEvent", [](int value) {
std::cout << "Lambda [KeyedEvent|int]: " << value << std::endl;
}));
broadcastTest(m);
}
std::cout << "\nBegin Test: MyMultiObserver\n";
{
MyMultiObserver listener(m);
broadcastTest(m);
}
broadcastTest(m); // no output expected
}
void broadcastTest(MV::Messenger& m){
m.broadcast(1);
m.broadcast(2);
m.broadcast(3.5);
m.broadcast(4.5);
m.broadcast(MyEventData{ 5, std::string("Cool Event") });
//Example of a keyed event.
m.broadcast("KeyedEvent", 6);
m.broadcastKey("NoDataEvent");
m.broadcastValue("My_Message");
m.broadcast(false);
}
</code></pre>
<blockquote>
<p>Console Output:</p>
</blockquote>
<pre><code>Begin Test: Manual Disconnect
Manual Disconnect [int]: 2
Begin Test: Lambda
Lambda Self Disconnect [int]: 1
Lambda Nested [int]: 2
Lambda [double]: 3.5
Lambda [double]: 4.5
Lambda [MyEventData]: 5, Cool Event
Lambda [KeyedEvent|int]: 6
Lambda [NoData]
Begin Test: MyMultiObserver
MultiObserver Self Disconnect [double]: 3.5
MultiObserver [KeyedEvent|int]: 6
MultiObserver [NoData]
MultiObserver [string]: My_Message
MultiObserver [bool]: 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T06:56:24.400",
"Id": "465841",
"Score": "1",
"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)*. Feel free to post a new question linking back to this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T20:07:51.090",
"Id": "465936",
"Score": "0",
"body": "Thank you, I think I'll just be posting the updated version to my github at this point. I apologize for breaking that rule."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T20:13:21.763",
"Id": "465938",
"Score": "0",
"body": "Oh, don't worry. It's confusing for people new to the site and we don't advertise it broadly enough. Luckily we keep track of these things, no problem."
}
] |
[
{
"body": "<p>Sorry, I probably should have used a \"comment\" for this, but it is way bigger than their limited size.</p>\n\n<p>In all fairness I did not read your code in full; I only scanned it. The thing that struck me as I was reading, is that this is incredibly hard to do well. Assuming a robust enterprise environment, you run into all kinds of issues that take lots of thought and lots of code to deal with.</p>\n\n<ul>\n<li>What happens if a thread/process/machine dies before processing a message?</li>\n<li>What happens if you need to go multi-process or multi-server because of load?</li>\n<li>What happens if what you want to send to a process or system that isn't up yet?</li>\n</ul>\n\n<p>These and 100s more issues just seem to show themselves over time.</p>\n\n<p>I'd use RabbitMQ instead (though I understand Microsoft also has a messaging offering). \n RabbitMQ is very robust. If you need bulletproofing, you can set up servers on multiple\nmachines such that if one goes down, no messages are lost. And there all kinds of fanout options and keeping of messages even if the receiver is down. Even if you are in a single process on a single machine, RabbitMQ offers you options and protections you are going to want and haven't thought of yet.</p>\n\n<p>Your first thought might be, but I don't want to make a multi-process call because it is too expensive. Since I didn't read your code, perhaps I am completely off base here. However, I claim that if this is for an enterprise-level system you are going to want more eventually.</p>\n\n<p>The other thing you could do is switch to C# and use delegates which are built into the language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T04:46:18.793",
"Id": "465345",
"Score": "0",
"body": "This might also be a helpful read: https://stackoverflow.com/questions/9568150/what-is-a-c-delegate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T05:39:55.053",
"Id": "465347",
"Score": "0",
"body": "After thinking about my rant above, I've decided to offer a more low key answer. This is a common design pattern. I Googled around and found a couple of delegate libraries already out there for C++. Why reinvent the wheel? NDH (Not Developed Here) is a professional disease. Everybody has it to one extent or another, but whenever possible I suggest fighting the urge unless there are obvious faults with other implementations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T15:52:30.557",
"Id": "465378",
"Score": "0",
"body": "Recommending a particular vendor is beyond the scope of a review, there are quite a number of vendors for messaging, many of them are free below a certain message level. https://www.ably.io/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T20:12:44.860",
"Id": "465620",
"Score": "0",
"body": "I appreciate being linked another library but I fail to see how this passes for a code review. You make a lot of assumptions presuming I have the option of shifting *languages* for the project I’m working on as well. Finally, I obviously know what a delegate is if you read my code I have such structures. :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T20:17:17.520",
"Id": "465621",
"Score": "0",
"body": "RabbitMQ grossly exceeds the scope of the problems I'm trying to solve. I’m working with iOS and Android and this is intended to work within a single application."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T04:43:34.053",
"Id": "237316",
"ParentId": "237117",
"Score": "4"
}
},
{
"body": "<p>The code fails to build for me, but that could be platform and compiler compatibility. I attempted to build this on Windows 10 using CLion and Visual Studio 2019. Here are the errors and warnings I received:</p>\n\n<blockquote>\n <p>main.cpp(9): error C2672: 'irqus::typeek': no matching overloaded function found<br>\n main.cpp(9): error C2893: Failed to specialize function template 'unknown-type irqus::typeek(irqus::typestring)'<br>\n typestring.hpp(110): note: see declaration of 'irqus::typeek'<br>\n main.cpp(9): note: With the following template arguments:<br>\n main.cpp(9): note: 'C={75, 101, 121, 101, 100, 69, 118, 101, 110, 116, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}'<br>\n main.cpp(9): error C3203: 'KeyPair': unspecialized class template can't be used as a template argument for template parameter 'ObservableTypes', expected a real type</p>\n</blockquote>\n\n<p>Note: line 9 in main.cpp is where the macro <code>MV_KEY(x)</code> is being used and the expansion of that macro is failing.</p>\n\n<h2>Maintainability</h2>\n\n<p>The most major issues in this code maintainability and expand-ability. When software engineer/developer designs a solution for a product they need to keep in mind that the product may be around for a long time and bug fixes and feature requests will be very common, especially in the early stages. The code must be easy to read, write, debug and expand. The code should be modular so that parts that are working as expected will not need to be changed when other portions of the code need to be updated or corrected.</p>\n\n<p>The structure of this program where all the classes and multiple namespaces are declared in a single header file is a problem. The file <code>messenger.hpp</code> should be broken up into multiple files, each class within <code>messenger.hpp</code> should have it's own header file. As an aide in building the project, each class should also have it's own <code>.cpp</code> file as well. Separating the declarations from the executable code reduces build time and eases shipping bug fixes to the users.</p>\n\n<p>It is possible that <code>messenger.hpp</code> can be a single file that includes all the other messenger header file to ease implementation.</p>\n\n<h2>Using Macros in C++</h2>\n\n<p>Macros in C++ are generally frowned upon, a major reason is because macro's can't be debugged and there is no type checking in macros, There are a few good uses of macros, primarily as <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow noreferrer\">Include Guards</a> that prevent an included file from being included a multiple times (can cause compilation errors). There is also a discussion of this on <a href=\"https://stackoverflow.com/questions/8020113/c-include-guards\">stackoverflow</a>. You may want to read <a href=\"https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives\">why macros are considered evil as well</a>.</p>\n\n<p>One alternative to macros are templates. In the C programming language templates are not available and macros are used for generic functions.</p>\n\n<p>Including a whole library which is macros (<code>typestring.hpp</code>) is somewhat questionable in C++.</p>\n\n<h2>Object Oriented Programming</h2>\n\n<p>It's not really clear why there is a <code>struct</code> rather than a <code>class</code> that instantiates the <code>MyMultiObserver</code> objects.</p>\n\n<h2>Include Files</h2>\n\n<p>The file <code>main.cpp</code> should directly include <code><iostream></code>, and it should be removed from <code>messenger.hpp</code> since IO is only performed in main.cpp.</p>\n\n<h2>Complexity</h2>\n\n<p>In addition to the complexity caused by declaring multiple classes in <code>messenger.hpp</code> the function <code>main()</code> is too complex (does too much) and could be broken up into 3 function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:00:40.790",
"Id": "465773",
"Score": "0",
"body": "Thank you for your feedback! I've made meaningful changes based on a few of your points. The most notable of which was failure to compile in visual studio.\n\nI've gone ahead and removed the original dependency on irrequietus typestring since it seemed to fail, replacing it with a working solution.\n\nI've also worked around a few \"if constexpr\" bugs and reported it to Microsoft: https://developercommunity.visualstudio.com/content/problem/920784/nested-constexpr-if-fails-to-conditionally-compile.html\n\nThis should now work just fine in Visual Studio 2019 with C++17 compilation selected"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:03:02.613",
"Id": "465774",
"Score": "0",
"body": "For your Maintainability headline: I do not feel like splitting 283 lines of relatively tightly coupled classes is going to significantly improve the maintainability of this project, if the library were larger I would do so. Thank you for the feedback anyway, modularization is important in code mantainability. This is a header-only library and as such there are no .cpp files required for the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:14:50.773",
"Id": "465777",
"Score": "0",
"body": "For your Macros in C++ Heading: If you can point me at a template-only solution in C++17 which supports a unique type based on a string as MV_KEY(\"Contents\") creates, then I will wholly embrace it. Unfortunately I do not believe it is possible, and there are still cases where Macros are necessary in C++ for simpler syntax of certain kinds of otherwise very verbose and obfuscated hand-written code.\n\nIt is overly simplistic to say Macros are evil, though I totally agree where they can be avoided they should be. Again, if an alternative exists for this case, please share it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:16:12.940",
"Id": "465778",
"Score": "0",
"body": "For your feedback on Object Oriented Programming: struct and class are identical in C++ except for their default access level (public vs private). MyMultiObserver was specified as a struct originally simply to avoid having to have a single accessor: \"public:\" at the top, but I've changed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:16:35.113",
"Id": "465779",
"Score": "0",
"body": "For your feedback on Include Files: I've resolved this, thanks for pointing that out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:19:09.307",
"Id": "465780",
"Score": "0",
"body": "For your feedback on Complexity: I agree with your assessment of main.cpp having too much going on inside of it. For the purposes of this example It was not my intention to fret over the contents of main.cpp as it is actually throw-away example code, I should have specified more clearly I was interested primarily in reviews about the internals of the messaging class.\n\nOverall I was really hoping for more discussion about the style/choices of the implementation of the messaging class. I thank you anyhow for the time you spent sharing your review with me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T20:20:48.277",
"Id": "465781",
"Score": "0",
"body": "I'm giving you an upvote, and will be awarding you the bounty within 3 days unless another review comes along which actually digs into the implementation more than the file layout and broad strokes."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T17:47:40.657",
"Id": "237391",
"ParentId": "237117",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237391",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T01:17:13.500",
"Id": "237117",
"Score": "5",
"Tags": [
"c++",
"event-handling",
"c++17",
"callback"
],
"Title": "Message Broadcaster"
}
|
237117
|
<p>I had a task to convert some JPG images into PNG format using <strong>Python</strong>. I successfully did it but I was wondering if somehow I could make my code better than my current one.</p>
<p>Code - </p>
<pre><code>#Python Code
import os
from PIL import Image
path1 = sys.argv[1]
path2 = sys.argv[2]
if not os.path.exists(path2):
os.makedirs(path2)
for filename in os.listdir(path1):
if filename.endswith(".jpg"):
# print(filename.split(".")[0])
im = Image.open(f"{path1}{filename}")
# print(Image.open(f"{path1}{filename}"))
im.save(f"{path2}/{filename.split('.')[0]}.png", "png")
print("Lets go")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T05:01:54.643",
"Id": "464862",
"Score": "18",
"body": "Welcome to Code Review. I rolled back your last edit.Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:34:14.683",
"Id": "464918",
"Score": "1",
"body": "Depending on your use-case and intended user-base, consider whether someone might try either `python test.py foo/img.jpg bar/img.png`, or `python test.py in/ out/` where `in/foo.jpeg` exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T00:10:56.090",
"Id": "464995",
"Score": "10",
"body": "On a slight tangent, it's probably worth noting that converting JPEG images to PNG format _without cleaning them up to remove compression artifacts_ is almost never actually useful. It'll just make the file (possibly many times) bigger without improving the quality of the image in any way. (Of course, there can be situational exceptions, like if you're trying to feed the images to some program that can parse PNG but not JPEG.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T12:55:34.890",
"Id": "465092",
"Score": "1",
"body": "Do you really want to `print(\"Lets go\")` once for each file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T12:57:21.720",
"Id": "465093",
"Score": "0",
"body": "***Always*** have exception handling. What if the file to write is in use by another application? What if it has a .JPG extension, but not JPEG contents? etc, etc, etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T18:19:29.223",
"Id": "465150",
"Score": "7",
"body": "I'd go even further than Ilmari here, and say that if I were given this task, I would feel compelled to tell my employer that if you think you need a tool to convert JPEG to PNG, there's almost certainly something wrong with your process as a whole. You're basically pouring water from a 1-gallon bucket into a 5-gallon bucket; you'll still only have 1 gallon. Find out what part of your process lost the other 4, and elimintate *that*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T08:40:26.083",
"Id": "465220",
"Score": "0",
"body": "@MawgsaysreinstateMonica having the program fail in those cases is a viable option. A log to show at what image the program failed would be useful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T09:04:55.373",
"Id": "465227",
"Score": "0",
"body": "It is certainly possible. Personally, I like to handle errors gracefully, and to explain to the user what went wrong"
}
] |
[
{
"body": "<p>Not much to improve upon, just some minor housekeeping.</p>\n\n<hr>\n\n<h1>Help the end user!</h1>\n\n<p>If I was using this script, and forgot to put one or both of the filepaths when calling the script, there would be this error: <code>IndexError: list index out of range</code>. This error wouldn't help the user in a significant way. Consider this:</p>\n\n<pre><code>try:\n path1 = sys.argv[1] \n path2 = sys.argv[2]\nexcept IndexError:\n raise Exception(\"Usage: python3 jpg_to_png.py <path to input folder> <path to output folder>\")\n</code></pre>\n\n<p>This gives the user a detailed message on how the use your script.</p>\n\n<h1>Remove commented code.</h1>\n\n<p>Code you don't need anymore adds useless clutter, and can make your code harder to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:10:40.110",
"Id": "464854",
"Score": "1",
"body": "Thank you Linny, I will improve the code by using your suggestion and thanks for the suggestion regarding the commented out code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:27:23.453",
"Id": "464855",
"Score": "2",
"body": "@Praguru After someone answers your question, you're not supposed to edit your code. Can you please rollback your edit to make their answrr valid agian?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:36:24.227",
"Id": "464919",
"Score": "5",
"body": "Even better is to just use the `argparse` library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T12:53:34.000",
"Id": "465091",
"Score": "1",
"body": "[argparse](https://docs.python.org/3/library/argparse.html) ***every time*** Upvote"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T13:21:27.463",
"Id": "465264",
"Score": "2",
"body": "While argparse is handy, it's rather painful to use, and for small projects that do one single task, it just causes a hindrance imo."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T02:57:21.873",
"Id": "237120",
"ParentId": "237118",
"Score": "37"
}
},
{
"body": "<p>The variable names <code>path1</code> and <code>path2</code> are bad since they are not as descriptive as possible. They should rather be <code>srcdir</code> and <code>dstdir</code> (if you prefer abbreviations), or <code>source_directory</code> and <code>destination_directory</code> if you want to have them spelled out.</p>\n\n<p>Instead of manipulating strings, it's better to use the <code>pathlib</code> library, which has the handy function <code>with_suffix</code>.</p>\n\n<p>You should test what happens with filenames that have multiple dots, to prevent any surprise about losing parts of the filename.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T05:27:55.213",
"Id": "237124",
"ParentId": "237118",
"Score": "31"
}
},
{
"body": "<p>Consider using <code>__main__</code> to make your script easier to import (see <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">here</a> ).</p>\n\n<p>Also, consider the use of functions to isolate the different steps, so that it is easier to add new functionalities in the future.</p>\n\n<p>One last thing, you could use a more explicit log message, something along the lines of <code>Converting {filename} from jpg to png</code> instead of <code>Lets go</code>, maybe using the <code>logging</code> module instead of a simple print.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:37:17.150",
"Id": "464920",
"Score": "0",
"body": "I doubt that the intent is to import this script in other Python source files. This sounds more like a standalone script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:40:08.383",
"Id": "464922",
"Score": "3",
"body": "@AleksandrH agree, yet preparing it for a future unforeseen use-case is not harmful if not overdone, like in this case. Also, it is always a good exercise to get better at modularity and architectures."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T16:56:32.677",
"Id": "464944",
"Score": "0",
"body": "Yeah, that's fair. It wouldn't involve much effort to just wrap everything in the `__main__` check."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:56:23.730",
"Id": "237147",
"ParentId": "237118",
"Score": "11"
}
},
{
"body": "<p>Apart from what's already mentioned I would like to point out that\nthe file <code>super.picture.jpg</code> will be converted to <code>super.png</code></p>\n\n<p>That can be a problem if someone runs your program in a loop and iterates through a folder with files named <code>anniversary.1.jpg</code> <code>anniversary.2.jpg</code>....</p>\n\n<p>Instead, because you have used <code>endswith('.jpg')</code> you can just use a substring of length <code>filename.length - 4</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T16:53:53.323",
"Id": "464943",
"Score": "7",
"body": "This wouldn't work for `.jpeg`. Instead of using substrings, consider using `os.path.splitext`. It correctly accounts for this use case, and even more general ones. OP could extend this script to convert all images of a specified format to another format. Alternatively, just search for the first period from the end of the string and split there. But it's better to use an existing library."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:35:26.117",
"Id": "237155",
"ParentId": "237118",
"Score": "16"
}
},
{
"body": "<p>In general the code is simple and concise.</p>\n\n<p>Depending on the target usage, apart from what other answers suggest, I would add:</p>\n\n<ul>\n<li>support for files ending on \". jpeg\" not only .jpg;</li>\n<li>likewise I would make filename filter also find uppercase or mixed case JPEG files;</li>\n<li>if I had to deal with unreliable sources I would add also Image.verify() and/or imghdr checks to see if I get a valid jpeg file, and to give meaningful error messages otherwise.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:49:52.320",
"Id": "237163",
"ParentId": "237118",
"Score": "5"
}
},
{
"body": "<h1>function</h1>\n\n<p>I would abstract this into a function you can call. Then you can also easily incorporate a few checks to see whether the source path really is a directory, that the destination path actually exists,...</p>\n\n<h1><code>pathlib.Path</code></h1>\n\n<p>Has a lot of convenience methods that help with file path handling.</p>\n\n<pre><code>from PIL import Image\nfrom pathlib import Path\ndef convert_jpg_to_png(\n source: Path, \n destination: Path, \n overwrite=False,\n) -> None:\n if not source.is_dir():\n raise ValueError(f\"{source} is not a directory\")\n if not source.exists():\n raise ValueError(f\"{source} does not exist\")\n if not destination.is_dir():\n raise ValueError(f\"{destination} is not a directory\")\n if not destination.exists():\n destiny.mkdir(parents=True)\n\n for source_name in source.glob(\"**/*.jpg\"):\n# If you want to cover both jpg and jpeg, \n# for source_image in source.glob(\"**/*\"):\n# if not source_image.suffix.lower in {\".jpg\", \".jpeg\"}:\n# continue\n destination_name = destination / (\n source_name.relative_to(source.with_suffix(\".png\"))\n )\n if destination_name.exists() and not overwrite:\n print(f\"{destination_name} already exists\")\n continue\n print(f\"renaming {source_name} to {destination_name}\")\n with Image.open(source_name) as im:\n im.save(destination_name, format=\"PNG\")\n</code></pre>\n\n<p>The commented bits are if you also want to transform .JPG, .JPEG and .jpeg</p>\n\n<h1>main guard</h1>\n\n<p>You can then hide your logic behind a <code>if __name__ == \"__main__\":</code> guard, so you can later import this module in another program if you want to:</p>\n\n<pre><code>if __name__ == \"__main__\":\n if len(sys.argv) == 1:\n source = Path(\".\") # default: current location\n destination = source\n overwrite = False\n source = Path(sys.argv[1])\n if len(sys.argv) > 2:\n if sys.argv[2] in {\"True\", \"False\"}:\n destination = source\n overwrite = sys.argv[2] == \"True\"\n else:\n destination = Path(sys.argv[2])\n else:\n destination = source\n overwrite = False\n if len(sys.argv) > 3:\n overwrite = sys.argv[3] == \"True\"\n convert_jpg_to_png(source, destination, overwrite)\n</code></pre>\n\n<p>Here I manually handled the arguments, but you can better check the <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module to simplify this</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T16:17:13.050",
"Id": "237165",
"ParentId": "237118",
"Score": "6"
}
},
{
"body": "<p>A couple of things that I would suggest that you do:</p>\n\n<ul>\n<li><p>A level of nesting can be removed by using a generator expression to filter the list of files:</p>\n\n<pre><code>files_to_convert = (f for f in os.listdir(path1) if f.endswith(\".jpg\"))\nfor filename in files_to_convert:\n ... process the file ...\n</code></pre></li>\n<li><p>Ensure that the listing of <code>*.jpg</code> are files, not subdirectories named <code>*.jpg</code>:</p>\n\n<pre><code>files_to_convert = (f for f in os.listdir(path1) if f.endswith(\".jpg\") and os.path.isfile(f))\n</code></pre></li>\n<li><p>Use <code>os.path.join</code> to construct paths:</p>\n\n<pre><code>im = Image.open(os.path.join(path1, filename))\n</code></pre></li>\n<li><p>Use <code>os.path.splitext</code> to split the filename:</p>\n\n<pre><code>root, _ = os.path.splitext(filename)\npng_file = os.path.join(path2, f'{root}.png')\nim.save(png_file, \"png\")\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:32:48.583",
"Id": "237175",
"ParentId": "237118",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "237120",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T02:00:04.290",
"Id": "237118",
"Score": "22",
"Tags": [
"python",
"python-3.x",
"image"
],
"Title": "Converting JPG images to PNG"
}
|
237118
|
<p>I need to write a method that will accept a timestamp and takes an array of votes, I need to return the <code>k</code> leading candidates with that timestamp. I came up with the following solution, </p>
<p>Here is the input to the methods:</p>
<pre><code>votes = [{'candidate':'a', 'timestamp':2},{'candidate':'c', 'timestamp': 5},{'candidate':'c', 'timestamp': 12}]
timestamp = 5
k = 5
</code></pre>
<p>And the method to solve the problem,</p>
<pre><code>def leading_candidates(votes, timestamp,k):
candidates = {}
leading_candidates = []
for vote in votes:
if vote['timestamp'] <= timestamp:
if vote['candidate'] not in candidates:
candidates[vote['candidate']] = 1
else:
candidates[vote['candidate']] += 1
sorted_votes = sorted(candidates.values())[:k]
for candidate in candidates:
if candidates[candidate] in sorted_votes:
leading_candidates.append(candidate)
return leading_candidates
print(leading_candidates(votes, timestamp, 2))
</code></pre>
<p>As you can see the second solution has a time complexity of <span class="math-container">\$O(k\,n)\$</span> where k is the time it takes to find the index in the leading candidates sorted array, In the worst case, it can be <span class="math-container">\$O(n^2)\$</span> and because of sorting it may be at least <span class="math-container">\$O(n\,\log n)\$</span>.</p>
<p>Is there any way we can make it work with <span class="math-container">\$O(n)\$</span>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T03:37:53.733",
"Id": "464852",
"Score": "0",
"body": "You already know that everything in sorted_votes is in candidates. Why not \"for sorted_votes\" k times instead of \"for candidates\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:47:42.100",
"Id": "464858",
"Score": "0",
"body": "@FrankMerrow Yes, but how efficient it is to find the key of particular value in the hash table?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:48:51.020",
"Id": "464859",
"Score": "0",
"body": "Is there any other thing I can do to change the time taken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:18:48.203",
"Id": "464865",
"Score": "0",
"body": "Welcome to CodeReview@SE. What is `timestamp duration`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:36:06.593",
"Id": "464868",
"Score": "0",
"body": "@greybeard It's 5, I added the inputs passed to the methods above, I just want to improve the method for the asymptotic conditions, In the extream conditions is it possible to get the O(n) result? I am using hashmap if we use any other data structure is there any improvement can be made on the time complexity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:42:28.297",
"Id": "464877",
"Score": "2",
"body": "(I do not want to know one/the value to use: I have no idea how to interpret it just from the problem description. I think one timestamp to mark one point in time, a *duration* could be specified by two *timestamp*s. Then, there is *before* and *after*.)"
}
] |
[
{
"body": "<p>So, you want to count something and afterwards get the top <code>k</code>? That sounds like a job for <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a>!</p>\n\n<pre><code>from collections import Counter\n\ndef leading_candidates(votes, timestamp, k):\n vote_counts = Counter(vote['candidate']\n for vote in votes\n if vote['timestamp'] <= timestamp)\n return [candidate[0] for candidate in vote_counts.most_common(k)]\n\n\nif __name__ == \"__main__\":\n print(leading_candidates(votes, timestamp, 2))\n</code></pre>\n\n<p>This way you don't need to special case a candidate not yet having received a vote (something you could have also done with a <code>collections.defaultdict(int)</code>). And it is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n\n<p>Also note that if <code>k</code> is large, the line <code>if candidates[candidate] in sorted_votes</code> will become slow, as it is a linear scan. At the same time, you can iterate over the keys and values of a dictionary at the same time with <code>candidates.items()</code>, so you don't need to do <code>candidates[candidate]</code>.</p>\n\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which recommends using spaces after commas, which you forgot to do before <code>k</code> in the function signature.</p>\n\n<p>You should always guard your code with an <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from the script without running it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T23:18:47.007",
"Id": "464986",
"Score": "0",
"body": "`Counter.most_common()` uses a heap so it is O(k log h), where h is the total number of candidates (e.g., the size of the heap). Of course for most uses, neither k nor h are large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T23:21:42.740",
"Id": "464988",
"Score": "0",
"body": "@RootTwo True. And `log h < n` and `k` is constant. But filling the Counter is still `O(n)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T01:42:46.137",
"Id": "464999",
"Score": "0",
"body": "@RootTwo Yup, `Counter.most_common()` uses a heap; more specifically, it uses `heapq.nlargest()`. Which according to https://stackoverflow.com/a/23038826 and https://stackoverflow.com/a/33644135 it actually has a time complexity of O(h log k), where h is the total number of candidates."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:29:37.683",
"Id": "237154",
"ParentId": "237119",
"Score": "6"
}
},
{
"body": "<p>Its took time sometime but finally, I understood how we can solve this in <code>O (n)</code>.</p>\n<p>Since the vote counts are Integers we can use bucket sort or in the worst case, we can use radix sort to sort the leading candidates and the resulting time complexity will be <code>O(n)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-26T00:49:59.373",
"Id": "269377",
"ParentId": "237119",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "237154",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T02:48:58.427",
"Id": "237119",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"complexity"
],
"Title": "The optimized way to find the top k leading candidates from a unsorted hash map in python"
}
|
237119
|
<p>I wonder whether I included too many libraries; also can you point out obvious beginner mistakes?</p>
<p>Is the <code>while</code> loop the best for what I intend, or is there a better way?</p>
<p>Also, is it possible to put more into functions such that the <code>main()</code> looks like this:</p>
<pre><code>int main()
{
call function1
call function2
etc.
return 0;
}
</code></pre>
<pre><code>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
string random_line()
{
string line;
vector<string> lines;
srand(time(0));
//input file stream
ifstream file("wordlist.txt");
//count number of total lines in the file and store the lines in the string vector
int total_lines=0;
while(getline(file,line))
{
total_lines++;
lines.push_back(line);
}
//generate a random number between 0 and count of total lines
int random_number=rand()%total_lines;
//fetch the line where line index (starting from 0) matches with the random number
return lines[random_number];
}
int main()
{
string secret_word=random_line();
cout << secret_word; //this has to be cut at the end
int word_length=secret_word.length();
string guess_word="";
string guessed_letters="";
for (int i=0; i<word_length; ++i)
{
guess_word.append("_");
}
int remaining_fails=10;
string guess="";
while(remaining_fails!=0)
{
if(guess_word==secret_word)
{
cout << "Congratulations, the word is: "<<secret_word<<endl;
return 0;
}
else
{
cout << string(50, '\n');
cout << guess_word << endl;
cout << "Remaining fails: " << remaining_fails << endl;
cout << "Guessed letters: " << guessed_letters << endl;
cout << "Guess your letter!" << endl;
cin >> guess;
if(guess.length() !=1)
{
cout << "Please only enter one character!";
}
else if(strstr(secret_word.c_str(),guess.c_str()))
{
for(int i=0; i<word_length; ++i)
{
if (guess.at(0)==secret_word.at(i))
{
guess_word.at(i)=guess.at(0);
}
else
{
}
}
}
else
{
guessed_letters.append(guess);
remaining_fails--;
}
}
}
cout << "You loose!"<<endl;
return 0;
}
</code></pre>
<p>The wordlist.txt contains?</p>
<pre class="lang-none prettyprint-override"><code>word
trio
list
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T06:21:26.317",
"Id": "464863",
"Score": "0",
"body": "What you mean too many includes? Are you using symbols from each of them? If yes then no, if no then yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T06:32:32.290",
"Id": "464864",
"Score": "0",
"body": "@slepic ah ok, i do use symbols from each of them."
}
] |
[
{
"body": "<ol>\n<li><p>I'm not sure if I'd use the phrase \"too many\", but I think you've included a header or two you'd probably be better off without.</p>\n\n<p>The most obvious example would be <code><cstring></code>. There's rarely a good reason to use any of the <code><cstring></code> functions in C++ code (and I don't see any hint that this code is one of the rare exceptions either).</p>\n\n<p>Right now, the main (only?) thing I see you using from <code><cstring></code> is <code>strstr</code>. <code>std::string</code> has a <code>find</code> member that can find a substring like <code>strstr</code> does.</p></li>\n<li><p>Your code also seems somewhat inconsistent, at least to me. For example, in one place you create a string with N repetitions of a single character using code like: <code>std::string(character, repetitions)</code>. In another place you do roughly the same thing using a loop to append on underscore at a time. Since they're doing the same thing, it would be better for them to do it the same way (preferably the constructor for <code>std::string</code>).</p></li>\n<li><p>Right now you use a string to hold a single character (and enforce its being only one character). Since it's only a single <code>char</code>, I'd rather just use a <code>char</code> to hold it.</p></li>\n<li><p>As a general rule of thumb, I'd prefer a well-chosen algorithm from the standard library over a raw loop.</p></li>\n<li><p>Yes, you can (and in my opinion, should) break the code up into more functions (and based on your question, it seems like you already agree, but may not be sure how to do it).</p></li>\n<li><p>I'd generally prefer to use the new random-number generation routines in <code><random></code> over the <code>srand</code>/<code>rand</code> from the C library. Likewise, I'd rather use the distribution classes in the standard library over the <code>rand() % total_lines</code> you have now. (but in fairness, they are more work to use, and it's unlikely to make a difference anybody's likely to notice or care about (but in many other cases, it's more important).</p></li>\n<li><p>I'd avoid <code>using namespace std;</code> I know at first it seems painful to type in <code>std::</code> everywhere, but it's still better than <code>using namespace std;</code>.</p></li>\n<li><p>There are also neater ways to read words from a file into an array of strings, such as:</p>\n\n<pre><code>std::ifstream infile(\"wordlist.txt\");\n\nstd::vector<std::string>{std::istream_iterator<std::string>(infile), {}};\n</code></pre>\n\n<p>One point though: this will produce different results if your input file has multiple words on one line. In this case your code treats a whole line as one word, but this treats each word separately.</p></li>\n<li><p>I generally advise against using <code>std::endl</code>. It's probably harmless in this case, but a habit I'd try to avoid anyway.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:29:12.300",
"Id": "464867",
"Score": "0",
"body": "2. ah, nice catch, to be honest i put some of the code together like lego. What you mean with \"ctor\"? i googled it but i'm not quite sure, has it something with contructors to do?\n3. I thought you can do this operation only with the same types, thanks for pointing that out.\n4.does a good written program still have variables initialized in the main() or can that also be outsourced?\n7. would an alternative be to only write \"using std::cout\" to save a few \"std::\"s?\n8. that's huge, because most lists don't come in the format i need(ed)\n9. is std::endl always worse than \"\\n\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:37:01.687",
"Id": "464869",
"Score": "0",
"body": "@SAJW: Sorry. \"ctor\" is just a common shorthand for \"constructor\". Can certainly initialize things in main if it makes sense (e.g., things shared between the other functions). Use the smallest scope that works. Writing `using std::cout` is certainly preferable to `using namespace std;`anyway. Like I said, I've taken to advising against `std::endl` in general--even when you want exactly what it does, it's been so heavily abused by so many for so long that nobody will really know whether you wanted what it does, or just used it because everybody thinks they should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:01:15.727",
"Id": "464870",
"Score": "0",
"body": "so to avoid confusion wether i want what std::endl does i should be using std::flush instead (with \"\\n\")? (if i want what endl does)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:38:18.150",
"Id": "464939",
"Score": "0",
"body": "@SAJW: Yes. Usually you just want `stream << '\\n'`, but if you really want to flush as well, `stream << '\\n' << std::flush;` (with the proviso that this is my opinion, and others undoubtedly disagree)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:02:32.687",
"Id": "237125",
"ParentId": "237122",
"Score": "5"
}
},
{
"body": "<p>I have some observations not mentioned in <a href=\"/a/237125/75307\">Jerry Coffin's answer</a>.</p>\n\n<hr>\n\n<p>Prefer <code><cstdlib></code> over <code><stdlib.h></code>. The former puts its identifiers into the <code>std</code> namespace where we want them.</p>\n\n<hr>\n\n<p>To select one line at random from all the input lines, we don't need to store them all. There's a single-pass algorithm that selects each line with equal probability, that's quite simple to understand:</p>\n\n<ul>\n<li>Choose the first line with probability 1 (i.e. always).</li>\n<li>Read the second line, and with probability ½ choose it instead of the first.</li>\n<li>Read the third line, and with probability ⅓ choose it instead of one of the first two.</li>\n<li>Read the fourth line, and replace selected line with probability ¼.</li>\n<li>and so on...</li>\n</ul>\n\n<p>In code, that looks like this:</p>\n\n<pre><code>#include <istream>\n#include <random>\n#include <string>\n\n#include <utility>\n\nstd::string random_line(std::istream& input)\n{\n static auto gen = std::mt19937{std::random_device{}()};\n auto count = 0u;\n auto selected = std::string{};\n std::string line;\n while (std::getline(input, line)) {\n if (std::uniform_int_distribution{0u,count++}(gen) == 0) {\n selected = std::move(line);\n }\n }\n return selected;\n}\n</code></pre>\n\n<p>We can demonstrate it with a simple test program, that will pick one of six lines, approximately 20000 times each:</p>\n\n<pre><code>#include <iostream>\n#include <map>\n#include <sstream>\nint main()\n{\n auto const lines = \"one\\n\"\n \"two\\n\"\n \"three\\n\"\n \"four\\n\"\n \"five\\n\"\n \"six\\n\";\n auto counts = std::map<std::string,unsigned int>{};\n for (auto i = 0; i < 120000; ++i) {\n auto is = std::istringstream{lines};\n ++counts[random_line(is)];\n }\n\n {\n // print the counts\n auto is = std::istringstream{lines};\n std::string line;\n while (std::getline(is, line)) {\n std::cout << line << \": \" << counts[line] << '\\n';\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Always check whether reading input succeeded:</p>\n\n<blockquote>\n<pre><code> std::cin >> guess;\n</code></pre>\n</blockquote>\n\n<p>If we reach the end of input, then <code>guess</code> will be empty (or in C++03 and earlier, won't be written to), and we'll enter an infinite loop.</p>\n\n<p>Similarly, make sure that <code>file</code> is good after opening it in <code>random_line()</code>.</p>\n\n<p>Consider ignoring non-word characters (e.g. <code>!</code>, <code>@</code>, ...) as invalid input, unless your word list actually contains them. And consider being nice to the user if they enter a guess they've already tried - don't penalise that as a wrong guess.</p>\n\n<hr>\n\n<p>Minor: Spelling error in the final result:</p>\n\n<pre><code>std::cout << \"You lose!\\n\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T12:52:44.220",
"Id": "465255",
"Score": "0",
"body": "Hi, with your example the wordlist would be limited to a magic number(here: 120000) I specify in the code or?\nThanks for your answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T13:05:53.613",
"Id": "465258",
"Score": "0",
"body": "No, that magic number is just for the test program - it determines how many times we randomly select a line, before showing how many times each was selected. There's no limit to the number of entries in the wordlist, other than the maximum file size your platform supports."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-20T20:58:56.183",
"Id": "466076",
"Score": "0",
"body": "Hi, i tried to compile this but it says \"error: expected ')' before '{' token\" in the random_line function right at the if statement. Could you please fix it? Here is the pastebin: https://pastebin.com/L9Wz6ubk"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T12:26:00.573",
"Id": "466133",
"Score": "0",
"body": "oh, i had gcc version 8.2, i will try with the newest! thanks for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T12:32:58.397",
"Id": "466136",
"Score": "0",
"body": "It's the C++ version rather than GCC version that's important: I used `g++ -std=c++17 -Wall -Wextra` (GCC version 9.2), but it won't build with `-std=c++14`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T13:03:47.040",
"Id": "466140",
"Score": "0",
"body": "ah, i have used an old c++ standard, now with -std=c++17 it works just fine! thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T13:41:02.830",
"Id": "466146",
"Score": "0",
"body": "Ok, now everything goes fine, but: the counts are always the same if i start the program a few times, is this then a random \"enough\" method to choose a random line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T15:11:33.903",
"Id": "466174",
"Score": "0",
"body": "I get different counts each time (generally close to 20000 each); I don't understand why you don't. It's like your `std::random_device` isn't very random. You'd expect reproducible results if you wrote `static auto gen = std::mt19937{};` for example (using default seed instead of one from the random device)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T11:11:15.987",
"Id": "237139",
"ParentId": "237122",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237125",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:07:46.120",
"Id": "237122",
"Score": "1",
"Tags": [
"c++",
"beginner",
"hangman"
],
"Title": "A first Hangman game in C++"
}
|
237122
|
<p>I am new to C# and would appreciate it if you review my code. This code finds the anagrams in a list of string. Where can I be more efficient in my code? is there any way I can save memory?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
namespace RA
{
class Anagram
{
//private List<List<string>> anagrams;
public static List<List<string>> find(List<string> strList)
{
var anagrams = new List<List<string>>();
var anagramsTable = new Dictionary<string, List<string>>();
foreach (string str in strList)
{
var sortedStr = string.Concat(str.OrderBy(c => c));
string.Concat(sortedStr.OrderBy(c => c));
if (anagramsTable.ContainsKey(sortedStr))
{
anagramsTable[sortedStr].Add(str);
}
else
{
var values = new List<string>();
values.Add(str);
anagramsTable.Add(sortedStr, values);
}
}
foreach (var pair in anagramsTable)
{
anagrams.Add(pair.Value);
}
return anagrams;
}
static void Main(string[] args)
{
var words = new List<string>();
words.Add("ACT");
words.Add("CAT");
words.Add("TAC");
var anagrams = find(words);
foreach (var sublist in anagrams)
{
foreach (var item in sublist)
Console.Write(item + " ");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:29:52.900",
"Id": "464904",
"Score": "4",
"body": "The code works and passes all the tests. It is supposed to do that! For example, suppose that we have the following strings:\n“cat”, “dog”, “act”, “door”, “odor”\n\nThen we should return these sets: {“cat”, “act”}, {“dog”}, {“door”, “odor”}. I changed the title to group anagrams which I believe is more clear. If you only have \"XYZ\" in the initial list then it has to return that as a single element set {\"XYZ\"}."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:36:03.360",
"Id": "464905",
"Score": "0",
"body": "http://blog.gainlo.co/index.php/2016/05/06/group-anagrams/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T13:53:51.253",
"Id": "464909",
"Score": "3",
"body": "Ok, it seems to be a visualisation issue then. You should place a `Console.WriteLine()` after printing a `sublist`. Remove Close Vote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T00:51:19.837",
"Id": "464996",
"Score": "0",
"body": "For your future posts, note that there is no need to put \"(C#)\" in the title; that's what tags are for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T10:58:59.477",
"Id": "465076",
"Score": "0",
"body": "I think `(anagramsTable[sortedStr] ??= new List<string>()).Add(str)` should work instead of the if-else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T00:53:49.103",
"Id": "465186",
"Score": "0",
"body": "Note that you may accept one answer by clicking the check mark next to the answer that you think is the best."
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Please follow the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"noreferrer\">Capitalization Conventions</a>.</p></li>\n<li><p>Use meaningful names. </p>\n\n<ul>\n<li><code>strList</code> is bad in various ways: not only does it contain the name of its type (<code>List</code>), it also contains a pointless abbreviation. Why not name this input parameter <code>words</code>, the term you actually use in your <code>Main()</code>? </li>\n<li>Same for <code>str</code> or <code>sortedStr</code>. </li>\n<li><code>anagramsTable</code> does not tell me what it actually is. </li>\n<li><code>values</code> is too generic. </li>\n<li><code>RA</code> is an unintelligible namespace name.</li>\n</ul></li>\n<li><p>If you need to work with the value of a key in a dictionary, <a href=\"https://stackoverflow.com/a/9382740/648075\">use <code>TryGetValue()</code></a> instead of <code>ContainsKey()</code>. </p></li>\n<li><p>The <code>foreach (var pair in anagramsTable)</code> section can be replaced by a simple LINQ query.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:40:14.167",
"Id": "237145",
"ParentId": "237123",
"Score": "8"
}
},
{
"body": "<blockquote>\n<pre><code> var sortedStr = string.Concat(str.OrderBy(c => c));\n string.Concat(sortedStr.OrderBy(c => c));\n</code></pre>\n</blockquote>\n\n<p>I think the second line is redundant as you don't bind its result to anything.</p>\n\n<hr>\n\n<blockquote>\n <p><code>var anagrams = new List<List<string>>();</code></p>\n</blockquote>\n\n<p>This is also redundant, because you actually have the lists of anagram items in the dictionary. So instead of moving the anagram lists from the dictionary to this list, you can just query the dictionary like:</p>\n\n<pre><code>return anagramsTable.Select(kvp => kvp.Value).ToList();\n</code></pre>\n\n<p>at the end of the method.</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code> if (anagramsTable.ContainsKey(sortedStr))\n {\n anagramsTable[sortedStr].Add(str);\n }\n else\n {\n var values = new List<string>();\n values.Add(str);\n anagramsTable.Add(sortedStr, values);\n }\n</code></pre>\n</blockquote>\n\n<p>You should use (as BCdotWEB mentions) <code>TryGetValue()</code>:</p>\n\n<pre><code> if (!anagramsTable.TryGetValue(sortedStr, out var anagrams))\n {\n anagramsTable[sortedStr] = anagrams = new List<string>();\n }\n\n anagrams.Add(sortedStr);\n</code></pre>\n\n<hr>\n\n<p>You could go the full linq way though:</p>\n\n<pre><code>public static List<List<string>> find(List<string> strList)\n{\n return strList.GroupBy(s => string.Concat(s.OrderBy(c => c))).Select(gr => gr.ToList()).ToList();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:19:37.337",
"Id": "237160",
"ParentId": "237123",
"Score": "6"
}
},
{
"body": "<p>I won't repeat the germane critiques of the other answers, which are good. Rather than concentrating on the line-by-line improvements, I have some suggestions for the general organization of the code.</p>\n\n<p>First off, your general technique here is sound. But I want to describe two techniques you can use to make the code easier to read and understand, and to make more powerful tools that you can use in other projects.</p>\n\n<p>The first is to notice that <em>you have created a new data structure but done it in a completely ad-hoc way</em>. You have built a data structure called \"multidictionary\" -- that is, a dictionary that is a map from a key to a <em>set</em> of values -- out of a dictionary. That's great, but your code would be easier to read and better organized if you actually just made a multidictionary type!</p>\n\n<pre><code>sealed class Multidictionary<K, V>\n{\n private Dictionary<K, List<V>> dictionary = ...\n // Can you fill in the rest of this class?\n // Here are some methods you'll probably want:\n public void Add(K k, V v) { ... }\n public IEnumerable<K> Keys { get ... }\n public IEnumerable<IEnumerable<V>> Values { get ... }\n}\n</code></pre>\n\n<p>(Of course you can always download a professional multidictionary class; there are plenty of such packages available. But for the learner it is skill-building to make your own.)</p>\n\n<p>Once you have that class, look at how much nicer your main algorithm gets:</p>\n\n<pre><code> var anagramsTable = new Multidictionary<string, string>();\n foreach (string str in strList)\n anagramsTable.Add(string.Concat(str.OrderBy(c => c), str);\n var anagrams = anagramsTable.Values\n .Select(vs => vs.ToList()).ToList();\n</code></pre>\n\n<p>By offloading the boring mechanical details into its own class, the <em>meaning</em> of the code becomes very clear. What are we doing? Putting each string into a multidictionary keyed on a canonicalization, then extracting the values of that multidictionary into a list of lists. The code makes it very clear what is happening.</p>\n\n<p>Some of the other answers have suggested that you can do the same with <code>GroupBy</code>. That is completely accurate. <strong>You now have some insight into how <code>GroupBy</code> is implemented</strong>. <code>GroupBy</code> constructs a multidictionary behind the scenes!</p>\n\n<p>Let's for the sake of pedagogy assume that <code>GroupBy</code> does not exist or you are not familiar with it. Can we improve this further? Yes, by again seeing that there is a generalization. What are you <em>really</em> doing here, <em>in general</em>? <em>You are taking a set and partitioning it into equivalence classes.</em></p>\n\n<p>In case you are not familiar with this jargon, let me give you a brief explanation. An <em>equivalence relation</em> is a function that takes two things and returns a Boolean that means \"equivalent\" if true and \"not equivalent\" if false. </p>\n\n<p>Equivalence relations follow three rules:</p>\n\n<ul>\n<li>X is always equivalent to itself no matter what X is. This is the <em>reflexive property</em>.</li>\n<li>The equivalence of X and Y is the same as the equivalence of Y and X. This is the <em>symmetric property</em>.</li>\n<li>If X is equivalent to Y and Y is equivalent to Z then X must be equivalent to Z. This is the <em>transitive property</em>.</li>\n</ul>\n\n<p>The two most basic equivalence relations are the two extremes. Equality -- two things are equivalent if they are exactly equal and unequivalent otherwise -- is the equivalence relation where the least number of things are equivalent to each other, and \"everything is equivalent to everything\" is the one with the most. </p>\n\n<p>The tricky bit comes when we have equivalences that are somewhere in the middle. \"Two strings are equivalent if they are anagrams of each other\" is an equivalence relation (exercise: check that all three properties are met).</p>\n\n<p>If you have a set of things -- strings in your case -- then a <em>partition into equivalence classes</em> is what you are doing. You are finding all the subsets of those strings which are equivalent to each other; that subset is called an \"equivalence class\". </p>\n\n<p>As you have discovered, an efficient algorithm for partitioning a set into its equivalence classes is the algorithm:</p>\n\n<ul>\n<li>For each member of the set, find the \"canonical value\" of the equivalence class, even if that member is not in the set itself. That is in your case, the <em>smallest string in lexicographic order that is equivalent to the given string</em>.</li>\n<li>Group the members of the set on <em>equality of their associated canonical value</em>.</li>\n</ul>\n\n<p>So my challenge to you is: can you implement this algorithm?</p>\n\n<pre><code>static List<List<T>> Partition(\n this IEnumerable<T> items,\n Func<T, T> canonicalize)\n{ ... }\n</code></pre>\n\n<p>If you can, then your specific problem becomes a one-liner!</p>\n\n<pre><code>var anagrams = items.Partition(s => string.Concat(s.OrderBy(c => c));\n</code></pre>\n\n<p>And you will then have a new tool in your toolbox. I use the partition-by-canonical-value function all the time in my work.</p>\n\n<p>Again, this is just a special case of <code>GroupBy</code>, as noted in other answers. However, consider now this challenge. Suppose we do not have a canonicalizer but we do have a relation:</p>\n\n<pre><code>static List<List<T>> Partition(\n this IEnumerable<T> items,\n Func<T, T, bool> relation)\n{ ... }\n</code></pre>\n\n<p>Can you come up with an efficient implementation of the partition function <em>only</em> having a predicate which tells you when two things are equivalent? Remember that you are allowed to take advantage of the reflexive, symmetric and transitive properties of the relation. A naive algorithm is straightforward but this is a surprisingly tricky problem to make efficient. The paper <a href=\"https://link.springer.com/chapter/10.1007%2F978-3-319-21840-3_36\" rel=\"noreferrer\">https://link.springer.com/chapter/10.1007%2F978-3-319-21840-3_36</a> has an analysis of this problem if it interests you.</p>\n\n<p>Another exercise to consider: suppose your original list contains duplicates. Is it correct to have duplicates in the output list of lists? Or should they be deduplicated? Can you modify the algorithms you've created so far to ensure that they are efficiently deduplicated?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T19:47:13.367",
"Id": "464973",
"Score": "2",
"body": "Don't break your tongue when pronouncing `c a n o n i c a l i z a t i o n`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T20:17:21.020",
"Id": "464974",
"Score": "2",
"body": "@OlivierJacot-Descombes: A key problem faced by leads when partner dancing is clearly indicating what move you're setting up for you and the follow to do next. I once was taking a class and asked the instructors \"what disambiguates (pattern X) from (similar pattern Y) for the follow?\" and got plenty of ribbing for using the five dollar word \"disambiguates\" in a dance class. It was ambiguous as presented, what else can I say? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:47:00.847",
"Id": "465159",
"Score": "1",
"body": "@OlivierJacot-Descombes: I hereby declare that people who oppose producing canonicalized forms before they are needed are antiprecanonicalizationists, and that the study of those people is antiprecanonicalizationistology."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T20:45:52.200",
"Id": "465165",
"Score": "1",
"body": "Definitely not suited for dance classes!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T05:48:57.283",
"Id": "465200",
"Score": "1",
"body": "@EricLippert [Here](https://codereview.stackexchange.com/a/237273/218343) I did some refactoring as you suggested except the last question."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:36:14.233",
"Id": "237176",
"ParentId": "237123",
"Score": "22"
}
},
{
"body": "<p>Other answers have pointed out the code issues, but you also asked about potential improvements in efficiency. Currently this program runs comparisons in <strong>O(n log n)</strong> time (per comparison), mainly due to the sorting algorithm. (Any default library sorting algorithm is going to have average case <strong>O(n log n)</strong> time.) Can we do better? Sure. This problem can be solved in <strong>O(2n + 2m)</strong> time (<strong>n</strong> being the number of characters per word and <strong>m</strong> being the number of unique letters in each word, strictly equal to or less than <strong>n</strong> by definition, so worst case <strong>O(4n)</strong>):</p>\n\n<ol>\n<li>Make a <code>Dictionary<char, int></code>. (Maybe change <code>int</code> to <code>long</code> if you're testing <em>really</em> big data...)</li>\n<li>For each character in the string, if its key is not in the dictionary, add it, setting the value to 1. If it is in the dictionary, add 1 to its value. This gives you a list of counts for each character in the string.</li>\n<li>For each character in the other strings to compare, simply repeat 1 and 2.</li>\n<li>Loop through keys on the dictionaries and compare your counts. If any key exists in one dictionary and not the other, or there are two values with different counts, the words are not anagrams. Otherwise, they are.</li>\n</ol>\n\n<p>Note: This comes at the expense of a some memory to store those dictionaries, but that's usually the case when you trade one resource (memory) for another (time). The benefits most likely won't be noticeable for small data sets like yours (your longest example has only 4 letters), but for larger data sets, this algorithm will scale more gracefully.</p>\n\n<p>You could also improve on this with some obvious sanity checks: e.g. if the strings are not the same length you can immediately return <code>false</code> without even bothering to check anything else, etc.</p>\n\n<p>If you're only comparing 2 words, you could also combine the last 2 steps - only keep one dictionary, and on the second word you decrease the counts in the dictionary for each letter (immediately shortcut returning <code>false</code> if a key is not found in the second word, and removing any entry whose count is reduced to 0), then check that the dictionary is empty at the end. (This only works for comparing just 2 words, because it destroys the dictionary in the process, but might be more efficient overall.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T11:17:38.783",
"Id": "465082",
"Score": "0",
"body": "So TL:DR you're proposing CountingSort with a dictionary of counts, and using that dictionary itself as the key. That's only going to be an overall perf win for *very* large words, much longer than typical dictionary words, compared to using flat strings as keys. CountingSort and then serializing the result into a compact format (like run-length encoding for repeated digits using decimal or octal digits) could be good, though. e.g. the key for \"dabccbdbd\" is `ab4c2d3`. You can already compare string lengths as an early out to string compare, if that doesn't happen internally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T11:20:32.833",
"Id": "465083",
"Score": "0",
"body": "Having separate top-level anagram dictionaries for each word length could maybe speed lookups, too. (Maybe call them chapters, like the sections in a paper crossword dictionary.) And BTW, string compare can go very fast; a good implementation should compare 16 bytes at a time for long strings on typical CPUs, so looping over keys of a dictionary is probably a lot worse than looping over a flattened string (especially with run-length encoding in the serialization format.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:26:38.043",
"Id": "465107",
"Score": "0",
"body": "@PeterCordes Yeah, I did specify that the advantages would only be noticeable for larger input, but only because the OP specifically asked for ways to improve efficiency. For smaller values of **n**, this is definitely overkill, and maybe not the best choice, but generally when you're asking about efficiency, it's because you're considering the possibility of **n** being larger, in which case this method might be the way to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:45:17.763",
"Id": "465109",
"Score": "0",
"body": "I understand that, but I'm optimizing for the more-likely case of feeding this program a full dictionary word list so you have *many* words to group, but each of them are small. (e.g. run it on `/usr/share/dict/words` to find all groups of dictionary-word anagrams, or to populate the data structure for queries with phrases from crossword clues). My proposed run-length-encoded flat string is I think better than using whole dictionaries as keys for both the huge-word case and the many-words case. (And the many huge words case)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T22:19:53.193",
"Id": "237191",
"ParentId": "237123",
"Score": "1"
}
},
{
"body": "<p>Answering questions of @Eric Lippert, I have done some refactoring.</p>\n\n<p>The <code>Multidictionary</code> class I implemented as follow</p>\n\n<pre><code>public class Multidictionary<K, V>\n{\n private Dictionary<K, List<V>> dictionary;\n\n public Multidictionary()\n {\n dictionary = new Dictionary<K, List<V>>();\n }\n\n public void Add(K k, V v)\n {\n List<V> list;\n dictionary.TryGetValue(k, out list);\n if (list == null)\n {\n list = new List<V>();\n dictionary.Add(k, list);\n }\n list.Add(v);\n }\n\n public IEnumerable<K> Keys { get { return dictionary.Keys; } }\n\n public IEnumerable<IEnumerable<V>> Values\n {\n get { return dictionary.Values; }\n }\n}\n</code></pre>\n\n<p>Now to find anagrams, we can use <code>Multidictionary</code>.</p>\n\n<pre><code> var words= new List<string>() { \"litu\", \"flit\", \"lift\", \"lute\", \"tule\", \"etui\", \"lieu\", \"lite\", \"tile\", \"flue\", \"fuel\", \"felt\", \"left\", \"file\", \"lief\", \"life\", \"flub\", \"bute\", \"tube\", \"blue\", \"lube\", \"belt\", \"blet\", \"bite\", \"bile\", \"luau\", \"latu\", \"alit\", \"lati\", \"tail\", \"tali\", \"tufa\", \"flat\", \"fiat\", \"alif\", \"fail\", \"fila\", \"late\", \"tael\", \"tale\", \"teal\", \"tela\", \"ilea\", \"fate\", \"feat\", \"feta\", \"alef\", \"feal\", \"flea\", \"leaf\", \"abut\", \"tabu\", \"tuba\", \"blat\", \"bait\", \"bail\", \"flab\", \"beau\", \"abet\", \"bate\", \"beat\", \"beta\", \"able\", \"bale\", \"blae\" };\n var anagramDictionary = new Multidictionary<string, string>();\n words.ForEach(word => anagramDictionary.Add(string.Concat(word.OrderBy(c => c)), word));\n var anagrams = anagramDictionary.Values.Select(vs => vs);\n</code></pre>\n\n<p>Another way, we can write <code>Partition</code> function as @Eric Lippert suggested using <code>GroupBy</code>.</p>\n\n<pre><code>public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> items, Func<T, T> canonicalize)\n{\n return items.GroupBy(_ => canonicalize(_)).Select(_ => _);\n}\n</code></pre>\n\n<p>In this way solution is one liner</p>\n\n<pre><code>var groups = words.Partition(s => string.Concat(s.OrderBy(c => c)));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-14T05:46:41.893",
"Id": "237273",
"ParentId": "237123",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T04:15:35.740",
"Id": "237123",
"Score": "14",
"Tags": [
"c#"
],
"Title": "Group Anagrams (C#)"
}
|
237123
|
<p>I am looking for general critique of my code and notice of any bugs or errors.
I have included the main file and the class files. Also, I'm wondering where would I need comments. Sorry it is such a monster ;).</p>
<pre><code>
#include <iostream>
#include <string>
#include <fstream>
#include "rooms.h"
#include "characters.h"
#include<bits/stdc++.h>
using namespace std;
struct Coord {
int x;
int y;
};
void save(vector<vector<Rooms>>& map, Characters& player, int numTurns);
void createOriginalSave(); // Creates original.txt
int load(string filename, vector<vector<Rooms>>& map, Characters& player, vector<Characters>& npcs); // Loads object data from save file
Coord move(string in, vector<vector<Rooms>> map, int x, int y, Characters& player, int moves);
int score (double moves, Characters& player);
void help();
void take(string in, vector<vector<Rooms>>& map, Characters& player);
void end(double moves);
int main() {
createOriginalSave();
int numberRows = 18;
int numberCols = 18;
int numTurns = 0;
Characters player("player");
vector<vector<Rooms>> map;
vector<Characters> npcs;
map.resize(numberRows, vector<Rooms>(numberCols));
string input;
int num;
string out;
cout << " _ _ _ _ _ _ \n"
" /_\\ /\\/\\ __ _ __ _(_) ___ __ _| | /_\\ __| |_ _____ _ __ | |_ _ _ _ __ ___ \n"
" //_\\\\ / \\ / _` |/ _` | |/ __/ _` | | //_\\\\ / _` \\ \\ / / _ \\ '_ \\| __| | | | '__/ _ \\\n"
"/ _ \\ / /\\/\\ \\ (_| | (_| | | (_| (_| | | / _ \\ (_| |\\ V / __/ | | | |_| |_| | | | __/\n"
"\\_/ \\_/ \\/ \\/\\__,_|\\__, |_|\\___\\__,_|_| \\_/ \\_/\\__,_| \\_/ \\___|_| |_|\\__|\\__,_|_| \\___|\n"
" |___/ " << endl;
cout << "By Ian Herman" << endl;
help();
cout << endl;
cout << "What save would you like to load from? Type original to start a new game." << endl;
cin >> input;
numTurns = load(input, map, player, npcs);
out = map[player.getX()][player.getY()].getDescription();
while (out.find('.') != -1) {
num = out.find('.');
if (num != -1) {
out.replace(num, 1, "\n");
}
}
cout << out << endl;
for (int i = 0; true; i++){
cin >> input;
Coord newPlayerCoords;
transform(input.begin(), input.end(), input.begin(), ::tolower);
if (input == "north") input = "n";
else if (input == "south") input = "s";
else if (input == "east") input = "e";
else if (input == "west") input = "w";
else if (input == "u") input = "up";
else if (input == "d") input = "down";
if (input == "up" || input == "down" || input == "n" || input == "s" || input == "w" || input == "e") {
newPlayerCoords = move(input, map, player.getX(), player.getY(), player, i);
player.setLocation(newPlayerCoords.x, newPlayerCoords.y);
}
else if (input == "look") {
out = map[player.getX()][player.getY()].getDescription();
while (out.find('.') != -1) {
num = out.find('.');
if (num != -1) {
out.replace(num, 1, "\n");
}
}
cout << out << endl;
}
else if (input == "hint") {
cout << map[player.getX()][player.getY()].getHint() << endl;
}
else if (input == "quit") {
return 0;
}
else if (input == "inventory") {
if (player.getInventory().size() != 0) {
cout << "Your inventory contains the following:" << endl;
for (int j = 0; j < player.getInventory().size(); j++) {
cout << player.getInventory()[j] << endl;
}
} else {
cout << "You have nothing." << endl;
}
}
else if (input == "help") {
help();
}
else if (input == "save") {
save(map, player, i);
}
else if (input == "take") {
cin >> input;
take(input, map, player);
}
else if (input == "score") {
cout << "Your score is " << score(static_cast<double >(i), player) << "%" << endl;
i--;
}
else {
cout << "¿Hablas Inglés?" << endl;
}
map[player.getX()][player.getY()].incrementActionCount();
}
}
int score (double moves, Characters& player) {
static int scr = 100;
if (player.getX() == 1 && player.getX() == 1) {
scr = 100/moves;
} else if (player.getX() == 6 && player.getY() == 1) {
scr = (4.0/moves) * 100.0;
} else if (player.getX() == 10 && player.getY() == 1) {
scr = (8.0/moves) * 100.0;
} else if (player.getX() == 13 && player.getY() == 3) {
scr = (12.0/moves) * 100.0;
} else if (player.getX() == 14 && player.getY() == 6) {
scr = (18.0/moves) * 100.0;
} else if (player.getX() == 11 && player.getY() == 4) {
scr = (23.0/moves) * 100.0;
}
return scr;
}
void save(vector<vector<Rooms>>& map, Characters& player, int numTurns) {
string name;
ofstream outfile;
cout << "WARNING: DO NOT SAVE DURING COMBAT, CURRENT COMBAT PROGRESS WILL NOT BE SAVED" << endl;
cout << "Enter save name, enter same name of pre-existing save to overwrite it, save name original will not work." << endl;
cin >> name;
name = name + ".txt";
outfile.open(name.c_str());
for (int i = 0; i < 17; i++) {
for (int j = 0; j < 17; ++j) {
if (!map[i][j].getEmpty()) {
outfile << "Room:" << endl;
outfile << i << " " << j << endl;
outfile << map[i][j].getName() << endl;
outfile << map[i][j].getDescription() << endl;
for (int k = 0; i < map[i][j].getInventory().size(); i++) {
outfile << map[i][j].getInventory()[k] << " ";
}
outfile << "null";
outfile << endl;
outfile << map[i][j].getHint() << endl;
outfile << map[i][j].getActions() << endl;
}
}
}
outfile << "Player:" << endl;
outfile << player.getX() << " " << player.getY() << endl;
outfile << player.getHealth() << " " << player.getMaxHealth() << endl;
outfile << player.getMana() << " " << player.getMaxMana() << endl;
for(int i = 0; i < player.getInventory().size(); i++) {
outfile << player.getInventory()[i] << " ";
}
outfile << "null" << endl;
outfile << numTurns;
outfile.close();
cout << "Save Completed." << endl << endl;
}
int load(string filename, vector<vector<Rooms>>& map, Characters& player, vector<Characters>& npcs) {
string in;
string in2 = " ";
filename = filename + ".txt";
ifstream infile;
int x, y;
int numIn;
infile.open(filename.c_str());
while(!infile.good()) {
infile.close();
cout << "Save does not exist, please enter valid save." << endl;
cin >> filename;
filename += ".txt";
infile.open(filename.c_str());
}
infile >> in;
while (in != "Player:") {
infile >> x >> y;
infile >> in;
map[x][y].setName(in);
infile.ignore(1000, '\n');
getline(infile, in);
map[x][y].setDescription(in);
while (true) {
if (infile.peek() == '\n') break;
else {
infile >> in2;
if (in2 == "null") break;
map[x][y].addItem(in2);
}
}
infile.ignore(1000, '\n');
getline(infile, in);
map[x][y].setHint(in);
infile >> numIn;
map[x][y].setActions(numIn);
infile >> in;
map[x][y].setEmpty(false);
}
//Load player data
infile >> x >> y;
player.setLocation(x,y);
infile >> numIn;
player.setHealth(numIn);
infile >> numIn;
player.setMaxHealth(numIn);
infile >> numIn;
player.setMana(numIn);
infile >> numIn;
player.setMaxMana(numIn);
while (true) {
infile >> in2;
if (in2 == "null") break;
player.addItem(in2);
}
infile >> numIn; // Takes in number of turns
infile.close();
return numIn;
}
Coord move(string in, vector<vector<Rooms>> map, int x, int y, Characters& player, int moves) {
Coord coords;
coords.x = x;
coords.y = y;
int num;
string out;
//This is a lot of super ugly and complex control structures that you don't want to read, please don't.
if (x == 1 && y == 1) {
if (in == "down") {
coords.x = 3;
coords.y = 1;
} else {
cout << "You run into a wall!" << endl;
}
} else if (x == 3 && y == 1 && in == "up") {
coords.x = 1;
coords.y = 1;
} else if (x == 0 && y == 0) {
if (in == "n") {
coords.x = 7;
coords.y = 4;
} else {
cout << "You run into a wall!" << endl;
}
}
else if ((y > 5 && x > 3) || (x >= 10 && y >= 3)) {
if (in == "n") {
if (y == 3 && x == 13) {
coords.x = 13;
coords.y = 1;
}
else if (map[x][y - 1].getEmpty()){
cout << "You run into a wall!" << endl;
} else {
coords.y--;
}
} else if (in == "s") {
if (y == 6 && x == 15) {
coords.x = 13;
coords.y = 4;
if(find(map[13][4].getInventory().begin(), map[13][4].getInventory().end(), "straw") == map[13][4].getInventory().end()) {
player.setHealth(player.getHealth()-2);
cout << "You slide down the chute spiraling deeper into the earth." << endl;
cout << "Suddenly, you are ejected into the air in another chamber, you fall down to the ground and hit the cold, hard floor. You take 2 damage." << endl;
} else {
cout << "You slide down the chute spiraling deeper into the earth." << endl;
cout << "Suddenly, you are ejected into the air in another chamber, you fall down on to a soft pile of straw, cushioning your fall." << endl;
}
} else if (x == 11 && y == 5) {
cout << "The sphinx blocks the door and says \" You may pass and enter my room of treasure if you solve my riddle, it goes like this\n "
"\'Six letters long\n"
"Guess if you choose\n"
"I am all but everything\n"
"I have nothing to lose\'\" " << endl;
cin >> out;
if (out == "vacuum") {
cout << "Alas, you have beaten me, go forth and take what you must." << endl;
coords.y++;
} else {
cout << "Wrong! You can try again if you so choose." << endl;
}
}
else if (map[x][y + 1].getEmpty()){
cout << "You run into a wall!" << endl;
}
else if (y == 8 && x == 5) {
end(static_cast<double > (moves));
}
else {
coords.y++;
}
} else if (in == "e") {
if (x == 5 && y == 7) {
coords.x = 10;
coords.y = 4;
}
else if (map[x + 1][y].getEmpty()){
cout << "You run into a wall!" << endl;
}
else if (x == 12 && y==4) {
if (find(player.getInventory().begin(), player.getInventory().end(), "amulet") != player.getInventory().end()) {
cout << " The amulet picks you up and flies you across the fissure." << endl;
coords.x = 13;
coords.y = 4;
}
else {
coords.x = 13;
coords.y = 4;
}
}
else {
coords.x++;
}
} else if ( in == "w") {
if (x == 10 && y==4) {
coords.x = 5;
coords.y = 7;
}
else if (map[x - 1][y].getEmpty()){
cout << "You run into a wall!" << endl;
}
else if (x == 12 && y==4) {
if (find(player.getInventory().begin(), player.getInventory().end(), "amulet") != player.getInventory().end()) {
cout << " The amulet picks you up and flies you across the fissure." << endl;
coords.x = 11;
coords.y = 4;
}
else {
cout << " Falling hundreds of feet may cause death." << endl;
}
}
else {
coords.x--;
}
}
}
else {
if (in == "n") {
if (y==1 && x < 10){
cout << "Are you TRYING to DIE?" << endl;
} else if (map[x][y].getName() == "apothecary") {
coords.x = 10;
coords.y = 1;
} else if (map[x][y].getName() == "blacksmith") {
coords.x = 11;
coords.y = 1;
}
else {
coords.y--;
}
} else if (in == "s") {
if (y==5 || (x == 12 && y == 1) || (x == 9 && y == 1)) {
cout << "You cannot cross the river on foot, but there may be another way." << endl;
}
else if (map[x][y].getName() == "library") {
coords.x = 10;
coords.y = 1;
}
else if (map[x][y].getName() == "tavern") {
coords.x = 11;
coords.y = 1;
}
else if (x == 13 && y == 1) {
coords.x = 13;
coords.y = 3;
}
else{
coords.y++;
}
} else if (in == "e") {
if (x == 13 && y <3) {
cout << "If you enter the forest it is likely you will be mutilated by a bear." << endl;
} else if (x == 8 && y < 6 && y > 1) {
cout << "You cannot cross the river on foot, but there may be another way." << endl;
} else if (x == 10 && y == 4) {
coords.x = 5;
coords.y = 7;
} else {
coords.x++;
}
} else if ( in == "w") {
if (x == 3) {
cout << "If you enter the forest it is likely you will be eaten by a Grue" << endl;
} else {
coords.x--;
}
}
}
if (coords.x == 7 && coords.y == 5) {
if(in == "s") {
coords.x = 0;
coords.y = 0;
} else {
cout << "You run into the side of the shack!" << endl;
coords.x = x;
coords.y = y;
}
} else if (coords.x == 11 && coords.y == 0) {
if (in == "n") {
coords.x = 0;
coords.y = 3;
} else {
cout << "You run into a wall!" << endl;
}
} else if (coords.x == 10 && coords.y == 0) {
if (in == "n") {
coords.x = 1;
coords.y = 4;
} else {
cout << "You run into a wall!" << endl;
}
} else if (coords.x == 10 && coords.y == 2) {
if (in == "s") {
coords.x = 0;
coords.y = 5;
} else {
cout << "You run into a wall!" << endl;
}
} else if (coords.x == 11 && coords.y == 2) {
if (in == "s") {
coords.x = 1;
coords.y = 6;
} else {
cout << "You run into a wall!" << endl;
}
}
out = map[coords.x][coords.y].getDescription();
while (out.find('.') != -1) {
num = out.find('.');
if (num != -1) {
out.replace(num, 1, "\n");
}
}
cout << out << endl;
return coords;
}
void help() {
cout << "This is a text based adventure game, you type commands into the terminal and the game will respond accordingly." << endl;
cout << "All commands MUST be lower-case AND MUST spelled correctly." << endl;
cout << "By using north, south, east, and west commands you can navigate through the game." << endl;
cout << "These commands can be shortened to their one letter variants: n, s, e, & w." << endl;
cout << "Sometimes you may have to move by using the up & down commands; they can also be shortened." << endl;
cout << "Use the inventory command to get a list of all the items contained within your inventory." << endl;
cout << "Use the save command to save the game state to a save file." << endl;
cout << "Use the take command to take items" << endl;
cout << "Use the help command to view these instructions and the quit command to exit the game." << endl;
cout << "Cave passages are twisty, the tunnels may not always behave the way you assume." << endl;
cout << "Any questions, comments, or concerns may be emailed to iankherman@gmail.com" << endl;
cout << "WARNING: We are not responsible for any serious injury or death caused by the playing of this game." << endl;
cout << "Thank you and enjoy!" << endl;
cout << endl;
}
void take(string in, vector<vector<Rooms>>& map, Characters& player) {
int x = player.getX();
int y = player.getY();
if (map[x][y].getName() == "library" || map[x][y].getName() == "tavern" || map[x][y].getName() == "apothecary" || map[x][y].getName() == "blacksmith") {
cout << "You decide against taking anything from this town, you feel as though a great amount has already been taken from it." << endl;
} else if (map[x][y].getName() == "sphinx_treasure" && in == "gold") {
cout << "You pick up some gold and put it in your knapsack." << endl;
player.addItem("gold");
} else if (map[x][y].getName() == "sphinx_treasure" && in == "jewels") {
cout << "You pick up some gems and put them in your knapsack." << endl;
player.addItem("gems");
} else if (map[x][y].getName() == "pit" && in == "amulet") {
cout << "As you place the amulet around your neck, suddenly it picks you up by the neck and flies you out over the pit, then it safely returns you to the platform." << endl;
map[x][y].setDescription("You are on a large stone platform over a MASSIVE pit, it seems to span on for miles!");
player.addItem("amulet");
map[x][y].removeItem("amulet");
} else if (map[x][y].getName() == "cave_branch" && in == "straw") {
cout << "You take the straw and stuff it into your knapsack." << endl;
map[x][y].removeItem("straw");
map[x][y].setDescription("Here the tunnel heads south, a small crack in the wall leads east, in front of you there is a chute high above the ground.");
player.addItem("straw");
} else if (map[x][y].getName() == "fork_room" && in == "fork") {
cout << "hah, you pick up the fork lol"<< endl;
}
}
void end(double moves) {
cout << "As you enter the room, you are splashed with confetti, and loud horns blare a melody. In front of you are many people, in the middle of them is a tall man, cloaked in wizards garb. \n He shouts \" Congradulations! You have passed my test, this marks your first day as the ruling wizard of this land. "
"\nAll these trials were to test your problem solving ability, so I could be sure I had a worthy heir, I knew you could do it! \n After this everyone made there way back up to the surface, where two pavillions were pitched, you all had a great feast and lived happily ever after! " << endl;
cout << "Your final score was " << ((27.0/moves) * 100);
exit(1);
}
void createOriginalSave() {
ofstream outfile;
outfile.open("original.txt");
outfile << "Room:\n";
outfile << "1 1\n";
outfile << "start\n";
outfile << "You are standing in a wizards tower, to your left and right are stained glass windows. On nearby shelves are various jars with strange pickled things, unfortunately these things are out of your reach. There is a staircase leading down from the tower.\n";
outfile << "null\n";
outfile << "GO DOWN GENIUS!!\n";
outfile << "1\n";
outfile << "Room:\n";
outfile << "3 1" << endl;
outfile << "tower_outside" << endl;
outfile << "You are outside a tall tower, ahead of you is a long dirt road. To the north is a deep ravine and to your the south is endless countryside. To your west is a dark, thick forest." << endl;
outfile << "null" << endl;
outfile << "Take THE ROAD *facepalms*" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "3 2" << endl;
outfile << "country_1" << endl;
outfile << "You are in the countryside, the forest is to your west & the wizard's tower is to the north." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "3 3" << endl;
outfile << "country_2" << endl;
outfile << "You are in the countryside, the forest is to your west." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "3 4" << endl;
outfile << "country_3" << endl;
outfile << "You are in the countryside, the forest is to your west." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "3 5" << endl;
outfile << "country_4"<< endl;
outfile << "You are in countryside, the forest is to your west, also, there is a large, fast moving river to the south." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "4 5" << endl;
outfile << "country_5"<< endl;
outfile << "You are in countryside, there is a large, fast moving river to the south." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "4 4" << endl;
outfile << "country_6" << endl;
outfile << "You are in the countryside." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "4 3" << endl;
outfile << "country_8" << endl;
outfile << "You are in the countryside, to the east is a large hill." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "4 2" << endl;
outfile << "country_9" << endl;
outfile << "You are in the countryside, to the north is the road." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 2" << endl;
outfile << "country_10" << endl;
outfile << "You are in the countryside, to the north is the road & to the south is a large hill." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 3" << endl;
outfile << "hill" << endl;
outfile << "After a brisk climb to the top of the hill, you finally look around you. On the top of the hill is a tall oak tree, providing much needed shade from the summer heat. From the tree you can see a town to the north-east and a hut to the south-east. There is also a path leading to the hut from the road, it passes by right at the foot of the hill." << endl;
outfile << "null" << endl;
outfile << "Head for the town" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 4" << endl;
outfile << "country_7" << endl;
outfile << "You are in the countryside, to the north is a large hill." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 5" << endl;
outfile << "country_11" << endl;
outfile << "You are in the countryside, to the south is a large, fast moving river." << endl;
outfile << "null" << endl;
outfile << "Maybe go back to the road?" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "4 1" << endl;
outfile << "road_1" << endl;
outfile << "You are on the road, and it is a beautiful day :)." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 1" << endl;
outfile << "road_2" << endl;
outfile << "You continue on the flat dirt road, not paying attention to anything else." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "6 1" << endl;
outfile << "road_3" << endl;
outfile << "Here there is a a small dirt path leading away from the road to the south." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "6 2" << endl;
outfile << "path_1" << endl;
outfile << "You are on a little, windy dirt path. To the north is the road." << endl;
outfile << "null" << endl;
outfile << "Go back!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "6 3" << endl;
outfile << "path_2" << endl;
outfile << "You are on a little, windy dirt path. To the west is a large hill." << endl;
outfile << "null" << endl;
outfile << "Go back!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "6 4" << endl;
outfile << "path_4" << endl;
outfile << "You are on a little, windy dirt path, here it turns eastward." << endl;
outfile << "null" << endl;
outfile << "Go back!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "7 4" << endl;
outfile << "witch_out_1" << endl;
outfile << "You are on the north side of a small wooden shack, on this side, there is a door. To the west a small dirt path winds away." << endl;
outfile << "null" << endl;
outfile << "Go south to enter the house dummy!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "6 5" << endl;
outfile << "witch_out_2" << endl;
outfile << "You are on the west side of a small wooden shack. To the north a small dirt path winds away, and to the south is a large, fast moving river." << endl;
outfile << "null" << endl;
outfile << "Enter the house dummy!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "8 5" << endl;
outfile << "witch_out_3" << endl;
outfile << "You are on the east side of a small wooden shack. To the south is a large, fast moving river. Here, the river turns to the north blocking you from traveling east." << endl;
outfile << "null" << endl;
outfile << "Enter the house dummy!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "0 0" << endl;
outfile << "witch" << endl;
outfile << "When you enter the shack you immediately notice how dark it is. There is a small bed in the corner and a long counter spanning the other wall. There are various herbs hanging from the ceiling. In the middle of the room is a large cauldron with a strange potion brewing in it." << endl;
outfile << "null" << endl;
outfile << "TALK to the witch." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "8 4" << endl;
outfile << "outhouse" << endl;
outfile << "You are in the countryside, there is an outhouse here. To the east is a large, fast moving river." << endl;
outfile << "null" << endl;
outfile << "Go back!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "8 3" << endl;
outfile << "countryside_12" << endl;
outfile << "You are in the countryside, to the east is a large, fast moving river." << endl;
outfile << "null" << endl;
outfile << "Go back to the road." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "8 2" << endl;
outfile << "countryside_13" << endl;
outfile << "You are in the countryside, to the east is a large, fast moving river. To the north is the road." << endl;
outfile << "null" << endl;
outfile << "Go back to the road." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "7 1" << endl;
outfile << "road_4" << endl;
outfile << "You are on yet another segment of road." << endl;
outfile << "null" << endl;
outfile << "Continue." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "7 2" << endl;
outfile << "countryside_14" << endl;
outfile << "You are in the countryside, to the north is the road." << endl;
outfile << "null" << endl;
outfile << "Go back to the road." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "7 3" << endl;
outfile << "countryside_15" << endl;
outfile << "You are in the deep countryside." << endl;
outfile << "null" << endl;
outfile << "Go back to the road." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "8 1" << endl;
outfile << "bandits" << endl;
outfile << "The road continues." << endl;
outfile << "null" << endl;
outfile << "Continue." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "9 1" << endl;
outfile << "gate_1" << endl;
outfile << "To your east is the gate to a walled town, the gate is open and there are no guards. To the north there is a ravine and to the south is the river." << endl;
outfile << "null" << endl;
outfile << "Enter the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "10 1" << endl;
outfile << "mainstreet_1" << endl;
outfile << "You are in the main street of the town, all the buildings of the town are boarded up, and some of the doors hang wide open. Everything is in disarray; on the street, trash skitters around in the wind. To the north is the library & to the south is the apothecary." << endl;
outfile << "null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "11 1" << endl;
outfile << "mainstreet_2" << endl;
outfile << "You are in the main street of the town, to the north is the tavern & to the south is the blacksmith." << endl;
outfile << "null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "0 3" << endl;
outfile << "tavern" << endl;
outfile << "You enter the tavern and immediately you are hit with the smell of stale beer, the smell seems to be wafting over from behind the counter, there is a beer keg here. The emptiness of the tavern gives you the shivers." << endl;
outfile << "beer null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "1 4" << endl;
outfile << "library" << endl;
outfile << "Some of the bookshelves have collapsed here, books are strewn all over the floor." << endl;
outfile << "null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "0 5" << endl;
outfile << "apothecary" << endl;
outfile << "Here, there are strange items scattered all around. There are strange animal horns placed on a rack along with large pieces of wood, some of which, have fallen onto the floor. Shattered vials and jars cover the floor. " << endl;
outfile << "null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "1 6" << endl;
outfile << "blacksmith" << endl;
outfile << "The blacksmiths walls and floor are made of wood, the store is empty except for a counter on the far wall. "<< endl;
outfile << "null" << endl;
outfile << "Explore the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "12 1" << endl;
outfile << "gate_2" << endl;
outfile << "To your west is the gate to a walled town, the gate is open and there are no guards. To the north there is a ravine and to the south is the river." << endl;
outfile << "null" << endl;
outfile << "Enter the town." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "13 1" << endl;
outfile << "road_end" << endl;
outfile << "The road comes to a halt just before a massive cave entrance to the south. It appears that the river runs right over the cave. To the north is the ravine and to the east is the forest." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "13 3" << endl;
outfile << "cave_enter" << endl;
outfile << "The cave is dark and moist, there is a small crack in the ceiling through which water trickles in." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "13 4" << endl;
outfile << "cave_branch" << endl;
outfile << "Here the tunnel heads west, a small crack in the wall leads east, in front of you there is a chute high above the ground, under which is a pile of straw." << endl;
outfile << "straw" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "11 4" << endl;
outfile << "cave_huge" << endl;
outfile << "You are in a massive chamber from which you suspect many tunnels lead from.The darkness is thick enough to prevent your light from reaching the far ends of the chamber." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "12 4" << endl;
outfile << "fissure" << endl;
outfile << "You are on a ledge facing a deep fissure, you see the outline of what could be a doorway on the other side of the fissure." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "11 5" << endl;
outfile << "sphinx" << endl;
outfile << "You are in a small room, there is a large sphinx here guarding a wooden door." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "11 6" << endl;
outfile << "sphinx_treasure" << endl;
outfile << "There are piles and piles of the spinx's gold and jewels filling the room, there is too much to carry!. " << endl;
outfile << "gold jewels null" << endl;
outfile << "Hooray!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "10 4" << endl;
outfile << "statue" << endl;
outfile << "Here there is a tall statue of a king, he is guarding a tunnel leading downwards, deeper into the cave." << endl;
outfile << "null" << endl;
outfile << "Deeper." << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 7" << endl;
outfile << "deep" << endl;
outfile << "There is no sound here, you can only hear the sound of your own heartbeat. There is a tunnel leading east, at a steep incline; to the south is a large opening leads into another chamber." << endl;
outfile << "null" << endl;
outfile << "Explore" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 8" << endl;
outfile << "antechamber" << endl;
outfile << "There is a massive door to the south, it seems to be made of the stone that makes up the rest of the cave. On the door is inscribed 'Mors propius' the rest of the door is covered with runes of an unknown nature." << endl;
outfile << "null" << endl;
outfile << "Darker" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "5 9" << endl;
outfile << "cult_room" << endl;
outfile << "" << endl;
outfile << "null" << endl;
outfile << "Darker" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "14 4" << endl;
outfile << "crack" << endl;
outfile << "You are in an east-west crack, on both sides the crack opens up into larger chambers." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "15 4" << endl;
outfile << "chamber_2" << endl;
outfile << "You are in a large chamber, the walls seem to have been built with great masonry. There is a crack in the wall to the east, it seems to have been formed after this chamber was constructed. To the north and south are two arched passage ways." << endl;
outfile << "null" << endl;
outfile << "Onwards!!" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "15 3" << endl;
outfile << "mana" << endl;
outfile << "On the far side of this small room, there is a carving of an angel, out of its mouth spills a dark liquid which is then collected in a basin beneath the carving." << endl;
outfile << "null" << endl;
outfile << "Drink it" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "15 5" << endl;
outfile << "corridor" << endl;
outfile << "You are in a long hallway." << endl;
outfile << "null" << endl;
outfile << "Forward" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "15 6" << endl;
outfile << "fork_room" << endl;
outfile << "There is a fork in the corridor. Ahead of you, in the middle of the fork is a arched chute that spirals down, deeper into the cave, if you were to enter it, you would slide down." << endl;
outfile << "fork null" << endl;
outfile << "Go south to enter the chute" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "16 6" << endl;
outfile << "shrine" << endl;
outfile << "This is the first room that has its own lighting, on the walls are two lanterns burning with a green flame of magical origin. In the center of the room is a large altar, it is carved in the shape of a twenty sided die." << endl;
outfile << "null" << endl;
outfile << "WORSHIP it" << endl;
outfile << "0" << endl;
outfile << "Room:" << endl;
outfile << "14 6" << endl;
outfile << "pit" << endl;
outfile << "You are on a large stone platform over a MASSIVE pit, it seems to span on for miles! There is a amulet hanging from a pedestal in front of you, it has a black gem set in the middle, also, set behind the gem is a pair of wings." << endl;
outfile << "amulet null" << endl;
outfile << "Take the amulet" << endl;
outfile << "0" << endl;
outfile << "Player:" << endl;
outfile << "1 1" << endl;
outfile << "10 10" << endl;
outfile << "10 10" << endl;
outfile << "null" << endl;
outfile.close();
}
</code></pre>
<p>Character Class:</p>
<pre><code>
#ifndef CHARACTERS_H
#define CHARACTERS_H
#include <string>
#include <vector>
using namespace std;
class Characters {
public:
Characters(string nm);
int getHealth();
int getMana();
void setMana(int mn);
void setHealth(int hp);
void setMaxMana(int mn);
void setMaxHealth(int hp);
int getXp();
string getName();
string getDescription();
void setDescription(string disc);
vector<string> getInventory();
void addItem(string nm);
void removeItem (string nm);
int getX();
int getY();
void setLocation(int ex, int why);
int getMaxHealth() const;
int getMaxMana() const;
private:
string name;
string description;
int health;
int mana; //Magic energy
int maxHealth;
int maxMana;
int xp; //Xp gained from kill
vector<string> inventory;
int x, y;
};
#endif //CHARACTERS_H
</code></pre>
<p>Implementation:</p>
<pre><code>
#include "characters.h"
string Characters::getName() {
return name;
}
vector<string> Characters::getInventory() {
return inventory;
}
string Characters::getDescription() {
return description;
}
void Characters::addItem(string nm) {
inventory.push_back(nm);
}
int Characters::getHealth() {
return health;
}
int Characters::getXp() {
return xp;
}
int Characters::getMana() {
return mana;
}
void Characters::setMana(int mn) {
if (mn > maxMana) {
mana = maxMana;
} else {
mana = mn;
}
}
void Characters::setMaxHealth(int hp) {
maxHealth = hp;
}
void Characters::setDescription(string disc) {
description = disc;
}
void Characters::removeItem(string nm) {
for (int i = 0; i < inventory.size(); ++i) {
if (inventory[i] == nm) {
inventory.erase(inventory.begin() + i);
break;
}
}
}
void Characters::setHealth(int hp) {
if (hp > maxHealth) {
health = maxHealth;
} else {
health = hp;
}
}
void Characters::setMaxMana(int mn) {
maxMana = mn;
}
Characters::Characters(string nm) {
name = nm;
maxMana = 10;
maxHealth = 10;
health = 10;
mana = 10;
description = "You are you, you dummy!";
xp = 0;
x = 1;
y = 1;
}
int Characters::getY() {
return y;
}
int Characters::getX() {
return x;
}
void Characters::setLocation(int ex, int why) {
x = ex;
y = why;
}
int Characters::getMaxHealth() const {
return maxHealth;
}
int Characters::getMaxMana() const {
return maxMana;
}
</code></pre>
<p>Room class:</p>
<pre><code>
#ifndef ROOMS_H
#define ROOMS_H
#include <string>
#include <vector>
using namespace std;
class Rooms {
public:
Rooms();
void addItem (string nm);
string getName();
vector<string> getInventory();
void removeItem (string nm);
string getDescription();
void incrementActionCount(); //Increments number of actions from player in room
int getActions();
void setDescription (string disc);
bool getEmpty();
const string &getHint() const;
void setName(string nm);
void setHint(string hnt);
void setActions(int act);
void setEmpty (bool emp);
private:
string name;
bool empty;
string description;
string hint; // Will be displayed after a certain number of actions
vector<string> inventory;
int actionCount; // Number of actions player has taken in room
};
#endif //ROOMS_H
</code></pre>
<p>Implementation:</p>
<pre><code>
#include "rooms.h"
Rooms::Rooms() {
hint = "Boy, you are taking a while to figure out this room aren't you?";
inventory = {};
description = "You are in a completely blank room";
name = "";
actionCount = 0;
empty = true;
}
void Rooms::addItem(string nm) {
inventory.push_back(nm);
}
void Rooms::setName(string nm) {
name = nm;
}
void Rooms::removeItem(string nm) {
for (int i = 0; i < inventory.size(); ++i) {
if (inventory[i] == nm) {
inventory.erase(inventory.begin() + i);
break;
}
}
}
int Rooms::getActions() {
return actionCount;
}
string Rooms::getDescription() {
return description;
}
vector<string> Rooms::getInventory() {
return inventory;
}
string Rooms::getName() {
return name;
}
void Rooms::incrementActionCount() {
actionCount++;
}
void Rooms::setDescription(string disc) {
description = disc;
}
bool Rooms::getEmpty() {
return empty;
}
void Rooms::setHint(string hnt) {
hint = hnt;
}
void Rooms::setActions(int act) {
actionCount = act;
}
void Rooms::setEmpty(bool emp) {
empty = emp;
}
const string &Rooms::getHint() const {
return hint;
}
</code></pre>
|
[] |
[
{
"body": "<p><code><bits/stdc++.h></code> is not a standard C++ header. Please use only standard headers, so your code is portable.</p>\n\n<p><code>using namespace std;</code> is a terrible idea - it completely removes the benefit of namespaces, meaning that all the standard library (including future types and functions not yet standardised) is mixed in with your program identifiers. Don't do that! Especially not in a header, where the harm is inflicted on every translation unit that includes that header.</p>\n\n<p>There's sometimes an argument for importing <em>a few</em>, <em>specific</em> names into a <em>smaller scope</em> (a function, usually), but seldom for bringing in an entire namespace at the top level.</p>\n\n<hr>\n\n<p>Many members are missing their <code>const</code> qualification. For example:</p>\n\n<pre><code>std::string getName() const;\n// ^^^^^\n// function must not modify 'this' object\n</code></pre>\n\n<hr>\n\n<p>Picking on a random function that just caught my eye:</p>\n\n<blockquote>\n<pre><code>void Rooms::setName(std::string nm) {\n name = nm;\n}\n</code></pre>\n</blockquote>\n\n<p>We're making an unnecessary copy; we can avoid doing so:</p>\n\n<pre><code>void Rooms::setName(std::string nm) {\n name = std::move(nm);\n}\n</code></pre>\n\n<p>And in <code>Rooms::removeItem</code>, we don't need a copy:</p>\n\n<pre><code>void Rooms::removeItem(const string& nm) {\n</code></pre>\n\n<p>There are many more functions that unnecessary copy their arguments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:38:05.190",
"Id": "464966",
"Score": "0",
"body": "What about comments, where would I need those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T22:00:53.990",
"Id": "464982",
"Score": "0",
"body": "I would just add, `using namespace std;` is often used so that things like `cout` can be written without a prefix, and you can get the same benefit with `using std::cout;` and bringing in just the few things you are going to use, individually. (I know you know this, Toby; just adding it for the benefit of OP.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:26:34.870",
"Id": "237136",
"ParentId": "237126",
"Score": "10"
}
},
{
"body": "<p>In addition to everything mentioned in Toby Speight's review:</p>\n\n<p>This program can use at least one additional class and probably more. The class that is obviously missing is <code>Game</code>. The class <code>Game</code> should be responsible for loading the game from a file, saving the game to a file and executing the game.</p>\n\n<p>The function <code>createOriginalSave()</code> should probably be broken up into <code>createNewGame()</code> and then use the <code>save()</code> function to save the new game.</p>\n\n<p>The suggested <code>createNewGame()</code> function should generate a map of rooms.</p>\n\n<p>Each room should be responsible for printing its data to the output file.</p>\n\n<p>Most of the functions in the file that contains <code>main</code> are too 'complex' and need to be broken up into smaller functions. You might find some reusable code this way. The code is currently very difficult to maintain and expand because it is so complex.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T18:48:39.263",
"Id": "237178",
"ParentId": "237126",
"Score": "3"
}
},
{
"body": "<p>In general when there is multiple options on a program like yours (on the section you manage the variable input), is desirable to make it more readable in order to avoid the multiples if statements. My recommendation is to use a map, or unordered_map with the input as first parameter and second a callback to the desire functionality. For example:</p>\n\n<pre><code>for (int i = 0; true; i++){\n\n cin >> input;\n Coord newPlayerCoords;\n\n transform(input.begin(), input.end(), input.begin(), ::tolower);\n\n if (input == \"north\") input = \"n\";\n else if (input == \"south\") input = \"s\";\n else if (input == \"east\") input = \"e\";\n else if (input == \"west\") input = \"w\";\n else if (input == \"u\") input = \"up\";\n else if (input == \"d\") input = \"down\";\n</code></pre>\n\n<p>Transform on</p>\n\n<pre><code>for (int i = 0; true; ++i){ // Check the increment here\n\n cin >> input;\n Coord newPlayerCoords;\n\n transform(input.begin(), input.end(), input.begin(), ::tolower);\n\n auto it = callbacks.find(input);\n if (it != callbacks.end()) {\n auto operation = it->second;\n\n operation(...);\n }\n</code></pre>\n\n<p>Hope you get the idea, just need to define statically the callbacks as your convenience.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T20:14:32.803",
"Id": "237182",
"ParentId": "237126",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T07:10:40.283",
"Id": "237126",
"Score": "3",
"Tags": [
"c++",
"game"
],
"Title": "Cool text based adventure game"
}
|
237126
|
<p>I use the below code to get a list of columns in a table, and assign the default value to the protected var $attributes in a Laravel Model.</p>
<p>In this code, I use the DB function because I don't know how to achieve the same result with Eloquent.</p>
<p><strong>Model.php</strong></p>
<pre><code>protected $attributes = [];
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$columns = DB::connection()->getDoctrineSchemaManager()->listTableColumns('mailboxes');
foreach ($columns as $column) {
$name = $column->getName();
$value = $column->getDefault();
if (!is_null($value)) {
$this->attributes[$name] = $value;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T22:14:06.917",
"Id": "464984",
"Score": "1",
"body": "I don't think there is any easier way to do this. The question to ask is, is it necessary. This will add an overhead to every model regardless of if you use it or not. If you were to set hard coded default attributes in the model, they will overwrite the database defaults anyway, making the database defaults redundant, unless you are also inserting records from a non-eloquent source."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T13:16:32.573",
"Id": "465094",
"Score": "0",
"body": "Hi. I have seen that there are no problems or costs, since I am testing 10,000 items and it does not show.\nThe reality is that it is a softward and third parties and the table has more than 50 fields, to which I need to pass the default value. It seems more logical and useful, to automate this than to write in the resource de nova, each of the default values, and do its testing. In this way it is more global. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T19:01:33.243",
"Id": "465154",
"Score": "0",
"body": "if it is working fast enough for you, then there is no nothing more i can add, your code looks fine to me."
}
] |
[
{
"body": "<p>If I’m fully understanding your need, the best approach would be to set the defaults at the database level. If a record is saved with a null value for that attribute, it will automatically get the default value set at the database level. The end result is much cleaner code and no extra processing needs during data load as the default is there at rest.</p>\n\n<p>In the migration, for example, <code>$table->string(‘favorite_color’)->default(‘Blue’);</code> , as described at <a href=\"https://laravel.com/docs/master/migrations#column-modifiers\" rel=\"nofollow noreferrer\">https://laravel.com/docs/master/migrations#column-modifiers</a></p>\n\n<p>Would this solve your need? If not, it probably means your need is contextual, and that this default doesn’t always need to apply. Think critically about that context and what it represents. It might indicate a difference in data which might cause further problems down the road. </p>\n\n<p>I hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T09:02:49.297",
"Id": "466411",
"Score": "0",
"body": "Hi. No you have not understood. The default values are already in the migrations. The question is simple. Obtain the default values of each column of a table, using Eloquent or DB. Why is it simple? He assures me that he does not forget any column with default value, in tables like many columns of these characteristics, and in addition to the development phase, in addition to allowing me to programmatically design some element constraint design, without repeating dozens of lines of code. Best regargds"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-23T14:03:03.407",
"Id": "237779",
"ParentId": "237128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T08:12:18.947",
"Id": "237128",
"Score": "3",
"Tags": [
"laravel",
"eloquent"
],
"Title": "Get list and default value of columns of table with Eloquent"
}
|
237128
|
<p><a href="https://projecteuler.net/problem=47" rel="nofollow noreferrer">Project Euler Problem 47</a></p>
<blockquote>
<p>Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?</p>
</blockquote>
<p>This is my solution for problem 47 on Project Euler. </p>
<pre class="lang-py prettyprint-override"><code>def primes2(n):
""" Input n>=6, Returns a list of primes, 2 <= p < n """
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n//3)
for i in range(1,int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k//3 ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]
def findSeq(lst):
""" Returns the index of the first term of a 4 term arithmetic sequence """
for x in range(len(lst)-2):
if sum(lst[x:x+4]) == (4*lst[x]+6):
return x
return False
def generateFactors(num,values,factors):
if len(values[num]) > 0:
factors += values[num]
return factors
else:
for i in range(2,num-1):
if num % i == 0:
return generateFactors(num//i,values,factors+[i])
n = 200000
primes = set(primes2(n))
factors = dict([[x,[]] for x in range(2,n)])
for item in factors.keys():
if item in primes:
factors[item] = [item]
else:
factors[item] = generateFactors(item,factors,[])
fourFact = [item for item in factors.keys() if len(set(factors[item])) == 4]
pos = findSeq(fourFact)
print(fourFact[pos])
</code></pre>
<p>The primes2 function isn't my code but I have included it for completeness. I am looking for feedback on my implementation and how to optimise the code.</p>
|
[] |
[
{
"body": "<p>Since you already have a nice implementation of a prime sieve, you should make use of it when checking for prime factors. Note that prime factors are needed, not all factors. I definitely would not use a recursive algorithm for this. It can fail with a stack limit and you need a lot of unreadable code just to set up the data structures.</p>\n\n<p>I would use something simple like this:</p>\n\n<pre><code>from math import sqrt\n\ndef prime_factors(n, primes=None):\n \"\"\"(int) -> iterable of ints\n\n Yields the prime factors of a number, excluding 1.\n Optionally takes an iterable of pre-computed prime numbers.\n \"\"\"\n max_p = int(sqrt(n)) + 1\n if primes is None:\n primes = primes2(max_p)\n for p in primes:\n while n > 1 and n % p == 0:\n n //= p\n yield p\n if n == 1 or p >= max_p:\n break\n if n > 1:\n yield n\n</code></pre>\n\n<p>The second part of the task can be done in multiple ways. You have chosen to just define a maximum value up to which to search, filter all numbers with the right number of prime factors and then search for an increasing sequence. This will take quite a bit of memory, potentially, depending on where the answer is.</p>\n\n<p>An easier way is to only remember the last four numbers with the right number of prime factors using a <code>collections.deque</code> with a <code>maxlen=4</code>, and check if they are an increasing sequence:</p>\n\n<pre><code>from itertools import count\nfrom collections import deque\n\ndef diff(it):\n it = iter(it)\n x = next(it)\n for y in it:\n yield y - x\n x = y\n\ndef is_increasing_sequence(it):\n return all(d == 1 for d in diff(it))\n\nif __name__ == \"__main__\":\n d = deque([], maxlen=4)\n for n in count(1):\n if len(set(prime_factors(n))) == 4:\n d.append(n)\n if len(d) == 4 and is_increasing_sequence(d):\n print(d[0])\n break\n</code></pre>\n\n<p>This can be sped up by re-introducing a maximum number to check and pre-computing the prime numbers for the prime number factorization:</p>\n\n<pre><code>if __name__ == \"__main__\":\n max_n = 200000\n primes = primes2(max_n)\n d = deque([], maxlen=4)\n for n in range(1, max_n):\n if len(set(prime_factors(n, primes=primes))) == 4:\n d.append(n)\n if len(d) == 4 and is_increasing_sequence(d):\n print(d[0])\n break\n</code></pre>\n\n<p>This solves the problem in less than a second on my machine, which is similar to your code.</p>\n\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends <code>lower_case</code> for functions and variables and surrounded my code with an <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without running the code. This is especially important for Project Euler, as you will need e.g. the prime sieve and the prime number factorization again in other problems.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T15:31:32.060",
"Id": "237161",
"ParentId": "237132",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:03:33.193",
"Id": "237132",
"Score": "2",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler #47: find four consecutive integers, each with four distinct prime factors"
}
|
237132
|
<p>Since hashing algorithms isn't something to mess around with as a beginner. Several howto's explain that one should use already made solutions.
Examples of such pages:</p>
<ul>
<li><a href="https://crackstation.net/hashing-security.htm" rel="nofollow noreferrer">https://crackstation.net/hashing-security.htm</a></li>
<li><a href="https://owasp.org/www-project-cheat-sheets/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2" rel="nofollow noreferrer">https://owasp.org/www-project-cheat-sheets/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2</a></li>
</ul>
<p>So I opted for ready-made solutions from <code>java.security</code> and <code>java.crypto</code> library packages.
But I feel there is still room for messing up, especially with regard to the parameters in <code>PBEKeySpec(password, salt, iterations, keyLength)</code>.</p>
<p>According to some HOWTOs, salt should be as long in bytes as the output from the hash function. So I chose 64, since SHA-512 outputs (64*8=512 bits) 64 bytes. (Although, it seems I can get larger output simply by increasing <code>keyLength</code> argument above 512, which makes me wonder).</p>
<p>So basically. Do you guys/girls find this code reasonable? Especially in regards to the arguments passed?
If not, please tell me what to change, how and why.</p>
<pre><code>package my.application;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.commons.codec.binary.Hex;
public class PasswordHasher {
private int ammountOfBytes = 64;
private int keyLength = 512;
private int iterations = 100000;
private byte[] salt;
private byte[] hash;
private char[] password;
private String saltHex;
private String hashHex;
public void hash(String rawPassword) {
makeSalt();
password = rawPassword.toCharArray();
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength);
SecretKey key;
try {
SecretKeyFactory generator = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
key = generator.generateSecret(spec);
hash = key.getEncoded();
hashHex = Hex.encodeHexString(hash);
spec.clearPassword();
key = null;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}
public void destroy() {
saltHex = null;
hashHex = null;
Arrays.fill(password, (char) 0);
Arrays.fill(salt, (byte) 0);
Arrays.fill(hash, (byte) 0);
}
private String makeSalt() {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
salt = new byte[ammountOfBytes];
random.nextBytes(salt);
saltHex = Hex.encodeHexString(salt);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return saltHex;
}
public String getSaltHex() {
return saltHex;
}
public String getHashHex() {
return hashHex;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:32:53.880",
"Id": "464893",
"Score": "1",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T11:26:09.847",
"Id": "464895",
"Score": "1",
"body": "It is indeed a nice concise title that explains what I try to accomplish with the code. Thanks :)"
}
] |
[
{
"body": "<p>There are a few things wrong security wise before we even get to the parameters.</p>\n\n<pre><code>private char[] password;\n</code></pre>\n\n<p>Storing the plain text password in an instance field makes it discoverable from memory dumps for a considerably long time. There is no need for the field to be an instance field since it is only used in the <code>hash</code> method.</p>\n\n<pre><code>public void hash(String rawPassword) {\n</code></pre>\n\n<p>Passing plain text password as a String parameter makes it impossible to be securely disposed of. When being passed around, passwords need to be char arrays and they need to be cleared immediately when they are no longer needed.</p>\n\n<pre><code>public void destroy() {\n</code></pre>\n\n<p>You have the right idea that the class needs to be cleared from sensitive data, but here you have made the clearing the responsibility of the caller while the data needing to be cleared is completely irrelevant to the caller. You should avoid having to rely on other people when dealing with sensitive data. Someone will forget to call <code>destroy()</code> because it is not something that needs to be done in a garbage collected environment. At least you could make it <code>Closeable</code> so there is some common contractual indication about the class needing cleanup. Because the method also clears the actual payload it is guaranteed that the sensitive data will be in memory as long as the payload is needed, which is much longer than the sensitive data needs to exist. But it's better to write the class so that it doesn't need external cleanup at all.</p>\n\n<pre><code>private int ammountOfBytes = 64;\nprivate int keyLength = 512;\nprivate int iterations = 100000;\n</code></pre>\n\n<p>These should be static and final constants, since you don't have any means to change them.</p>\n\n<pre><code>private String saltHex;\nprivate String hashHex;\n</code></pre>\n\n<p>These are the only fields that have a information that needs to be kept for a longer period. Instead of wrapping all the fields into a same <code>PasswordHasher</code> class, you should put these two fields into a dedicated data class called <code>HashedPassword</code>, have all the other code be static utilities and have the hash method return the data class.</p>\n\n<p>If we look at the naming, <code>PasswordHasher</code> implies that the class is an actor that implements an algorithm. Your implementation uses it as both a data container and the algorithm. It is better to separate the responsibilities to two different classes (single responsibility principle)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:34:57.810",
"Id": "237137",
"ParentId": "237134",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "237137",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:11:08.013",
"Id": "237134",
"Score": "4",
"Tags": [
"java",
"security",
"hashcode"
],
"Title": "Securely hash passwords"
}
|
237134
|
<p>I want to rework my current game-server engine to use some global queue of tasks which will be distributed through all the working threads.</p>
<p>I started with task interface. I want it to be able to accept any kind of method and store it under queue for later execution. I'd like to hear your opinions on my implementation.</p>
<pre><code>#include <iostream>
#include <string>
#include <queue>
#include <memory>
#include <functional>
class ITask
{
public:
virtual ~ITask() = default;
virtual void execute() = 0;
};
class GameTask : public ITask
{
public:
GameTask(std::function<void()> func) : func_(func) {}
void execute() final
{
func_();
}
private:
std::function<void()> func_;
};
// lets imitate some bigger classes with various methods
class BigClassA
{
public:
void func1(int a) { std::cout << ++a; }
int func2(const std::string& s) { std::cout << s; return b; }
int b = 4;
};
class BigClassB
{
public:
double func1(BigClassA& bca, int i) { bca.b += i; return 0.1; }
};
int main()
{
BigClassA a;
BigClassB b;
// perform immidiately by current main thread:
a.func1(2);
b.func1(a, 3);
a.func2("Hello");
//store under queue for later execution
std::queue<std::unique_ptr<ITask>> queue;
queue.push(std::make_unique<GameTask>( [&a]() { a.func1(2); } ));
queue.push(std::make_unique<GameTask>( [&a, &b]() {b.func1(a, 3); } ));
queue.push(std::make_unique<GameTask>( [&a]() { a.func2("Hello"); } ));
// delayed execution
while (queue.size())
{
queue.front()->execute();
queue.pop();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:08:29.730",
"Id": "464900",
"Score": "5",
"body": "Welcome to Code Review! Which part of the code do you want to review? The `BigClass*` part falls under the category of [hypothetical code](https://codereview.meta.stackexchange.com/q/1709), so you may want to extract the core part and list the \"lets imitate some bigger classes with various methods\" as an usage example to avoid getting your question closed. Also, please include a brief explanation of what the code does. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T09:11:51.857",
"Id": "465055",
"Score": "0",
"body": "@L.F. To me it doesn't look like it's devoid of all meaning that it's unanswerable. Maybe you could say what's missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T09:29:17.593",
"Id": "465058",
"Score": "0",
"body": "@Peilonrayz I think the task part is fine, but the name of the classes (`BigClassA`) may accumulate some CVs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T09:40:06.750",
"Id": "465059",
"Score": "0",
"body": "Hi, Thanks for your contribution all. Im new to this sub and Its my first review request. The intention of that topic was to review the correctness of my queue for many kind of tasks that will be more expanded but will all contain execute function.\n\nAlso back to the 'BigClassA' thing. Since im working on pretty complex and big project that contains many classes and methods I wanted to try to imitate many diversified things that my abstraction can met and it should be able to handle it."
}
] |
[
{
"body": "<p>Your code does effectively nothing but add a useless layer of indirection.</p>\n\n<p>There is functionally nothing different between a simple <code>std::queue<std::function<void()>> queue;</code> and your OOP for the sake of OOP hierarchy and queue of unique_ptrs to pure interface.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T09:10:52.633",
"Id": "465053",
"Score": "0",
"body": "Thats right, Im going to modify and expand ITasks deriveds in the future. I wanted to hear your opinions about that skeleton of my task queue"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T10:14:14.563",
"Id": "465068",
"Score": "2",
"body": "@Piodo flesh it out and then come back, There is nothing here to comment on other than that it's abstraction for abstraction's sake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T11:56:16.587",
"Id": "465086",
"Score": "0",
"body": "Will do, thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:54:45.060",
"Id": "237146",
"ParentId": "237138",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T10:40:42.440",
"Id": "237138",
"Score": "-2",
"Tags": [
"c++",
"design-patterns",
"queue",
"c++17",
"interface"
],
"Title": "C++ generic task interface for delayed execution"
}
|
237138
|
<p>I had to make this blackjack game for school, but this is only the first part. We only had to use a random value between 2 and 11 to generate the cards, as we will have a library of cards later, and the dealer will keep pulling cards until their total value is at or equal to 17. The player needs to decide whether they want to hit or stay, and will always bet $25. I want to clean up the code to make it clearer, as it seems a bit messy.</p>
<pre><code>import random
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (bank_balance >= 25 and restart == True):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
print (f"Betting $25")
bank_balance-=25
deal_hand = play_hand(player_name)
play=input("Type 'y' to play again, or type any key to quit" + '\n')
if (play == 'y'):
restart=True
print('\n')
elif (play != 'y'):
print('Thanks for playing ')
restart=False
def play_hand(name):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
main()
</code></pre>
|
[] |
[
{
"body": "<p>My main tip is to use <code>break</code> and <code>continue</code> to control the flow of your while loops rather than having a bunch of extra bools in the loop condition. For example, instead of:</p>\n\n<pre><code> restart = True\n while (bank_balance >= 25 and restart == True):\n\n print (f\"Welcome {player_name}, your bank balance is ${bank_balance} \")\n print (f\"Betting $25\")\n bank_balance-=25\n\n deal_hand = play_hand(player_name)\n\n play=input(\"Type 'y' to play again, or type any key to quit\" + '\\n')\n\n if (play == 'y'):\n restart=True\n print('\\n')\n elif (play != 'y'):\n print('Thanks for playing ')\n restart=False\n</code></pre>\n\n<p>get rid of the <code>restart</code> flag and do:</p>\n\n<pre><code> while bank_balance >= 25:\n\n print (f\"Welcome {player_name}, your bank balance is ${bank_balance} \")\n print (f\"Betting $25\")\n bank_balance-=25\n\n deal_hand = play_hand(player_name)\n\n play=input(\"Type 'y' to play again, or type any key to quit\" + '\\n')\n\n if (play == 'y'):\n print('\\n')\n elif (play != 'y'):\n print('Thanks for playing ')\n break\n</code></pre>\n\n<p>(Also, for a true/false value instead of saying <code>flag == True</code> or <code>flag == False</code> just say <code>flag</code> or <code>not flag</code>.)</p>\n\n<p>You can apply this same principle to the loops in <code>play_hand</code> where you're checking several bools in each while loop:</p>\n\n<pre><code> player_bust = False\n dealer_bust = False\n\n while True:\n hors= input(f\"Type 'h' to hit and 's' to stay \")\n if (hors == 'h'):\n new_card= random.randint(1, 11)\n player.append(new_card)\n print(f'{name} pulled a {new_card}')\n elif (hors == 's'):\n print('stay')\n break\n print(f'Dealer total is {sum(dealer)}')\n print(f\"{name}'s cards are\", *player)\n print(f\"{name}'s total is {sum(player)}\", '\\n')\n if sum(player) > 21:\n player_bust = True\n break\n\n if not player_bust:\n while sum(dealer) > 17:\n dealer.append(random.randint(1, 11))\n print('The dealers total is', sum(dealer), '\\n')\n if sum(dealer) > 21:\n dealer_bust = True\n\n if player_bust:\n print(\"You busted!\")\n elif dealer_bust:\n print(\"You win! The dealer busted!\"\n elif sum(dealer) > sum(player):\n print(\"The dealer wins!\")\n elif sum(player) < sum(dealer):\n print(\"You win!\")\n else:\n print('Its a Tie! ')\n</code></pre>\n\n<p>The idea is to minimize the number of conditions that each check depends on; it gives you less to keep track of as you read your code and try to figure out what it's going to do in any given situation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T16:18:20.590",
"Id": "237166",
"ParentId": "237148",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T13:35:11.460",
"Id": "237148",
"Score": "2",
"Tags": [
"python"
],
"Title": "Part one of blackjack game"
}
|
237148
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.