text
stringlengths
1
2.12k
source
dict
java, json, spring Title: Read from dynamic source and caching Question: I want to load JSON data from a link at the beginning of an application. I need to be a little bit about clear the following code. And also want to ask about another opinions that what could be the best approach if I need to read from a URL and want to read data from this resource. package com.app; import com.app.entity.Event; import com.app.service.EventCommandService; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; @SpringBootApplication public class Application { static HttpURLConnection connection; Logger logger = LoggerFactory.getLogger(Application.class); @Value("${url.path}") String urlValue; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner runner(CommandService CommandService) { return args -> { BufferedReader reader; String line; StringBuilder responseContent = new StringBuilder(); // read json and write to db ObjectMapper mapper = new ObjectMapper(); TypeReference<List<Event>> typeReference = new TypeReference<>() { }; try { URL url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection();
{ "domain": "codereview.stackexchange", "id": 43738, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, json, spring", "url": null }
java, json, spring // Request setup connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { responseContent.append(line); } int index = responseContent.toString().indexOf("[{"); byte[] bytes = responseContent.substring(index).getBytes(); InputStream inputStream = new ByteArrayInputStream(bytes); try { List<Event> events = mapper.readValue(inputStream, typeReference); // Save events to h2 db CommandService.save(events); logger.info("Events Saved"); } catch (IOException e) { logger.info("Unable to save events: {}", e.getMessage()); } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { connection.disconnect(); } }; } }
{ "domain": "codereview.stackexchange", "id": 43738, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, json, spring", "url": null }
java, json, spring }; } } Answer: Validate inputs The program expects a valid HTTP URL to work correctly. It would be good to have some validation logic, and exit with a user-friendly error message, rather than a stack trace. Also, even if the URL is valid, the content might not be valid JSON. It would be good to add validation for that too, and handle unexpected content more gracefully than crashing. Use try-with-resources with AutoCloseables The try-with-resources greatly simplifies the correct closing of AutoCloseables. The reader and inputStream should use it. Close objects as soon as you're done with them The reader stays open while using the mapper and saving to database. It would be better to close it after it's no longer needed. The same goes for connection. Declare variables in the smallest necessary scope When variables are visible outside the scope where they are necessary, they might get referenced or overwritten by mistake. In case of the posted code: connection should be a local variable reader and inputStream should be declared in a try-with-resources statement line should be declared within the scope of the reader mapper and typeReference should be declared right before they are needed Separate concerns Too many things are mixed together in the class and the runner method: It's best when the runnable class with the main method has almost no logic at all. The implementation of runner would be better in another class, injected into the main application. The runner does multiple logical steps intermixed in one method. These steps could be in separate methods, and unit tested separately: Read text from a URL Parse the list of events from text Save the list of events
{ "domain": "codereview.stackexchange", "id": 43738, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, json, spring", "url": null }
java, json, spring Read text from a URL Parse the list of events from text Save the list of events Note that when the logic is separated like that, comments like "// read json and write to db" become unnecessary, since you will be able to simply read the same thing when reading the code top to bottom. Consider making member variables private final urlValue will never change during the execution of the class, and shouldn't be visible outside of the class, therefore it should be private final. Same for logger, and it should also be static, as commonly the case with loggers. Other smaller things The variable CommandService should be commandService to avoid confusion with the class with the same name, and follow common Java conventions. Avoid printing to stdout or stderr as in e.printStackTrace(), use the logger Instead of responseContent.toString().indexOf("[{"), you can do responseContent.indexOf("[{")
{ "domain": "codereview.stackexchange", "id": 43738, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, json, spring", "url": null }
c++, algorithm, c++17, knapsack-problem Title: Bin-packing C++ solution using multi-map
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem Question: The need (context). Several times a day, we need to migrate a set of digital assets from one system to another. The process uses memory (the assets are held in memory for a short time) and we need to do our best to keep the memory capacity down. Fortunately, we have some flexibility (there is no hard ceiling) but there is a noticeable performance improvement if we keep our migration to about 50Mb of assets at a time. Each migration consists of about 15,000 digital assets, ranging from a hundred bytes or so, up to well over 50Mb (but very rarely). A typical (std) distribution of our assets has a mean (μ) of 213777.0 and a standard deviation (σ) of 1591525.0 - this isn't very accurate - (there's a slight pull towards the low end and then a few very big assets), but it's good enough. Each asset has a unique id and, along with some other metadata, we have its size available to us. Although we could use an 'asset' struct, for flexibility sake (and because I am unused to templates), I chose to use a pair<size_t,size_t> to represent each asset - the first being the id, the second being the actual size of the asset. (size_t is suitable for both the id and the asset size). I know structs would be more suitable, and will make the change as suggested below. Therefore, it seemed reasonable (still does) to use a bin-packing solution (a 1-D knapsack-problem). The criteria of assessment. The calculation speed of the bin-packing solution is not very important (we are looking at only 15k assets), and neither is a terribly optimal solution. The primary criterion was ease of understanding, and ease of use. Some of our juniors have never heard of bin-packing, and finding a reasonably easy to read method with few lines is more important than a very generalised, maximally optimal, super-fast solution. The search. Wikipedia, StackOverflow, and Google are always the first places to look, of course; and bin-packing is a very well-addressed area.
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem From these, I found the code by Bastian Rieck on his bin-packing GitHub repo, specifically the max_rest_pq function that uses a priority queue. While it worked fine, I am not familiar with std::priority_queue, and likewise, it seemed only to store the size of each bin, not the contents of each bin. I chose to use pair size_t/size_t for asset-id/weight - I'm not so good at templates, but structs will probably be used in the deployed solution. The novelty(?!) Instead, I chose to replace Bastian's use of a std::priority_queue with a std::multimap, by exploiting its lower_bound() method (The map's key here represents space available, not size of current fill). Likewise, using extract()/insert() instead of pop()/push() found in std::priority_queue. Why I asked this question. While I may be an experienced programmer, I am not a good programmer. I'm looking to improve on the solution I wrote. It seems to work well against than many other (more complex, lengthy) algorithms solutions, but maybe it's no good. The code #include <vector> #include <iostream> #include <map> #include <unordered_map>
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem std::multimap<size_t,std::vector<std::pair<size_t,size_t>>> make_bins(const std::unordered_map<size_t,size_t>& objects, size_t K) { std::multimap<size_t,std::vector<std::pair<size_t,size_t>>> bins; bins.insert({K,{}}); for(auto& item: objects) { //ID-Weight if (item.second >= K) { bins.insert({0,{item}}); } else { auto bin = bins.lower_bound(item.second); // we have a bin that has space. if (bin != bins.end()) { auto node = bins.extract(bin); node.key() = node.key() - item.second; node.mapped().push_back(item); bins.insert(std::move(node)); } else { bins.insert({K-item.second,{item}}); } } } return bins; }
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem // Test data.. int main() { size_t max_capacity = 500; std::vector<size_t> obj = {2,42,2,32,21,32,19,2,4,2,4,5,2,5,6,6,96,37,34,54,80,55,84,20,74,50,56,95,40,93,28,37,17,101,28,82,55,58,42,101,29,54,88,73,4,37,22,25,71,93,99,51,14,95,82,90,99,66,63,58,14,73,7,6,98,63,60,79,60,49,91,58,68,52,6,51,69,82,36,71,7,28,88,42,80,81,42,32,52,93,53,3,20,15,8,211,91,52,38,46,79,60,76,86,22,50,101,70,92,43,27,6,33,19,15,30,99,87,52,59,38,92,71,85,32,76,21,10,82,96,61,30,9,75,39,14,6,31,28,75,61,33,85,42,2,41,43,64,3,68,60,77,39,61,63,38,25,66,93,30,75,71,31,23,67,20,93,2,4,45,51,81,23,25,27,2,17,66,17,32,26,31,35,54,2,5,65,51,31,84,42,36,2,50,46,22,53,50,84,84,65,51,72,54,99,46,90,44,60,2,40,38,80,26,95,2,94,56,66,31,25,18,89,42,59,3,86,50,97,18,58,79,100,32,82,94,66,87,61,32,85,87,48,76,7,24,33,19,64,15,60,10,47,7,44,80,100,72,39,61,17,83,48,100,79,52,20,26,66,50,64,26,44,85,22,68,62,72,9,16,2,35,35,14,15,9,8,33,93,50,21,30,75,51,64,40,27,23,34,83,29,35,58,17,81,7,40,43,62,35,10,121,95,30,92,71,16,16,43,16,76,40,33,6,26,23,68,66,80,92,101,52,11,60,71,18,65,11,42,14,5,49,2,89,80,23,121,5,9,53,58,23,2,10,98,19,29,38,91,57,51,9,40,76,62,96,83,35,96,64,4,46,40,5,28,35,26,57,101,78,63,59,3,68,61,23,61,101,70,76,37,74,46,43,30,66,32,73,22,6,49,33,23,91,111,39,76,98,7,78,72,50,43,92,56,15}; std::unordered_map<size_t,size_t> u; size_t x = 1002; for (auto &i : obj) { u[x++] = i; } auto bins = make_bins(u,max_capacity); // 69,99 for (auto& bin: bins) { size_t wt = 0; std::cout << max_capacity - bin.first << ": ["; for (auto& i: bin.second) { wt += i.second; std::cout << '{' << i.first << ',' << i.second << '}'; } std::cout << "]\n"; } return 0; } Answer: Choice of algorithm It seems to work better than many (more complex) algorithms, but maybe it's no good?
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem It seems to work better than many (more complex) algorithms, but maybe it's no good? Wikipedia has a very nice article about the bin packing problem. Your algorithm only processes items in the order they appear in the input, it's therefore one of the possible "online" algorithms. Offline algorithms that can look at the whole input and process it in the optimal order can be better. Your algorithm is the Best-Fit algorithm: from all the bins that exist and have enough space, you choose the one that has the least space left, thus trying to fill existing bins as fast as possible. To show that your algorithm doesn't always pack in the best way, just consider the following input: std::vector<size_t> obj = {100, 300, 200, 400}; Assume that this is also the order they are processed in by make_bins() (the std::unordered_map makes it a bit unpredictable). It then ends up with three bins of sizes 400, 200 and 400. But ideally you would only get two bins with sizes 500 and 500. The order matters, and your test vector just happens to result in a very good fit. Probably, the (modified) first-fit-decreasing algorithm is better and is still relatively simple to implement. Also note that your algorithm is an approximation, it is possible to calculate the optimal bin packing, but this is an NP-hard problem, and thus is going to be very slow for large inputs. Don't create an empty bin at the start Even though some descriptions of bin packing algorithms tell you to start with creating an empty bin, this is not necessary, as some step of the algorithm will tell you that if no bin exists that a new item can fit in, you have to create a new bin anyway. In your code, you can remove the line that inserts an empty bin. Create your own struct instead of using std::pair I am using pair size_t/size_t for weight/object id - I'm not so good at templates.
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c++, algorithm, c++17, knapsack-problem I am using pair size_t/size_t for weight/object id - I'm not so good at templates. The problem with std::pair<> is that it makes the code hard to read, and you have to remember the order in which things are stored in the pair. If you can, just create your own struct, like so: struct object { std::size_t id; std::size_t size; }; std::multimap<std::size_t, std::vector<object>> make_bins(...) { ... } Instead of having an unordered map to hold the input, you can use a std::vector<object>; you don't need the \$O(1)\$ lookup by id. Consider using auto and creating type aliases Long type names take long to type and are hard to read. Sometimes you can avoid writing a type by using auto, and in other cases you can create an alias for a type. For example: using bin_type = std::vector<object>; using bin_map = std::multimap<std::size_t, bin_type>; auto make_bins(const std::vector<object>& objects, std::size_t K) { bin_map bins; for (auto& item: objects) { if (item.size >= K) { bins.emplace(0, {item}); } else if (auto bin = bins.lower_bound(item.size); bin != bins.end) { auto node = bins.extract(bin); node.key() -= item.second(); node.mapped().push_back(item); bins.insert(std::move(node)); } else { bins.emplace(K - item.size, {item}); } } return bins; }
{ "domain": "codereview.stackexchange", "id": 43739, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, c++17, knapsack-problem", "url": null }
c#, generics, inheritance, coordinate-system, constructor Title: Classes representing 2D points and pixels Question: How can I improve this code or make it tidier? public class Point2d : IEquatable<Point2d> { public double X { get; set; } public double Y { get; set; } #region constructor public Point2d(double x, double y) { X = x; Y = y; } public Point2d(double [] points) { if (points.GetLength(0) < 2) throw new Exception("[in Point2d(double [] points)] the array must be at least 2 elements long."); X = points[0]; Y = points[1]; } #endregion public void Print() { Console.Write("("); Console.Write(X); Console.Write(","); Console.Write(Y); Console.Write(") "); } public double GetDistance(Point2d otherPoint) { return Math.Sqrt(GetSquaredDistance(otherPoint)); } public double GetSquaredDistance(Point2d otherPoint) { return ((otherPoint.X - X) * (otherPoint.X - X)) + ((otherPoint.Y - Y) * (otherPoint.Y - Y)); } public Point2d GetTranslated(double x, double y) { return GetTranslated(new Point2d(x, y)); } public Point2d GetTranslated(Point2d center) { return new Point2d(X + center.X, Y + center.Y); } #region override string ToString() public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:0.00}, {1:0.00})", X, Y); return sb.ToString(); } #endregion
{ "domain": "codereview.stackexchange", "id": 43740, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, generics, inheritance, coordinate-system, constructor", "url": null }
c#, generics, inheritance, coordinate-system, constructor return sb.ToString(); } #endregion #region equality comparison implementations public override bool Equals(object other) { if (!(other is Point2d)) return false; return Equals((Point2d)other); } public bool Equals(Point2d other) { return Math.Round(X, 2) == Math.Round(other.X, 2) && Math.Round(Y,2) == Math.Round(other.Y, 2); } public override int GetHashCode() { return (int)Math.Round(Y * 31.0 + X, 0); // 31 = some prime number } public static bool operator ==(Point2d a1, Point2d a2) { return a1.Equals(a2); } public static bool operator !=(Point2d a1, Point2d a2) { return !a1.Equals(a2); } #endregion } public class Pixel2d : Point2d, IEquatable<Pixel2d> { public int State { get; set; } public Pixel2d(): this(0,0,0) { } public Pixel2d(int x, int y, int State) : base(x, y) { this.State = State; } #region equality comparison implementations public override bool Equals(object other) { if (!(other is Pixel2d)) return false; return Equals((Pixel2d)other); } public bool Equals(Pixel2d other) { return Math.Round(X, 2) == Math.Round(other.X, 2) && Math.Round(Y, 2) == Math.Round(other.Y, 2) && State == other.State; } public override int GetHashCode() { return (int)Math.Round(Y * 31.0 + X, 0); // 31 = some prime number } public static bool operator ==(Pixel2d a1, Pixel2d a2) { return a1.Equals(a2); } public static bool operator !=(Pixel2d a1, Pixel2d a2) { return !a1.Equals(a2); } #endregion } For example: Is it possible to merge IEquatable<> implementations into a single generic function or separate them into another class? Is there any better way to write 'Point2d and Pixel2d parameterized constructors? What else can be made tidier?
{ "domain": "codereview.stackexchange", "id": 43740, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, generics, inheritance, coordinate-system, constructor", "url": null }
c#, generics, inheritance, coordinate-system, constructor Answer: A fine example how modern C# can make your life so much easier! But first things first: Errors and maybe errors Your GetHashCode() is realy weak! Just take two example points (1|1) and (0|32) and compare their hashcode! Also your Point2d uses doubles for X and Y while Pixel2d runs on int, no technical issue because of implicit conversions but maybe not what youre looking for. Point2d.Equals(object other) will crash if you pass in null. X and Y are setable which is most likely not useful in any given scenario. I can't see the use case for the Point2d constructor taking an double[]. If you realy need it, atleast make it explicit and check for a length of exactly 2, instead of taking anything big enough. You allow an parameterless constructor on Pixel2d but disallow it for Point2d. Equals() look rather suspicious due to its rounding. Codestyle I do not see the benefit of regions here, so i'd rather remove them. Single line if-brackets are ommited while unnecessary ones for arithmetic expressions are included. I prefer always settings them for scopes and include arithmetic ones if its getting to complex, but thats personal preference after all. Read up on string interpolation and your ToString() can be a single line return $"({X:0.00}, {Y:0.00})"; // Note the leading $ Your Print() could be a single line of Console.Write($"({X},{Y}) "); Point2D.Equals() can be simplified to public override bool Equals(object other) { return other is Point2d point2d && Equals(point2d); }
{ "domain": "codereview.stackexchange", "id": 43740, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, generics, inheritance, coordinate-system, constructor", "url": null }
c#, generics, inheritance, coordinate-system, constructor Modern C# Beside string interpolation modern C# has way more tools to help you keep your code clean. This is an prime example why there are socalled "Records", capable of auto implementing Equals(), GetHashCode() and many more! Another term to look up is "Primary Constructors" and maybe you also want to check for nullable context, to easily spots errors like that nullreference exception on your Equals(). Simplified Using all these tools your code could look something like this: public record Point2d(double X, double Y) { public void Print() { Console.Write($"({X},{Y}) "); } public double GetDistance(Point2d otherPoint) { return Math.Sqrt(GetSquaredDistance(otherPoint)); } public double GetSquaredDistance(Point2d otherPoint) { return (otherPoint.X - X) * (otherPoint.X - X) + (otherPoint.Y - Y) * (otherPoint.Y - Y); } public Point2d GetTranslated(double x, double y) { return GetTranslated(new Point2d(x, y)); } public Point2d GetTranslated(Point2d center) { return new Point2d(X + center.X, Y + center.Y); } public override string ToString() { return $"({X:0.00}, {Y:0.00})"; } public virtual bool Equals(Point2d? other) { return other != null && Math.Round(X, 2) == Math.Round(other.X, 2) && Math.Round(Y, 2) == Math.Round(other.Y, 2); } } And public record Pixel2d(double X, double Y, int State) : Point2d(X, Y) { public int State { get; set; } = State; public virtual bool Equals(Pixel2d? other) { return base.Equals(other) && State == other.State; } } Hope that helps!
{ "domain": "codereview.stackexchange", "id": 43740, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, generics, inheritance, coordinate-system, constructor", "url": null }
javascript, node.js, mongodb, graphql Title: Optimising a simple graphql mutation resolver Question: I am writing a resolver for a typical updateUser mutation with node, Apollo Server and mongoDB. I want to make it such that, when the email input is provided, it will update the email; when the password input is provided, it will hash and then update the password; and when the plan input is provided, it will update the plan - but I only want the compulsory field when calling the mutation at the front-end to be id (and at least one of email, password or plan). Here is my code: export const updateUser = async ( _: undefined, { input: { id, email, password, plan } }: any ): Promise<any> => { const collection = getCollection(USERS_COLLECTION_NAME); try { const updateWith = (() => { const toUpdate: any = {}; if (email) toUpdate['email'] = email; if (password) toUpdate['hashedPassword'] = (async () => await bcrypt.hash(password, 10))(); if (plan) toUpdate['plan'] = plan; return toUpdate; })(); const updateResult = await collection.findOneAndUpdate( { _id: new mongodb.ObjectId(id), // new mongodb.ObjectId needed, otherwide null; converts to BSON }, { $set: updateWith, }, { returnDocument: 'after' } // returns updated user rather than user before updates ); if (!updateResult?.value) { throw new HttpError(500, 'Could not update user'); } // note: it updates the user even if the value provided is the same as the existing value return updateResult.value; } catch (error: any) { throw new HttpError(error.statusCode, error.message); } }; It would be great to get some feedback and become a better developer, hence I have a few questions:
{ "domain": "codereview.stackexchange", "id": 43741, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, mongodb, graphql", "url": null }
javascript, node.js, mongodb, graphql It would be great to get some feedback and become a better developer, hence I have a few questions: Could the updateWith function be improved? Is it correct to add another try-catch block inside the inner async function (near if (password)), despite there being an outer one? Is it bad practice to have one resolver to update multiple fields rather than creating separate resolvers for each field (e.g. a mutation for changeUserEmail, changeUserPlan, changeUserPassword, etc)? The code has to run many if statements, so I’m wondering whether it’s using unnecessary bandwidth What should the type be for error in the catch block, rather than any? Should updateWith be outside the try block? Thanks for any advice. Answer: Introduction Exposing a single mutation to update a whole model is one of the pitfalls for most inexperienced developers in a domain driven environment. I've made the mistake countless times. The queries and mutations you expose should be driven by the use-cases of your business. In this answer, I'll be assuming a few things regarding your use-cases. You'll have to adapt them to your needs. What do you mean use-cases? When I talk about use-cases, I think a better phrase would be "user oriented actions" or "user oriented scenarios". Essentially, what actions can a user trigger? The specific "action" names from the user's point of view should be reflected in your backend. For example, it's unlikely that there is a use-case where the user will at the same time update their email, password and plan all at once? Most flows are separated. A user can change plans A user can reset their password A user can change their email
{ "domain": "codereview.stackexchange", "id": 43741, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, mongodb, graphql", "url": null }
javascript, node.js, mongodb, graphql A user can change plans A user can reset their password A user can change their email These are specific use-cases which have their own independant flows. For example, in the password reset flow, the user clicks "reset password" button, the user needs to check their email for the reset password link, then the user needs to choose a new password. Ubiquitous language In the book, Domain Driven Design by Eric Evans, he illustrates the importance of building a vocabulary understandable between the developer team and the domain expert. A domain expert is simply someone who understands the business that your application will reflect. In this scenario, it would be your user. When you interact with your users and talk about some of the processes that exist, the concept of "udpateUser" probably wouldn't make much sense to the user. If the user has an issue with the password reset, they're not going to contact you and say "I'm having issues updating my user in your database", they'll probably say something like "I'm unable to reset my password". And this is an interesting phenomenon. Sure, if you work by yourself on an application you'll probably be able find the issue at hand quickly since it's your code. However, realistically, in a business you'll work on a large codebase that may have many developers and you may find yourself having to debug a scenario that you may have never worked on. It would be helpful if what the user is describing is reflected exactly in the backend. So you don't have to do some mental gymnastics to understand that "reset password" = "update user" (even if this scenario is simple). Expose a resolver for each use-case I would probably do something like this. input ForgetPasswordInput { email: String! }
{ "domain": "codereview.stackexchange", "id": 43741, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, mongodb, graphql", "url": null }
javascript, node.js, mongodb, graphql input ForgetPasswordInput { email: String! } input ResetPasswordInput { password: String! # The reset email contains a automatically generated url, # usually containg some form of a hash, which can be passed # here along with the new password to validate that it comes from the user secretHash: String! } enum Plan { PLAN_ONE PLAN_TWO } input ChangePlanInput { plan: Plan! } input ChangeEmailInput { email: String! } type Mutation { # Unauthenticated actions forgetPassword(input: ForgetPasswordInput!): Boolean! resetPassword(input: ResetPasswordInput!): Boolean! # Authenticated actions changePlan(input: ChangePlanInput!): User! changeEmail(input: ChangeEmailInput!): User! } export const forgetPassword = () => { // todo } export const resetPassword = () => { // todo } export const changePlan = () => { // todo } export const changeEmail = () => { // todo } Here you're probably wondering where did the user id go? Well, you don't need the id for the forgetPassword and resetPassword mutation since the user probably won't be authenticated. And if they do request a password change while authenticated, it can go through the same flow (doesn't matter). For the changePlan and the changeEmail mutation, you don't need to pass the current user's id since they are already authenticated. You already have access to the user's access_token (or jwt token, etc). You can provide apollo a custom function (where you fetch the user id using the access token) and inject it in graphql's context. Something like: const server = new ApolloServer({ context: ({ req }) => ({ // create a function to fetch the user id from the token userId: getUserIdFromAccessToken(req.headers.authorization) }) // other props });
{ "domain": "codereview.stackexchange", "id": 43741, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, mongodb, graphql", "url": null }
javascript, node.js, mongodb, graphql Once you inject it properly in the context, you can then access it via the resolver like so: export const changePlan = (parent, args, context) => { const { userId } = context; // I named it "userId" but it's completely customizable }
{ "domain": "codereview.stackexchange", "id": 43741, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, mongodb, graphql", "url": null }
python, tkinter, polymorphism Title: Parametric visibility and order of tkinter labels Question: I'm writing software which allows a user to view data in a number of different formats, and they can switch between formats at any time. I'm wondering if there's a better way to do this than switching between subclasses, and if not, if there's a better way to write this than I have. import tkinter as tk from tkinter import ttk class Display(ttk.Frame): def __init__(self, master=None): ttk.Frame.__init__(self, master, relief='sunken', padding='20') self.widgets = [ ttk.Label(self, text="Data Value #1"), ttk.Label(self, text="Data Value #2"), ttk.Label(self, text="Data Value #3"), ttk.Label(self, text="Data Value #4"), ttk.Label(self, text="Data Value #5"), ttk.Label(self, text="Data Value #6"), ttk.Label(self, text="Data Value #7"), ttk.Label(self, text="Data Value #8"), ttk.Label(self, text="Data Value #9"), ttk.Label(self, text="Data Value #10"), ] def show(self): for i in self.widgets: i.pack() class Display1(Display): def show(self): for i, widget in enumerate(self.widgets): if i % 2 == 0: widget.pack() class Display2(Display): def show(self): for i, widget in enumerate(self.widgets): if i % 2 == 1: widget.pack() class Display3(Display): def show(self): for i, widget in enumerate(self.widgets): if i > 4: widget.pack() class Display4(Display): def show(self): for i, widget in enumerate(self.widgets): if i < 5: widget.pack() class Display5(Display): def show(self): for i, widget in enumerate(self.widgets): self.widgets[-i].pack() class Window(tk.Tk): def __init__(self): tk.Tk.__init__(self)
{ "domain": "codereview.stackexchange", "id": 43742, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, polymorphism", "url": null }
python, tkinter, polymorphism class Window(tk.Tk): def __init__(self): tk.Tk.__init__(self) # # # Initialize buttons to select how to view the data. self.selection = tk.StringVar(self, value="Option 1") self.display_options = [ ttk.Radiobutton(self, text="Option 1", variable=self.selection, value="Option 1", command=self.change_display), ttk.Radiobutton(self, text="Option 2", variable=self.selection, value="Option 2", command=self.change_display), ttk.Radiobutton(self, text="Option 3", variable=self.selection, value="Option 3", command=self.change_display), ttk.Radiobutton(self, text="Option 4", variable=self.selection, value="Option 4", command=self.change_display), ttk.Radiobutton(self, text="Option 5", variable=self.selection, value="Option 5", command=self.change_display), ] for i, button in enumerate(self.display_options): button.grid(row=i, column=1, padx=20) # # # Initialize the frame holding the data self.data_frame = Display(self) self.data_frame.grid(row=0, column=0, rowspan=10) self.data_frame.show() def change_display(self): for i in self.data_frame.pack_slaves(): i.pack_forget() self.data_frame.grid_forget() match self.selection.get(): case "Option 1": self.data_frame = Display1(self) case "Option 2": self.data_frame = Display2(self) case "Option 3": self.data_frame = Display3(self) case "Option 4": self.data_frame = Display4(self) case "Option 5": self.data_frame = Display5(self) case _: self.data_frame = Display(self) self.data_frame.show() self.data_frame.grid(row=0, column=0, rowspan=10) if __name__ == '__main__': win = Window() win.mainloop()
{ "domain": "codereview.stackexchange", "id": 43742, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, polymorphism", "url": null }
python, tkinter, polymorphism if __name__ == '__main__': win = Window() win.mainloop() The program initializes a window with a selection of formats to view the data, and shows the data in some default format. Each subclass of Display only overrides the show() method. This isn't the entire program I'm working on, but the important part is that the subclasses of Display don't actually initialize themselves, and only override certain parent methods. Is there a better way to change the way the data is displayed than this? Answer: Display and Window should both follow has-a rather than is-a for better loose coupling; that is, they should keep the widgets to themselves and only selectively expose functionality as needed. Subclassing is not justified in this case. Your conditional packing loops (1) should not use conditions at all, and (2) should simply iterate over a range of indices instead. You had the right(ish) idea to use a Var, but it shouldn't be a StringVar - it should be an IntVar, since that's usable as an index. You need to make use of loops to fill your label and radio lists. Rather than manually checking every single option, just pull the value of the IntVar and use that as an index into a tuple of ranges. Rather than command, prefer to trace the variable itself. After these changes you will not need to save your display_options and the parent Tk as members of your class. Suggested import tkinter as tk from tkinter import ttk from typing import Sequence displays = ( range(1, 10, 2), range(2, 11, 2), range(6, 11, 1), range(1, 6, 1), range(10, 0, -1), ) class Display: def __init__(self, parent: tk.Tk) -> None: self.frame = ttk.Frame(parent, relief='sunken', padding='20') self.frame.grid(row=0, column=0, rowspan=10) self.labels = [ ttk.Label(self.frame, text=f'Data Value #{i}') for i in range(1, 11) ]
{ "domain": "codereview.stackexchange", "id": 43742, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, polymorphism", "url": null }
python, tkinter, polymorphism def show(self, indices: Sequence[int]) -> None: for label in self.frame.pack_slaves(): label.pack_forget() for i in indices: self.labels[i - 1].pack() class Window: def __init__(self): parent = tk.Tk() self.mainloop = parent.mainloop self.selection = tk.IntVar(parent) self.selection.trace_add('write', self.change_display) for i in range(5): button = ttk.Radiobutton( parent, text=f"Option {i + 1}", variable=self.selection, value=i, ) button.grid(row=i, column=1, padx=20) self.data_frame = Display(parent) self.selection.set(0) def change_display(self, name: str, index: str, mode: str) -> None: display = displays[self.selection.get()] self.data_frame.show(display) if __name__ == '__main__': win = Window() win.mainloop() An alternative method involves calls to grid/gridremove instead of pack: import tkinter as tk from tkinter import ttk from typing import Sequence DISPLAYS = ( range( 1, 10, 2), range( 2, 11, 2), range( 6, 11, 1), range( 1, 6, 1), range(10, 0, -1), ) class Display: def __init__(self, parent: tk.Tk) -> None: self.frame = ttk.Frame(parent, relief='sunken', padding='20') self.frame.grid(row=0, column=0, rowspan=5) self.labels = [ ttk.Label(self.frame, text=f'Data Value #{i}') for i in range(1, 11) ] def show(self, indices: Sequence[int]) -> None: for y, i in enumerate(indices): self.labels[i - 1].grid(row=y, column=0) for i in set(range(1, 11)) - set(indices): self.labels[i - 1].grid_remove() class Window: def __init__(self) -> None: parent = tk.Tk() self.mainloop = parent.mainloop self.selection = tk.IntVar(parent) self.selection.trace_add('write', self.change_display)
{ "domain": "codereview.stackexchange", "id": 43742, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, polymorphism", "url": null }
python, tkinter, polymorphism for i in range(5): button = ttk.Radiobutton( parent, text=f"Option {i + 1}", variable=self.selection, value=i, ) button.grid(row=i, column=1, padx=20) self.data_frame = Display(parent) self.selection.set(0) def change_display(self, name: str, index: str, mode: str) -> None: display = DISPLAYS[self.selection.get()] self.data_frame.show(display) if __name__ == '__main__': Window().mainloop()
{ "domain": "codereview.stackexchange", "id": 43742, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, tkinter, polymorphism", "url": null }
python, performance, beginner, mathematics, integer Title: Find all ways to express each of a list of even numbers as the sum of 2 positive, even numbers Question: This code was a challenge from a friend. Essentially she wanted a way to "Divide an even number into 2 even numbers." So I made this quick and dirty Python program to find the solutions up to 1000000. I'd like to know if there's a way to make it faster and improve readability. from progress.bar import Bar def checksolve(a,b,c): return a==(2*b+2*c) def checknumber(a): results=[] for b in range(1,a): for c in range(1,a): if checksolve(a,b,c) and tuple((a,2*c,2*b)) not in results: results.append(tuple((a,2*b,2*c))) return results if __name__=='__main__': bar=Bar('computing',max=len(range(0,1000002,2)),suffix='%(percent)d%%') for a in range(0,1000002,2): solutions=checknumber(a) for solution in solutions: x,y,z=solution with open('caro.txt', 'a+') as f: f.write('{}={}+{}\n'.format(x,y,z)) bar.next() Answer: In terms of readability, one major thing is spacing. PEP-8 recommends 2 blank lines between top level functions (although that's probably unnecessary for something this short), a space on each side of most binary operators including assignment, and a space after commas in places like sequences and function calls. For more specific things in your code, there are a couple things that could be more clear. if checksolve(a,b,c) and tuple((a,2*c,2*b)) not in results: results.append(tuple((a,2*b,2*c)))
{ "domain": "codereview.stackexchange", "id": 43743, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, mathematics, integer", "url": null }
python, performance, beginner, mathematics, integer The tuple() is unneeded since using parentheses like in (a,2*b,2*c) is already the form of a tuple literal. Also while keeping your algorithm, we can change the loop to be more efficient. Since we don't care about the order of b and c, it's redundant to check numbers for c that are less than b (they will have already been tested when b was that value previously). This avoids equivalent checksolve calls, and can also simplify the logic since we don't have to check for duplicate solutions. for b in range(1, a): for c in range(b, a): # Start from b if checksolve(a, b, c): results.append((a, 2*b, 2*c)) For your main code, I like that you're using a with to open the file and a __name__ == '__main__' guard, but I think it would make sense to open it once for writing instead of once for every solution for appending. You might also want to put the logic into a main() function for if you import the module somewhere else. if __name__ == '__main__': bar = Bar('computing', max=len(range(0, 1000002, 2)), suffix='%(percent)d%%') with open('caro.txt', 'w') as f: # Will overwrite a current file instead of appending to for a in range(0, 1000002, 2): solutions = checknumber(a) for solution in solutions: x, y, z = solution f.write(f'{x}={y}+{z}\n') # I'd prefer f-string formatting if on python>=3.6 bar.next() All together this ran about 360 times as fast for me when doing up to 100. However, even though this was an improvement to your algorithm, using a search solution like this at all is unnecessary. It's pretty simple to see that as we increase one term by two, the other should decrease by two. Implementing this is also about 3 times as fast as before, and completely removes the need for a separate function. if __name__ == '__main__': bar = Bar('computing', max=len(range(0, 1000002, 2)), suffix='%(percent)d%%')
{ "domain": "codereview.stackexchange", "id": 43743, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, mathematics, integer", "url": null }
python, performance, beginner, mathematics, integer with open('caro.txt', 'w') as f: for a in range(0, 1000002, 2): for off in range(2, a//2 + 1, 2): f.write(f'{a}={off}+{a - off}\n') bar.next() Algorithmically, this will be very fast. However it's still going to be an issue for writing the output to the file. The size of output for all the numbers up to 1,000,000 like in your example would be somewhere around 5TB I believe. So I'd recommend sticking to a smaller size.
{ "domain": "codereview.stackexchange", "id": 43743, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, mathematics, integer", "url": null }
performance, google-apps-script, google-sheets Title: Slow performance of Google Apps Script that updates data Question: I have a Google Spreadsheet with a few hundreds of sheets there. Users update those sheets with new data under a strict and specific template. I created a Google Apps Script where once every while, I run it to change several things on every sheet, by keeping the original data intact and export those in multiple CSV files I store in Google Drive. In more details, Iterate on every sheet Duplicate the current one Run a set of functions on every cell I have to update (~500 on each) Export the sheet to CSV and store it in Drive Delete the temp sheet Move to the next one Number 3 is the most time consuming. It might takes 30-40 seconds for every sheet and the functions are simple math formulas or dictionaries. Here is the code which I have removed functions that I just repeat for more cells. function saveAsCSV() { var maxSheetID = 100; var sheetsFolder = DriveApp.getFoldersByName('sheetsFolder_CSV').next(); var folder = sheetsFolder.createFolder('sheetsFolder' + new Date().getTime()); for (var sheetID = 1; sheetID <= maxSheetID; sheetID++) { createTempSheet(); copyRowsWithCopyTo(sheetID); var tempSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('temp'); tempSheet.getDataRange().setDataValidation(null); //remove all validations I have var cell1 = tempSheet.getRange(5,4); cell1.setValue(function1(cell1.getValue())); var cell2 = tempSheet.getRange(6,4); cell2.setValue(function2(cell2.getValue())); var cell3 = tempSheet.getRange(7,4); cell3.setValue(function3(cell3.getValue())); //continue for several cells like this on specific i,j indexes. No pattern. //Table for (var p = 9; p <= 30; p++) { var tCell1 = tempSheet.getRange(p,2); tCell1.setValue(function5(tCell1.getValue())); var tCell2 = tempSheet.getRange(p,3); tCell2.setValue(function6(tCell2.getValue()));
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
performance, google-apps-script, google-sheets var tCell2 = tempSheet.getRange(p,3); tCell2.setValue(function6(tCell2.getValue())); //continue for several cells like this with dynamic p and several columns } fileName = sheetID + ".csv"; var csvFile = convertRangeToCsvFile_(fileName, tempSheet); folder.createFile(fileName, csvFile); } Browser.msgBox('Files are waiting in a folder named ' + folder.getName()); } function createTempSheet() { var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var tempSheet = activeSpreadsheet.getSheetByName("temp"); if (tempSheet != null) { activeSpreadsheet.deleteSheet(tempSheet); } tempSheet = activeSpreadsheet.insertSheet(); tempSheet.setName("temp"); } function convertRangeToCsvFile_(csvFileName, sheet) { // get available data range in the spreadsheet var activeRange = sheet.getDataRange(); try { var data = activeRange.getValues(); var csvFile = undefined; // loop through the data in the range and build a string with the csv data if (data.length > 1) { var csv = ""; for (var row = 0; row < data.length; row++) { for (var col = 0; col < data[row].length; col++) { if (data[row][col].toString().indexOf(",") != -1) { data[row][col] = "\"" + data[row][col] + "\""; } } // join each row's columns // add a carriage return to end of each row, except for the last one if (row < data.length-1) { csv += data[row].join(",") + "\r\n"; } else { csv += data[row]; } } csvFile = csv; } return csvFile; } catch(err) { Logger.log(err); Browser.msgBox(err); } }
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
performance, google-apps-script, google-sheets function copyRowsWithCopyTo(sourceName) { let spreadSheet = SpreadsheetApp.getActiveSpreadsheet(); let sourceSheet = spreadSheet.getSheetByName(sourceName); let sourceRange = sourceSheet.getDataRange(); let targetSheet = spreadSheet.getSheetByName('temp'); sourceRange.copyTo(targetSheet.getRange(1, 1)); } Answer: As the documentation says, Using JavaScript operations within your script is considerably faster than calling other services. Anything you can accomplish within Google Apps Script itself will be much faster than making calls that need to fetch data from Google's servers or an external server, such as requests to Spreadsheets, Docs, Sites, Translate, UrlFetch, and so on. Your scripts will run faster if you can find ways to minimize the calls the scripts make to those services. The slowest part in the script is all those .getValue() and .setValue() calls. Not only is the script making those calls, it is alternating them as well, even in the same line(rg.setValue(function(rg.getValue()))). Alternating read and write is slow: Every time you do a read, we must first empty (commit) the write cache to ensure that you're reading the latest data (you can force a write of the cache by calling SpreadsheetApp.flush()). Likewise, every time you do a write, we have to throw away the read cache because it's no longer valid. Therefore if you can avoid interleaving reads and writes, you'll get full benefit of the cache. http://googleappsscript.blogspot.com/2010/06/optimizing-spreadsheet-operations.html The script here leaves out essential information. What does function1 do? More importantly, whether function1 does anything to the data. Does it modify the sheet again? Also, when getting the csv, does the sheet make any calculations through formula? Ideally, Your script structure should look like: INPUT: Get data from one sheet OUTPUT: Set modified data to Drive This implies:
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
performance, google-apps-script, google-sheets INPUT: Get data from one sheet OUTPUT: Set modified data to Drive This implies: no temporary sheet creation, no repeated get/set calls, no relying on sheet formulas after getting data Other minor changes include: Use const and let as needed instead of declaring all variables as var. This helps the javascript engine optimize the memory and processing of such variables The script repeats almost all the code multiple times. Practice DRY(Don't Repeat Yourself) principle. See eg below. Use loops where possible: Even in cases, where there isn't a pattern, you can create a list of indexes that you want and then loop over them. insertSheet is able to create new sheet with old sheet as a template. So, the functions createTempSheet and copyRowsWithCopyTo are completely unnecessary. console is a newer standard class. Use it instead of Logger
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
performance, google-apps-script, google-sheets console is a newer standard class. Use it instead of Logger Script with sample modifications: function saveAsCSV() { const maxSheetID = 100; const sheetsFolder = DriveApp.getFoldersByName('sheetsFolder_CSV').next(); const folderName = 'sheetsFolder' + new Date().getTime(); const folder = sheetsFolder.createFolder(folderName); const ss = SpreadsheetApp.getActiveSpreadsheet(); for (let sheetID = 1; sheetID <= maxSheetID; sheetID++) { /*needed? why not directly get the data*/ const tempSheet = ss.insertSheet( 'temp', 1, { template: ss.getSheetByName(sheetID), } ), datarange = tempSheet.getDataRange(), /*1 GET call*/data = datarange.getValues(), indexes = [ [5, 4], // automatically use index to calculate function number [6, 4], [7, 4, 'function3'], // or specify a function ]; datarange.setDataValidation(null); //remove all validations I have indexes.forEach(/*DRY loop*/ ([i, j, func], funcIdx) => (data[i][j] = this[ func ?? `function${funcIdx + 1}`](data[i][j])) ); //continue for several cells like this on specific i,j indexes. No pattern. //Table for (let p = 9; p <= 30; p++) { data[p][2] = function5(data[p][2]); data[p][3] = function5(data[p][3]); //continue for several cells like this with dynamic p and several columns } /*needed?1 SET call*/ datarange.setValues(data); const fileName = sheetID + '.csv'; const csvFile = convertRangeToCsvFile_(/*DRY*/data); folder.createFile(fileName, csvFile); ss.deleteSheet(tempSheet); } Browser.msgBox('Files are waiting in a folder named ' + folderName/*DRY*/); }
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
performance, google-apps-script, google-sheets function convertRangeToCsvFile_(data) { try { let csvFile; // loop through the data in the range and build a string with the csv data if (data.length > 1) { let csv = ''; for (let row = 0; row < data.length; row++) { for (let col = 0; col < data[row].length; col++) { if (data[row][col].toString().indexOf(',') != -1) { data[row][col] = '"' + data[row][col] + '"'; } } // join each row's columns // add a carriage return to end of each row, except for the last one if (row < data.length - 1) { csv += data[row].join(',') + '\r\n'; } else { csv += data[row]; } } csvFile = csv; } return csvFile; } catch (err) { console.log(err); Browser.msgBox(err); } }
{ "domain": "codereview.stackexchange", "id": 43744, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, google-apps-script, google-sheets", "url": null }
java, programming-challenge, change-making-problem Title: Coin Change in Java Question: Inspired by a leetcode exercise, I wrote my own coin changer: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 CoinType public class CoinType implements Comparable<CoinType>{ private final int value; public CoinType(int value){ this.value = value; } public int getValue() { return value; } @Override public String toString() { return "value = "+value; } @Override public int compareTo(CoinType o) { return -1 * Integer.compare(value, o.getValue()); //biggest first! } } CoinTypes public class CoinTypes { private List<CoinType> coinTypes = new ArrayList<>(); public CoinTypes(int[] samples) { coinTypes = new ArrayList<>(Arrays.stream(samples).mapToObj(CoinType::new).toList()); Collections.sort(coinTypes); } public List<CoinType> getCoinTypes() { return coinTypes; } } Change (returned money, my bad english, sorry) public class Change { private Map<CoinType, Integer> change = new HashMap<>(); private int amount; public Change(int amount) { this.amount = amount; } public int getRemaining() { int sum = change.entrySet().stream().mapToInt(Change::multiply).sum(); return amount - sum; } public static int multiply(Map.Entry<CoinType, Integer> entrySet){ return entrySet.getKey().getValue() * entrySet.getValue(); } public void add(CoinType coinType, int amount) { change.put(coinType, amount); }
{ "domain": "codereview.stackexchange", "id": 43745, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge, change-making-problem", "url": null }
java, programming-challenge, change-making-problem public void add(CoinType coinType, int amount) { change.put(coinType, amount); } @Override public String toString() { return change.entrySet().stream().map(e -> ""+e.getValue()+" coins of "+e.getKey()).collect(Collectors.joining(",")); } public int getAmountCoins() { return change.values().stream().mapToInt(i -> i).sum(); } public boolean hasRemaining() { return getRemaining() != 0; } } CoinChanger public class CoinChanger { private final CoinTypes coinTypes; public CoinChanger(int[] coinTypes) { this.coinTypes = new CoinTypes(coinTypes); } public Change change(int result) { Change change = new Change(result); for(CoinType coinType: coinTypes.getCoinTypes()){ int amount = change.getRemaining() / coinType.getValue(); change.add(coinType, amount); } if(change.hasRemaining()){ throw new IllegalArgumentException("cannot change to that amount with my coinTypes"); } return change; } } App running example public class App{ public static void main(String[] args) { int[] coins = {1,2,5}; int amount = 11; CoinChanger coinChanger = new CoinChanger(coins); try { Change change = coinChanger.change(amount); System.out.println(change); }catch (IllegalArgumentException e){ System.out.println("cannot give change: "+e); } } }
{ "domain": "codereview.stackexchange", "id": 43745, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge, change-making-problem", "url": null }
java, programming-challenge, change-making-problem Answer: First, and most importantly, this program, as currently written, fails for some inputs where it shouldn't. For example, it can't make change for a value of 11 when using coins of values 2 and 5, even though 3*2 + 1*5 = 11 That aside, I'm not sure the CoinTypes class is doing much here. It's just a wrapper around a List<CoinType>, only ever interacted with as a way to get to that list. Using the List<CoinType> directly seems more appropriate The CoinType class almost feels overkill as well, being a thin wrapper around an int. That said, it arguably helps a bit with readability and clarity (Map<CoinType, Integer> is more meaningful than Map<Integer, Integer>), but I'm still not a huge fan Change::multiply does not interact with the Change object's state, and can be static. It also does not really seem like part of Change's public-facing API (no object but a Change object is expected to ever call it), so I'd argue it should be made private
{ "domain": "codereview.stackexchange", "id": 43745, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, programming-challenge, change-making-problem", "url": null }
rust, statistics Title: Calculate mode in Rust Question: I'm new to Rust and still getting used to the ownership model. I'm done with chapter 8 of the book and was trying to solve this exercise: Given a list of integers, use a vector and return the [...] mode (the value that occurs most often; a hash map will be helpful here) of the list. Here's my solution: use std::collections::HashMap; pub fn vectors() { let mut numbers: Vec<i32> = vec![ 12, 15, 6, 44, 6, 32, 77, 77, 77, 77, 77, 94, 6, 2, 67, 0, 25, 14, 84, 81, 59, 31, 7, 9, ]; println!("{:?}", numbers); // calculating and displaying the mode let mut numbers_count = HashMap::new(); for num in &numbers { let count = numbers_count.entry(num).or_insert(0); *count += 1; } let mut mode = 0; let mut prev_value = 0; for (key, value) in &numbers_count { if *value > prev_value { prev_value = *value; mode = **key; } } println!("Mode: {}", mode); } The code works but... is this considered a good solution? After I finished I searched online and found this alternative which seems to be more accepted. Also, on line 21 I had to use the dereference operator twice; is this ok, or is it considered bad practice? Answer: that looks like some really nice code, there is a few things I want to highlight, though: numbers does not need to be declared mutable (and thus should not be). Always declare with the least powerful borrowing specification possible. That simplifies the compiler's job and makes the checker more valuable by exposing unintended mutability. numbers and numbers_count are not really stellar names, but then again the code is small, and very clear, so that should be fine.
{ "domain": "codereview.stackexchange", "id": 43746, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, statistics", "url": null }
rust, statistics There is a much more powerful way of expressing the "get the key associated with the maximum value", using Iterator::max_by, which condenses the whole map iteration and two variables to: let (mode, _) = numbers_count.iter() .max_by(|(_, lv), (_, rv)| lv.cmp(rv)) .expect("We need at least one value to calculate a mode"); return **mode; Note that this update introduces a subtle semantic difference in that the last element in the iter() with the most items in the list is given instead of the first. But since the iter() returned by a HashMap is not ordered in the first place, that should not make any difference :) As it is, with this solution you are not learning about one of the most powerful features of the borrow checker: Argument passing to functions. Instead of just working off a constant vector, it's much more enlightening to pass the vector as an argument to vectors pub fn mode_v1(numbers: &Vec<i32>) -> i32 { let mut numbers_count = HashMap::new(); for num in numbers { let count = numbers_count.entry(num).or_insert(0); *count += 1; } ... Note how this moves the borrow behaviour enforcement to the caller of the method. This can of course be further extended to cover cases like there not being elements in the vector, but not wanting to panic when determining the mode. Another interesting step is to move away from the type bound of Vec<i32> to something a little more generic, by accepting more collection-y things. For that rust has Slice which can be easily introduced as follows: pub fn mode(numbers: &[i32]) -> Option<i32> { // or i32, depending on error behaviour This in turn can then be extended to include generics to allow for a more diverse set of inputs. Maybe you want the mode of a list of i64s or i8 or something else entirely?: pub fn mode<T>(elements: &[T]) -> Option<T> where T: Ord + Hash + Copy {
{ "domain": "codereview.stackexchange", "id": 43746, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, statistics", "url": null }
strings, vba, vb6 Title: A more readable InStr: StringContains Question: Consider the following: If myString = "abc" Or myString = "def" [...] Or myString = "xyz" Then In C# when myString == "abc" the rest of the conditions aren't evaluated. But because of how VB works, the entire expression needs to be evaluated, even if a match is found with the first comparison. Even worse: If InStr(1, myString, "foo") > 0 Or InStr(1, myString, "bar") > 0 [...] Then I hate to see these things in code I work with. So I came up with these functions a while ago, been using them all over the place, was wondering if anything could be done to make them even better: StringContains is used like If StringContains("this is a sample string", "string"): Public Function StringContains(string_source, find_text, Optional ByVal caseSensitive As Boolean = False) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String find = CStr(find_text) src = CStr(string_source) If caseSensitive Then StringContains = (InStr(1, src, find, vbBinaryCompare) <> 0) Else StringContains = (InStr(1, src, find, vbTextCompare) <> 0) End If End Function StringContainsAny works in a very similar way, but allows specifying any number of parameters so it's used like If StringContainsAny("this is a sample string", false, "foo", "bar", string"): Public Function StringContainsAny(string_source, ByVal caseSensitive As Boolean, ParamArray find_strings()) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String, i As Integer, found As Boolean src = CStr(string_source) For i = LBound(find_strings) To UBound(find_strings) find = CStr(find_strings(i)) If caseSensitive Then found = (InStr(1, src, find, vbBinaryCompare) <> 0) Else found = (InStr(1, src, find, vbTextCompare) <> 0) End If If found Then Exit For Next
{ "domain": "codereview.stackexchange", "id": 43747, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, vba, vb6", "url": null }
strings, vba, vb6 StringContainsAny = found End Function StringMatchesAny will return True if any of the passed parameters exactly matches (case-sensitive) the string_source: Public Function StringMatchesAny(string_source, ParamArray find_strings()) As Boolean 'String-typed local copies of passed parameter values: Dim find As String, src As String, i As Integer, found As Boolean src = CStr(string_source) For i = LBound(find_strings) To UBound(find_strings) find = CStr(find_strings(i)) found = (src = find) If found Then Exit For Next StringMatchesAny = found End Function Answer: My 2 cents, the first function seems fine, you could make it a little DRYer by just setting the compareMethod in your if statement and then have only 1 complicated line of logic. And if you are doing that, you might as well put the Cstr's there. Public Function StringContains(haystack, needle, Optional ByVal caseSensitive As Boolean = False) As Boolean Dim compareMethod As Integer If caseSensitive Then compareMethod = vbBinaryCompare Else compareMethod = vbTextCompare End If 'Have you thought about Null? StringContains = (InStr(1, CStr(haystack), CStr(needle), compareMethod) <> 0) End Function Notice as well that I love the idea of searching for needles in haystacks, I stole that from PHP. For StringContainsAny, you are not using the code you wrote for StringContains, you repeat it. If you were to re-use the first function, you could do this: Public Function StringContainsAny(haystack, ByVal caseSensitive As Boolean, ParamArray needles()) As Boolean Dim i As Integer For i = LBound(needles) To UBound(needles) If StringContains(CStr(haystack), CStr(needles(i)), caseSensitive) Then StringContainsAny = True Exit Function End If Next StringContainsAny = False 'Not really necessary, default is False.. End Function
{ "domain": "codereview.stackexchange", "id": 43747, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, vba, vb6", "url": null }
strings, vba, vb6 StringContainsAny = False 'Not really necessary, default is False.. End Function For the last one I wanted to you consider passing values that you will convert as ByVal, since you are going to make a copy anyway of that variable. Public Function StringMatchesAny(ByVal string_source, ParamArray potential_matches()) As Boolean string_source = CStr(string_source) ... 'That code taught me a new trick ;) End Function
{ "domain": "codereview.stackexchange", "id": 43747, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, vba, vb6", "url": null }
python Title: Update a dict with list values with another dict Question: The code below works. The question is if there is a better and more elegant (maintainable) way. The task is to update a Python dictionary which values are lists with another dictionary with the same structure (values are lists). The usual dict.update() doesn't work because values (the lists) are replaced not updated (via list.extend()). Example: a = {'A': [1, 2], 'C': [5]} b = {'X': [8], 'A': [7, 921]} Using dict.update() would result in {'A': [7, 921], 'C': [5], 'X': [8]} But A should become [1, 2, 7, 921]. Here is my working solution: #!/usr/bin/env python3 from typing import Any def update_dict_with_list_values( a: dict[Any,list], b: dict[Any,list]) -> dict[Any,list]: """Update a dictionary and its list values from another dict.""" # create a local deep copy a = a.copy() for key in a: try: # remove the list b_value = b.pop(key) except KeyError: pass else: # extend the list a[key] = a[key] + b_value # add the rest of keys that are not present in the dict to update a.update(b) return a if __name__ == '__main__': a = { 'A': [1, 2], 'C': [5] } b = { 'X': [8], 'A': [7, 921] } c = update_dict_with_list_values(a, b) print(c) # -> {'A': [1, 2, 7, 921], 'C': [5], 'X': [8]} Answer: Avoid conditionals by using defaultdict. There is only one case: you want to extend-merge lists from the second dictionary, with the target defaulting to an empty list. from collections import defaultdict from typing import Any, Iterable def update_dict_with_list_values( a: dict[Any, list], b: dict[Any, Iterable], ) -> dict[Any, list]: """Update a dictionary and its list values from another dict.""" union = defaultdict(list, a) for k, values in b.items(): union[k].extend(values) return union
{ "domain": "codereview.stackexchange", "id": 43748, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python for k, values in b.items(): union[k].extend(values) return union This assumes that you don't mind mutating the value lists of a, which is a risky assumption indeed. To avoid this you would deep-copy a first, via something like union = defaultdict(list, ( (k, list(v)) for k, v in a.items() )) Or, for a very different approach which is naturally immune to side-effect concerns, return { k: a.get(k, []) + b.get(k, []) for k in a.keys() | b.keys() }
{ "domain": "codereview.stackexchange", "id": 43748, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
windows, assembly, nasm, amd64 Title: "Hello world" in x64 assembly for Windows - Shadow space / Stack alignment Question: I`m currently trying to delve into x64 assembly under windows using NASM, and created a minimalistic "Hello World" application. It is mainly meant as an educational resource for me and possibly others, hence the heavy documentation style. A full repo with build instructions and code is located at hello_kernel32, this is the relevant source file: ;; Resources: ;; https://sonictk.github.io/asm_tutorial/ ;; https://gist.github.com/mcandre/b3664ffbeb4f5764b36a397fafb04f1c ;; https://retroscience.net/x64-assembly.html ;; Make clear this file contains 64bit assembly bits 64 ;; Use rip-relative addressing default rel ;; Export entry symbol (this is specified in the call to link.exe) global _start ;; Import external symbols ;; (all of them exist in kernel32.lib, which gets passed to link.exe in addition to the programs object file hello.obj) ;; ;; Why import symbols/functions from kernel32.lib? ;; ;; In windows, the "low level API stack" is: Kernel < Syscalls < ntdll.dll < kernel32.dll (and others like user32.dll) ;; ;; * The kernel itself cannot be accessed by user programs for obvious reasons (CPU ring protection modes) ;; * Syscalls could be performed, but are undocumented and evidently unstable between different versions of windows ;; * ntdll.dll is only partially documented and not intended for external use ;; * kernel32.dll (and friends) are the "official" low-level entry points to the windows API extern GetStdHandle extern WriteFile extern ExitProcess ;; This section contains read-only data section .rodata ;; Store the output string followed by CRLF as a sequence of bytes, at address 'msg' msg db "Hello World!", 0x0d, 0x0a
{ "domain": "codereview.stackexchange", "id": 43749, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "windows, assembly, nasm, amd64", "url": null }
windows, assembly, nasm, amd64 ;; The length will be needed by the output function, and can be statically calculated at assembly time by using 'equ' ;; It is actually a nifty trick that calculates the offset between the current address '$', and the address of 'msg' ;; See https://nasm.us/doc/nasmdoc3.html#section-3.2.4 msg_len equ $ - msg ;; This section contains the code section .text _start: ;; For being able to print text, we first need to acquire a HANDLE to STDOUT ;; This HANDLE is a required parameter for the call to WriteFile ;; HANDLE = GetStdHandle(-11) ;; ;; See https://docs.microsoft.com/en-us/windows/console/getstdhandle ;; ;; Parameter 1 (rcx): requests the type of HANDLE, -11 is the constant for STDOUT ;; Return value (rax): HANDLE (an address with some type of meaning) is stored in rax, as per calling conventions mov rcx, -11 sub rsp, 40 ;; Allocate 32 bytes of shadow space and 8 bytes to keep the stack 16-byte aligned call GetStdHandle add rsp, 40 ;; Undo shadow space + alignment padding ;; code = WriteFile(HANDLE, msg, msg_len, NULL, NULL) ;; ;; See https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile ;; ;; Parameter 1 (rcx): HANDLE to write to ;; Parameter 2 (rdx): Address of message to print ;; Parameter 3 (r8): Length of message ;; Parameter 4 (r9): Write amount of written bytes to this address, null pointer ;; (Required according to docs when parameter 5 is null, but passing null seems to work just fine) ;; Parameter 5 (on stack): Unused optional parameter, null pointer ;; Return value (rax): Nonzero on success mov rcx, rax mov rdx, msg mov r8, msg_len mov r9, 0 push qword 0 sub rsp, 32 ;; The previous push aligned us to 16 bytes, only allocate shadow space call WriteFile add rsp, 40 ;; Undo shadow space + push
{ "domain": "codereview.stackexchange", "id": 43749, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "windows, assembly, nasm, amd64", "url": null }
windows, assembly, nasm, amd64 ;; ExitProcess(code) ;; ;; See https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitprocess ;; ;; Parameter 1 (rcx): Exit code mov rcx, rax sub rsp, 40 ;; Shadow space + 8 byte alignment call ExitProcess ;; add rsp, 40 ;; Not necessary because the previous function call will end the program anyway My main question is about: Shadow space + stack alignment Most resources I found seem to completely neglect this when doing simple "hello world" programs. My program also seems to run just fine when removing all the sub rsp/add rsp statements. So I'm wondering what the implications of not following those conventions really means for code correctness. My current understanding is that GetStdHandle/WriteFile/ExitProcess are simply not using shadow space and also do not perform any operation that requires an aligned stack in their current implementation as present on my machine. However, any update to kernel32.dll is free to change those implementations in a way that relies on shadow space being present and/or an aligned stack. Therefore code neglecting shadow space/stack alignment for external calls is incorrect in the general sense of incorrectly interfacing with an external API, even though many APIs may be built in a way they can tolerate that slightly incorrect access (but this tolerance is an implementation detail that may change at any time). -> Is this definition/understanding correct? / Anything to add/clarify? General question Are there any other apparent mistakes / misunderstandings in the code or comments? Answer: Shadow space + stack alignment Most resources I found seem to completely neglect this when doing simple "hello world" programs. Is this true? Keep in mind that the most common way to take it into account is to do something like the following:
{ "domain": "codereview.stackexchange", "id": 43749, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "windows, assembly, nasm, amd64", "url": null }
windows, assembly, nasm, amd64 in the prologue, allocate however much space this function ever needs (including the parameter and shadow space of any callee), plus either 8 to compensate for the call to that function or using push rbp to both save rbp and restore alignment. in the body of the function, don't change rsp (eg don't push qword 0 but mov qword [rsp + something], 0). I looked at a few tutorials and guides, and they used that technique. That technique is semi-required on win64 anyway, at least if you want SEH unwinding, since the stack unwinding data is quite restrictive in what it can express. Code that employs that technique looks like it's neglecting alignment and shadow space, but they are taken into account in the amount of stack space allocated by the prologue. Anyway I recommend that you employ that technique also, even if you aren't emitting unwinding information yet, you may as well get used to it.
{ "domain": "codereview.stackexchange", "id": 43749, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "windows, assembly, nasm, amd64", "url": null }
java, performance, programming-challenge Title: ProjectEuler.net problem #50, Consecutive Prime Sum Question: I am trying to solve ProjectEuler.net problem #50, Consecutive Prime Sum. Here is the problem: The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? I have written some code which solve the problem just fine when the limit is 10, 100, 1000 or 10000 but when the limit is 1000000 as the problem requires, the program takes too much time to finish running!! What can be done to my code to make the program faster? package com.company; import java.util.ArrayList; class ConsecutivePrimeSum { public static int limit=1000000; int lengthOfTheLongest =0; int sumOfTheLongest =0; void solution(){ ArrayList<Integer> arrayOfPrimes=generatePrimes(); scanSequences(arrayOfPrimes); System.out.println("The longest sum is "+ sumOfTheLongest +" and contains "+lengthOfTheLongest+" terms"); } private ArrayList<Integer> generatePrimes(){ ArrayList<Integer> arrayOfPrimes=new ArrayList<Integer>(); for(int i=limit;i>=2;i--){ if(isPrime(i)){ arrayOfPrimes.add(i); } } return arrayOfPrimes; }
{ "domain": "codereview.stackexchange", "id": 43750, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, programming-challenge", "url": null }
java, performance, programming-challenge /** * @param s * this scans ArrayList s, to get sequence of prime numbers and calculate * their sum and corresponding length * then assign the longest length to the variable lengthOfTheLongest, and its sum to variable sumOfTheLongest */ private void scanSequences(ArrayList<Integer> s){ ArrayList<Integer> cumulativeSums=generateCumulativeSums(s); for(int start=1;start<=s.size();start++){ for (int end=s.size()-1;end>=start;end--){ if(!isPrime(sumFromTo(cumulativeSums,start,end))) continue; if(sumFromTo(cumulativeSums,start,end)>limit) break; if ((end-start+1)> lengthOfTheLongest){ sumOfTheLongest =sumFromTo(cumulativeSums,start,end); lengthOfTheLongest =(end-start+1); } } } } /** * @param s * @return arraylist of cumulative sums of the elements in s */ private ArrayList<Integer> generateCumulativeSums(ArrayList<Integer> s){ int sum=0; ArrayList<Integer> cumulativeSums=new ArrayList<Integer>(); for (int i=0;i<s.size();i++){ cumulativeSums.add(sum=sum+s.get(i)); } return cumulativeSums; } /** * @param a is an ArrayList whose elements are to be summed * @param start is the index of where summing should start * @param end is the index of where summing should end * @return the obtained sum */ private int sumFromTo( ArrayList<Integer> a,int start, int end){ int sum; sum=a.get(end)-a.get(start-1); return sum; } private static boolean isPrime(int number){ boolean isPrime=false; int divider=2; int count=0; while(divider<=number){ if(number%divider==0) count=count+1; divider=divider+1; } if(count==1) isPrime=true; return isPrime; }
{ "domain": "codereview.stackexchange", "id": 43750, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, programming-challenge", "url": null }
java, performance, programming-challenge return isPrime; } } class Test{ public static void main(String [] args){ ConsecutivePrimeSum consecutivePrimeSum=new ConsecutivePrimeSum(); consecutivePrimeSum.solution(); } } Answer: Generation of prime numbers is suboptimal. Use a sieve of Erathosthenes. isPrime is highly suboptimal. You already generated an array of all necessary primes, so just binary search it. Breaking the loop in if(sumFromTo(cumulativeSums,start,end)>limit) break; looks like a bug. The intention is to loop by decreasing end, yet since the loop starts with the very long sequence, its sum is likely to exceed the limit right away. Shorter sequences with the same start are never tested. Consider finding the proper end as an upper limit of a sumFromTo(cumulativeSums, start, end) <= limit predicate (hint: another binary search). You are not interested in all sequences of the primes. Most of the primes execs 2 are odd. Notice that if the sequence has an even number of odd primes, its sum is even, that is not a prime. Once the correct end is established, you may safely decrease it by 2. Style wise, give your operators some breathing space. for (int end = s.size() - 1; end >= start; end--) { is much more readable than for (int end=s.size()-1;end>=start;end--){ PS: I am not aware of any math regarding sums of consecutive primes. It is very much possible that such math exists, and the goal of this problem is to discover it. That would be a true optimization.
{ "domain": "codereview.stackexchange", "id": 43750, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, programming-challenge", "url": null }
javascript, beginner, node.js, web-scraping Title: A Language Bot: For creating noun declension or verb conjugation tables Question: I'm a freshman student. What does my program solve? This is actually a bot for reddit, and there are language learning subreddits on that website, sometimes when discussing something with people, we may need to show declension or conjugation tables to them, instead of sending a link, this bot will help you to comment it automatically. What does my code do in my opinion? It only works for lithuanian language, there is a website for declensions or conjugations for lithuanian language, and my program goes to that website, scrapes the html table off of it, makes it form into a table, and then replies in the comments. Why do I want a review? Well actually, this was supposed to be a learning project, I want to know the weaknesses in my code, stuff I've done wrong or the parts that I could code it better. It does work for sure, but I dont think that's enough to be a good programmer. Is my code clean enough? Is my code DRY enough or not? Is it slow? Anything broken or wrong? Any suggestions? Did I seperate the folders correctly? You can find all the source code here on github This is how a comment looks like This is how my directory looks like: >src >config >lietuvos-config.js >service >bot.js >util >extract-word.js >get-table.js >pretty-stringified.js >app.js >package.lock >readme.md >package.json extract-word.js const extractor = function(query){ const pattern = /<[a-zA-Z]+>/; //only works with latin letters for now, to be updated const stringToSplit = query; //make it case insensitive const extractedWord= stringToSplit.match(pattern) extractedWord[0] = extractedWord[0].replace("<","") extractedWord[0] = extractedWord[0].replace(">","") return extractedWord } module.exports={ extractor: extractor }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping module.exports={ extractor: extractor } get-table.js var scraper = require('table-scraper'); const {prettifier} = require('../util/pretty-stringified') const tableOfContent = function(query){ return scraper.get('https://morfologija.lietuviuzodynas.lt/zodzio-formos/'+query) .then(function(tableData){ console.log(tableData) return prettifier(tableData).toString() //JSON.stringify(tableData) }) .catch((error)=>{ return "error" }) } module.exports = { tableOfContent: tableOfContent } pretty-stringified.js const tablemark = require('tablemark')
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping const prettifier = function(query){ const decider = nounOrVerb(query); if(decider == "noun"){ return declineNouns(query) }else if(decider == "verb"){ return conjugateVerbs(query) }else if(decider == "adjective"){ return declineAdjectives(query) } } const convertArrays = function(array){ var newArr = []; for(var i = 0; i < array.length; i++){ newArr = newArr.concat(array[i]); } return newArr } const declineNouns = function (query){ const newArr = convertArrays(query) var tidiedArr = [] for (var i = 0; i < newArr.length; i++) { tidiedArr.push(newArr[i]["\Š\."]) tidiedArr.push(newArr[i].Vienaskaita) } var redditTable = tablemark([ {Form:"**V.**",Vienaskaita:tidiedArr[0],Daugiskaita:tidiedArr[1]}, {Form:"**K.**",Vienaskaita:tidiedArr[2],Daugiskaita:tidiedArr[3]}, {Form:"**K.**",Vienaskaita:tidiedArr[4],Daugiskaita:tidiedArr[5]}, {Form:"**G.**",Vienaskaita:tidiedArr[6],Daugiskaita:tidiedArr[7]}, {Form:"**Įn.**",Vienaskaita:tidiedArr[8],Daugiskaita:tidiedArr[9]}, {Form:"**Vt.**",Vienaskaita:tidiedArr[10],Daugiskaita:tidiedArr[11]}, {Form:"**Š.**",Vienaskaita:tidiedArr[12],Daugiskaita:tidiedArr[13]}, ]) return redditTable; } const conjugateVerbs = function(query){ const newArr = convertArrays(query) var tidiedArr = [] for (var i = 0; i < newArr.length; i++) { tidiedArr.push(newArr[i]["Jie/jos"]) tidiedArr.push(newArr[i]["Esamasis laikas"]) tidiedArr.push(newArr[i]["Būtasis kartinis laikas"]) tidiedArr.push(newArr[i]["Būtasis dažninis"]) } var redditTable = tablemark([ {Įvardis:"**Aš**","**Esamasis laikas**":tidiedArr[0],"**Būtasis kartinis laikas**":tidiedArr[1],"**Būtasis dažninis**":tidiedArr[2],"**Būsimasis laikas**":tidiedArr[3]},
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping {Įvardis:"**Tu**","**Esamasis laikas**":tidiedArr[4],"**Būtasis kartinis laikas**":tidiedArr[5],"**Būtasis dažninis**":tidiedArr[6],"**Būsimasis laikas**":tidiedArr[7]}, {Įvardis:"**Jis/ji**","**Esamasis laikas**":tidiedArr[8],"**Būtasis kartinis laikas**":tidiedArr[9],"**Būtasis dažninis**":tidiedArr[10],"**Būsimasis laikas**":tidiedArr[11]}, {Įvardis:"**Mes**","**Esamasis laikas**":tidiedArr[12],"**Būtasis kartinis laikas**":tidiedArr[13],"**Būtasis dažninis**":tidiedArr[14],"**Būsimasis laikas**":tidiedArr[15]}, {Įvardis:"**Jūs**","**Esamasis laikas**":tidiedArr[16],"**Būtasis kartinis laikas**":tidiedArr[17],"**Būtasis dažninis**":tidiedArr[18],"**Būsimasis laikas**":tidiedArr[19]}, {Įvardis:"**Jie/jos**","**Esamasis laikas**":tidiedArr[20],"**Būtasis kartinis laikas**":tidiedArr[21],"**Būtasis dažninis**":tidiedArr[22],"**Būsimasis laikas**":tidiedArr[23]}, ]) return redditTable; } const declineAdjectives = function(query){ const newArr = convertArrays(query) var tidiedArr = [] for (var i = 0; i < newArr.length; i++) { tidiedArr.push(newArr[i]["\Š\."]) tidiedArr.push(newArr[i].Vienaskaita) tidiedArr.push(newArr[i].Daugiskaita) tidiedArr.push(newArr[i]["Vienaskaita_2"]) } var redditTable = tablemark([ {Form: "",name:"**Vienaskaita**",name2:"**Daugiskaita**",name3:"**Vienaskaita**",name4:"**Daugiskaita**"}, {Form:"**V.**",name:tidiedArr[0],name2:tidiedArr[1],name3:tidiedArr[2],name4:tidiedArr[3]}, {Form:"**K.**",name:tidiedArr[4],name2:tidiedArr[5],name3:tidiedArr[6],name4:tidiedArr[7]}, {Form:"**K.**",name:tidiedArr[8],name2:tidiedArr[9],name3:tidiedArr[10],name4:tidiedArr[11]}, {Form:"**G.**",name:tidiedArr[12],name2:tidiedArr[13],name3:tidiedArr[14],name4:tidiedArr[15]}, {Form:"**Įn.**",name:tidiedArr[16],name2:tidiedArr[17],name3:tidiedArr[18],name4:tidiedArr[19]},
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping {Form:"**Vt.**",name:tidiedArr[20],name2:tidiedArr[21],name3:tidiedArr[22],name4:tidiedArr[23]}, {Form:"**Š.**",name:tidiedArr[24],name2:tidiedArr[25],name3:tidiedArr[26],name4:tidiedArr[27]}, ],{ columns:[ "Form", {name: "Vyriškoji giminė"}, {name:" "}, {name: "Moteriškoji giminė"}, {name:" "} ] }) return redditTable; } const nounOrVerb = function(array){ try{ const listOfTable = Object.keys(array[0][0]); if(listOfTable[0] == "Jie/jos"){ return "verb" }else if(listOfTable[3] =="Vienaskaita_2"){ return "adjective" }else if(listOfTable[0] == "Š."){ return "noun" } }catch{ return "Error" } } module.exports = { prettifier:prettifier }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping bot.js const {comments} = require('../config/lietuvos-config') const {extractor} = require('../util/extract-word') const {tableOfContent} = require('../util/get-table') const BOT_START = Date.now() / 1000; const canSummon = (msg) => { /*if(msg){ msg.toLowerCase().includes('!inspect'); //function return; } return*/ return msg && msg.toLowerCase().includes('!inspect'); };
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping const commenting = function(){ comments.on('item',async (item) => { try{ var replyString = "labas u/"+item.author.name+"! esu robotas ir pateikiu lentelę apie žodžius, veiksmažodžius, būdvardžius."+ " jei prieš nieko, čia tavo žodžio lentelė. net galite sužinot daugiau čia ^[šaltinis](https://morfologija.lietuviuzodynas.lt/zodzio-formos/"+extractedWord+ ") \n\n " var errorReply= "labas u/"+item.author.name+"! esu bandęs rasti žodį, kurį rašėi, atsiprašau ir dėja, bet negalėjau rasti. "+ "gal tas žodis neegzistuoja lietuvių kalboj, rašėi neteisingai - arba yra klaida mano kode.\n šiaip ar taip, galite bandyt rast savarankiškai čia ^[žodynas](https://morfologija.lietuviuzodynas.lt/" var replyStringEnder = " \n\n \*\*\* \n ^feel ^free ^to ^report ^bugs ^or ^errors\n ^\[[source-code]\](https://github.com/wulfharth7/lietuvos-robotas) ^| ^\[[buy-me-a-coffee☕]\](https://www.buymeacoffee.com/beriscen)" if(item.created_utc < BOT_START) return; if(!canSummon(item.body)) return; var extractedWord = extractor(item.body) tableOfContent(extractedWord).then(function(tableofLog){ if(tableofLog !== "error"){ item.reply(replyString+ tableofLog+replyStringEnder) }else{ item.reply(errorReply+replyStringEnder) } }) }catch(Error){ var errorReply= "labas u/"+item.author.name+"! esu bandęs rasti žodį, kurį rašėi, atsiprašau ir dėja, bet negalėjau rasti. "+ "gal tas žodis neegzistuoja lietuvių kalboj, rašėi neteisingai - arba yra klaida mano kode.\n\n šiaip ar taip, galite bandyt rast savarankiškai čia ^[žodynas](https://morfologija.lietuviuzodynas.lt/)" item.reply(errorReply+replyStringEnder) } }); } module.exports={ commenting: commenting }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping module.exports={ commenting: commenting } Answer: extract-word.js Well, you're clearly already aware that it only working with latin letters is an issue, but I'll point it out anyway. Since, y'know, it excludes a few letters used in lithuanian. By the way, the regular expression can be made case-insensitive with the i flag, like const pattern = /<[a-z]+>/i stringToSplit is a bit redundant - it contains exactly the same content as query, so we may as well operate on query directly We can clean up the extracting a bit by using capturing groups. If we do const pattern = /<([a-z]+)>/i, the parens define a group, and we can access that group as extractedWord[1] All in all, that function could be boiled down into a one-liner like return query.match(/<([a-z]+)>/i)[1];. Or perhaps return query.match(/<([a-ząčęėįšųūž]+)>/i)[1]; to add some letters (I hope those are the right ones). More sensible might be to keep the pattern on a separate line, like: const extractor = function(query){ const pattern = /<([a-ząčęėįšųūž]+)>/i; return query.match(pattern)[1]; } module.exports={ extractor: extractor } get-table.js I do wonder if returning "error" in case of failure is the most useful behaviour. Would it not be more convenient to just... let the failure remain a failure, to make it easier for the caller to detect and clean up? Since bot.js already has a catch block that provides an error message, it might be best to just... let it deal with errors from here as well Then we could have this file looking closer to var scraper = require('table-scraper'); const {prettifier} = require('../util/pretty-stringified') const tableOfContent = function(query) { return scraper.get('https://morfologija.lietuviuzodynas.lt/zodzio-formos/' + query) .then(function(tableData) { console.log(tableData); return prettifier(tableData).toString(); }); } module.exports = { tableOfContent: tableOfContent }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping module.exports = { tableOfContent: tableOfContent } pretty-stringified.js Well, for one, the name of nounOrVerb is a bit misleading, since it has three possible results. For now. Maybe one day it might even have a fourth? Let's give it a name that leaves room for expansion. Something like const typeOfWord = getTypeOfWord(query); perhaps? Alternatively, instead of having a function return a string, and then branching based on what that string is... we could just return the function directly: const prettify = function(query) { const prettifier = choosePrettifier(query); return prettifier(query); } const choosePrettifier = function(table) { try { const listOfTable = Object.keys(table[0][0]); if (listOfTable[0] == "Jie/jos") { return conjugateVerbs; } else if (listOfTable[3] == "Vienaskaita_2") { return declineAdjectives; } else if (listOfTable[0] == "Š.") { return declineNouns; } } } We could even call it right there but... I don't know, I think that looks worse somehow. Which might be a sign that there's an even better solution that I'm missing right now. Moving on to the conjugate/decline functions, they seem to follow a somewhat odd pattern. They take an array containing some manner of structured objects, removes that structure by shoving their fields into a flat array, then re-adds structure by working on individual array indices. That feels a bit roundabout. For example, looking at declineNouns, it seems like something like this should work: const declineNouns = function(query) { const newArr = convertArrays(query); const forms = ["**V.**", "**K.**", "**K.**", "**G.**", "**Įn.**", "**Vt.**", "**Š.**"];
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping const tidiedArr = []; // There's probably some even neater functional way to do this, but I don't remember it right now for (var i = 0; i < newArr.length; ++i) { tidiedArr.push({Form: forms[i], Vienaskaita: newArr[i]["\Š\."], Daugiskaita: newArr[i].Vienaskaita}); } return tablemark(tidiedArr); }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping return tablemark(tidiedArr); } Now, I know that Daugiskaita: newArr[i].Vienaskaita part looks a bit questionable to me when a Vienaskaita key also exists, but the old code had Daugiskaita: tidiedArr[1], and tidiedArr[1] was set by tidiedArr.push(newArr[i].Vienaskaita), so I'm gonna assume that it's correct bot.js Commented-out code in canSummon should be deleted. Should we need it back for some reason, there's always version control. errorReply is defined the exact same way twice. I would suggest doing it just once by the start of the function instead. Since it depends on the comment author's username, we could either define it by the start of the callback passed to comments.on, or we could have a "template function" of sorts that just takes a username and spits out the correct error message. I kind of like the latter, but either works. extractedWord seems to be used to create replyString before it is actually set. Thanks to JS's scoping rules, I wouldn't be entirely surprised if it finds a word, but I would expect it to find a word an earlier commenter asked for instead. We'll probably want to make sure the reply is created after we have all the content that goes into it, whether that be by moving the definition later or by passing it to a function that slots it into a string We may also be able to save some repetition by having only a single item.reply call towards the end If we also go with the "throwing an exception instead of returning "error"" idea mentioned earlier, I'd probably do something not too far from the following: const commenting = function(){ let replyString = function(username, extractedWord) { return `labas u/${username}! esu robotas ir pateikiu lentelę apie žodžius, veiksmažodžius, būdvardžius.` + ` jei prieš nieko, čia tavo žodžio lentelė. net galite sužinot daugiau čia ^[šaltinis](https://morfologija.lietuviuzodynas.lt/zodzio-formos/${extractedWord}")`; };
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
javascript, beginner, node.js, web-scraping let errorReply = function(username) { return `labas u/${item.author.name}! esu bandęs rasti žodį, kurį rašėi, atsiprašau ir dėja, bet negalėjau rasti. ` + "gal tas žodis neegzistuoja lietuvių kalboj, rašėi neteisingai - arba yra klaida mano kode.\n šiaip ar taip, galite bandyt rast savarankiškai čia ^[žodynas](https://morfologija.lietuviuzodynas.lt/"; } let replyStringEnder = " \n\n \*\*\* \n ^feel ^free ^to ^report ^bugs ^or ^errors\n ^\[[source-code]\](https://github.com/wulfharth7/lietuvos-robotas) ^| ^\[[buy-me-a-coffee☕]\](https://www.buymeacoffee.com/beriscen)"; comments.on('item',async (item) => { let message; try { if(item.created_utc < BOT_START) return; if(!canSummon(item.body)) return; let extractedWord = extractor(item.body); table = await tableOfContent(extractedWord); message = replyString(item.author.name) + table; } catch(Error) { message = errorReply(item.author.name); } item.reply(message + replyStringEnder); }); }
{ "domain": "codereview.stackexchange", "id": 43751, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, node.js, web-scraping", "url": null }
python, beginner, wordle Title: Correct logic for string comparison in Wordle Question: I'm a beginner trying to make a Wordle clone in python. I already have most of it sorted out but am concerned about my code being difficult to read. The part I'm struggling with the most is the algorithm for how guesses are displayed. An easily overlooked aspect of the original game is that it tries to make the player's life easier by hiding additional instances of a character in a guess whenever all instances of that letter have been found. That is, if the solution was "walls", and the player inputs "lulls", the last three characters would show as green as expected, but the first 'L' would be greyed out to indicate that all instances of that letter have been found (only for that line, subsequent lines/guesses reset this). This may seem obvious if you've played the game a lot, but many clones don't do this, which has the side effect of making the game harder. This answer to another wordle related question touches on this. I'm trying to implement this functionality in the function that compares player input with the solution in my version, the relevant section of which currently looks like this: from collections import Counter, defaultdict green = 3 yellow = 2 grey = 1
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle green = 3 yellow = 2 grey = 1 def compare_word(string, solution): def clear_yellow_letters(): # use counter to count instaces # of a letter in each string str_c_count = Counter(string) sol_c_count = Counter(solution) for k, v in c_green_count.items(): if v == sol_c_count[k]: # if there are more instances of letter than # have been located in solution, grey-out # additional instances if str_c_count[k] > sol_c_count[k]: for i in range(len(color_dic[0])): char = color_dic[0][i] if char == k and color_dic[1][i] == yellow: color_dic[1][i] = grey return color_dic # color_dic is actually a list >_>. since the same letter can appear # multiple times in a word, we prefer to use the index as a key # instead of a real dictionary, where repeated letters would all # point to the same color regardless of location. color_dic = string, [0 for c in string] c_green_count = defaultdict(int) # creates keys if they don't exist # this loop compares the chars in string and solution based on index, # and assigns a color to the respective position in the array. for i in range(len(color_dic[0])): char = color_dic[0][i] if char == solution[i]: color = green c_green_count[char] += 1 elif char in solution: color = yellow else: color = grey color_dic[1][i] = color if c_green_count.items(): color_dic = clear_yellow_letters() return color_dic print(compare_word('lulls', 'walls'))
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle print(compare_word('lulls', 'walls')) This prints a tuple containing a string, and a list of ints referencing each color used for displaying guesses. Note that this use of print is just for demonstration, the actual output is handled in curses (that's what the numbers are for). Here clear_yellow_letters() does what I just described. Without it compare_word() would return the int that maps to l in our string as 2 (yellow). While this works as it is, I feel there must be a simpler way to do it, as that section is a bit difficult to follow, even with all the comments. Another thing I'm confused about is code style/formatting. This is only an excerpt of my full project, which I've split into several modules due to its length, but one issue I keep coming across is how to know when to break-down functions into smaller functions and when to not. With compare_word() for example, clear_yellow_letters() is only called inside of it. Should I give the latter any parameters if all the vars it uses exist in the same scope, or is it okay to use the same names in this case? Would it be best to define it as a separate function for legibility? I hope this excerpt is sufficient for understanding the logic for how I'm trying to get the words displayed, I am not including the whole thing because as I mentioned, it's rather long, but if more context is needed I'll oblige. I'd appreciate any suggestions on what could be improved. Answer: First of all, I think it's great that you ask for feedback on a well isolated and explained piece of code. I also like your attention to detail in the rules of the game. I also find this code complex, I think for two main reasons: The algorithm itself is a bit complex The implementation of the algorithm is a bit complex Simplifying the algorithm The current algorithm goes something like this: In a 1st pass, check the letters pairwise: if the pair is a match: mark the position green update the count of matches of this letter
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle if the pair is a match: mark the position green update the count of matches of this letter or else if the guess exists somewhere else in the solution: mark the position yellow or else mark the position grey If there were any matches, make a 2nd pass to clear some yellows for each matched letter and its count if all instances of this letter were matched if the guess contains more instances of this letter find all unmatched positions of this letter and mark them grey Consider a simpler alternative: Initialize all positions to grey Compute a count of all letters in the solution In a 1st pass, check the letters pairwise: if the pair is a match: mark the position green update the count of matches of this letter In a 2st pass, check the letters pairwise: if the pair is not a match, and the solution contains unmatched positions of this letter mark the position yellow That's fewer steps, and also simpler to implement: (Using the Status enum idea from the answer of @Reinderien) class Status(Enum): MATCH = 3 MISPLACE = 2 MISMATCH = 1 status = [Status.MISMATCH] * len(guess) counts_in_solution = Counter(solution) matches = defaultdict(int) for index, (g, s) in enumerate(zip(guess, solution)): if g == s: status[index] = Status.MATCH matches[g] += 1 for index, (g, s) in enumerate(zip(guess, solution)): if g != s and matches[g] < counts_in_solution[g]: status[index] = Status.MISPLACE return [s.value for s in status] Simplifying the implementation Even if we don't change the main algorithm, the implementation of the original algorithm can be written simpler. First of all, some of the variable names don't help understanding the logic. string would describe itself better as guess Note that string was also a poor name because it shadows a common Python package the color codes would be better in all-caps c_green_count would be less cryptic as green_counts or matches Then there is color_dic...
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle Then there is color_dic... color_dic = string, [0 for c in string] In a comment you had the right instinct: "color_dic is actually a list". Even further: color_dic is a tuple, and the comment was probably referring to the 2nd element only color_dic was not useful at all: the first value is just the guess, and there is no need to store it in another tuple the second value is probably just what you intended for color_dic. A better name would be colors. Even with just these renames, and the minor transformation of dropping color_dic, I think the code already looks a bit less complex: matches = defaultdict(int) colors = [0 for c in guess] for i in range(len(guess)): char = guess[i] if char == solution[i]: color = GREEN matches[char] += 1 elif char in solution: color = YELLOW else: color = GREY colors[i] = color if matches.items(): clear_yellow_letters() return guess, colors Next, let's apply some idiomatic transformations: colors = [GREY] * len(guess) for index, [g, s] in enumerate(zip(guess, solution)): if g == s: colors[index] = GREEN matches[g] += 1 elif g in solution: colors[index] = YELLOW if matches: clear_yellow_letters() That is: To create a list of the same value, you can use [the_value] * count It's good to initialize colors to all grey because: It's a valid value, unlike the original 0 It's a sensible default This way we don't need to overwrite values to grey later Instead iterating over indexes, enumerate lets us iterate over (index, value) pairs Instead using index to get pairs of characters from guess and solution, we can use zip to line them up Instead of if matches.items() it's equivalent and shorter to write if matches For the 2nd pass, again I would start with renaming variables that look cryptic and hard to understand, to names that seem more natural and descriptive:
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle str_c_count -> counts_in_guess sol_c_count -> counts_in_solution k, v -> letter, count With the above renames, and other minor transformations we get: def clear_yellow_letters(): counts_in_guess = Counter(guess) counts_in_solution = Counter(solution) for letter, count in matches.items(): if count == counts_in_solution[letter] and counts_in_guess[letter] > count: for index, g in enumerate(guess): if g == letter and colors[index] == YELLOW: colors[index] = GREY Where the other transformations are: Joined the two ifs in the outer loop: this is equivalent, and looks simpler Replaced the second reference to counts_in_solution[letter] with count, because at that point we know they are the same Using enumerate to loop over index + value pairs Not returning colors, since we can manipulate the variable in the context Having a for loop nested within another for loop still looks complex of course. If you think about it, the inner loop is clumsy, because what we don't really want to iterate over all the letters in guess, what we really want is operate on the matched letters only. In other words, currently we're iterating over dictionary entries and then doing a search in a list. If we reverse these operations we would iterate over a list and then do a search in a dictionary, which is easier and faster too: def clear_yellow_letters(): counts_in_solution = Counter(solution) for index, (g, s) in enumerate(zip(guess, solution)): if g != s and matches[g] == counts_in_solution[g]: colors[index] = GREY Lastly, since this function doesn't really buy us much, we as well inline it, arriving at something that looks simpler, with simple equivalent transformations, and a very small change in the algorithm: def compare_word(guess, solution): matches = defaultdict(int) colors = [GREY] * len(guess)
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
python, beginner, wordle for index, (g, s) in enumerate(zip(guess, solution)): if g == s: colors[index] = GREEN matches[g] += 1 elif g in solution: colors[index] = YELLOW if matches: counts_in_solution = Counter(solution) for index, (g, s) in enumerate(zip(guess, solution)): if g != s and matches[g] == counts_in_solution[g]: colors[index] = GREY return guess, colors Defining functions inside functions Defining functions inside functions is reasonable when: The function is not useful outside The function is called more than once In the posted code you only call the inner function once, so I think it doesn't add value. And when defining inner functions, beware of accidentally modifying variables that our defined in their outer scope. Code editors like PyCharm will give a warning for variables in inner functions whose names shadow variables in the outer scope, which can be confusing for readers, and a source of mistakes.
{ "domain": "codereview.stackexchange", "id": 43752, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, wordle", "url": null }
algorithm, c, sorting Title: Simple selection_sort in C Question: I study algorithms, and I try to implement each algorithm in C (Perhaps it would be better to choose C++, but okay) Here is my implementation of sorting by choice. How would you rate it? To be honest, I'm a bit intimidated by malloc and whether I used it correctly. (returning an array from a function is not that easy) Here is code: #include <stdlib.h> #include <stdio.h> int *selection_sort(int *arr, int size) { int small = arr[0]; int small_index = 0; int swap; int* n_arr = malloc(sizeof(int) * size); for (int i = 0; i < size; ++i) { for (int j = i + 1; j < size; ++j) { if (arr[i] > arr[j]) { swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; } } n_arr[i] = arr[i]; } return n_arr; } int main(int argc, char const *argv[]) { int size = 5; int arr[] = {5, 3, 6, 2, 10}; int *n_arr = selection_sort(arr, size); if (n_arr) { for (int i = 0; i < size; ++i) { printf("%d\n", n_arr[i]); } } free(n_arr); return 0; } P.S I have not yet figured out how to make the code work elegantly with any array (now I have to change the size and the array data themselves)
{ "domain": "codereview.stackexchange", "id": 43753, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, sorting", "url": null }
algorithm, c, sorting Answer: Test for Possible Memory Allocation Errors In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer). To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL. int* n_arr = malloc(sizeof(int) * size); if (n_arr == NULL) { fprintf(stderr, "ERROR: selection_sort malloc() failed\n"); return n_arr; } Convention When Using Memory Allocation in C When using malloc(), calloc() or realloc() in C a common convention is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. int* n_arr = malloc(sizeof(*n_arr) * size);
{ "domain": "codereview.stackexchange", "id": 43753, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, sorting", "url": null }
algorithm, c, sorting Prefer calloc() Over malloc() for Arrays The calloc() memory allocation function is primarily for empty arrays, the memory it provides has previous content removed. The memory returned by all the allocation functions is from the heap and may have been used previously there is no guarantee that the contents will not have values. The Code May Attempt to Free a Null pointer The code in main() calls free() even if the pointer returned from selection_sort() is null, it would be better to move the free() into the compound statement of the if.
{ "domain": "codereview.stackexchange", "id": 43753, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, sorting", "url": null }
html, classes, snake-game Title: Object-oriented Snake game in HTML without using canvas Question: I wanted to try out classes in Javascript and implemented a snake game. You can control the snake by using the arrow keys. I would be interested to know if the source code can be improved in terms of class structure or source code structure in general. I never implemented snake in an other language and also didnt look into examples for doing that - so maybe this code seems a little bit odd to game programmers. Class Structure There are four Classes. Table: Manages the graphical display of a table and provides fundamental functions for changing the look of cells. Position: Represents a position with an x and an y coordinate. Snake: Manages "body parts" that are just a list of positions and can move and grow. GameBoard: Puts all these classes together to a game and also manages the graphical display via a Table instance. There is also a function for checking which arrow key is pressed, and a function that repeatedly calls the mainloop of the gameboard-object. <html> <head> <title>Snake</title> <style> table { border: 1px solid; } td { width: 25px; height: 25px; } </style> </head> <body> <div id="table"></div> </body> <script> /* classes */ class Table { rows; columns; tableNode; constructor(rows, columns) { this.rows = rows; this.columns = columns; } initTableNode() { this.tableNode = document.createElement("table"); for (let i = 0; i < this.rows; i++) { let tr = document.createElement("tr"); for (let j = 0; j < this.columns; j++) { let td = document.createElement("td"); tr.appendChild(td); } this.tableNode.appendChild(tr); } }
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game changeColor(x, y, color) { if (x >= 0 && x < this.rows && y >= 0 && y < this.columns) this.tableNode.rows[x].cells[y].style.background = color; } makeWhite() { for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { this.tableNode.rows[i].cells[j].style.background = "white"; } } } } class GameBoard { table; snake; applePosition; gameOver; constructor(height, width) { this.table = new Table(height, width); this.snake = new Snake(); this.makeRandomApple(); } makeRandomApple() { start: while (true) { let x = randomInt(0, this.table.rows-1); let y = randomInt(0, this.table.columns-1); this.applePosition = new Position(x, y); // check if snake is already there for (let i = 0; i < this.snake.bodyParts.length; i++) { if (this.snake.bodyParts[i].x == x && this.snake.bodyParts[i].y == y) { continue start; } } return; } } checkIfAppleIsEaten() { if (this.snake.head().x == this.applePosition.x && this.snake.head().y == this.applePosition.y) { this.snake.grow(); this.makeRandomApple(); } } gameLoop() { this.snake.moveForward(direction); this.checkIfAppleIsEaten(); // check if snake crashes into border let head = this.snake.head(); if (head.x < 0 || head.x >= this.table.rows || head.y < 0 || head.y >= this.table.columns) { this.gameOver = true; }
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game // check if snakes crashes into himself let bodyParts = 0; for (let i = 0; i < this.snake.bodyParts.length; i++) { if (head.x == this.snake.bodyParts[i].x && head.y == this.snake.bodyParts[i].y) { bodyParts += 1; } if (bodyParts > 1) { this.gameOver = true; break; } } this.table.makeWhite(); this.table.changeColor(this.applePosition.x, this.applePosition.y, "green"); // draw snake for (let i = 0; i < this.snake.bodyParts.length; i++) { this.table.changeColor(this.snake.bodyParts[i].x, this.snake.bodyParts[i].y, "red"); } } } class Snake { bodyParts; // can contain strings: left, up, right, down directionCurrently; grown; constructor() { let p1 = new Position(1, 1); let p2 = new Position(1, 2); let p3 = new Position(1, 3); let p4 = new Position(1, 4); let p5 = new Position(1, 5); this.bodyParts = [p1, p2, p3, p4, p5]; this.directionCurrently = "right"; this.grown = false; } grow() { this.grown = true; } // direction can contain strings: left, up, right, down moveForward(direction) { let head = this.bodyParts[this.bodyParts.length-1] let newHead; if ((this.directionCurrently == "right" && direction != "left") || (this.directionCurrently == "left" && direction != "right") || (this.directionCurrently == "up" && direction != "down") || (this.directionCurrently == "down" && direction != "up")) { this.directionCurrently = direction; }
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game if (this.directionCurrently == "left") { newHead = new Position(head.x, head.y-1); } else if (this.directionCurrently == "up") { newHead = new Position(head.x-1, head.y); } else if (this.directionCurrently == "right") { newHead = new Position(head.x, head.y+1); } else if (this.directionCurrently == "down") { newHead = new Position(head.x+1, head.y); } if (this.grown) { this.grown = false; } else { this.bodyParts.shift(); } this.bodyParts.push(newHead); } head() { return this.bodyParts[this.bodyParts.length-1] } } class Position { x; y; constructor(x, y) { this.x = x; this.y = y; } equals(position) { return this.x == x.position && this.y == y.position; } } /* functions */ function randomInt(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min) } /* global variables */ let gameBoard = new GameBoard(10, 20); let direction = "right" const LEFT_KEY_CODE = 37; const TOP_KEY_CODE = 38; const RIGHT_KEY_CODE = 39; const BOTTOM_KEY_CODE = 40; /* commands, event listeners and timed routines */ // init html display var divArea = document.getElementById("table"); gameBoard.table.initTableNode(); divArea.append(gameBoard.table.tableNode);
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game // start game let gameLoop = window.setInterval(function() { gameBoard.gameLoop(); if (gameBoard.gameOver) { alert("Game over."); divArea.removeChild(gameBoard.table.tableNode) gameBoard = new GameBoard(10, 20); gameBoard.table.initTableNode(); divArea.append(gameBoard.table.tableNode); direction = "right"; } }, 500); // change direction by keyPress document.onkeydown = function (event) { if (event.keyCode == LEFT_KEY_CODE) { direction = "left"; } else if (event.keyCode == TOP_KEY_CODE) { direction = "up"; } else if (event.keyCode == RIGHT_KEY_CODE) { direction = "right"; } else if (event.keyCode == BOTTOM_KEY_CODE) { direction = "down"; } } </script> </html> Answer: Overall, OOP feels a bit heavy for the size of the application but I'll approach the review without tossing out the design. Clarify and tighten interfaces One staple of OOP design is the concept of a public interface that provides clearly-labeled methods for the user to call to manipulate an object. On a physical device, these might be knobs or buttons. These controls should be clearly defined, intuitive to manipulate and shouldn't be able to put the object into an illegal state. However, in your design, there's client code like: gameBoard.table.initTableNode(); divArea.append(gameBoard.table.tableNode);
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game This accesses a property table on gameBoard to call a method on it, then dips through nested properties to access what should probably be an internal piece of data with gameBoard.table.tableNode. No getters or setters are used here, so these properties can be easily corrupted by an unwitting client. There's no clear interface--the client has to somehow know about all of these nested properties. GameBoard is basically a namespace and not much more than that. It can't be refactored internally without breaking the contract with the calling code. This leads to tight coupling between client and class, something that OOP is supposed to help you avoid. Due to the tight coupling, the client code and classes can't be broken out into separate files or modules, a next step if you were to expand this app. Here, gameBoard.table.initTableNode(); could be an internal sub-step of a call gameBoard.initialize() that's exposed to the client. divArea.append(gameBoard.table.tableNode); could provide access to the tableNode with a top-level getter directly on gameBoard. Alternately, divArea (the root element for the board to be injected into) into the gameBoard constructor. Getters and setters can help clarify and tighten the public interfaces for your classes. You can use the _ prefix character to denote private data that isn't part of the interface. The rule of thumb is that as little should be exposed as possible: keeping Table as an implementation detail of GameBoard simplifies the client code by hiding complexity. As an exercise, write out the public interface for each class in a comment. As a rule for the exercise, any chaining like foo.getInternalObject().callMethodOnInternalObject() (with or without methods) should be forbidden. Only use foo.takeActionOnThisObject(). Avoid globals
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game Avoid globals In keeping with the previous point, the Snake class is tightly coupled to the direction global variable. This makes it extremely difficult for a client to reuse the class--they would have to know to create a direction variable globally and change its value to a magic string "up", "down" (etc). This is a very brittle situation that's extremely hard to generalize and debug. The rule I suggest applying is that the class is not allowed to access mutable variables outside of its scope (and a bare minimum of immutable variables as well, usually library dependencies, configuration and constants [although these should be class-scoped or constructor parameters when possible]). The solution is the same as above: create class methods that allow you to change the snake's direction, then eliminate the shared global state and call those methods. Stick with OOP throughout Your code seemed very committed to OOP, but then sort of dropped the ball when it came to writing the global logic. The client still has too much work to do to use the GameBoard instance. Imagine if you had to come up with all of this setup boilerplate to use a typical popular JS library. The holy grail for your top-level class should be: const game = new SnakeGame(someRootDiv); game.play();
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game or something like that, possibly with a configuration object if more options were available. This involves moving the game loop and key listeners into the game class. If this seems to bake too much UI into the game, you could move the key listener out and use methods to inform the game of any keypresses. Design your classes as typical black-box library calls you might use--assume the client/calling code has no idea (or need to know) how the internals of the class work and wants to have the simplest set of options available to achieve what they want. Turn comments into methods gameLoop is too long and has comments like // check if snake crashes into border. That's an easy refactor to a new method snake.checkBorderCollision(). Also, this method doesn't run a whole game loop, it just executes a single frame rerender. Name accordingly. Other Use a code formatter like prettier. Your CSS has random indentation as well. Separate the .css and .js files. As mentioned earlier, separating the classes into separate files and modules will expose the dirty global practices for what they are and keep you honest. Keep CSS out of your JS: .style.background = "white" should be refactored to toggle/add/remove CSS classes that have the actual style properties. Follow W3 guidance on <!DOCTYPE html> and other important head tags to keep your HTML validated. keyCode is deprecated; use code. Use const instead of let except for loop counters and occasional variables you need to reassign, and avoid var unless there's some scoping need (unlikely) or legacy compatibility need (use a transpiler). Prefer document.addEventListener("keydown", ...) over document.onkeydown = . Try to avoid booleans like grown--usually, method return values are enough to report state changes without adding class variables. In this case, checkIfAppleIsEaten could return true/false.
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game Maybe make a class for Apple with a Position or x/y (be consistent) and a reposition() method that repositions the apple. The caller could check for a collision with the snake and repeat the reposition() call until valid, or the snake could be passed as a parameter. Follow the single responsibility principle: checkIfAppleIsEaten does more than check that condition; it actually grows the snake and repositions the apple if the condition is true, complex and surprising side effects. The title should be complete and honest about what it does, growSnakeAndRepositionAppleIfEaten() (or checkAndHandleEatingApple()). Once you see a name this long, then the method is clearly overburdened and should be split into multiple steps to simplify its contract. Use requestAnimationFrame() rather than setInterval. Use arrow functions for callbacks unless you need this. Position.equals(position) is unused. Be consistent about whether you want to use loose x/y pairs or Position objects. Never use ==, always ===. == is broken and can introduce extremely subtle bugs. I'd prefer randomInt to be exclusive at the end so it works with array indexing naturally and you won't have to subtract 1 from the second parameter when you call it. this.bodyParts[this.bodyParts.length-1] can be this.bodyParts.at(-1) if supported or transpiled. Maybe premature optimization, but keep in mind that allocating a new Position on every frame is a bit expensive. You might want to move the last position to the head and set its x and y to the new location. Rather than all of the (this.directionCurrently == "right" && direction != "left") ... checks, use an object: const opposites = Object.freeze({ up: "down", down: "up", left: "right", right: "left", }); // ... if (direction !== opposites[this.currentDirection]) { // move is OK }
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
html, classes, snake-game To actually make the move, you can avoid if chains once again by pre-declaring an object that maps the directions to the positions: const steps = Object.freeze({ up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0], }); // ... newHead = new Position(...steps[direction]); alert("Game over."); is poor UX. Set text in an element instead.
{ "domain": "codereview.stackexchange", "id": 43754, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "html, classes, snake-game", "url": null }
image, swift, ios, extension-methods Title: UIImage downscale and compression Question: getFinalImageData(:UIImage) takes a UIImage and downscales its size dimensions (to 400 points, in this example) and returns it as Data that has been compressed to be within the byte limit (using the two UIImage extensions). This function works great but I would love to get some other eyes on it. typealias Bytes = Int64 extension Bytes { static let KB300: Int64 = 300_000 static let MB1: Int64 = 1_048_576 static let MB2: Int64 = 2_097_152 static let MB80: Int64 = 83_886_080 static let MB100: Int64 = 104_857_600 static let MB120: Int64 = 125_829_120 } extension UIImage { func compressedToJPEGData(maxBytes limit: Int64) -> Data? { /// These are compression multipliers (1 = least compression, /// 0 = most compression) to define the granularity of /// compression reduction. let multipliers: [CGFloat] = [1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0] for m in multipliers { if let data = jpegData(compressionQuality: m), data.count <= limit { return data } } return nil } func downscaled(maxPoints limit: CGFloat) -> UIImage { let width = size.width let height = size.height let maxLength = max(width, height) guard maxLength > limit else { return self } let downscaleDivisor = maxLength / limit let downscaledDimensions = CGSize(width: width / downscaleDivisor, height: height / downscaleDivisor) return UIGraphicsImageRenderer(size: downscaledDimensions).image { (_) in draw(in: CGRect(origin: .zero, size: downscaledDimensions)) } } } func getFinalImageData(from image: UIImage) -> Data? { let downscaled = image.downscaled(maxPoints: 400)
{ "domain": "codereview.stackexchange", "id": 43755, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "image, swift, ios, extension-methods", "url": null }
image, swift, ios, extension-methods if let compressed = downscaled.compressedToJPEGData(maxBytes: Bytes.KB300) { return compressed } return nil } Answer: A couple of quick observations: In UIGraphicsImageRenderer, make sure to set the scale in the UIGraphicsImageRendererFormat to be the scale of the image. Usually it is 1.0, unless it is a screen snapshot, in which case it is the scale of the device that it was snapshotted from. Bottom line, UIGraphicsImageRenderer will default to the scale of the device, which may make your image much bigger than you intended. E.g., take a 400×400 px image, and the renderer on a 3× device will make it 1200×1200 with no additional data, which is the exact opposite of what you obviously intend. The correct scale is a function of the image in question, not the device. Do you have access to the original Data associated with this asset? (Note, I am not asking about the output of pngData or jpegData, but the raw data of the original asset.) E.g., a photo taken with a camera generally has decent JPEG compression with it already, and round-tripping it through UIImage and then adding JPEG compression like 0.9 can actually simultaneously lose data and make it bigger. Bottom line, make the decision to downscale/compress only if the original raw asset demands it. Once you decide that the original asset is really too big, on the array of JPEG compression rates, you should probably remove the 1.0 scale from the list, as that will make the asset huge with absolutely no image improvement. I think 0.8 is a fine starting point. 0.9 if you want to be conservative. Try it out and you will see what I mean. Bottom line 1.0 compression makes it much bigger. 0.7-0.8 results in barely visible JPEG artifacts, and it falls apart quickly below 0.6, IMHO. Below you mention that you are using UIImagePickerController. If so, consider the following:
{ "domain": "codereview.stackexchange", "id": 43755, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "image, swift, ios, extension-methods", "url": null }
image, swift, ios, extension-methods Below you mention that you are using UIImagePickerController. If so, consider the following: let formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) guard let asset = info[.phAsset] as? PHAsset else { return } asset.requestContentEditingInput(with: nil) { [self] input, info in guard let fileURL = input?.fullSizeImageURL, let data = try? Data(contentsOf: fileURL), let image = UIImage(data: data), let data1 = image.jpegData(compressionQuality: 1), let data9 = image.jpegData(compressionQuality: 0.9), let data8 = image.jpegData(compressionQuality: 0.8), let data7 = image.jpegData(compressionQuality: 0.7), let data6 = image.jpegData(compressionQuality: 0.6) else { return } print("original", formatter.string(for: data.count)!) // 2,227,880 print(1.0, formatter.string(for: data1.count)!) // 6,242,371 print(0.9, formatter.string(for: data9.count)!) // 3,672,570 print(0.8, formatter.string(for: data8.count)!) // 3,004,577 print(0.7, formatter.string(for: data7.count)!) // 2,576,892 print(0.6, formatter.string(for: data6.count)!) // 1,958,503 } } }
{ "domain": "codereview.stackexchange", "id": 43755, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "image, swift, ios, extension-methods", "url": null }
image, swift, ios, extension-methods I am obviously not suggesting the above implementation in your code, but rather merely illustrating that (a) one way you can fetch the original asset; and (b) to show how its size compares to jpegData of various compression quality settings after round-tripping to a UIImage. Obviously, my numbers are from a random image in my photo library, and your values will vary, but the above sizes are entirely consistent with my historical experiments with various compression settings for JPEGs. Perhaps needless to say, if accessing the photos library, you must request permission: PHPhotoLibrary.requestAuthorization { granted in print(granted) } And set NSPhotoLibraryUsageDescription in the Info.plist.
{ "domain": "codereview.stackexchange", "id": 43755, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "image, swift, ios, extension-methods", "url": null }
bash Title: Bash script for user backups with BorgBackup Question: I use BorgBackup to handle backups for my personal computer. The following is a bash script that creates backups of my system to various different targets. I have little experience with bash and hope to get some pointers regarding best practices and possible security issues/unanticipated edge cases. One specific question is about the need to unset environment variables (in particular BORG_PASSPHRASE) like I have seen people doing (for example here) From my understanding this should not be necessary because the environment is only local. Ideally I would also like to automatically ensure the integrity of the Borg repositories. I know there is borg check which I could run from time to time, but I am not sure if this is even necessary when using create which supposedly already makes sure the repository is in a healthy state? Some notes regarding the code below: noti is a very simple script for notifications with i3status but could be replaced with anything else Some paths and names are replaces with dummies I can not exit properly on errors of borg create because I backup /etc where some files have wrong permissions and BorgBackup will throw errors The TODO comments in the code are things I may want to look into at some time, but the code works for now Bash script: #!/bin/bash # User data backup script using BorgBackup with options for different target repositories # usage: backup.sh <targetname> # Each target must have a configuration file backup-<targetname>.conf that provides: # - pre- and posthook functions # - $repository - path to a valid borg repository or were one should be created # - $backup - paths or exclusion paths # - $pruning - borg pruning scheme # Additional borg environment variables may be provided and will not be overwritten. # Output is logged to LOGFILE="$HOME/.local/log/backup/<date>"
{ "domain": "codereview.stackexchange", "id": 43756, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
bash # INSTALLATION # Place script and all target configs in $HOME/.local/scripts # $HOME/.config/systemd/user/borg-backup.service # ``` # [Unit] # Description=Borg User Backup # [Service] # Environment=SSH_AUTH_SOCK=/run/user/1000/keyring/ssh # ExecStart=%h/.local/scripts/backup.sh target1 # Nice=19 # IOSchedulingClass=2 # IOSchedulingPriority=7 # ``` # # $HOME/.config/systemd/user/borg-backup.timer # ``` # [Unit] # Description=Borg User Backup Timer # [Timer] # OnCalendar=*-*-* 8:00:00 # Persistent=true # RandomizedDelaySec=10min # WakeSystem=false # [Install] # WantedBy=timers.target # ``` # $ systemctl --user import-environment PATH # reload the daemon # $ systemctl --user daemon-reload # start the timer with # $ systemctl --user start borg-backup.timer # and confirm that it is running # $ systemctl --user list-timer # you can also run the service manually with # $ systemctl --user start borg-backup function error () { RED='\033[0;91m' NC='\033[0m' printf "${RED}%s${NC}\n" "${1}" notify-send -u critical "Borg" "Backup failed: ${1}" noti rm "BACKUP" noti add "BACKUP FAILED" exit 1 } ## Targets if [ $# -lt 1 ]; then echo "$0: Missing arguments" echo "usage: $0 targetname" exit 1 fi case "$1" in "target1"|"target2"|"target3") target="$1" ;; *) error "Unknown target" ;; esac # TODO abort if specified target is already running # exit if borg is already running, maybe previous run didn't finish #if pidof -x borg >/dev/null; then # error "Backup already running." #fi ## Logging and notification # notify about running backup noti add "BACKUP" # write output to logfile log="$HOME/.local/log/backup/backup-$(date +%Y-%m-%d-%H%M%S).log" exec > >(tee -i "$log") exec 2>&1 echo "$target" ## Global Prehook # create list of installed software pacman -Qeq > "$HOME/.local/log/package_list.txt" # create list of non backed up resources ls -R "$HOME/misc/" > "$HOME/.local/log/resources_list.txt"
{ "domain": "codereview.stackexchange", "id": 43756, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
bash # create list of non backed up resources ls -R "$HOME/misc/" > "$HOME/.local/log/resources_list.txt" # create list of music titles ls -R "$HOME/music/" > "$HOME/music/music_list.txt" ## Global Config # set repository passphrase export BORG_PASSCOMMAND="cat $HOME/passwd.txt" compression="lz4" ## Target specific Prehook and Config CONFIGDIR="$HOME/.local/scripts" source "$CONFIGDIR"/backup-"$target".conf # TODO make non mandatory and only run if it is defined prehook || error "prehook failed" ## Borg # TODO use env variables in configs instead? # export BORG_REPO=$1 # export BORG_REMOTE_PATH=borg1 # borg create ::'{hostname}-{utcnow:%Y-%m-%dT%H:%M:%S}' $HOME SECONDS=0 echo "Begin of backup $(date)." borg create \ --verbose \ --stats \ --progress \ --compression $compression \ "$repository"::"{hostname}-{utcnow:%Y-%m-%d-%H%M%S}" \ $backup # || error "borg failed" # use prune subcommand to maintain archives of this machine borg prune \ --verbose \ --list \ --progress \ "$repository" \ --prefix "{hostname}-" \ $pruning \ || error "prune failed" echo "End of backup $(date). Duration: $SECONDS Seconds" ## Cleanup posthook noti rm "BACKUP" echo "Finished" exit 0 Example configuration file: backup="$HOME --exclude $HOME/movie --exclude $HOME/.cache --exclude $HOME/.local/lib --exclude $HOME/.thumbnails --exclude $HOME/.Xauthority " pruning="--keep-daily=6 --keep-weekly=6 --keep-monthly=6" repository="/run/media/username/DRIVE" prehook() { :; } # e.g. mount drives/network storage posthook() { :; } # unmount ... Answer: Your specific question
{ "domain": "codereview.stackexchange", "id": 43756, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
bash posthook() { :; } # unmount ... Answer: Your specific question One specific question is about the need to unset environment variables (in particular BORG_PASSPHRASE) like I have seen people doing (for example here) From my understanding this should not be necessary because the environment is only local. When you execute a Bash script with path/to/script.sh or bash path/to/script.sh, the script runs in a sub-shell, and cannot modify its caller environment. No matter if the script has export FOO=bar or unset FOO, these will not be visible in the caller shell. So the example you linked to, having BORG_PASSPHRASE="" (and followed by exit) is completely pointless. Use an array for $backup This setup will break if ever $HOME contains whitespace: backup="$HOME --exclude $HOME/movie --exclude $HOME/.cache --exclude $HOME/.local/lib --exclude $HOME/.thumbnails --exclude $HOME/.Xauthority " Even if that's unlikely to happen, it's easy enough and a good practice to make it safe, by turning it into an array: backup=( "$HOME" --exclude "$HOME/movie" --exclude "$HOME/.cache" --exclude "$HOME/.local/lib" --exclude "$HOME/.thumbnails" --exclude "$HOME/.Xauthority" ) And then in the calling command: borg create \ --verbose \ --stats \ --progress \ --compression $compression \ "$repository"::"{hostname}-{utcnow:%Y-%m-%d-%H%M%S}" \ "${backup[@]}" I suggest to do the same thing for $pruning too. Although there is no risk there (with the current value) of something breaking, it's a good practice to double-quote variables used on the command line. So it should be: pruning=(--keep-daily=6 --keep-weekly=6 --keep-monthly=6) And then when using it: "${pruning[@]}" Use stricter input validation Looking at: if [ $# -lt 1 ]; then echo "$0: Missing arguments" echo "usage: $0 targetname" exit 1 fi
{ "domain": "codereview.stackexchange", "id": 43756, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
bash if [ $# -lt 1 ]; then echo "$0: Missing arguments" echo "usage: $0 targetname" exit 1 fi According to the usage message, only one argument is expected, but the validation logic allows any number above that, and will simply ignore them. I suggest to strengthen the condition: if [ $# != 1 ]; then Output error messages to stderr The error function, and a few other places print error messages on stdout. It's recommended to use stderr in these cases, for example: if [ $# -lt 1 ]; then echo "$0: Missing arguments" >&2 echo "usage: $0 targetname" >&2 exit 1 fi Don't use SHOUT_CASE for variables It's not recommended to use all caps variable names, as these may clash with environment variables defined by system programs. Use modern function declarations The modern syntax doesn't use the function keyword, like this: error() { # ... } Simplify case patterns In this code: case "$1" in "target1"|"target2"|"target3") target="$1" ;; You can use glob patterns to simplify that expression: case "$1" in "target"[1-3]) target="$1" ;; Why exit 0 at the end? The exit 0 as the last statement is strange: Bash will do the same thing automatically when reaching the end of the script. You can safely remove it. SECONDS Wow, I completely forgot about this feature of Bash, very cool, thanks for the reminder!
{ "domain": "codereview.stackexchange", "id": 43756, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
java, beginner, object-oriented Title: Java object oriented code to find points lying in a rectangle Question: I created this short code as an exercise to learn and practice my OOPS. The aim is - given a string of points as x1,y1,x2,y2... figure out how many of them lie inside a given rectangle. Can anyone please point out what things I can improve in this code design and best practices wise. public class Solution{ private String points; public Solution(String points) { this.points = points; } @Override public String checkPointsInRectangle() { String[] numbers = points.split(", "); List<Point> pointList = getPointsList(numbers); SortedSet<Point> pointsByX = new TreeSet<>(Comparator.comparingInt((Point p) -> p.x) .thenComparingInt((Point p) -> p.y)); SortedSet<Point> pointsByY = new TreeSet<>(Comparator.comparingInt((Point p) -> p.y) .thenComparingInt((Point p) -> p.x)); pointsByX.addAll(pointList); pointsByY.addAll(pointList); Rectangle rect = new Rectangle(-3,7,-10,10); Set<Point> result = getPointsInRect(rect, pointsByX, pointsByY); StringBuilder joined = new StringBuilder(); for(Point s : result){ joined.append(s.x); joined.append(s.y); } return joined.toString(); } List<Point> getPointsList(String [] points){ List<Point> result = new ArrayList<>(); for(int i=0;i< points.length-1;i++) { if (i % 2 == 0) { Point point = new Point(Integer.parseInt(points[i]), Integer.parseInt(points[i + 1])); result.add(point); } } return result; }
{ "domain": "codereview.stackexchange", "id": 43757, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented Set<Point> getPointsInRect(Rectangle rect, SortedSet<Point> pointsByX, SortedSet<Point> pointsByY) { Point minXMinY = new Point(rect.x0, rect.y0); Point maxXMaxY = new Point(rect.x1, rect.y1); Set<Point> pointsX = pointsByX.subSet(minXMinY, maxXMaxY); Set<Point> pointsY = pointsByY.subSet(minXMinY, maxXMaxY); Set<Point> rectPoints = new HashSet<>(pointsY); rectPoints.retainAll(pointsX); return rectPoints; } } public class Point { final int x; // made final so that user provided input is immutable. final int y; public Point(int x, int y){ this.x = x; this.y = y; } } EDIT Added the Rectangle class as well package dummy; public class Rectangle { final int x0,x1,y0,y1; public Rectangle(int x0, int x1, int y0, int y1) { this.x0 = x0; this.x1 = x1; this.y0 = y0; this.y1 = y1; } } Answer: You're practicing OOP, but this doesn't make very good use of OOP patterns. Solution and checkPointsInRectangle incorrectly concern themselves with more than they should (set construction, comparison). Solution doesn't show an entry point and stores points as a member which it should not. Point should be responsible for its own parsing and formatting, and should be a record instead of a class. Rectangle should be responsible for point checking inside of its bounds. Consider using the streaming interface, since this is really just an iterative parse, filter and format. This: for(Point s : result){ joined.append(s.x); joined.append(s.y); }
{ "domain": "codereview.stackexchange", "id": 43757, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented if intended for display purposes, wouldn't produce very useful output - there are no separators. I'm trying to understand how your getPointsInRect could do what it's intended to do; I don't think it does. Set operations are not enough to calculate geometric containment unless you fill a set with every possible coordinate inside of the rect, which you don't - and even if you did, this would be pretty inefficient. Just do numeric bounds checking instead; no sets needed. Suggested Main.java import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Rectangle rect = new Rectangle(-3,7, -10, 10); String contained = Point.parse("-11,-11,0,0,1,2") .filter(rect::contains) .map(Point::toString) .collect(Collectors.joining(", ")); System.out.println(contained); } } Rectangle.java public record Rectangle(int x0, int x1, int y0, int y1) { public boolean contains(Point p) { return x0 <= p.x() && p.x() <= x1 && y0 <= p.y() && p.y() <= y1; } } Point.java import java.util.stream.IntStream; import java.util.stream.Stream; public record Point(int x, int y) { public static Stream<Point> parse(String str) { String[] segments = str.split(","); return IntStream.range(0, segments.length/2) .mapToObj(i -> new Point( Integer.parseInt(segments[2*i]), Integer.parseInt(segments[2*i+1]) )); } @Override public String toString() { return "(%d, %d)".formatted(x, y); } } Output (0, 0), (1, 2)
{ "domain": "codereview.stackexchange", "id": 43757, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
c, formatting Title: K&R Exercise 1-19. "detab" program that replaces tabs with the appropriate number of blanks Question: I am trying to do a few exercises from the K&R book from the first chapter - exercise 1-19. I have to write a program "detab" which replaces tabs in the input with the proper number of blanks to the next tab stop. Assume a fixed set of tab stops, say every n position. Here is what I've written so far (My Solution): #include <stdio.h> #include <stdlib.h> #define TAB '\t' #define SPACE ' ' #define DEFTABSIZE 4 /* default tab size */ #define calc_n_spaces(x, y) ( (y - (x % y)) ) void detab(const char *restrict); int main(void) { char *buf = NULL; size_t bufsiz = 0; while (getline(&buf, &bufsiz, stdin) != -1) (void) detab(buf); free(buf); exit(EXIT_SUCCESS); } void detab(const char *restrict from) { int i, j, spaces; char to[BUFSIZ]; i = j = 0; while ((to[i] = from[i]) != '\0') { if (to[i] == TAB) { spaces = calc_n_spaces(j, DEFTABSIZE); /* calculate number of spaces. */ while (spaces-- > 0) { (void) putchar(SPACE); ++j; } } else { (void) putchar(to[i]); ++j; } ++i; } return; } I'd like to know if there is a way I can improve it. Note: I am using the 1st version of the book. Answer: When defining macros with arguments, it's good practice to avoid precedence-related surprises by enclosing those arguments with parens in the expansion: #define calc_n_spaces(x, y) ((y) - (x) % (y)) As another answer observes, a simple inlinable function is more appropriate here, and that avoids repeating any side-effects in y. Or, since it's used only once, just inline it yourself. The restrict qualifier on detab()'s argument doesn't add anything, as there's nothing in the function which could be aliased to the argument. Just omit it.
{ "domain": "codereview.stackexchange", "id": 43758, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, formatting", "url": null }
c, formatting We always return a success status, but there's plenty that can go wrong in reading or writing to streams. We need to check every I/O operation for errors and respond accordingly. The detab() function runs into undefined behaviour as soon as we encounter a line with BUFSIZ or more characters. However, we don't really use to anywhere (the two places we read from it, we just get the value we recently assigned, i.e. from[i]), so we can remove it, fixing this bug: while (from[i] != '\0') { if (from[i] == TAB) { int spaces = calc_n_spaces(j, DEFTABSIZE); /* calculate number of spaces. */ while (spaces-- > 0) { putchar(SPACE); ++j; } } else { putchar(from[i]); ++j; } ++i; } The variable names i and j aren't very informative here. From reading the code, it seems that i is the logical (input) column number, and j is the output(physical) column number. There's no need to cast the return value of functions that are ignored. It's particularly odd to read that in main() given that detab() is declared as returning void anyway. The getline() function is not standard C (it's required by POSIX, but not by the C standard). However, we don't need to read a whole line before working on it, as the algorithm only considers a character at a time. We just need to reset our column number when we see a newline. Here's a vastly modified version that does exactly that: #include <stdio.h> #include <stdlib.h> #define TAB_STOP 8 int main(void) { int col = 0; /* logical column number */ for (;;) { int c = getchar();
{ "domain": "codereview.stackexchange", "id": 43758, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, formatting", "url": null }
c, formatting switch (c) { case EOF: return ferror(stdin) ? EXIT_FAILURE : EXIT_SUCCESS; case '\t': { int spaces = TAB_STOP - col % TAB_STOP; if (printf("%.*s", spaces, " ") != spaces) { return EXIT_FAILURE; } col += spaces; break; } case '\r': case '\n': col = -1; /* FALLTHROUGH */ default: if (putchar(c) == EOF) { return EXIT_FAILURE; } ++col; } } } Note the checking of more error conditions, too.
{ "domain": "codereview.stackexchange", "id": 43758, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, formatting", "url": null }
c++, template, integer, casting Title: Absolute value meta programming Question: I am implementing a generic absolute value function that handles signed and unsigned integer values correctly over the input type's domain. The std::abs(...) function leaves the case of std::abs(INT_MIN) as undefined behavior cppreference. I hope to resolve the undefined behavior by representing the returned absolute value in the input type's corresponding unsigned type. For example, int input = INT_MIN; // -2147483648 unsigned output = integral::abs(input); will correctly return 2147483648, but as an unsigned type. To accomplish this I implemented the following, namespace integral { template<typename integral_value_t> auto abs(integral_value_t const val) { static_assert(std::is_integral<integral_value_t>::value); if(val < 0) { return static_cast< typename std::make_unsigned<integral_value_t>::type>(-val); } return static_cast< typename std::make_unsigned<integral_value_t>::type>(val); } } but it created some concerns. Concerns: Returning an unsigned type creates a type management challenge for the caller. Maybe there is a better name for the function or namespace? Is the typename keyword required in static_cast<typename(gcc 12.1 complained)? Can the make_unsigned<...> call be made once? Making it twice is overly verbose. The code is also available on godbolt. Answer: To answer your specific concern (3): yes, the typename keyword is required, because at parse time the type std::make_unsigned<integral_value_t> isn't known, so its type member could be an object as far as the compiler is concerned. It's only once integral_value_t is known that it becomes a complete type. For concern (4), I'd recommend a using statement to avoid repeating the long type name.
{ "domain": "codereview.stackexchange", "id": 43759, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, integer, casting", "url": null }
c++, template, integer, casting For concern (4), I'd recommend a using statement to avoid repeating the long type name. We should include the <type_traits> header so that our function is usable immediately. Instead of the static_assert, I'd use a constraint to make the non-integral overloads disappear. Perhaps: auto abs(std::integral auto&& val) It might even be worth constraining to accept only signed types, though that could inhibit its use in generic code. It looks like we're assuming 2's-complement representation, given that -INT_MAX is undefined in standard C++. The if/else seems to be duplicating std::abs(), so why not call that? It's no more undefined than -val is. To eliminate undefined behaviour, we can't simply use -val in all cases. I'd do it by adding to val until it is large enough to be negated without overflow: #include <concepts> #include <limits> #include <type_traits> namespace integral { template<std::unsigned_integral T> auto abs(T&& val) { return val; } template<std::signed_integral T> auto abs(T&& val) { using U = typename std::make_unsigned_t<T>; if (val >= 0) { return static_cast<U>(val); } static constexpr auto maxval = std::numeric_limits<T>::max(); U retval = 0; while (val < -maxval) { val += maxval; retval += maxval; } return retval - val; } } I think it's guaranteed that the while will only ever perform one iteration, but I can't find where the standard says that negative range of signed types can only be slightly greater than their positive range.
{ "domain": "codereview.stackexchange", "id": 43759, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, template, integer, casting", "url": null }