Hot answers tagged

10

PyCharm complains on this line: m = json.loads(data) If the above call to fetch_compressed_data fails, and the resulting error doesn't contain a reason or code attribute, the program won't close despite the error, and will then give a not-super-helpful NameError when you try to use data. I don't know if such a situation is possible, but I might add some ...


8

This is how I see things... Throwing ArgumentException insinde a try/catch that at the same time swollows it is pointless. You use ArgumentException to inform the user that he called your API in a wrong way. This is not something one should hangle because he won't see it until he looks at the logs. The app should crash in this case. The message of the ...


8

I don't think that what you're doing is good style. I think you're adding a lot of extra complexity and places for things to go wrong, or become hard to understand, or whatever. I don't think you lose anything by just making very small methods that call super and your special method. I talk about those options at the bottom of the post. With that out of the ...


8

Just a couple stylistic points Function/Variable Naming Functions and variables should be in snake_case (PEP 8). getMessage -> get_message encodeMessage -> encode_message sendMessage -> send_message Docstrings You can include docstrings to provide some explanation for your methods and describe your parameters and return value. (PEP 8). ...


7

There are two points that showed up immediately when looking at your implementation: You missed one of the goals of the task: It should read the data from standard input and writes it the result to standard output. You are reading in the complete binary data into memory and process it from there. The latter is a no go, if we're talking about large ...


7

You should probably start with a profiler whenever you have unexplained performance problems, that should quickly point you to the functions or areas that take most of the runtime. That said, I immediately noticed the json.load and json.dump are called more than once. That seems to be at least a first candidate for optimisation. Either start keeping ...


6

Great job. Here are some minor notes though. In newer versions of C# you can leverage async Main in order not to wait for your test method. public static async Task Main(string[] args) { await Test(); } You can speed things up a bit with executing your tests in parallel public static async Task Test() { var successExecute = Execute("https://...


6

Welcome to Codereview, and welcome to Python! Your code looks good -- indentation is good, names are mostly good (but see below), docblock comments are mostly good (but see below). It seems like you need to "soak in" Python a bit, and you'll be up and running. Names Python's coding standard is PEP8 which for the purposes of naming can be simplified to: ...


6

Improving HTTP communication scheme Instead of urllib.request/urllib.error use requests lib as well-known, elegant and simple HTTP library for Python, built for human beings. import requests ... fetch_compressed_data function: def fetch_compressed_data(url): r = requests.get(url) r.raise_for_status() return gzip.GzipFile(fileobj=io.BytesIO(r....


5

Functions are your friend Even in Jython, functions are a valid construct. They allow for scope, so that you can better reason about temporary variables; give better stack traces when things go wrong; increase testability; etc. So you should move your code into some functions. Invert your logic This: if len(laty) == 7 and len(longx) == 6: should ...


5

I'd recommend (if it isn't already) converting to the type from json to jsonb and adding a GIN index. The documentation below lays it out pretty clear. Good luck! https://www.postgresql.org/docs/9.4/datatype-json.html For my recommendation, reason for using jsonb as opposed to vanilla json is that regular json is stored as an exact copy in postgres and you ...


4

My take is that there is no harm in adding a few named functions. Also it is probably better to ignore the result of setting a standard .net property. open System open System.Net open Newtonsoft.Json.Linq let downloadPriceInfo () = let client = new WebClient() client.DownloadString("https://blockchain.info/ticker") let getPriceOfEuro (price: ...


4

A few notes: Firstly, I would add some docstrings to each function to document what the expected behaviour is. In select when you're not doing any mutations (i.e. under the * case), it seems you could just return self. Is there any reason to make a new copy? In select, where, astype instead of creating a temporary dict, you could use a dict comprehension ...


4

Minor, but I'd expand your foreach a bit to make it clearer that func is a side-effect function that happens to return an indicator. In its current form, it looks like the function is only being run for the purpose of the condition. Something closer to: def foreach(self, func): for key, value in self.json.items(): should_continue = func(key, ...


4

Maintenance by design There are many times when I see this type of question regarding maintainability of the code. The line between code maintenance and user friendly becomes blurred. This is most evident when the coder is also the end user, the interface UI is misunderstood by familiarity of use, it is of course the IDE. This may sound somewhat pedantic, ...


4

Before separating the code into classes try separating it into more methods. At the very least separate business/logic code and input/output code. You should be able to use the same, unchanged business code no matter if it's a command line program, has a GUI or is a web application. For example getJSONAPIdataFromURL shouldn't write to System.out, but return ...


4

The main problem I see is that it's not obvious what the output is because there's too much auxiliary code that effectively obfuscates the logic. Offload some of the code into a function. Use template strings. If the data amount isn't in multi-megabyte range I would write a single string to improve readability: const dataJson = JSON.parse(data); const ...


4

A big inefficiency of the initial approach is that for each person (which is actually a person's name) messages collection will be traversed 4 times. To significantly optimize the traversal algorithm the current one is substituted with a single loop with multiple conditions per iteration. All the needed specific counts are declared beforehand and used as ...


4

Overview My main issue is that you convert the whole stream into tokens first. Then you parse the tokens. This can get very expensive. Normally you would parse (and push) enough tokens to understand the next part to interpret. Then pop the bit you can to convert the next part. I dislike the way you have two different types of token state: ...


4

Your code flattens the entire array of {} objects, indiscriminately flattening all properties. It does not mind, if there is only one single property, but it does not make sense semantically, especially if the array is named paintings. Rather consider the resulting array a projection/mapping to a single property painting. For a consistent array check and ...


3

The S3-functionality wraps the specific code, which does not change the variables. So how about a decorator? from functools import wraps def handle_s3_upload(fcn): @wraps(fcn) def inner(data_fp, data, *args, **kwargs): # handle S3 path s3 = False if data_fp.lower().startswith('s3://'): s3_data_fp = data_fp ...


3

type(x) == y is unidiomatic, and prone to errors. Use isinstance(x, y) instead. Your variable names aren't great. k, kk, kkk, vv. You can simplify changing the data. data[data.index(k)] == k. You can simplify kkk[list(vv[0].keys())[0]] to list(kkk.values())[0]. You can simplify set([...]) with a set comprehension {...}. Your function looks like a hack. I ...


3

I am prejudiced against variables named data. You need to escape literal ", \, and \n characters in quoted strings. It's good form to do tabs too. Using a dispatch table for types (instead of if/else) makes it easy to handle all the types. Instead of passing tab up and down the call stack, wrap the calls in a function that indents a block of text. ...


3

You cannot use a return in a __construct() method. If you need to check for any "badness", you can use throw/try/catch.Relevant resources: Return false from __constructor & PHP - constructor function doesn't return false (In the end, I support Sam's advice about writing class constants.) Regarding your regex patterns, they can be simplified. /\r\n|\r|\...


3

Your code is impressingly well structured and easy to follow, thanks to its comprehensive documentation. The first thing I noticed that I would do differently is when initializing the space character. Your code reads: > 20 space >[-]++[-<++++++++++++++++>]< You can leave out the [-] since the memory is zeroed out when the ...


3

Use the csv library x.writerows(custom_tuple(row) for row in data['results']) Grabbing mutable data from the global scope is, I'm pretty sure, poor form. You should pass data as an argument to search_output. Just pass in data['results'] as results, not the whole data object. Consider calling it output_search_results. Consider using precise type hints. The ...


3

What a wall of text! Also known as write-only code, or job security. You want to write understandable code, that you can come back to in 6 months, and within 5 minutes understand enough to change it, if necessary. This has a for-loop over a sorted list comprehension, with embedded if-then-else, of a zip of two sorted json queries, with a lambda thrown in ...


3

Whenever you have code that sets up an array, then has a loop to push items into that array, Array.map() could be used to condense that code. For example, these lines: const jsonData = []; data.forEach( (row) => { const json = {}; row.forEach( (item, index) => { json[columns[index]] = item; }); jsonData.push(json); }); return jsonData; ...


3

Let's go through the code and see what can be improved. #pragma once This shouldn't be in a non-header. #include <list> #include <map> #include <string> #include <variant> #include <vector> #include <fstream> #include <iostream> #include <sstream> Sort the include directives in alphabetical order. ...


3

I'm just adding some elements to the explanation by RoToRa, use the method toString of the class LocalDate because it outputs the date in ISO-8601 format uuuu-MM-dd, and this is exactly the format you are using. If you are looking for math operations on streams of Double like searching for min, max, average you can use the class DoubleSummaryStatistics like ...


Only top voted, non community-wiki answers of a minimum length are eligible