text
stringlengths
1
2.12k
source
dict
java, strings, lambda, column public Columns alignCenter(){ align = left -> word -> right -> left + word + right; return this; } public Columns alignRight(){ align = left -> word -> right -> left + right + word; return this; } } By waiting until all the lines have been added before printing it can figure out the width each column needs. Looking for a code review to reveal problems. Anything from better names to fewer bugs to better ideas. Along with some minor fixes the string concatenation has been modified which simplified the alignment lambdas (and lengthened padCell() and toString()). Micro-optimization? Answer: Those are some interesting and inventive changes. Here are some thoughs (some new, some of which I missed - or just left out - last time): First off, a bug: You are assuming that pad has a length of 1. I'd change it to a char or validate it in the setter. I like the initialisation of align instead of the duplicate lambda. The initializer block is an obscure feature and I believe, if there were multiple contructors its code is copied into each of them by the compiler creating artifical code duplicate. That's why I'd personally put it into a constructor, but I guess in this case the initializer block is fine, too. Using a "curried" (is that the right word?) type to create the type of align is interesting. I guess it's fine here, but if the type would be needed at multiple locations this could become cumbersome. Personally I'd define my own AlignFunction functional interface. In addLine() it may be sensibe to disallow lines with zero items. I can't see any immediate problems for that edge case, but it would avoid potential future problems. An else between the two if would be good, because the two cases are exclusive. The filling of maxLength could be done with Collections.nCopies(). Actually thinking about it, I'd drop the maxLength field and just calculate the maximum lengths in the toString method.
{ "domain": "codereview.stackexchange", "id": 44564, "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, strings, lambda, column", "url": null }
java, strings, lambda, column I'd drop the print() method to avoid the unnecessary coupling with the console. The calculation of the size of the StringBuffer is unnecessary IMO, but if you do it, you don't need to loop of the lines. It can be done with just summing up maxLengths and multiplication: // Or just a loop. I prefer `Stream`s. final int totalMaxLengths = maxLength.stream().reduce(0, (a, b) -> a + b); // TODO Format better final int totalLength = (totalMaxLengths + columnSeparator.length() * (maxLengths.size() - 1) + System.lineSeparator().length()) * lines.size(); For the actual output building I suggested StringBuilder last time, but I'd probably also use Streams. The repeatition of strings in padCell is also interesting (you got it from Stackoverflow didn't you :) ). Since Java 11 however there is String::repeat(). Or at the very least extract the expression into a well named method.
{ "domain": "codereview.stackexchange", "id": 44564, "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, strings, lambda, column", "url": null }
php Title: Calculate cost of standard or express delivery Question: I've got the following code, which calculates net delivery cost to 4 decimal places. Delivery can be either standard or express shipping. It is intended to return a string in 4 decimal places of the cost of delivery. I can't think of another time where I've written something like $standardShipping = !$expressShipping or generically variable = !boolean. But it feels much more readable this way as I often find when reading !$variable the exclamation is easy to miss. Any reason why I this is a bad idea? Or perhaps I should instead do false === $variable instead of !$variable ? public function calculateNetDelivery4dp(bool $expressShipping = false): string { $standardShipping = !$expressShipping; // if account has free standard delivery or free standard and express delivery and using standard delivery if ( ($this->user?->getAccount()?->isFreeStandardDelivery() || $this->user?->getAccount()?->isFreeStandardAndExpressDelivery() ) && $standardShipping ) { return '0.0000'; } // if account has free express delivery and using express delivery if ($this->user?->getAccount()?->isFreeStandardAndExpressDelivery() && $expressShipping) { return '0.0000'; } $basket = $this->basketService->getCurrentBasket(); $basketItemsAllFreeStandardDelivery = true; foreach ($basket->getBasketItems() as $basketItem) { if (false === $basketItem->getProduct()->isFreeStandardDelivery()) { $basketItemsAllFreeStandardDelivery = false; break; } } if ($basketItemsAllFreeStandardDelivery && $standardShipping) { return '0.0000'; } if ($standardShipping) { return '4.1600'; } return '6.6600'; }
{ "domain": "codereview.stackexchange", "id": 44565, "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": "php", "url": null }
php if ($standardShipping) { return '4.1600'; } return '6.6600'; } Answer: I wouldn't bother declaring the inverse boolean variable $standardShipping. If you like seeing the explicit variable, that's fine too. I don't think I support the idea of returning float values as strings. For a method that "calculates" a price, I wouldn't expect the return value to be any kind of formatted string. String formatting is a responsibility for another method in your application. Perhaps it would be helpful for you to define some class level constants for STANDARD_SHIPPING_COST and EXPRESS_SHIPPING_COST. If you don't like the bloat of the "whole basket" loop in your method, you can pull that out into a new private method. New code: public function calculateNetDelivery4dp(bool $expressShipping = false): float { // handle unrestricted free shipping if ($this->user?->getAccount()?->isFreeStandardAndExpressDelivery()) { return 0; } // handle express shipping if ($expressShipping) { return self::EXPRESS_SHIPPING_COST; } // handle standard shipping if ( $this->user?->getAccount()?->isFreeStandardDelivery() || $this->hasFreeStandardDeliveryForWholeBasket() ) { return 0; } return self::STANDARD_SHIPPING_COST; } private function hasFreeStandardDeliveryForWholeBasket(): bool { foreach ($this->basketService->getCurrentBasket()->getBasketItems() as $basketItem) { if (false === $basketItem->getProduct()->isFreeStandardDelivery()) { return false; } } return true; }
{ "domain": "codereview.stackexchange", "id": 44565, "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": "php", "url": null }
validation, kotlin Title: Given an EAN-8 or an EAN-13 code, tell if that code is valid Question: I have the requirement to validate product codes which include EAN-8, EAN-13 and UPC-A encoded as EAN-13. I have implemented a use-case to perform this check by comparing the actual check digit with the computed one. I followed this explanation for EAN-13 and that one for EAN-8. The reason I'm asking for a review is because I haven't worked with EANs before and also noticed that my previous versions that had logical flaws still passed the tests with some codes, so the error wasn't obvious. Example: in an earlier version, I did not drop the last digit (which is the check digit), so it was mistakenly used in the calculation. The result was that the tests passed for the UPC-A (wrapped as EAN-13) code that can be seen in the test, but failed for a "real" EAN-13 and EAN-8, adding to my confusion. Another example of a bad idea was giving ChatGPT a shot on solving the problem because the thing often contradicted itself and produced code that worked with some codes and didn't work with others - so be careful with that one because you might go from "I somewhat know what I'm doing and want to save time" to "I have no idea, throw everything away and start from scratch". Note: the code can be seen in action on the Kotlin Playground Description: the code format is valid if it consists of exactly 8 or 13 digits. take the last digit - this is the reference check digit take the input digits remove the check digit convert the rest to a List of Ints compute the check digit
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
validation, kotlin remove the check digit convert the rest to a List of Ints compute the check digit In the sumForEAN8() and sumForEAN13() extensions, you may notice that the calculation is exactly opposite of the specification, e.g. for EAN-13, I multiply odd digits by 3, whereby the spec says one should do that for even digits. The reason is that the spec divides all digits in even and odd based on the complete number including the check digit. Since we remove the check digit before proceeding with the calculation, the "odd" and "even" numbering basically shifts by one. now I realize that this explanation is wrong (because digits are iterated left-to-right, so dropping the last one cannot affect even/odd): the swap is still needed, but the real reason is that we have 0-based indices in programming, while the spec uses a 1-based index) internal class ValidateEANUseCase() { private val eanFormatRegex = Regex("^\\d{8}|\\d{13}$") fun run(ean: String): Boolean = when { ean.hasInvalidFormat() -> false else -> { val actualCheckDigit = ean.last() .digitToInt() val computedCheckDigit = ean .dropLast(1) .map { char -> char.digitToInt() } .computeEANCheckDigit() actualCheckDigit == computedCheckDigit } } private fun String.hasInvalidFormat(): Boolean = !this.matches(eanFormatRegex) private fun List<Int>.computeEANCheckDigit(): Int { val sum = if (size == 7) sumForEAN8() else sumForEAN13() return (10 - (sum % 10)) % 10 } private fun List<Int>.sumForEAN8(): Int = withIndex() .sumOf { (index, digit) -> if (index % 2 == 0) digit * 3 else digit } private fun List<Int>.sumForEAN13(): Int = withIndex() .sumOf { (index, digit) -> if (index % 2 == 0) digit else digit * 3 } }
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
validation, kotlin } Below are the unit tests (all passing; tested refers to the instance of the class being tested). Any further inputs to consider? @Test fun `GIVEN a valid EAN-8 number THEN the validation result is TRUE`() { val result = tested.run(VALID_EAN_8) assertThat(result).isTrue } @Test fun `GIVEN a valid EAN-13 number THEN the validation result is TRUE`() { val result = tested.run(VALID_EAN_13) assertThat(result).isTrue } @Test fun `GIVEN a valid UPC-A number encoded as EAN-13 THEN the validation result is TRUE`() { val result = tested.run(VALID_UPC_A_ENCODED_AS_EAN_13) assertThat(result).isTrue } @Test fun `GIVEN ANY invalid input THEN the validation result is FALSE`() { val results = mutableListOf<Boolean>() invalidInputs.forEach { results.add(tested.run(it)) } assertThat(results).allMatch { it == false } } private companion object { const val VALID_EAN_13 = "5060762541604" const val VALID_EAN_8 = "42307167" const val VALID_UPC_A_ENCODED_AS_EAN_13 = "0670367004760" val invalidInputs = listOf( "", " ", "\n\t", "\\§$%&()=?ß`+´ü-!äö'#*´;¿\"@<>", "123", "12345678", "5060962541604", "00123456789012", "hello EAN", "привет EAN", "你好 EAN" ) } Thank you. Answer: You cite e.g. open.edu. I would feel better about a citation to the (500 page!) EAN-{8,13} spec: § 7.9.1 and 7.9.5 (They are named GITIN-{8,13}, there.) internal class ValidateEANUseCase() { I really like the initial portion of that identifier. The second half seems awkward, but maybe y'all have some convention this is conforming to, where a restricted vocabulary that includes UseCase is always used as a suffix. Regex("^\\d{8}|\\d{13}$")
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
validation, kotlin Regex("^\\d{8}|\\d{13}$") I don't understand that expression. Or rather, I believe that instead of saying ^X|Y$ you intended ^(X|Y)$ BTW, the instinct to anchor the expression is a good one, I applaud it. If you're going to use just a single anchor, the ^ caret offers the bigger win, as it will typically do more to limit expensive backtracking. The run function is laudably clear, thank you. Maybe breaking out a hasInvalidFormat helper was overkill? Maybe choose to define it in the positive, hasValidFormat, and let caller negate if needed? Humans tend to reason about the positive case better than they do about not not negatives. In computeEANCheckDigit this expression is interesting: return (10 - (sum % 10)) % 10 It's not explicit in the code, but I assume we could assert sum >= 0. I confess I do not understand this expression. We have an integer 0 .. 9 inclusive, which we subtract from ten. And then we modulo it again? Why? I have to believe that the difference is already within range. Consider the 10 - 0 case. Sorry, I was wrong, I withdraw the remark. It's not like the spec asks for nine minus something. I would very much appreciate seeing a unit test that draws attention to this case. Whenever we make a mistake, it is useful to memorialize it in a (now Green!) test.
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
validation, kotlin I'm sure that sumForEAN8 and sumForEAN13 are correct; please ship them as-is. But I will just say that I'm not super happy with them, and I guess that feeling started with your wonderfully forthright description up top about "exactly opposite". Here's what I was looking for: a direct linkage to the spec. In the language of the spec, we're talking about N1 .. N7 for EAN8, and N1 .. N12 for EAN13. And then the spec offers integer multipliers, either 1 or 3, in the "Multiply value of each position by" section. Like I said, I believe the correct quantity winds up being calculated. But I wouldn't mind seeing more direct traceability to what the standards body actually specifies. Also, given a pair of multiplier vectors, I believe we could implement these with just a single function. Look into the future for a moment. Maybe a use case will come down the pike that requires EAN-14 support? Common code that exploits commonality in the spec seems desirable. val result = tested.run(VALID_EAN_8) assertThat(result).isTrue This impresses me as being about twice as verbose as needed, but fine, whatever, I'm sure there's some cultural Kotlin thing going on here that I'm unfamiliar with. Always follow the cultural norms. I would have just asserted the expression, without defining a temp var. The bigger issue is that, while I really like the helpfully descriptive VALID_EAN_8 identifier, I'm sad that the value is so far away in a companion object. I would much rather see a line defining it right here in the test function, given that the value isn't shared with other functions. I like the immediacy of it, no scrolling back and forth to see what's happening. But again, if we're conforming to some cultural norm here, good, so be it. Kind of like the practice of putting SPACE characters in function names, I guess. There's an opportunity to include more than a single example of each kind of valid product code, here. You wrote "5060962541604", "00123456789012", ...
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
validation, kotlin You wrote "5060962541604", "00123456789012", ... I ran out of fingers to count on. I would much rather see those constants expressed as "5060962541604", "00123456789012", ... to visually emphasize their relative lengths. Ok, we have been diving down into the nitty gritty. Let's up-level for a moment, and critique the whole unit testing approach. There's a testing aspect that I am not yet satisfied with. We could do amplification of our test inputs. That is, for each known-valid product code, we also know how to trivially create nine invalid codes. So let's do it, it's cheap! And verify that each one fails. Overall? A regex should be fixed, and perhaps a modulo cleaned up. This code has been carefully implemented, and achieves its design objectives. I would gladly delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44566, "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": "validation, kotlin", "url": null }
c#, object-oriented, .net, asp.net, error-handling Title: OOP methods/functions that can return a value or an exception Question: I'm currently working through a series of bugs in an application. Our application is written in C#/ASP.NET (on the server) and HTML/CSS/JavaScript (on the client). We are using ELMAH to log any uncaught exceptions in the system so that we may identify it later and fix it, which is what I'm currently doing. The way ELMAH works is to log any uncaught exception, so once you catch and handle the exception, it can be omitted from ELMAH. This article closely relates to a question I asked here on Stack Overflow. To give a little bit of insight into this article, ELMAH logs uncaught exceptions, but sometimes you have certain scenarios where the exception is thrown to the browser and handled there. ELMAH doesn't know that it's being handled elsewhere, so it still logs the exception. In our application, we use WCF web services to send JSON data back to the client. Say for example one of those services fails and throws an exception, we send that exception back to the browser and handle it there (and as stated, ELMAH still logs it). So I had this idea, which might only apply to a small set of use cases, but as an idea, I wanted to know what the community thought of it. As OO programmers know, methods/functions have a return type (or void). Example public void SayHello() { Print("Hello"); } public string GetMyName() { return "Joe Bloggs"; } All well and good so far, but what if I wanted my method/function to return either a value, or an exception if one was to occur? I can do this in C# using the dynamic keyword. Example public dynamic GetMyNameOrCryLikeABaby() { try { return DoSomethingWrong(); // might throw an exception, but should return a string. } catch(Exception ex) { return ex; } }
{ "domain": "codereview.stackexchange", "id": 44567, "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#, object-oriented, .net, asp.net, error-handling", "url": null }
c#, object-oriented, .net, asp.net, error-handling Personally I don't like this approach. I don't think it is a good use of the dynamic keyword, and it involves the developer adding in additional code to check whether the return value was (in this example) a string, or an Exception. The idea I came up with to get around this was based somewhat on .NET's Nullable<T> structure. The idea here being that a ValueType wrapped in a Nullable<T> (e.g. Nullable<int>) can return null. The structure below has some interesting characteristics! The aim was to write a structure that could implicitly be cast to the expected type, but could also return an exception, should one occur. This structure is called "Exceptable" meaning it might hold an exception. Exceptable<T> Source Code /// <summary> /// Represents a generic type that can also hold an associated exception. /// </summary> /// <typeparam name="T">The type of this Exceptable object.</typeparam> public struct Exceptable<T> { /// <summary> /// Gets or sets the value of this object. /// </summary> public T Value { get; set; } /// <summary> /// Gets or sets an exception that may occur when using this type. /// </summary> public Exception Exception { get; set; } /// <summary> /// Gets a value indicating whether this object has a value. /// </summary> public Boolean HasValue { get { return this.Value != null; } } /// <summary> /// Gets a value indicating whether this object has an exception. /// </summary> public Boolean HasException { get { return this.Exception != null; } } /// <summary> /// Allows implicit casting between a raw type, and an Exceptable type. /// </summary> /// <param name="value">The exceptable value to convert to a raw type.</param> /// <returns>A raw type</returns> public static implicit operator T(Exceptable<T> value) { return value.Value; }
{ "domain": "codereview.stackexchange", "id": 44567, "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#, object-oriented, .net, asp.net, error-handling", "url": null }
c#, object-oriented, .net, asp.net, error-handling /// <summary> /// Allows implicit casting between an Exceptable type and a raw type. /// </summary> /// <param name="value">The raw type to convert to an excepable type.</param> /// <returns>An excepable type.</returns> public static implicit operator Exceptable<T>(T value) { return new Exceptable<T> { Value = value }; } } So as you can see here, it wraps the expected type into Exceptable as a generic type and provides implicit conversion between Exceptable<T> and T. Use Cases Exceptable<string> name = "Joe Bloggs"; Exceptable<int> age = 26; public static Exceptable<string> GetMyNameOrCryLikeABaby() { Exceptable<string> result = String.Empty; try { result = DoSomethingWrong() // might throw an exception but should return a string. } catch(Exception ex) { result.Exception = ex; } return result; } string name = GetMyNameOrCryLikeABaby(); Exceptable<string> nameOrException = GetMyNameOrCryLikeABaby(); As you can see from the examples above, I can assign values directly to Exceptable<T>. I can also use it as a return type for a method, and due to implicit conversion, I can choose whether to return just the associated value of the structure, or the structure itself, in case I want to handle the associated exception. What do you think?
{ "domain": "codereview.stackexchange", "id": 44567, "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#, object-oriented, .net, asp.net, error-handling", "url": null }
c#, object-oriented, .net, asp.net, error-handling Answer: Doing this instead of working with exceptions the usual way (throw and catch) is a big code smell. I think I would need a really good justification for this and I'm not sure slightly improved logging is that. I would try looking more into other possibilities, like filtering Exceptions based on their type, or something like that. This code comes close to reinventing the Exception monad. You might want to study that for some ideas. Your type should protect its invariants. If it's supposed to contain a value or an exception, but not both, you shouldn't allow the user to use the type the wrong way. A similar principle also applies to reading: if a value is not present, Value should throw an exception, instead of silently returning the default value. The same probably applies to Exception. For a simple type like this, it often makes sense to make it immutable. Also, mutable value types are evil, you should never use them without a really good reason (and I don't see that reason here). You should be very careful with implicit conversions. An implicit conversion should never lead to loss of information and it should be always valid. In your case, that's not true for the case when Exceptable contains an exception, because then the implicit conversion silently returns the default value. So, if you want to have a conversion from Exceptable<T> to T, it should be explicit and it should throw when an exception is present. You're checking Value against null. This is a bad idea for several reasons: In some cases, null can be a legitimate return value that does not indicate an error. Your type won't handle that correctly. If T is a non-nullable value type, then the default value is not null, so HasValue won't work correctly. If your type is meant to support only reference types, you should make that explicit by adding the constraint where T : class to it. The name “exceptable” is not great. Though I'm not sure what would be a better name.
{ "domain": "codereview.stackexchange", "id": 44567, "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#, object-oriented, .net, asp.net, error-handling", "url": null }
javascript Title: function to get title from result object depending on if title is empty Question: I want to rewrite if else statements with something nicer or refactor the code i have to something neat using javascript. below is the code, const title = () => { if (result) { //here checking if the title field is not undefined or null and title field //has no empty string "" if (result?.title && !isEmpty(result?.title)) return result.title; // checking if title is undefined or null or is empty string "" if (!result?.title || isEmpty(result?.title)) return something[status] (name); } else { return titleByStatus[status]; }; could someone help me with this. thanks. } could someone help me rewrite this neat. thanks Answer: You don't need to use ? inside the if(result) block, because you know that its not null or undefined Your two if statements are opposite, use an else block if (result) { if (result.title && result.title != "") { return result.title; } else { return something[status](name) } } else { return titleByStatus[status]; };
{ "domain": "codereview.stackexchange", "id": 44568, "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", "url": null }
performance, c, edit-distance Title: Damerau-Levenshtein distance performance improvements Question: I am working on a Python C-extension to calculate Damerau-Levenshtein distance. I am not really familiar with C at all--I just know that it generally has better performance. However, I am not sure how to bring about these performance gains. I translated a Python version from https://github.com/jamesturk/jellyfish/blob/main/jellyfish/_jellyfish.py basically 1:1, and the speed is fine, but I suspect I am making performance concessions an experienced C programmer would not. I would be grateful if anyone could point out anything inefficient I am doing! Also, I am just worried dealing with ASCII characters. #define PY_SSIZE_T_CLEAN #include <Python.h> #include <string.h> // This is a 1:1 translation of https://github.com/jamesturk/jellyfish/blob/main/jellyfish/_jellyfish.py int min_int(int arr[], size_t size) { // simply loop over an array of integers to find the min int min = arr[0]; for (size_t i = 1; i < size; i++) { int val = arr[i]; if (val < min) { min = val; } } return min; } static PyObject* distance(PyObject *self, PyObject *args) { const char* s1; const char* s2; if ( !PyArg_ParseTuple(args, "ss", &s1, &s2) ) // s means string argument { return NULL; } int len1 = strlen(s1); int len2 = strlen(s2); int infinite = len1 + len2; int nrows = len1 + 2; int ncols = len2 + 2; // initialize distance matrix int score[nrows][ncols]; for (size_t i = 0; i < nrows; i++) { for (size_t j = 0; j < ncols; j++) { score[i][j] = 0; } }
{ "domain": "codereview.stackexchange", "id": 44569, "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, c, edit-distance", "url": null }
performance, c, edit-distance score[0][0] = infinite; for (size_t i = 0; i <= len1; i++) { score[i + 1][0] = infinite; score[i + 1][1] = i; } for (size_t i = 0; i <= len2; i++) { score[0][i + 1] = infinite; score[1][i + 1] = i; } // Since we are only dealing with ascii characters, this is equivalent to the dictionary // in the Python implementation. Instead of accessing using the character as the index, we // can cast the character to its integer version, and access by index. int da[256] = { 0 }; for (size_t i = 1; i <= len1; i++) { int db = 0; for (size_t j = 1; j <= len2; j++) { const char s2_char = s2[j - 1]; int i1 = da[(int)s2_char]; int j1 = db; int cost = 1; if (s1[i - 1] == s2_char) { cost = 0; db = j; } int arr[4] = { score[i][j] + cost, score[i + 1][j] + 1, score[i][j + 1] + 1, score[i1][j1] + (i - i1 - 1) + 1 + (j - j1 - 1) }; score[i + 1][j + 1] = min_int(arr, 4); } const char s1_char = s1[i - 1]; da[(int)s1_char] = i; } long distance = score[len1 + 1][len2 + 1]; return PyLong_FromLong(distance); } The compiler flags are -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk It's available to view and play with on Godbolt. I am compiling on MacOS x86_64-apple-darwin21.6.0, clang version 14. Answer: Please write this int min_int(int arr[], size_t size) { assert(size > 0);
{ "domain": "codereview.stackexchange", "id": 44569, "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, c, edit-distance", "url": null }
performance, c, edit-distance Answer: Please write this int min_int(int arr[], size_t size) { assert(size > 0); That will avoid UB, and give the caller a nice diagnostic if he messes up his contract. Or if asserts might be disabled, add an explicit if. Also, it would be useful to write down why this code doesn't target C++20 or similar which offers std::min. You voice concerns about speed of your code. Using code that others wrote and tuned is one of the best ways to address such concerns. In distance, kudos on the very helpful "ss" comment, thank you. I am sad the function isn't named damerau_levenshtein_distance, for better traceability to the python source. Establishing traceability is important whenever one artifact is supposed to correspond 1:1 to another artifact. Kudos on nicely preserving all the variable names. The corresponding python source raises a nicely diagnostic TypeError if caller messed up. Here, maybe a NULL does something similar? That is, we're not returning a None object to caller, are we? Oh, I see, there's an exception teed up and ready to go when it returns false, good. Zeroing out the score matrix works fine. If you benchmark you might observe memset doing it quicker. Or, ask that it be zeroed at allocation time. (Side note: the python code uses integer objects, implying a lot of object pointer chasing. There's an opportunity for it to use an array instead.) int arr[4] = { I understand why you create a temporary array, going for a literal rendering of the min argument in the python code. But it feels more natural here to just compute ordinary min(), more than once if necessary. (Or #define min4 if you feel it improves legibility.) da[(int)s1_char] = i;
{ "domain": "codereview.stackexchange", "id": 44569, "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, c, edit-distance", "url": null }
performance, c, edit-distance I guess we should prefer an unsigned ssize_t cast, right? And, I know you said there's an "ASCII" assumption (7 bit?), but the const char s1_char declaration should probably be unsigned. What I'm shooting for is to help the compiler easily prove it has a valid da index. The score entries are positive, with a signed representation, and that seems OK. There is an opportunity to make each entry consume fewer bits. The "not Unicode" assumption could be written down more clearly. Also, for a pair of strings with fewer than 256 distinct codepoints, a preprocessor could map the glyphs to small values that work directly with the current (unmodified) function. Here's a design consideration. I assume a python app will call this function repeatedly in a loop. Does it make sense to offer a bigger API than what the original python source offers? That is, would we bench quicker if an extra function let caller pass in a container of words to compute distance on? The idea being that C iterates through them faster than a python for loop would.
{ "domain": "codereview.stackexchange", "id": 44569, "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, c, edit-distance", "url": null }
c++, calculator Title: A simple tokenizer in c++, it just creates a vector of tokens Question: #include <iostream> #include <vector> #include <memory> #define IS_DIGIT(x) x >= 48 && x <= 67 static unsigned int allocated = 0; void* operator new(size_t size) { allocated += size; void* mem = malloc(size); //std::cout << "allocating: " << mem << " with size: " << size << std::endl; return mem; } static unsigned int deleted = 0; void operator delete(void* ptr, size_t size) { deleted += size; //std::cout << "deleting: " << ptr << " with size: " << size << std::endl; free(ptr); } enum class Type { None, Number, Operator }; std::ostream& operator<<(std::ostream& os, Type& type) { switch (type) { case Type::None: os << "None"; break; case Type::Number: os << "Number"; break; case Type::Operator: os << "Operator"; break; default: std::cout << "Unknown type for: " << &type << std::endl; break; } return os; } class Token { public: Type type = Type::None; virtual void Fn() {}; }; class Number : public Token { public: int value; Number(int _value) : value(_value) { type = Type::Number; } }; class Operator : public Token { public: Operator() { type = Type::Operator; } virtual Number Operate(const Number& num1, const Number& num2) = 0; }; class Plus : public Operator { public: Number Operate(const Number& num1, const Number& num2) override { return Number(num1.value + num2.value); } }; class Minus : public Operator { public: Number Operate(const Number& num1, const Number& num2) override { return Number(num1.value - num2.value); } }; void Tokenize(const std::string& input, std::vector<std::unique_ptr<Token>>& vec) { std::string number;
{ "domain": "codereview.stackexchange", "id": 44570, "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++, calculator", "url": null }
c++, calculator for (auto& c : input) { if (c == '\n' || c == ' ' || !c) continue; std::cout << "char: " << c << std::endl; if (IS_DIGIT(c)) number.push_back(c); else { vec.push_back(std::move(std::make_unique<Number>(std::stoi(number.c_str())))); number.clear(); switch (c) { case '+': vec.push_back(std::move(std::make_unique<Plus>())); break; case '-': vec.push_back(std::move(std::make_unique<Minus>())); break; default: std::cout << "Unknown operator: " << c << std::endl; break; } } } // for last digit if (!number.empty()) vec.push_back(std::move(std::make_unique<Number>(std::stoi(number.c_str())))); } int main() { // main scope { std::vector<std::unique_ptr<Token>> tokens; Tokenize(" 78 + 1 *5-3", tokens); for (auto& i : tokens) { std::cout << "type: " << i.get()->type; Number* op = dynamic_cast<Number*>(i.get()); if (op) std::cout << " num: " << op->value; std::cout << std::endl; } } std::cout << "total allocated: " << allocated << std::endl; std::cout << "total deleted: " << allocated << std::endl; return 0; } Can someone smart please check my code for inefficiencies and better optimizations ? Also I am not even sure if I do this right. thanks in advance Answer: As mentioned in the comments, you are perhaps confusing tokenizer, parser and interpreter, but I will review the code anyways. Token Hierarchy
{ "domain": "codereview.stackexchange", "id": 44570, "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++, calculator", "url": null }
c++, calculator Your Token class has two direct children i.e Number and Operator. This makes the type enum redundant and error-prone. The only reason you have a Type enum is to print the type, so why not just return a std::string instead? Your type variable is exposed and breaks encapsulation. Consider making it private and have a getType method in the class. Your Number class breaks Liskov's substitution principle. It has a public member variable value (which IMHO should be private with a public accessor) that is not present in your base class aka the token. This forces you to do a dynamic cast which is a code smell. If we look at the hierarchy carefully, neither Number nor Operator are tokens but it's the other way around. A token can be a Number or an Operator. Hence, a std::variant is better suited for this. If I had to make Token the root of the hierarchy and also keep the Type enum for some reason, I would change the implementation to be something like this: { public: virtual char const * const getType() = 0; virtual int evaluate() = 0; private: }; class Number : public Token { public: char const * const getType() override final { return "Number"; } int evaluate() override { return value; } private: int value; }; class Operator : public Token { public: char const * const getType() override final { return "Operator"; } private: }; class Plus : public Operator { public: int evaluate() { return operand1->evaluate() + operand2->evaluate(); } private: std::unique_ptr<Token> operand1; std::unique_ptr<Token> operand2; }; Tokenize function Prefer returning values over "out" parameters; i.e. use the signature std::vector<std::unique_ptr<Token>> Tokenize(const std::string& input) instead.
{ "domain": "codereview.stackexchange", "id": 44570, "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++, calculator", "url": null }
assembly, x86 Title: Replace specific characters (CR and LF) in a file Question: Context This program has been created to "fix" files originating from Cobol databases. In Cobol, files extracted via something called a "copy" have the same number of characters per line. However, user inputs might include new line characters which can cause problems when interpreted by other systems. This program aims to solve this by replacing CR/LF characters in the file, except the END OF LINE sequence (LF). Code ; This programs reads from STDIN ; It sends this content back to STDOUT ; It replaces CR (0xd) and LF (0xa) by space (0x20) ; It reads a number from invocation parameters (1 to 255 --> 1 byte number only) ; This number represents the number of character per ligne and must not ; take into account the EOL LF. ; The EOL LF will not be replaced ; If the parameter number is incorrect, output will not be correctly formatted ; (you will lose EOL LF) ; Compile and link with: ; ld -o main.exe main.o -m elf_i386 && ; nasm -f elf -ggdb -F stabs main.asm ; Run with: ; ./main.exe 8 <toto.txt ; Where toto contains: ; 1234|678 ; 1234|<cr> ; 7 ; 1234|678 ; 1234| ; 78 ; Output: ;/app/asm # ./main.exe 8 <toto.txt ; 1234|678 ; 1234| 7 ; 1234|678 ; 1234| 78 section .data section .bss line_length: resb 1 count_buffer: resb 1 input_buffer: resb 1 section .text global _start _start: mov byte [count_buffer], 0 ; using ATOI, gets the first command line argument, transform it into ; a number. _get_line_length: mov eax, 0 mov ecx, [esp+8] ; ecx pointe sur la stack à l'emplacement du premier parametre _atoi: movzx esi, byte [ecx] ; store into esi a the byte at adress where ecx points to cmp esi, 0 ; compare esi with 0 (NULL char) jz _check_line_length ; if esi = 0, jump to _check_line_length
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
assembly, x86 cmp esi, 48 ; compare esi with 48 ("0" char) jl _exit_1 ; if esi is lower than 0, exit in error cmp esi, 57 ; compare esi with 57 ("9" char) jg _exit_1 ; if esi is greater, exit in error sub esi, 48 ; substract 48 to esi (transforms the char into its decimal equivalent) imul eax, 10 ; multiply eax by 10 add eax, esi ; add esi to eax inc ecx ; make ecx point to the next byte jmp _atoi ; jump to _atoi (loop) _check_line_length: cmp eax, 0 jz _exit_1 ; TODO message erreur jl _exit_1 ; TODO message erreur add al, 1 ; Take expected linefeed into account (the mandatory LF) push ax ; push al (ax because can't push less that 16 bits) to the stack. Acces later via [esp] _read_stdin: add byte [count_buffer], 1 ; increase loop counter mov eax, 3 mov ebx, 0 mov ecx, input_buffer mov edx, 1 int 80H cmp eax, -1 ; if error, exit input jz _exit_1 cmp eax, 0 ; if 0, then no more content to read jz _exit_0 xor eax, eax mov ax, [esp] ; get the line length. We get two bytes, the lower end is in al, the higher one is in ah mov ah, [count_buffer] ; get the current loop counter cmp al, ah ; compare nbr char read and line length jz _finish_process_line jmp _process_char _finish_process_line: mov byte [count_buffer], 0 jmp _stdout
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
assembly, x86 _finish_process_line: mov byte [count_buffer], 0 jmp _stdout _process_char: mov ecx, [ecx] ; store the value of the memory ecx points at to the ecx reg cmp cl, 0xa ; compare the lower byte of ecx 32 bits to LF jz .replace_char cmp cl, 0xd jz .replace_char ; compare the lower byte of ecx 32 bits to CR jmp _stdout .replace_char: xor ecx, ecx ; clean the ecx reg mov cl, 20h ; set cl reg to space mov [input_buffer], cl ; move value to input_buffer memory jmp _stdout _stdout: mov eax, 4 mov ebx, 1 mov edx, 1 mov ecx, input_buffer int 80H jmp _read_stdin _exit_0: mov eax, 1 mov ebx, 0 int 80H _exit_1: mov eax, 1 mov ebx, 1 int 80H Questions This program is "slow". With an input file of 43 858 bytes, it takes 0.087 seconds to execute. So arround 504 115 bytes per second. I have a python program that does the equivalent, which is capable of processing 12 Gb in 24 minutes, so arround 8 333 333 bytes per second. Is it possible to increase performances ? Answer: A major improvement would be to read/write more than one character at a time. System calls of any kind and especially I/O like it is the case here, always introduce a lot of overhead. And since your, from Cobol databases originating, files have the same number of characters per line, that's the amount to read/write in one go. Below is my implementation for this. I have also improved other aspects of the code:
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
assembly, x86 simplified the atoi character validation and conversion removed checking for negative numerical input which is not possible in this code added checking for an input exceeding 255 the code that processes a complete line got much simpler than what you had written for dealing with just a single character... section .data section .bss line_length: resd 1 input_buffer: resb 256 section .text global _start _start: _get_line_length: xor eax, eax mov ecx, [esp + 8] ; pointe à l'emplacement du premier paramètre _atoi: movzx esi, byte [ecx] test esi, esi jz _check_line_length sub esi, "0" cmp esi, 9 ja _exit_1 imul eax, 10 add eax, esi inc ecx jmp _atoi _check_line_length: ; Expected input [1,255] test eax, eax jz _exit_1 ; TODO message erreur cmp eax, 255 ja _exit_1 ; TODO message erreur inc eax ; Take mandatory linefeed into account mov [line_length], eax ; Valid [2,256] _read_stdin: mov eax, 3 mov ebx, 0 mov ecx, input_buffer mov edx, [line_length] int 80h ; -> EAX cmp eax, -1 ; if error, exit input je _exit_1 cmp eax, [line_length] jne _exit_0 _process_line: lea esi, [eax - 2] ; EAX=[2,256] -> ESI=[0,254] .next_char: cmp byte [input_buffer + esi], 13 je .replace_char cmp byte [input_buffer + esi], 10 jne .keep_char .replace_char: mov byte [input_buffer + esi], 32 .keep_char: dec esi jns .next_char ; Stops looping at ESI=-1 _stdout: mov eax, 4 mov ebx, 1 mov ecx, input_buffer mov edx, [line_length] int 80h jmp _read_stdin
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
assembly, x86 Going for something better The above proposed solution is not perfect! If it so happens that the (user-inputted) linelength is very small, then the revised program would still be doing a lot of I/O operations. Although it is true that loading the file whole would reduce the number of necessary I/O operations to just one read and one write, in practice we would use a big buffer capable of holding large chunks of the file. In the below code I apply this technique. A bytes_per_io_request is calculated such that every chunk of the file can provide the program with a whole number of lines. section .data section .bss BUFFERSIZE equ 1048576 ; Arbitrarily chosen size of 1MB line_length: resd 1 bytes_per_io_request: resd 1 input_buffer: resb BUFFERSIZE section .text global _start _start: _get_line_length: xor eax, eax mov ecx, [esp + 8] ; pointe à l'emplacement du premier paramètre _atoi: movzx esi, byte [ecx] test esi, esi jz _check_line_length sub esi, "0" cmp esi, 9 ja _exit_1 imul eax, 10 add eax, esi inc ecx jmp _atoi _check_line_length: ; Expected input [1,255] test eax, eax jz _exit_1 ; TODO message erreur cmp eax, 255 ja _exit_1 ; TODO message erreur inc eax ; Take mandatory linefeed into account mov [line_length], eax ; Valid [2,256] mov eax, BUFFERSIZE xor edx, edx div dword [line_length] imul eax, [line_length] mov [bytes_per_io_request], eax _read_stdin: mov edx, [bytes_per_io_request] mov ecx, input_buffer mov ebx, 0 mov eax, 3 int 80h ; -> EAX cmp eax, -1 ; if error, exit input je _exit_1
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
assembly, x86 _process_group_of_lines: mov edi, [line_length] ; CONST xor edx, edx ; EDX:EAX is NumberOfBytes that were actually read div edi ; -> EAX is NumberOfLines (This should divide evenly) test edx, edx jnz _exit_0 ; Error out on partial line ? Or just ignore it. test eax, eax jz _done ; No lines in curent I/O request, so at end-of-file mov ebx, input_buffer _process_line: lea esi, [edi - 2] ; EDI=[2,256] -> ESI=[0,254] .next_char: cmp byte [ebx + esi], 13 je .replace_char cmp byte [ebx + esi], 10 jne .keep_char .replace_char: mov byte [ebx + esi], 32 .keep_char: dec esi jns .next_char ; Stops looping at ESI=-1 add ebx, edi ; Move to next line dec eax jnz _process_line _stdout: lea edx, [ebx - input_buffer] mov ecx, input_buffer mov ebx, 1 mov eax, 4 int 80h jmp _read_stdin _done: ...
{ "domain": "codereview.stackexchange", "id": 44571, "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": "assembly, x86", "url": null }
vba, excel, ms-access, ms-word, powerpoint Title: Sub that calls itself when its parent Workbook is closed Question: and no, I'm not talking about Workbook_BeforeClose. Note that the motivation of this question is Excel specific but the technique I'd like feedback on is not. If you don't care about the motivation, you can skip to the chapter Option 3, the "magic" way. If additionally, you already know about the IUnknown::Release trick, you can skip to the chapter Implementation using IUnknown::Release I recently came across the following question on StackOverflow: How can i get the NOW function to update every second? Immediately, I thought about Application.OnTime and implemented a solution using this technique. I will not post the original code here as it is not what this question is about, but rather what motivated it. A simplified example of the code looks like this: Sub KeepRecalculating() Sheet1.Range("A1").Calculate Application.OnTime DateAdd("s", 1, Now()), "KeepRecalculating" End Sub In principle, this solution works well and there are quite a few other questions on StackOverflow with answers that adhere to the same idea. Unfortunately, there two subtle and quite annoying drawbacks to this technique that originate in some rather interesting features of Application.OnTime. Both of these issues have to do with how to cancel a task scheduled with Application.OnTime. Enabling the solution to stop the recursive updating. This is still quite straight forward. We need to save the planned next execution time and call Application.OnTime again with the additional parameter schedule:=False. The following code implements an additional parameter that enables the update loop to be stopped manually. Sub KeepRecalculating(Optional ByVal schedule As Boolean = True) Static nextExec As Double Sheet1.Range("A1").Calculate If schedule Then nextExec = DateAdd("s", 1, Now()) Application.OnTime nextExec, "KeepRecalculating", , schedule End Sub
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint My solution also took parameters like Range and updateRate and was able to run multiple tasks simultaneously independent of each other to make it more generally applicable. There is still the annoying fact that with this solution, pressing the Stop button in the VBA IDE does not stop the loop from running. A specific sub has to be called every time to stop it. The next issue, however, is even more annoying. What if the user just closes the workbook expecting it to also stop updating? Well in this case Application.OnTime has a trick up its sleeve that can be a very useful feature in other situations. Application.OnTime will reopen a closed Workbook if a macro was scheduled to run in it! There seem to be two options to deal with this: The user stops the loop manually before closing. This is very inconvenient and not really viable for most people. The user adds code to the Workbook_BeforeClose event. This is a more reasonable option and the one I recommended in my answer on StackOverflow. It comes with the disadvantage of adding code to the ThisWorkbook module which is unsatisfying regarding encapsulation. It would be nice to have everything in one place.
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint The best option seems to be 2), yet this still comes with some drawbacks. Firstly, the Stop button in the VBA IDE still can't interrupt the loop, and secondly, if the user for some reason had set Application.EnableEvents = False, the Workbook_BeforeClose event would never be called and the loop would have to be interrupted manually. While both of these are not huge issues, it would still be nice to overcome them. When I asked @CristianBuse about this, I got a hint that opened the door to some hacking, making all of this possible. Option 3, the "magic" way I'm talking about the IUnknown::Release trick. The code to produce all of this magical behavior looks like this: #If Mac Then Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr #Else Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) #End If Public Sub Release(ByVal instancePtr As LongPtr) MsgBox "Magic!" End Sub 'If the Sub Main gets executed, Release will be called once the object containing 'this code gets terminated or the VBA environment is reset (e.g. Stop button) Sub Main() Static o As IUnknown Static vtbl(0 To 2) As LongPtr, vtblPtr As LongPtr If vtblPtr = 0 Then vtbl(2) = VBA.Int(AddressOf Release) vtblPtr = VarPtr(vtbl(0)) CopyMemory ByVal VarPtr(o), VarPtr(vtblPtr), LenB(vtblPtr) End If End Sub This code works by creating a "fake" object of type IUnknown and hooking into its Release method. A static variable of type IUnknown is declared and a fake virtual method table is inserted. The virtual method table can point to three methods:
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint IUnknown::AddRef, called whenever the instances reference counter is incremented IUnknown::QueryInterface, called whenever information about the object's interface is required IUnknown::Release, called whenever the instances reference counter is decremented For the above-described problem, the Release method seems very, very interesting. Once Main was called, Release will be called, whenever the object o's reference count gets decremented. Because o is static and we don't create other instances, this happens in three cases: When the function containing it gets recompiled. (Excel will crash) When the Stop button in the VBA-IDE is pressed. When the Workbook is closed. The two latter cases are exactly what we need! The first one is not really a problem as long as the function isn't touched while o is active. Implementation of the original problem using IUnknown::Release The obvious (and probably best) way to implement this is as follows: #If Mac Then Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr #Else Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) #End If Public Sub Release(ByVal instancePtr As LongPtr) KeepRecalculating schedule:=False End Sub Sub SetIUnknown() Static isSet As Boolean: If isSet Then Exit Sub Static o As IUnknown Static vtbl(0 To 2) As LongPtr, vtblPtr As LongPtr If vtblPtr = 0 Then vtbl(2) = VBA.Int(AddressOf Release) vtblPtr = VarPtr(vtbl(0)) CopyMemory ByVal VarPtr(o), VarPtr(vtblPtr), LenB(vtblPtr) End If isSet = True End Sub
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint Sub KeepRecalculating(Optional ByVal schedule As Boolean = True) Static nextExec As Double SetIUnknown Sheet1.Range("A1").Calculate If schedule Then nextExec = DateAdd("s", 1, Now()) Application.OnTime nextExec, "KeepRecalculating", , schedule End Sub
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint This works beautifully. Clicking Stop in the IDE stops the loop, closing the Workbook stops the loop, even if Application.EnableEvents = False. This trick is not application specific, just a little bit hacky. In the above example, only Application.OnTime and Range.Calculate are Excel-specific. The trick could also be useful in other contexts in other applications. My first question is: Is this approach viable? It's a bit hacky, for example placing a breakpoint inside the Release method or anything called through it crashes the Application. This would be no problem in "production", are there other issues? I can't see any. Venturing further into the possibilities Bad habits led me to perform further experiments on the limits of this method. Because of the VBA-IDEs inability to organize larger amounts of modules, I sometimes seek to implement certain features in a single procedure. I like the portability of having one blob of code without dependencies, which I can just copy into a module and use. This way, the amount of modules in actual projects stays small, and navigating the code is easier. Knowing about the drawbacks of this habit, but fueled by a certain curiosity I wondered if it was possible to implement all of the above-described functionality in a single procedure. As it turned out, yes it is. I will not post the entire subroutine here, as it contains a lot of irrelevant fluff. For those interested, it can be found in this Gist. If you insist on critiquing it I won't object since this is CodeReview but please know that I'm well aware of its terrible style and utter unreadability in its current form. My goal was to create a magic blob of code, its usefulness was questionable from the beginning. The following Sub showcases the essence of the technique. #If Mac Then Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr #Else
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint #Else Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) #End If
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint Public Sub KeepRecalculating(Optional ByRef Range As Object = Nothing, _ Optional ByRef refreshTimeSeconds As Long = 1&, _ Optional ByRef schedule As Boolean = True, _ Optional ByRef stopAll As Boolean = False) Static o As IUnknown '<--- this MUST be the first static variable allocated! Static vtbl(0 To 2) As LongPtr, vtblPtr As LongPtr If vtblPtr = 0 Then vtbl(2) = VBA.Int(AddressOf KeepRecalculating) vtblPtr = VarPtr(vtbl(0)) CopyMemory ByVal VarPtr(o), VarPtr(vtblPtr), LenB(vtblPtr) End If Static nextExec As Double, isSet As Boolean #If Win64 Then 'Detect if sub was called as "Release": If VarPtr(o) = VarPtr(schedule) Then #Else If VarPtr(o) = VarPtr(stopAll) Then #End If If Not isSet Then Exit Sub Application.OnTime nextExec, "KeepRecalculating", , False Exit Sub 'Exit Sub if called as "Release" to prevent accessing of parameters End If 'The Subs parameters MUST NOT be accessed before this line! Sheet1.Range("A1").Calculate If schedule Then nextExec = DateAdd("s", 1, Now()) Application.OnTime nextExec, "KeepRecalculating", , schedule isSet = True End Sub
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint You may notice that this function has a bunch of parameters that go practically unused. In my original solution, I need all of these parameters and more, here they are just necessary to showcase the method. Safely implementing parameters for this function is actually the crux of this entire problem. IUnknown::Release only expects one ByVal argument, the instance pointer. We now want a function with completely different parameters to be called in place of Release. There are certain implications that come with this. During the automatic Release call, all of the parameters now defined point to the memory occupied by the ByVal instancePtr argument, or the memory next to it on the stack frame. Because the parameters now essentially point to memory having nothing to do with their type, accessing them in any way assuming their type will crash the Application. This of course includes copying them, the reason why the parameters must be ByRef. Of course, we'd like to use the arguments inside the Sub. In order to do this, the Sub must have a way of "knowing" it was called as the fake Release method and exit before accessing any of the arguments. This can be achieved by examining the memory passed to the optional parameters when called as Release. A way to do this is as follows: Debug.Print "Pointer of the object:" Debug.Print VarPtr(o) '<-- VarPtr of the Static object (instancePtr!) Debug.Print "Memory passed into parameters:" Debug.Print VarPtr(Range) '<-- First parameter Debug.Print VarPtr(refreshTimeSeconds) Debug.Print VarPtr(schedule) '<-- instancePtr on x64 Debug.Print VarPtr(stopAll) '<-- instancePtr on x86 Debug.Print VarPtr(param5) Debug.Print VarPtr(param6) Debug.Print VarPtr(param7) Debug.Print VarPtr(param8)
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint Note that accessing the variables like this does not assume their type, doesn't lead to a QueryInterface call, and hence doesn't crash the application. Running this test will reveal, that the actual memory containing instancePtr seems to align with the third parameter schedule in 64-bit and the fourth parameter stopAll in 32-bit applications. The memory before that (parameter 1 and 2) seems to be something related to the implementation of the ByVal argument, and the memory after seems to be Null followed by random stuff. Interestingly, the equality of e.g. VarPtr(schedule) = VarPtr(o) on x64, does only hold if o is the first Static variable declared in the Sub. Declaring other Static variables before will create an offset between VarPtr(o) and VarPtr(schedule) equal to the number of bytes declared before o. If o is not declared Static but just regular with Dim, there seems to be a base offset of 8 between the two values VarPtr(schedule) and VarPtr(o), and in this case, every regularly Dim'd variable before o seems to create an offset in the other direction than in the Static case. My testing seems to suggest, however, that as long as o is Static and declared as the first variable, there is no offset and the equality does hold. This can be used to recognize that the Sub was called as the Release method and therefore we can exit the Sub before actually accessing any of the parameters. Because I have little understanding of the underlying workings of VBA, I'm interested in how all of these observed behaviors can be explained. I'd like to know if using this admittedly quite hacky technique bears too many risks or if, henceforth, I can assume it is reliable enough to actually be used. Are there any risks of having the ByRef parameters point to random memory as long as it can be assured that they will not be touched while doing so? Does the condition I'm using to detect the Release call hold reliably or was I just "lucky"?
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
vba, excel, ms-access, ms-word, powerpoint Answer: Unfortunately, the Release magic trick is dangerous because it can mess with the underlying EbMode function used by VB to determine if code is running or not. To replicate, run Main as presented in the question under the Option 3, the "magic" way section. Here is the same code for convenience: Option Explicit #If Mac Then Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr #Else Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) #End If Public Sub Release(ByVal instancePtr As LongPtr) MsgBox "Magic!" End Sub Sub Main() Static o As IUnknown Static vtbl(0 To 2) As LongPtr, vtblPtr As LongPtr If vtblPtr = 0 Then vtbl(2) = VBA.Int(AddressOf Release) vtblPtr = VarPtr(vtbl(0)) CopyMemory ByVal VarPtr(o), VarPtr(vtblPtr), LenB(vtblPtr) End If End Sub After running Main run any method and reset state while code is still running. Here are 2 ways: Run this: Sub Boom() End End Sub Or: Run this: Sub Boom2() Stop End Sub and when the code breaks on the Stop line, press the Reset button in the IDE: Although, state was lost, the Locals window will show "Running": and now VBA has gone 'crazy' as there is no way to step through code anymore or run other macros until the whole Application is restarted. In short, using this trick directly or via the Sub that calls itself is: safe, if state is lost while no code is running unsafe, if state is lost while code is running and Application needs restarting Alternatively, I've created the StateLossCallback class that is: safe, if state is lost while no code is running safe, but does nothing (callback not called), if state is lost while code is running
{ "domain": "codereview.stackexchange", "id": 44572, "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": "vba, excel, ms-access, ms-word, powerpoint", "url": null }
c# Title: Engine that performs certain amount of ticks per second Question: This class will fires a certain amount of ticks per second. I would greatly appreciate any suggentions, I'm more then welcome for any feedback since I haven't coded for long in C#. It is intentional that if there is a heavy load on the ticks that the ticks per second don't match the desired input. It is more of a maximum were it should aim to run at, but because of that this class needs to be as performant as possible and with this we come to my first problem with this code: I'm not really happy with the Thread.Sleep in the Pulse Method, which is my main concern, but could'nt figure out a better way. I needed it to reduce stress on the CPU on lower TPS.. Also the thing that this is using Time ticks to calculate the ticks for the engine makes it a little bit annouing to read but don't really know what to name it since both are ticks.. TickEngine.cs using System; using System.Threading.Tasks; using System.Threading; using System.Runtime.Serialization; namespace TickEngine { class TickEngine { public event EventHandler<TickEventArgs> OnStart = null!; public event EventHandler<TickEventArgs> OnPreTick = null!; public event EventHandler<TickEventArgs> OnTick = null!; public event EventHandler<TickEventArgs> OnPostTick = null!; public event EventHandler<TickEventArgs> OnStop = null!; private readonly int _resolution; private long _maxTick; private TimeSpan _delay; private ulong _tickCnt = 0; private float _deltaTickSum = 0; private bool _isEnabled = false; private long _timestamp = 0; private uint _tps; /// <summary> /// Is the Engine running /// </summary> public bool IsEnabled { get { return _isEnabled; } }
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# /// <summary> /// Total ticks that have been processed since engine was started /// </summary> public ulong Tick { get { return _tickCnt; } } /// <summary> /// Ticks per Second /// </summary> public uint TPS { get { return _tps; } set { _tps = value; _maxTick = TimeSpan.TicksPerSecond / _tps; _delay = new TimeSpan(TimeSpan.TicksPerSecond / _tps / _resolution); } } /// <summary> /// Initialzise the Tick engine /// </summary> /// <param name="tps">How many Ticks per Second should the Engine process</param> /// <param name="resolution">How many Checks per Tickinterval, higher number more CPU usage, but higher accuracy</param> public TickEngine(uint tps, int resolution = 3) { _resolution = resolution; TPS = tps; } /// <summary> /// Start the tick engine, need to handle own pulse loop /// </summary> /// <exception cref="TickEngineException">If engine is already running</exception> public void Start() { if (_isEnabled) throw new TickEngineException("Tick engine is already running"); _tickCnt = 0; _deltaTickSum = 0; _timestamp = DateTime.Now.Ticks; _isEnabled = true; OnStart?.Invoke(this, new TickEventArgs { tick = _tickCnt }); }
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# /// <summary> /// Start the tick engine with async pulse loop /// </summary> /// <exception cref="TickEngineException">If engine is already running</exception> public void StartWithPulse() { if (_isEnabled) throw new TickEngineException("Tick engine is already running"); Start(); Task.Run(() => { while (_isEnabled) { Pulse(); } }); } /// <summary> /// Perform a pulse on the engine if enough time has passed a tick will be fired /// </summary> public void Pulse() { Update(); Thread.Sleep(_delay); } /// <summary> /// Stop tick engine /// </summary> /// <exception cref="TickEngineException">Tick engine is Not running</exception> public void Stop() { if (!_isEnabled) throw new TickEngineException("Tick engine is NOT running"); _isEnabled = false; OnStop?.Invoke(this, new TickEventArgs { tick = _tickCnt }); } /// <summary> /// Update the timing and check if a tick(engine) will be fired. /// </summary> private void Update() { _deltaTickSum += DeltaTick(); if (_deltaTickSum >= _maxTick) { _deltaTickSum -= _maxTick; _tickCnt++; TickEventArgs args = new TickEventArgs { tick = _tickCnt }; OnPreTick?.Invoke(this, args); OnTick?.Invoke(this, args); OnPostTick?.Invoke(this, args); } }
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# /// <summary> /// Calculate ticks(time) that have passed /// </summary> /// <returns>Returns the ticks(time) that have passed since last call</returns> private long DeltaTick() { long a = DateTime.Now.Ticks; long delta = a - _timestamp; _timestamp = a; return delta; } public class TickEventArgs : EventArgs { public ulong tick; } [Serializable] public class TickEngineException : Exception { public TickEngineException() : base() { } public TickEngineException(string message) : base(message) { } protected TickEngineException(SerializationInfo info, StreamingContext ctxt) : base(info, ctxt) { } } } } Example Program.cs using System; using System.Diagnostics; namespace TickEngineExample // Note: actual namespace depends on the project name. { internal class Program { static Stopwatch asyncStopwatch = new Stopwatch(); static Stopwatch syncStopwatch = new Stopwatch(); static readonly uint tps = 50; static readonly uint endTick = tps * 10; static void Main(string[] args) { AsyncExample(); SyncExample(); Console.ReadLine(); } static void SyncExample() { //Creates a Tick Engine that fires 50 ticks per Second TickEngine.TickEngine engine = new TickEngine.TickEngine(tps);
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# //Set Event engine.OnStart += (sender, e) => { Console.WriteLine("[Sync] Started"); syncStopwatch.Start(); }; engine.OnTick += (sender, e) => { Console.WriteLine("[Sync] Tick: " + e.tick); }; engine.OnPostTick += (sender, e) => { if (e.tick == endTick) engine.Stop(); }; engine.OnStop += (sender, e) => { syncStopwatch.Stop(); Console.WriteLine("[Sync] Stopped after " + syncStopwatch.Elapsed.TotalSeconds + " Seconds"); }; engine.Start(); while (engine.IsEnabled) { engine.Pulse(); } } static void AsyncExample() { asyncStopwatch.Start(); //Creates a Tick Engine that fires 50 ticks per Second TickEngine.TickEngine engine = new TickEngine.TickEngine(tps); engine.OnStart += (sender, e) => { Console.WriteLine("[Async] Started"); asyncStopwatch.Start(); }; engine.OnTick += (sender, e) => { Console.WriteLine("[Async] Tick: " + e.tick); }; engine.OnPostTick += (sender, e) => { if (e.tick == endTick) engine.Stop(); }; engine.OnStop += (sender, e) => { asyncStopwatch.Stop(); Console.WriteLine("[Async] Stopped after " + asyncStopwatch.Elapsed.TotalSeconds + " Seconds"); }; engine.StartWithPulse(); } } } ``` Answer: static readonly uint tps = 50;
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# Answer: static readonly uint tps = 50; Beautiful! No magic number trouble here. From the context I had it seemed clear enough, but consider throwing in a // ticks per second comment. //Creates a Tick Engine that fires 50 ticks per Second Please delete this comment (and similarly in AsyncExample). We use code to explain the "what", and comments to explain the "why". My biggest objection to this line is that it requires next year's maintenance engineer to find / update a comment after updating the tps constant. There's an interesting amount of copy-n-paste duplication between the sync and async examples, and in this case I feel it is OK. They are nearly unit tests, where we embrace copy-n-paste. And they have clear instructional value for someone who has a sync use case, or an async one, and wishes to get started. If the two were in different source files, then it would be more convenient for the curious to quickly diff them. public event EventHandler<TickEventArgs> OnStart = null!; This is accurate. And consistent. But maybe "arg" is a bit vague? Maybe each of these is a TickEventHandler ? I really like the naming of the local variables, that's lovely. You already touched on how _tps is perhaps a bit awkward. static readonly uint endTick = tps * 10; _maxTick = TimeSpan.TicksPerSecond / _tps; These kind of feel like they're doing the same thing, at the app level and library level. Except that they're not? Sorry, I find this code unclear. It seems like the units are clear, with the app level endTick shooting for ten seconds elapsed time. For the dimensional analysis of _maxTick to work out to "dimensionless" leaves me puzzled. /// <param name="resolution">How many Checks per Tickinterval, higher number more CPU usage, but higher accuracy</param>
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# I don't understand what "Tickinterval" means in this context. The documentation seems to suggest that multiple check calls could happen per tick, which surprises me. I was thinking we might check every K ticks or so. I'm fine with saying the code is "right". I'm just saying that the documentation left me with some puzzles to work out. /// Perform a pulse on the engine if enough time has passed a tick will be fired Oohhhh! There's a concept that this is now explaining to me. Apparently there shall be K low-level pulses in between each tick. Hmm, what a curious approach. I am accustomed to consulting the clock to see time_till_next_tick and sleeping that long. But ok, I can see that this works. I am reading Update. It's pretty clear to me that I do not yet understand the concept that _maxTick embodies -- I do not find this is clear code that others could readily maintain. It definitely isn't dimensionless; it has units of "number of ticks". I don't get the error analysis at all. Presumably there is some quantization trouble we're worried about, which we want to smooth out in the long run. Yet we're quantizing from microseconds (nanoseconds?) down to ticks, and keeping running sum of those. That doesn't make sense. The usual approach would be to define a _nextScheduledTick in terms of wall clock time, and then frequent pulse() will eventually notice the clock is slightly after that scheduled time, triggering a tick and updating the schedule. Up in Start I think this is the part I didn't initially notice: _timestamp = DateTime.Now.Ticks; That is, it claims to have units of ~ seconds since 1970, yet clearly it has units of ticks (20 msec in this commit). EDIT: no, apparently it's a unit of 100 nanoseconds. Ok, now I understand why this code was so confusing.
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# I am reading the vendor documentation, and it turns out they have already given "tick" a well-known meaning of "100-nanosecond interval". I suppose one might use an identifier of tenth_usec for that. There are three sections to any engine-based app you deploy: util (currently empty) library app Within each section, the four characters "tick" should have a single, unambiguous meaning, or should be accompanied by a comment explaining its alternate meaning. You have some decisions to make. In my opinion the library and app sections should see only the kind of tick that you're describing here. And it should be in terms of a scheduling promise, rather than measuring an elapsed time since an epoch. The (to be defined) utility layer should consume the vendor's Tick abstraction and convert it to SI units of seconds. Or microseconds or nanoseconds, something related to the natural world, and definitely not derived from computer clocks, timers, and their resolutions. The loss of clarity in communicating your technical ideas just isn't worth it. if (e.tick == endTick) engine.Stop(); It's not obvious to me that real applications have a use case for terminating after N ticks have triggered. I recommend that you not expose such a running count via the API. If an application cares, it can certainly maintain its own counter. For this example I would rather see a termination criterion of "now > start + 10 seconds". Other apps might terminate when a demo vehicle crosses some finish line, or more likely according to a UI button being clicked. Why not expose it? Because there's the temptation to equate current tick number with some number of seconds past an epoch. But that's not what it means, since it's valid to trigger fewer than tps ticks in a second if the system happens to be busy then. Stick to "scheduling" for your tick abstraction, and leave "time keeping" to well established interfaces that already offer such services.
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
c# FP timestamps get a bad rep because FP was slow on ancient machines, plus repeatedly doing stamp += .001 and then asking e.g. whether stamp == 1 won't work. Consider adopting FP timestamps in your codebase. Why? Clarity. Plus you only really care about the comparison operator, now > scheduled, which will do just what you want. Fifty-three bits of mantissa is a lot, giving you considerable latitude to choose some sensible combination of resolution and starting epoch. For example this standard library offers high-resolution "seconds since 1970" as a FP result. Design consideration: The examples do not sleep(), and it seems like they ought to, right? I mean, someone has to have the main event loop, and here it doesn't look like the library will, it looks like the higher level app will have it. Then the app can pulse() quite often, and the library will tick() when appropriate and will never sleep. The example while (engine.IsEnabled) { engine.Pulse(); } loop just doesn't make sense to me -- it doesn't call sleep. But even if it did, I would still want to see example code that sets up interrupt-based pulses to support a while (1) { sleep(1); } application. That is, if the app is continuously busy, it should still be easy for the library to produce pulses and hence ticks in the background. And yes, I get it that not all apps will want that, sometimes an app would rather not be interrupted, cool. This code appears to run without crashing. I would not be willing to delegate or accept maintenance tasks on this codebase in its current form. It appears that small changes to it would dramatically improve its clarity.
{ "domain": "codereview.stackexchange", "id": 44573, "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#", "url": null }
python, game, console, chess Title: Fully-functioning chess game in Python Question: This post is in succession to this question. I have implemented all functionalities like castling, en-passant, pawn promotion etc. 50 move rule and 3-move repetition is pending. I would like my code to be reviewed before going to the AI (simple) part of the project. I would appreciate any improvements and also bugs found. Run the console_ui.py file to play chess! White is at the bottom and black is at the top. Uppercase characters represent white pieces and lowercase represent black. utility.py from enum import Enum # Piece and board related stuff START_MATRIX = [ ["R", "N", "B", "Q", "K", "B", "N", "R"], ["P"] * 8, ["."] * 8, ["."] * 8, ["."] * 8, ["."] * 8, ["p"] * 8, ["r", "n", "b", "q", "k", "b", "n", "r"] ] class Color(Enum): NONE = 0 WHITE = 1 BLACK = 2 def get_color(piece: str) -> bool: if piece == ".": return Color.NONE elif piece.isupper(): return Color.WHITE return Color.BLACK def get_opposite_color(color: Color) -> Color: if color == Color.WHITE: return Color.BLACK elif color == Color.BLACK: return Color.WHITE return color.NONE def is_white(piece: str) -> bool: return get_color(piece) == Color.WHITE def is_black(piece: str) -> bool: return get_color(piece) == Color.BLACK def is_empty(piece: str) -> bool: return piece == "." def is_king(piece: str) -> bool: return piece.lower() == "k" def is_queen(piece: str) -> bool: return piece.lower() == "q" def is_rook(piece: str) -> bool: return piece.lower() == "r" def is_bishop(piece: str) -> bool: return piece.lower() == "b" def is_knight(piece: str) -> bool: return piece.lower() == "n" def is_pawn(piece: str) -> bool: return piece.lower() == "p" # Piece movement related stuff def is_in_bounds(*nums: int): return all([0 <= num <= 7 for num in nums])
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def is_in_bounds(*nums: int): return all([0 <= num <= 7 for num in nums]) class MoveType(Enum): NORMAL = 0 SHORT_CASTLE = 1 LONG_CASTLE = 2 PAWN_PROMOTION = 3 FILE_TO_INDEX_MAP = { "a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7 } INDEX_TO_FILE_MAP = {v: k for k, v in FILE_TO_INDEX_MAP.items()} def encode_move(move: dict) -> str: # Normal move: e2e4 if move["type"] == MoveType.NORMAL: start_y, start_x = move["start_pos"] end_y, end_x = move["end_pos"] return ( INDEX_TO_FILE_MAP[start_x] + str(start_y + 1) + INDEX_TO_FILE_MAP[end_x] + str(end_y + 1) ) elif move["type"] == MoveType.PAWN_PROMOTION: start_y, start_x = move["start_pos"] end_y, end_x = move["end_pos"] return ( INDEX_TO_FILE_MAP[start_x] + str(start_y + 1) + INDEX_TO_FILE_MAP[end_x] + str(end_y + 1) + "=" + move["promoted_piece"] ) # Short castle: 0-0 elif move["type"] == MoveType.SHORT_CASTLE: return "0-0" # Long castle: 0-0-0 elif move["type"] == MoveType.LONG_CASTLE: return "0-0-0" # Pawn promotion: ToDo
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def decode_move(move: str) -> dict: # Normal move: e2e4 if len(move) == 4: return { "type": MoveType.NORMAL, "start_pos": [int(move[1]) - 1, FILE_TO_INDEX_MAP[move[0]]], "end_pos": [int(move[3]) - 1, FILE_TO_INDEX_MAP[move[2]]], } # Pawn Promotion: e7e8=q elif len(move) == 6: return { "type": MoveType.PAWN_PROMOTION, "start_pos": [int(move[1]) - 1, FILE_TO_INDEX_MAP[move[0]]], "end_pos": [int(move[3]) - 1, FILE_TO_INDEX_MAP[move[2]]], "promoted_piece": move[5] } # Short castle: 0-0 elif move == "0-0": return { "type": MoveType.SHORT_CASTLE } # Long castle: 0-0-0 elif move == "0-0-0": return { "type": MoveType.LONG_CASTLE } # Pawn promotion: ToDo KNIGHT_DELTAS = [ # delta_y, delta_x [2, 1], [1, 2], [-2, 1], [-1, 2], [1, -2], [2, -1], [-1, -2], [-2, -1] ] BISHOP_DELTAS = [ # delta_y, delta_x [1, 1], [-1, -1], [-1, 1], [1, -1] ] ROOK_DELTAS = [ # delta_y, delta_x [1, 0], [0, 1], [-1, 0], [0, -1] ] QUEEN_DELTAS = BISHOP_DELTAS + ROOK_DELTAS KING_DELTAS = [ # delta_y, delta_x [1, 0], [0, 1], [-1, 0], [0, -1], [1, 1], [-1, -1], [-1, 1], [1, -1] ] board.py from utility import * from copy import deepcopy class GameState(Enum): RUNNING = 0 CHECKMATE = 1 STALEMATE = 2
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess class GameState(Enum): RUNNING = 0 CHECKMATE = 1 STALEMATE = 2 class Board: def __init__(self, matrix=None, current_turn_color=Color.WHITE) -> None: self.matrix = matrix if not matrix: self.matrix = START_MATRIX self.current_turn_color = current_turn_color self.game_state = GameState.RUNNING self.moves_history = [] self.en_passant_squares = { Color.WHITE: [], Color.BLACK: [] } self.can_castle = { Color.WHITE: { MoveType.SHORT_CASTLE: True, MoveType.LONG_CASTLE: True }, Color.BLACK: { MoveType.SHORT_CASTLE: True, MoveType.LONG_CASTLE: True } } self.legal_moves = self.generate_legal_moves() def play_move(self, str_move: str) -> None: if str_move in self.legal_moves: move_data = decode_move(str_move) print("Printing en-passant squares: ", self.en_passant_squares) self.implement_move(move_data) self.en_passant_squares[self.current_turn_color] = [] self.current_turn_color = get_opposite_color(self.current_turn_color) self.legal_moves = self.generate_legal_moves() self.moves_history.append(str_move) self.update_game_state() else: print(f"{str_move} not legal!! Error!!") return def update_game_state(self): if len(self.legal_moves) == 0: if self.is_check(): self.game_state = GameState.CHECKMATE else: self.game_state = GameState.STALEMATE else: self.game_state = GameState.RUNNING
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def implement_move(self, move: dict) -> None: if move["type"] == MoveType.NORMAL: start_y, start_x = move["start_pos"] end_y, end_x = move["end_pos"] piece = self.matrix[start_y][start_x] self.matrix[end_y][end_x] = piece self.matrix[start_y][start_x] = "." # Prevent castle if is_rook(piece): if start_x == 7: # h1/h8 rook self.can_castle[self.current_turn_color][MoveType.SHORT_CASTLE] = False elif start_x == 0: # a1/a8 rook self.can_castle[self.current_turn_color][MoveType.LONG_CASTLE] = False # En passant elif is_pawn(piece): # If en-passant happens if [end_y, end_x] in self.en_passant_squares[self.current_turn_color]: self.matrix[start_y][end_x] = "." # If black pawn moves 2 steps ahead if start_y - end_y == 2: self.en_passant_squares[Color.WHITE].append([start_y - 1, start_x]) # If white pawn moves 2 steps ahead elif start_y - end_y == -2: self.en_passant_squares[Color.BLACK].append([start_y + 1, start_x]) elif move["type"] == MoveType.PAWN_PROMOTION: start_y, start_x = move["start_pos"] end_y, end_x = move["end_pos"] promoted_piece = move["promoted_piece"] if self.current_turn_color == Color.WHITE: promoted_piece = promoted_piece.upper() self.matrix[end_y][end_x] = promoted_piece self.matrix[start_y][start_x] = "." elif move["type"] == MoveType.SHORT_CASTLE: pos_y = 0 if self.current_turn_color == Color.WHITE else 7 # Move h1/h8 rook to f1/f8 self.matrix[pos_y][5] = self.matrix[pos_y][7] self.matrix[pos_y][7] = "." # Move e1/e8 king to g1/g8
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess self.matrix[pos_y][7] = "." # Move e1/e8 king to g1/g8 self.matrix[pos_y][6] = self.matrix[pos_y][4] self.matrix[pos_y][4] = "." self.can_castle[self.current_turn_color][MoveType.SHORT_CASTLE] = False self.can_castle[self.current_turn_color][MoveType.LONG_CASTLE] = False elif move["type"] == MoveType.LONG_CASTLE: pos_y = 0 if self.current_turn_color == Color.WHITE else 7 # Move a1/a8 rook to d1/d8 self.matrix[pos_y][3] = self.matrix[pos_y][0] self.matrix[pos_y][0] = "." # Move e1/e8 king to c1/c8 self.matrix[pos_y][2] = self.matrix[pos_y][4] self.matrix[pos_y][4] = "." self.can_castle[self.current_turn_color][MoveType.SHORT_CASTLE] = False self.can_castle[self.current_turn_color][MoveType.LONG_CASTLE] = False
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def get_all_pieces_pos(self, color: Color) -> list: pieces_pos = [] for y, rank in enumerate(self.matrix): for x, piece in enumerate(rank): if type(piece) == int: print(rank, x, piece) if get_color(piece) == color: pieces_pos.append([y, x]) return pieces_pos
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def generate_primitive_moves(self) -> list[str]: "Generates all move without validating any checks" primitive_moves = [] # Normal moves pieces_pos = self.get_all_pieces_pos(self.current_turn_color) opposite_color = get_opposite_color(self.current_turn_color) # print("pieces_pos:", pieces_pos) for pos_y, pos_x in pieces_pos: piece = self.matrix[pos_y][pos_x] # print(f"pos_y: {pos_y}, pos_x: {pos_x}, piece: {piece}") if is_pawn(piece): delta_y = 1 if self.current_turn_color == Color.WHITE else -1 # Forward 1 square if is_in_bounds(pos_y + delta_y) and is_empty(self.matrix[pos_y + delta_y][pos_x]): if (pos_y + delta_y) in [0, 7]: for promoted_piece in ["q", "r", "n", "b"]: primitive_moves.append(encode_move({ "type": MoveType.PAWN_PROMOTION, "start_pos": [pos_y, pos_x], "end_pos": [pos_y + delta_y, pos_x], "promoted_piece": promoted_piece })) else: primitive_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [pos_y + delta_y, pos_x] })) # Forward 2 square if is_in_bounds(pos_y + 2*delta_y) and is_empty(self.matrix[pos_y + 2*delta_y][pos_x]): if ( (self.current_turn_color == Color.WHITE and pos_y == 1) or (self.current_turn_color == Color.BLACK and pos_y == 6) ): primitive_moves.append(encode_move({
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess ): primitive_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [pos_y + 2*delta_y, pos_x] })) # Diagonal 1 square left/right for delta_x in [1, -1]: if ( is_in_bounds(pos_y + delta_y, pos_x + delta_x) and ( get_color(self.matrix[pos_y + delta_y][pos_x + delta_x]) == opposite_color or [pos_y + delta_y, pos_x + delta_x] in self.en_passant_squares[self.current_turn_color] ) ): if (pos_y + delta_y) in [0, 7]: for promoted_piece in ["q", "r", "n", "b"]: primitive_moves.append(encode_move({ "type": MoveType.PAWN_PROMOTION, "start_pos": [pos_y, pos_x], "end_pos": [pos_y + delta_y, pos_x + delta_x], "promoted_piece": promoted_piece })) else: primitive_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [pos_y + delta_y, pos_x + delta_x] })) elif is_knight(piece): primitive_moves += self.generate_knight_legal_moves(pos_y, pos_x) elif is_bishop(piece): primitive_moves += self.generate_bishop_legal_moves(pos_y, pos_x) elif is_rook(piece): primitive_moves += self.generate_rook_legal_moves(pos_y, pos_x)
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess primitive_moves += self.generate_rook_legal_moves(pos_y, pos_x) elif is_queen(piece): primitive_moves += self.generate_queen_legal_moves(pos_y, pos_x) elif is_king(piece): primitive_moves += self.generate_king_legal_moves(pos_y, pos_x) pos_y = 0 if self.current_turn_color == Color.WHITE else 7 if ( self.can_castle[self.current_turn_color][MoveType.SHORT_CASTLE] and is_empty(self.matrix[pos_y][5]) and is_empty(self.matrix[pos_y][6]) ): primitive_moves.append("0-0") if ( self.can_castle[self.current_turn_color][MoveType.LONG_CASTLE] and is_empty(self.matrix[pos_y][1]) and is_empty(self.matrix[pos_y][2]) and is_empty(self.matrix[pos_y][3]) ): primitive_moves.append("0-0-0") return primitive_moves
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def generate_legal_moves(self) -> list[str]: legal_moves = [] for move in self.generate_primitive_moves(): copy_board = deepcopy(self) copy_board.implement_move(decode_move(move)) if not copy_board.is_check(): if move == "0-0": start_y = 0 if self.current_turn_color == Color.WHITE else 7 if not copy_board.is_attacked(start_y, 5, get_opposite_color(self.current_turn_color)): legal_moves.append(move) elif move == "0-0-0": start_y = 0 if self.current_turn_color == Color.WHITE else 7 if not copy_board.is_attacked(start_y, 3, get_opposite_color(self.current_turn_color)): legal_moves.append(move) else: legal_moves.append(move) return legal_moves def is_attacked(self, pos_y: int, pos_x: int, color: Color) -> list: original_turn_color = self.current_turn_color self.current_turn_color = color for move in self.generate_primitive_moves(): move_data = decode_move(move) if move_data["type"] == MoveType.NORMAL: start_y, start_x = move_data["start_pos"] if move_data["end_pos"] == [pos_y, pos_x]: if is_pawn(self.matrix[start_y][start_x]): if abs(start_x - pos_x) == 1: self.current_turn_color = original_turn_color return True else: self.current_turn_color = original_turn_color return True self.current_turn_color = original_turn_color return False
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def find_king(self, color: Color) -> list[int, int]: for y, rank in enumerate(self.matrix): for x, piece in enumerate(rank): if is_king(piece) and get_color(piece) == color: return [y, x] return False def is_check(self): king_pos = self.find_king(self.current_turn_color) return self.is_attacked(*king_pos, get_opposite_color(self.current_turn_color)) def generate_knight_legal_moves(self, pos_y: int, pos_x: int) -> list[str]: legal_moves = [] for delta_y, delta_x in KNIGHT_DELTAS: end_y = pos_y + delta_y end_x = pos_x + delta_x if ( is_in_bounds(end_y, end_x) and get_color(self.matrix[end_y][end_x]) != self.current_turn_color ): legal_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [end_y, end_x] })) return legal_moves def generate_bishop_legal_moves(self, pos_y: int, pos_x: int) -> list[str]: legal_moves = [] for delta_y, delta_x in BISHOP_DELTAS: for i in range(1, 9): end_y = pos_y + i*delta_y end_x = pos_x + i*delta_x if ( not is_in_bounds(end_y, end_x) or get_color(self.matrix[end_y][end_x]) == self.current_turn_color ): break legal_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [end_y, end_x] })) if not is_empty(self.matrix[end_y][end_x]): break return legal_moves
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def generate_rook_legal_moves(self, pos_y: int, pos_x: int) -> list[str]: legal_moves = [] for delta_y, delta_x in ROOK_DELTAS: for i in range(1, 9): end_y = pos_y + i*delta_y end_x = pos_x + i*delta_x if ( not is_in_bounds(end_y, end_x) or get_color(self.matrix[end_y][end_x]) == self.current_turn_color ): break legal_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [end_y, end_x] })) if not is_empty(self.matrix[end_y][end_x]): break return legal_moves def generate_queen_legal_moves(self, pos_y: int, pos_x: int) -> list[str]: return ( self.generate_bishop_legal_moves(pos_y, pos_x) + self.generate_rook_legal_moves(pos_y, pos_x) ) def generate_king_legal_moves(self, pos_y: int, pos_x: int) -> list[str]: legal_moves = [] for delta_y, delta_x in KING_DELTAS: end_y = pos_y + delta_y end_x = pos_x + delta_x if ( is_in_bounds(end_y, end_x) and get_color(self.matrix[end_y][end_x]) != self.current_turn_color ): legal_moves.append(encode_move({ "type": MoveType.NORMAL, "start_pos": [pos_y, pos_x], "end_pos": [end_y, end_x] })) return legal_moves def __repr__(self) -> str: output = "" for row in reversed(self.matrix): output += " ".join(row) + "\n" return output[:-1] console_ui.py from board import * game = Board()
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess console_ui.py from board import * game = Board() def print_chess_board(): new_array = [] reversed_matrix = list(reversed(game.matrix)) for i in range(8): new_array.append([str(i + 1), *reversed_matrix[i]]) new_array.append([" ", "a", "b", "c", "d", "e", "f", "g", "h"]) print("\n".join([" ".join(rank) for rank in new_array])) while True: print_chess_board() if game.game_state == GameState.CHECKMATE: print("Checkmate!!") print(f"{turn} wins the game!!") break elif game.game_state == GameState.STALEMATE: print("Stalemate!! The game is a draw!") break turn = "White" if game.current_turn_color == Color.WHITE else "Black" move = input(f"{turn}!! Enter your move: ").lower().strip() game.play_move(move) Edit 1: There is small mistake in the interface, the numbering from 1 to 8 is written in inverse order.
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess Answer: Don't build everything on top of primitives. Your current code is carefully done and not difficult to follow. Its primary drawback is that nearly all of the logic operates on primitive data types: pieces are letters; moves are stored as strings (chess notation) that must be repeatedly decoded into a dict; the board is a two-dimensional matrix; the castling data is a two-level dict; nearly all methods stick their fingers directly into one of both of those data structures. To advance this program to the next level of coding proficiency, you need to stop performing all of the logic with primitive information types like this. Be generous in creating the data-objects your program needs. Other reviewers have already suggested a couple of data objects, such as Pos and Move. I'm encouraging you to take that approach farther, both in terms of additional data objects (such as Piece) and in terms of moving more of your coding logic, helper utilities, and coding conveniences into those classes. These data objects often serve as an interface between primitive types of information (for example the string e7e5) and higher-level information like a Move instance. The rest of your program will work with the higher-level stuff, not the primitives. Start with some constants and enumerations. from enum import Enum from dataclasses import dataclass FILE_TO_INDEX = dict((f, i) for i, f in enumerate('abcdefgh')) class MoveType(Enum): NORMAL = 0 SHORT_CASTLE = 1 LONG_CASTLE = 2 PAWN_PROMOTION = 3 class Color(Enum): NONE = 0 WHITE = 1 BLACK = 2 class PieceType(Enum): KING = 0 QUEEN = 1 ROOK = 2 BISHOP = 3 KNIGHT = 4 PAWN = 5 Define a Piece data object. It might seem strange to have a class with a single letter as its only attribute, but notice what you can do once you introduce the concept of a Piece. Based on its symbol, it can compute its Color and PieceType. @dataclass(frozen = True) class Piece: sym: str
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess TYPES = dict( k = PieceType.KING, q = PieceType.QUEEN, r = PieceType.ROOK, b = PieceType.BISHOP, n = PieceType.KNIGHT, p = PieceType.PAWN, ) @property def color(self): return Color.WHITE if self.sym.isupper() else Color.BLACK @property def type(self): return self.TYPES[self.sym.lower()] Define a Move data object. A move has start and end positions, a type, and sometimes a promoted piece. We can use a class method to support the decoding of a primitive (chess notation) into a proper Move instance. @dataclass(frozen = True) class Pos: x: int y: int @dataclass(frozen = True) class Move: start: Pos = None end: Pos = None type: MoveType = MoveType.NORMAL promoted: Piece = None @classmethod def from_notation(cls, notation): # Handle castling. if notation == '0-0': return cls(type = MoveType.SHORT_CASTLE) elif notation == '0-0-0': return cls(type = MoveType.LONG_CASTLE) # Unpack notation: start file/row, end file/row, promoted piece. sf, sr, ef, er, _, pp = tuple((notation + ' ')[0:6]) promoted = pp.strip() or None mtype = MoveType.PAWN_PROMOTION if promoted else MoveType.NORMAL # Assemble Move and return. return cls( start = Pos(FILE_TO_INDEX[sf], int(sr) - 1), end = Pos(FILE_TO_INDEX[ef], int(er) - 1), type = mtype, promoted = promoted, )
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess Using convenience variables to aid readability. Notice the use of convenience variables when unpacking the chess notation. Due to their shortness, the variables could be cryptic in many situations. But in this case, the method is simple enough and the comments provide enough context to keep everything easy to read -- indeed the compactness of the variables aids that readability. Those variable names also help to reinforce a naming convention that I extended further in the class (properties to easily access position parameters). And while working on another part of the program, I found that I wanted Move instances to have other conveniences and helpers. @dataclass(frozen = True) class Move: ... @property def sx(self): return self.start.x @property def sy(self): return self.start.y @property def ex(self): return self.start.x @property def ey(self): return self.start.y @property def is_castle(self): return self.type in (MoveType.SHORT_CASTLE, MoveType.LONG_CASTLE) @property def indexes(self): return (self.sx, self.sy, self.ex, self.ey) Demonstration in the Board class. Now that we have the data objects we need, the logic in Board can operate at a higher level, working with the attributes, properties, and conveniences provided by the data objects. In this example, I will rewrite most of the implement_move() to illustrate the difference that building on top of higher-level information can make. Delegate grubby details. In addition to operating on richer types of data, the Board class also needs to delegate its own low-level manipulations and logic to helper methods. I ended up using one to implement a piece move on the board matrix; another to check current color; and a couple more to set or get castling data. class Board:
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
python, game, console, chess def do_move(self, sx, sy, ex, ey): piece = self.matrix[sy][sx] self.matrix[ey][ex] = piece self.matrix[sy][sx] = None return piece @property def is_white(self): return self.current_turn_color == Color.WHITE def disable_castle(self, *move_types): for mt in move_types: self.can_castle[self.current_turn_color][mt] = False def castle_indexes(self, move_type): y = 0 if self.is_white else 7 if move_type == MoveType.SHORT_CASTLE: return (y, 7, 5, 4, 6) else: return (y, 0, 3, 4, 2) Work with higher-order data and operations. Finally, in implement_move() we end up with less code, less logical complexity, and code that reads fairly naturally. class Board: def implement_move(self, mv): if mv.type == MoveType.PAWN_PROMOTION: # Move pawn. self.do_move(*mv.indexes) # Promote. pp = mv.promoted new_piece = Piece(pp.upper() if self.is_white else pp) self.matrix[mv.ey][mv.ex] = new_piece elif mv.is_castle: # Get indexes for y, rook start/end, king start/end. y, rs, re, ks, ke = self.castle_indexes(mv.type) # Move rook, then king. self.do_move(rs, y, re, y) self.do_move(ks, y, ke, y) # Disable. self.disable_castle(MoveType.SHORT_CASTLE, MoveType.LONG_CASTLE) else: # Move piece. piece = self.do_move(*mv.indexes) # Disable castle. if piece.type == PieceType.ROOK: self.disable_castle(mv.type) # En passant if piece.type == PieceType.PAWN: # Omitted in this demo. ...
{ "domain": "codereview.stackexchange", "id": 44574, "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, game, console, chess", "url": null }
recursion, haskell, mathematics, monads Title: Ackermann-Péter function call count using Writer monad Question: I'm quite new to Monads and I tried add function call counting to the Ackermann function code. The goal was simplicity, not performance. I want to have code review on the ackCount function. module AckermannPeterWrite where import Data.Monoid import Control.Monad.Writer (Writer, tell, runWriter) ackCount :: Int -> Int -> Writer (Sum Int) Int ackCount m n | m == 0 = do tell (Sum 1) return $ n + 1 | (m > 0) && (n == 0) = do tell (Sum 1) ackCount (m-1) 1 | (m > 0) && (n > 0) = do tell (Sum 1) let (secondArg, count) = runWriter $ (ackCount m (n-1)) tell (Sum $ getSum count) ackCount (m-1) secondArg ackCountMain :: Int -> Int -> String ackCountMain m n = do let (result, count) = runWriter $ ackCount m n "A(" ++ show m ++ ", " ++ show n ++ ") == " ++ show result ++ ", " ++ show (getSum count) ++ " function calls" main :: IO () main = do putStrLn $ ackCountMain 0 77 putStrLn $ ackCountMain 0 9 putStrLn $ ackCountMain 1 9 putStrLn $ ackCountMain 2 9 putStrLn $ ackCountMain 3 6 Bonus. A code that gives the same result without monads. ackCounter :: (Int, Int) -> (Int, Int) -> (Int, Int) ackCounter (m, sm) (n, sn) | m == 0 = (n + 1, sm+sn+1) | (m > 0) && (n == 0) = let (res, s) = ackCounter (m-1, 0) (1, 0) in (res, s+sm+sn+1) | (m > 0) && (n > 0) = let (res, s) = ackCounter (m-1, 0) (ackCounter (m, 0) (n-1, 0)) in (res, s+sm+sn+1) ackC :: Int -> Int -> (Int, Int) ackC m n = ackCounter (m, 0) (n, 0) Answer: The first thing that jumps out is these lines: let (secondArg, count) = runWriter $ ackCount m (n-1) tell (Sum $ getSum count) You're not really using the monad you're using; the whole point is for the accumulation to happen in the background: secondArg <- ackCount m (n-1)
{ "domain": "codereview.stackexchange", "id": 44575, "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": "recursion, haskell, mathematics, monads", "url": null }
recursion, haskell, mathematics, monads Other than that, it's mostly good! It's a good idea to make your functions total, even if that means including an | otherwise = error "message" clause. Alternately, you can avoid all your < 0 by retyping your function in terms of Naturals. Unfortunately, there's no first-class Natural data-type in Haskell, I found two options: natural-numbers and naturals, each of which deals with the problems in different ways. (See also) Finally, with a little reorganization, you can avoid repeating the call to tell $ Sum 1 for every case. This tests as correct for small values :) ackNew :: Natural -> Natural -> Writer (Sum Natural) Natural ackNew m n = do tell $ Sum 1 case (m, n) of (0, _) -> return $ n + 1 (_, 0) -> ackNew (m - 1) 1 _ -> do secondArg <- ackNew m (n - 1) ackNew (m - 1) secondArg
{ "domain": "codereview.stackexchange", "id": 44575, "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": "recursion, haskell, mathematics, monads", "url": null }
linux, shell Title: Improving Shell Installation Script Question: I'm currently working on a project and currently have this code. I already improved it by having some pointers, but I want to make it more professional looking and right. What should I implement next? installation() { echo '------------------------------------'>&2 echo 'Installing Dependensies'>&2 echo '------------------------------------'>&2 echo "">&2 echo 'Installing pkgconf ..'>&2 apt install pkgconf echo '------------------------------------'>&2 echo 'Installing libvte-2.91-dev ..'>&2 apt install libvte-2.91-dev echo '------------------------------------'>&2 echo 'Installing meson ..'>&2 apt install meson echo '------------------------------------'>&2 echo 'Installing libcairo2-dev ..' apt install libcairo2-dev echo '------------------------------------'>&2 echo 'Installing libpango1.0-dev ..'>&2 apt install libpango1.0-dev echo '------------------------------------'>&2 echo 'Installing libgnutls28-dev ..'>&2 apt install libgnutls28-dev echo '------------------------------------'>&2 echo 'Installing libgtk-3-dev ..'>&2 apt install build-essential libgtk-3-dev echo '------------------------------------'>&2 echo 'Installing libsystemd-dev ..'>&2 apt install libsystemd-dev echo '------------------------------------'>&2 echo 'Installing libgirepository1.0-dev ..'>&2 apt install libgirepository1.0-dev echo '------------------------------------'>&2 echo 'Installing valac ..'>&2 apt install valac echo '------------------------------------'>&2 echo 'Finished Installing the Dependensies'>&2 echo '------------------------------------'>&2 echo 'Cloning https://gitlab.gnome.org/GNOME/vte.git/'>&2 git clone https://gitlab.gnome.org/GNOME/vte.git/ echo 'Entering vte directory'>&2 cd vte echo 'Building VTE'>&2 meson _build ninja -C _build ninja -C _build install echo 'Done'>&2 } installation
{ "domain": "codereview.stackexchange", "id": 44576, "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": "linux, shell", "url": null }
linux, shell echo 'Done'>&2 } installation Any recommendations are welcome. It's pretty simple, all it does is install different dependencies. Answer: Please start with a shebang: #! /usr/bin/env bash It's unclear why you're logging ordinary messages to stderr, but OK, maybe that's a requirement. Define a log function for that, and prefer it over echo. echo 'Installing Dependensies'>&2 The typo is definitely not professional. Prefer the conventional spelling of "Dependencies", both here and for the "finished" message. (Pretty sure there's no "dependensy" British-ism.) echo 'Installing pkgconf ..'>&2 apt install pkgconf ... echo 'Installing libvte-2.91-dev ..'>&2 apt install libvte-2.91-dev ... It just goes on and on in this vein, it makes my eyes water. DRY. Write a loop already: for PKG in pkgconf libvte-2.91-dev ... Or put the package names in an env var, one-per-line for convenient git diff'ing, and loop over that. apt install ... I wonder if you maybe want apt install -y ..., to prevent user prompting? It is possible to ask apt to install a bunch of packages all at once in a single command. But that would alter the apt output and your progress reporting, so maybe you prefer not to. Total time spent waiting for downloads will often be reduced if you batch requests together, as some downloads will happen in parallel and the bottleneck router might have lots of bandwidth available. You didn't show us where you're already cd'd to, so it's unclear where the git clone will write to, but I imagine you've got that worked out already. ninja -C _build ninja -C _build install What a curious idiom! First build wasn't enough? Ok, I accept that maybe that's a "feature" of the build system and is really necessary for a correct install.
{ "domain": "codereview.stackexchange", "id": 44576, "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": "linux, shell", "url": null }
linux, shell Here are a few non-default settings you might choose to embrace. set -e will bail upon error, that is, upon running cd, apt, or any other command that returns non-zero status. It is useful for preventing an errant script from running amok. For example cd /tmp/baz; git clone $URL won't pollute $CWD with some annoying repo if destination dir doesn't exist. A related idiom is cd /tmp/baz && git clone $URL, another way of insisting the dest dir exists. set -o pipefail is similar to set -e, so e.g. echo | false | false | true will bail instead of reporting $? status of 0. I didn't notice any pipelines in your script, but you might add some over time. Suppose we never set the env var FOO. set -u will make e.g. echo ${FOO} a fatal error, instead of interpolating a null-string value. Think of it as "lint for bash". You don't need any of these. But they can help improve the robustness of what you write. Often I will set -x to see which stage a script has progressed to, similar to make. But you have explicit echo statements for that, so it isn't needed in this script.
{ "domain": "codereview.stackexchange", "id": 44576, "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": "linux, shell", "url": null }
rust, hangman Title: Rust implementation of Hangman Question: I created a rust implementation of hangman as a command line version. The user can enter characters to find out the desired word. I really appreciate any helpful comment which highlights how I could improve the code and in particular make more "rustacean". use std::io; use std::collections::HashSet; fn extract_char(line: &str) -> char{ line.trim().chars().nth(0).expect("Please input a single character.") } fn get_current_guess(word: &str, chars: &HashSet<char>) -> String { word.chars().map(|x| if chars.contains(&x) {x} else {'_'}).collect() } fn main() { println!("Welcome to Hangman!"); let word = "declaration"; let mut user_chars: HashSet<char> = HashSet::new(); let max_incorrect_guesses = 5; let mut incorrect_guesses = 0; loop { println!("Please input a single char:"); let mut current_input = String::new(); io::stdin() .read_line(&mut current_input) .expect("Failed to read input."); let current_char = extract_char(&current_input); if user_chars.contains(&current_char) { println!("You already chose {}.", current_char); continue } else if !word.contains(current_char){ incorrect_guesses += 1; println!("{} is not in word.", current_char); println!("Number of incorrect guesses is now {}", incorrect_guesses); } user_chars.insert(current_char); if incorrect_guesses > max_incorrect_guesses { println!("You have reached the maximum number of incorrect guesses."); println!("The correct word is {}.", word); break } println!("Your current guess is {:?}", get_current_guess(&word, &user_chars)); } } Answer: fn extract_char(line: &str) -> char{ line.trim().chars().nth(0).expect("Please input a single character.") }
{ "domain": "codereview.stackexchange", "id": 44577, "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, hangman", "url": null }
rust, hangman This doesn't actually check if the user entered a single character, just if they entered at least one. It also panics on an error in user input which would normally be bad, but maybe its okay for this learning excercsize. You can actually simplify by using the parse() method: fn extract_char(line: &str) -> char{ line.trim().parse().expect("Please input a single character.") } This asks rust to parse the string into a char and it know how to do that properly. Also worth looking at is the text_io create which provides some macros to simplify the text input. if user_chars.contains(&current_char) { println!("You already chose {}.", current_char); continue } You should use insert rather then contains. insert returns false if the set already contains the item. Thus is allows insertion and checking if the set already had the element in one call. continue } else if !word.contains(current_char){ The else is redundant with the continue. Both are useful sometimes, but I'd suggest not doing them both together. Gameplay wise: There appears to be no win condition It doesn't show me the number of spaces before I start guessing.
{ "domain": "codereview.stackexchange", "id": 44577, "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, hangman", "url": null }
c++, template-meta-programming, variadic, variant-type, constrained-templates Title: Transpose types variadicly Question: I want to do template metaprogramming to compute the conversion from std::variant<Ts...> to std::tuple<std::vector<Ts>...> I came up with something that worked template <typename T> requires std::is_specialization_of_v<T, std::variant> struct type_transpose {}; template<typename... Args> struct type_transpose<std::variant<Args...>> { using type = std::tuple<std::vector<Args>...>; }; which can be used as using Input = std::variant<float, int>; using Result = type_transpose<Input>::type; using Correct = std::tuple<std::vector<float>, std::vector<int>>; static_assert(std::is_same_v<Correct, Result>); Is this the best way achieve this type computation? Is this the only way? I don't know template metaprogramming and was lucky to get anything working... Full use case: https://godbolt.org/z/GoxzY59Px (I'm not asking to review the code in the link) I called this transposing because the templates are equivalent to the std::vector<std::tuple<Ts...>> -> std::tuple<std::vector<Ts>...> operation. But what is a better name for this std::tuple<Ts...> to std::tuple<std::vector<Ts>...> operation? It's like we are mapping the std::vector type constructor/Functor over std::tuple<Ts...> a functor domain (sorry for by small my category theory vocabulary). Answer: Is this the best way achieve this type computation? Is this the only way? For this case where there is template specialiation, yes, I think this is the only way. You could add the following convenience alias though: template<typename T> using type_transpose_t = type_transpose<T>::type; I don't know template metaprogramming and was lucky to get anything working... Congratulations, you do now! Note that it probably wasn't luck, but rather your intuition gained from "normal" programming, that you could apply to TMP.
{ "domain": "codereview.stackexchange", "id": 44578, "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-meta-programming, variadic, variant-type, constrained-templates", "url": null }
c++, template-meta-programming, variadic, variant-type, constrained-templates I do think that the name is a bit misleading though. The word "transpose" implies you swap two things. So for example, a variant of vectors could get transposed to a vector of variants. Here you are creating a more efficient vector of variants (although some of the ordering will get lost). Maybe to_tuple_of_vectors would be a more correct name, even if it is a bit verbose.
{ "domain": "codereview.stackexchange", "id": 44578, "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-meta-programming, variadic, variant-type, constrained-templates", "url": null }
c++, file, search, stream, c++98 Title: Copy file with text replacement Question: I am currently learning C++. I coded a tiny program for school and I wonder if there could be issues (like bugs or security issues) with it. Any ways to make it have weird behaviours would be very appreciated, any suggestions to improve my code in terms or performance or readability are also welcomed. Instructions Given a file named filename, and two strings s1and s2, this program should create a new file named filename.replace in which all occurrences of s1 are replaced by s2. code needs to compile with the -std=c++98 flag (so no C++11 standard or more) I only can use the standard library's functions no *printf, *allocor free no C file manipulation functions, only C++ no STL, no containers nor <algorithm> header no std::string::replace function #include <iostream> #include <fstream> int main( int ac, char **av ) { if (ac != 4) { std::cout << "Invalid number of arguments" << std::endl; return -1; } std::string infile_name(av[1]); std::fstream infile(infile_name, std::ios::in); if (!infile.is_open()) { std::cout << "'" << av[1] << "': issue while opening the file" << std::endl; return -1; } std::cout << "'" << av[1] << "': successfully opened in read mode" << std::endl; std::string outfile_name(av[1]); outfile_name += ".replace"; std::fstream outfile(outfile_name, std::ios::out | std::ios::trunc); if (!outfile.is_open()) { std::cout << "'" << av[1] << "': issue while opening the file" << std::endl; return -1; } std::cout << "'" << outfile_name << "': successfully opened and truncated in write mode" << std::endl;
{ "domain": "codereview.stackexchange", "id": 44579, "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++, file, search, stream, c++98", "url": null }
c++, file, search, stream, c++98 std::string line; std::string s1(av[2]); std::string s2(av[3]); size_t pos; while (std::getline(infile, line)) { if (!infile.eof()) line += '\n'; do { pos = line.find(s1); if (pos == std::string::npos) outfile << line; else { outfile << line.substr(0, pos); outfile << s2; line = line.substr(pos + s1.size()); } } while (pos != std::string::npos); } // not necessary to close the files manually as std::fstream objects are RAII // objects: https://stackoverflow.com/questions/4802494/do-i-need-to-close-a-stdfstream // infile.close(); // outfile.close(); } Answer: std::getline and std::string are in the <string> header, so we need to include that. Rather than using std::fstream directly, we can use the specific types std::ifstream and std::ofstream for input and output files respectively. Error messages should be sent to std::cerr, rather than std::cout. Progress messages should go to std::clog. (It may not matter here, but it's a useful habit to get into for writing programs where the standard output is piped to a file, or used as input by another program.) We create the variable infile_name, but continue to use av[1] in many places. We should use infile_name throughout, since it's more meaningful. Note that the error message if we fail to open outfile shows the wrong file name. (We might have noticed if we had used the more meaningful name, instead of av[1] ;) ). Variables should be marked const when we don't need them to be mutable (e.g. infile_name, outfile_name, s1, s2).
{ "domain": "codereview.stackexchange", "id": 44579, "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++, file, search, stream, c++98", "url": null }
c++, file, search, stream, c++98 After each replacement, the line string is reassigned to a new string object: line = line.substr(pos + s1.size());. This is likely to be quite slow (as it will probably involve memory allocation). Note that std::string::find takes a second argument, which is the offset in the string at which to start searching. By using a second std::size_t variable to track the start point of the search (and adjusting the output code a bit), we can avoid the expensive substring operation. In modern C++, we could avoid the use of substr when outputting to the stream by using std::string_view, but that's not available in C++98. The code that does the actual processing could be moved to separate function: void stream_replace(std::istream& in, std::ostream& out, std::string const& search_term, std::string const& replacement); This is neater - it gives this section of code clear inputs and outputs, and a meaningful name, and makes our main function shorter and more readable. It also makes the code more testable: we can pass file streams to this function, but we could also pass std::stringstreams. So we could write a bunch of test cases with various input strings, and check that the code gives the expected output in each case. This is called unit testing. (Note that both std::string and the file streams are in the C++ standard library (often and somewhat erroneously called the STL - see the big purple box at the bottom of this page for details). std::string is definitely a container type. This may just be just a mistake in the instructions you've been given; if you're sure you can use std::string then I don't think you're doing anything wrong. If you're actually supposed to avoid std::string too, then you'll probably need to look into using a fixed size character array when processing the files.)
{ "domain": "codereview.stackexchange", "id": 44579, "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++, file, search, stream, c++98", "url": null }
c++, multithreading, mvc, c++17, curses Title: Multithreaded MVC game engine Question: This is an attempt at a multithreaded model-view-controller based engine for 2d console games (board games, roguelikes that sort of thing.) The code below will provide a fully working example but is missing a lot of bits as I am specifically interested in a critique of the multithreading and MVC bits though any other advice you may have will be gratefully received. You will need a c++17 capable compiler and the ncurses library to compile it. There are multiple source files: model.h #ifndef MODEL_H #define MODEL_H #include <functional> #include <memory> #include <mutex> #include <queue> constexpr inline const int MAXROWS = 10; constexpr inline const int MAXCOLS = 10; struct Command; class Model { public: Model(); std::function<void()> render; std::function<void()> shutdownController; bool at(int, int) const; void gameloop(); void move(int, int); void receiveCommand(Command*); void quit(); private: void update(); std::queue<std::unique_ptr<Command>> commands_; std::mutex mutex_; std::array<std::array<bool, MAXCOLS>, MAXROWS> board_; int row_; int col_; }; #endif model.cc #include <algorithm> #include <chrono> #include <csignal> #include <cstdlib> #include "command.h" #include "model.h" constexpr const double TICK = 1E6 / 60.0; volatile static std::sig_atomic_t endflag = 0; static void end(int sig) { switch (sig) { case SIGINT: case SIGTERM: endflag = 1; break; case SIGHUP: exit(EXIT_FAILURE); break; default: break; } } Model::Model() : render{}, shutdownController{}, commands_{}, mutex_{}, board_{}, row_{3}, col_{7} { board_[row_][col_] = true; } bool Model::at(int row, int col) const { return board_[row][col]; }
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses bool Model::at(int row, int col) const { return board_[row][col]; } void Model::gameloop() { struct sigaction act; act.sa_handler = end; sigemptyset (&act.sa_mask); act.sa_flags = 0; sigaction(SIGHUP, &act, NULL); sigaction(SIGINT, &act, NULL); sigaction(SIGTERM, &act, NULL); std::chrono::steady_clock clock; auto previous = clock.now(); double lag = 0.0; while (!endflag) { auto current = clock.now(); auto elapsed = current - previous; previous = current; lag += elapsed.count(); while (lag >= TICK) { lag -= TICK; update(); } render(); } shutdownController(); } void Model::move(int row, int col) { board_[row_][col_] = false; row_ = std::clamp(row_ + row, 0, MAXROWS - 1); col_ = std::clamp(col_ + col, 0, MAXCOLS - 1); board_[row_][col_] = true; } void Model::receiveCommand(Command* command) { std::lock_guard<std::mutex> lock(mutex_); commands_.emplace(command); } void Model::quit() { endflag = 1; } void Model::update() { std::lock_guard<std::mutex> lock(mutex_); while (!commands_.empty()) { auto& nextCommand = commands_.front(); nextCommand->execute(*this); delete nextCommand.release(); commands_.pop(); } } view.h #ifndef VIEW_H #define VIEW_H #include <memory> #include <ncurses.h> class View { public: View(); ~View(); bool draw(const int, const int, const chtype); WINDOW* window() const; private: std::shared_ptr<WINDOW> window_; }; #endif view.cc #include <clocale> #include "view.h" struct WindowDeleter { void operator()(WINDOW* window) { delwin(window); } }; View::View() : window_{nullptr} { setlocale(LC_ALL, ""); initscr(); cbreak(); noecho(); intrflush(stdscr, FALSE); keypad(stdscr, TRUE); window_.reset(subwin(stdscr, 0, 0, 0, 0), WindowDeleter()); curs_set(0); }
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses window_.reset(subwin(stdscr, 0, 0, 0, 0), WindowDeleter()); curs_set(0); } View::~View() { curs_set(1); endwin(); clear(); } bool View::draw(const int row, const int col, const chtype ch) { const auto& win = window_.get(); if (wmove(win, row, col) == ERR) { return false; } if (waddch(win, ch) == ERR) { return false; } return true; } WINDOW* View::window() const { return window_.get(); } controller.h #ifndef CONTROLLER_H #define CONTROLLER_H #include <functional> #include <unordered_map> #include <ncurses.h> #include "command.h" class Controller { public: explicit Controller(WINDOW*); Controller(const Controller&)=delete; Controller(const Controller&&)=delete; bool operator=(const Controller&)=delete; bool operator=(const Controller&&)=delete; std::function<void(Command*)> sendCommand; void handleEvents(); void shutdown(); protected: std::unordered_map<chtype, std::function<Command*()>> keymap_; private: WINDOW* window_; bool finished_; std::mutex mutex_; }; #endif controller.cc #include "controller.h" Controller::Controller(WINDOW* window) : sendCommand{}, keymap_{ { 'h', [](){ return new MoveCommand( 0, -1); } }, { 'j', [](){ return new MoveCommand(-1, 0); } }, { 'k', [](){ return new MoveCommand( 1, 0); } }, { 'l', [](){ return new MoveCommand( 0, 1); } }, { 'q', [](){ return new QuitCommand(); } } }, window_{window}, finished_{false}, mutex_{} { nodelay(window_, TRUE); } void Controller::handleEvents() { int c; while (!finished_) { if ((c = wgetch(window_)) != ERR) { auto input = keymap_.find(c); if (input != keymap_.end()) { sendCommand(std::invoke(input->second)); } } } } void Controller::shutdown() { std::lock_guard<std::mutex> lock(mutex_); finished_ = true; } command.h #ifndef COMMAND_H #define COMMAND_H
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses command.h #ifndef COMMAND_H #define COMMAND_H #include "model.h" struct Command { virtual ~Command() {} virtual void execute(Model&)=0; }; struct MoveCommand : public Command { virtual ~MoveCommand() {} explicit MoveCommand(int row, int col) : row_{row}, col_{col} { } void execute(Model& model) override { model.move(row_, col_); } private: int row_, col_; }; struct QuitCommand : public Command { virtual ~QuitCommand() {} void execute(Model& model) override { model.quit(); } }; #endif main.cc #include <cstdlib> #include <thread> #include "model.h" #include "view.h" #include "controller.h" int main() { Model model; View view; Controller controller(view.window()); controller.sendCommand = [&model](Command* command) -> void { model.receiveCommand(command); }; model.shutdownController = [&controller]() -> void { controller.shutdown(); }; model.render = [&view, &model]() -> void { for (auto row = 0; row < MAXROWS; ++row) { for (auto col = 0; col < MAXCOLS; ++col) { view.draw(row, col, model.at(row, col) ? '@' : '-'); } } }; auto controllerThread = std::thread(&Controller::handleEvents, &controller); auto modelThread = std::thread(&Model::gameloop, &model); modelThread.join(); controllerThread.join(); return EXIT_SUCCESS; } You can compile it like this: g++ -std=c++17 -Wall -Wextra -Weffc++ -O2 -g -o game main.cc model.cc view.cc controller.cc -lncurses
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses As I mentioned, the idea is that the game should follow the Model-View-Controller pattern. Each of the big 3 components should be unaware of and independent of the others. I couldn't see a way to make the Controller not have a reference to the window which is a member of the View object. And should the Model really be shutting down the Controller? It seems that should happen in main() but when I tried it I had thread synchronization problems which froze the game. Can the std::functions and lambdas I have to connect up the classes (like Qt's "signals and slots") be made more generic? Speaking of threads, I have two (for now) one listens for input and the other runs the game loop, updating the Model 60 times a second and rendering the View as necessary. Am I doing this right? These are some questions that come to mind but, again, any critique or guidance will be gratefully received. Answer: About the MVC pattern As I mentioned, the idea is that the game should follow the Model-View-Controller pattern. Each of the big 3 components should be unaware of and independent of the others. The goal of the MVC pattern is not that each of the three components are unaware and independent of each other. Rather, the goal is to separate responsibilities, and to make it easier to replace components with different implementations, without affecting the other components. So it is fine if the components depend on each other, as long as they depend on a well-defined interface, and not on implementation details. For example, you could have created base classes ModelBase, ViewBase and ControllerBase, which the concrete classes derive from, and pass a pointer to ModelBase to Controller, and have move() and quit() be public virtual member functions of ModelBase. I couldn't see a way to make the Controller not have a reference to the window which is a member of the View object.
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses You could create a class Window which represents a curses window. You could pass a reference to that to both the Controller and the View. This removes the responsibility of creating a window from View, the latter is now only responsible for drawing the state of the Model. Can the std::functions and lambdas I have to connect up the classes (like Qt's "signals and slots") be made more generic? Probably, but why do you need it to be more generic? In this case, you could even argue that they are already too generic, and they can be made more specific. About the threads And should the Model really be shutting down the Controller? It seems that should happen in main() but when I tried it I had thread synchronization problems which froze the game. If I had to design it I would probably have the Controller be in charge of stopping things, but it's not the only way to do it. You could also start the controller thread after the model thread, and instead of sending a quit command to the model, the controller will just exit handleEvents() when you press the quit key. Then in main(), you could write something like: auto modelThread = std::thread(&Model::gameloop, &model); auto controllerThread = std::thread(&Controller::handleEvents, &controller); controllerThread.join(); model.quit(); modelThread.join(); This way, Model::shutdownController is no longer necessary. Speaking of threads, I have two (for now) one listens for input and the other runs the game loop, updating the Model 60 times a second and rendering the View as necessary. Am I doing this right?
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses No. You never sleep, so a lot of CPU cycles are wasted between updates to Model. Use std::this_thread::sleep_for() or std::this_thread::sleep_until() to sleep. Also, you unconditionally call render(), not just when there is an update, again wasting CPU cycles. Thread safety issues You should worry more about thread safety. Is your curses library thread safe? You have two threads calling curses functions possiby simulatenously. Model::endflag is read by one thread and modified by another. You made it volatile, but that is not the same as atomic. std::sig_atomic_t is a type meant for POSIX signal handlers, not for threads. While it most likely will do what you want, it is much better to use a std::atomic_flag, which is guaranteed to do what you want. Also, why is this a global variable? It should be a private member variabel of Model. Controller::finished_ looks like it serves a similar purpose as Model::endflag, but it is implemented in a completely different way. You do lock mutex_ inside shutdown(), but you don't use the mutex in handleEvents(). That's definitely wrong; if you lock a mutex to guard a variable at one place, you should almost always do that in every other place as well. But again, std::atomic_flag is a much better solution here. Handing commands keymap_ is unnecessarily complex. It stores lambdas which in turn create objects that derive from Command, and those in turn have a virtual execute() function which does the actual work. Why not just use std::function<void(Model&)> to store commands? using Command = std::function<void(Model&)>; … std::unordered_map<chtype, Command> keymap_; … Controller::Controller(WINDOW* window) : sendCommand{}, keymap_{ { 'h', [](Model& model){ model.move( 0, -1); } }, … { 'q', [](Model& model){ model.quit(); } }, }, … And then in Model: std::queue<Command> commands_; … void Model::receiveCommand(Command command) { std::lock_guard<std::mutex> lock(mutex_); commands_.emplace(command); }
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
c++, multithreading, mvc, c++17, curses void Model::update() { std::lock_guard<std::mutex> lock(mutex_); while (!commands_.empty()) { commands_.front()(*this); commands_.pop(); } } It gives you exactly the same flexibility and decoupling, but now you no longer need the Command class hierarchy, there is less indirection, and if the commands don't have any captures, it avoids heap allocations. I also wonder why it is necessary to use a queue to pass commands from the Controller to the Model. Why not call the commands directly in the Controller's thread? You can do this if you do proper locking in Model's move(), quit() and gameloop(). This avoids passing Command objects around.
{ "domain": "codereview.stackexchange", "id": 44580, "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++, multithreading, mvc, c++17, curses", "url": null }
python Title: How to better write this Python String manipulation Question: The following code creates a list of questions and options from a multiline string. import json import re text_string = ''' Question 1 ### Consider the following figure: Select one: * **a. The optimal solution** * b. An infeasible solution * c. An Alternate vertex * d. None of these answers ***The correct answer is: The optimal solution*** ----- Question 2 ### If the characters 'D', 'C', 'B', 'A' are placed in a queue (in that order), and then removed one at a time, in what order will they be removed? ``` // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], v alue, low , high) { // in variants: v alue >= A[i] for all i < low v alue < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > v alue) return BinarySearch_Right(A, v alue, low , mid-1) else return BinarySearch_Right(A, v alue, mid+1, high) } ``` Select one: * a. ABCD * b. ABDC * c. DCAB * **d. DCBA ** * e. ACDB ***The correct answer is: DCBA***
{ "domain": "codereview.stackexchange", "id": 44581, "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 ***The correct answer is: DCBA*** ''' questions = text_string.split('-----') quizzes = [] for ques in questions: # create array to get question text # this should remove the question number like (Question 1) question_array = ques.strip().split('*')[0].split('\n') # Question text question = '\n'.join(question_array[1:len(question_array)]) # Remove ### if starts with ### if question.startswith("###"): question = question[3:] # build a dict item to add to quizzes array quiz_item = { 'question': question.strip(), 'options': [], 'answer_string': '' } # get index of string staring 'select' for option in ques.strip().split('\n'): if option.startswith("*") and not (option.startswith("***") and option.endswith("***")): quiz_item['options'].append({ 'option': option.replace('*', '').strip(), 'answer': True if option.startswith("* **") and option.endswith("**") else False }) if option.startswith("***") and option.endswith("***"): quiz_item['answer_string'] = option.replace('*', '').strip() quizzes.append(quiz_item) print(json.dumps(quizzes, indent=2)) It works as I do get the results I want. However, I feel it is not efficient enough. Is there any better way to write this? Thank you. Answer: When parsing, attach meaningful labels to important markers, dividers, etc. Your code is littered with magic strings that drive the parsing logic. But those raw strings don't mean anything to a reader of the code. Help your reader (ie, you in the future) by giving those entities meaningful names. QUESTION_DIVIDER = '-----' QUESTION_PREFIX = '#' OPTION_MARK = '*' ANSWER_MARK = '**' ANSWER_TEXT_MARK = '***'
{ "domain": "codereview.stackexchange", "id": 44581, "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 When parsing, don't try to do everything at once. Parsing is often tricky and complicated. Focus your energies on trying to reduce that complexity. Your current approach does not do that: all within a single mega-loop you break the full text into chunks of question-text; nested under that, you perform all of the detailed steps to extract each bit of information. That's too much logical complexity to put in one place: the human brain has trouble keeping track of everything in a context like that. A better strategy is to break the problem down into a sequence of very simple operations, each in its own function, and each individually understandable at a glance. In the illustration below, parsing occurs in two phases: the first just breaks the question-text into its major sub-sections (question, options, answer). Then, those sections are handled individually. Speaking of functions, all of your code should be in them. This discipline has many benefits. One could argue that this practice is the strongest and oldest lesson in the history of computer programming. You would be well advised to embrace this wisdom of the ancients even if you don't fully appreciate all of the benefits yet. At the top level, one typically has a main() function or something similar. Its job it to orchestrate things, not engage in the grubby details of parsing. import json # Your example text. QUIZ_TEXT = """ ... """ def main(): questions = list(parse_quiz(QUIZ_TEXT)) print(json.dumps(questions, indent = 4)) ... if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44581, "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 ... if __name__ == '__main__': main() Then we have a top-level parsing function. By design, we don't want it doing much detailed work. Its job is to assemble the desired data structure (a dict in your case) by delegating lower-level operations to other functions. def parse_quiz(text): # Takes the full text of a quiz. # Yields dicts, each representing a question # and its options and answer. for question_text in quiz_text_to_question_texts(text): qsection, osection, asection = parse_into_sections(question_text) yield dict( question = parse_question_section(qsection), options = parse_options_section(osection), answer = asection, ) Finally, there are the helper functions that perform the actual parsing. We want these functions to be short and narrowly focused on specific task. Because they are narrowly defined and because they take advantage of named constants, most of their work is fairly easy to understand. Equally important, my prediction is that you will discover that your current parsing logic has some edge-case problems if you run it against a variety of inputs. When you have to modify your program to handle these unanticipated complications, your work will be much easier because the adjustments will be happening in these little utility functions rather than in a sprawling mass of code that tries to parse everything at once. def quiz_text_to_question_texts(text): # Breaks the full text into separate blobs of question text. return [ qt.strip() for qt in text.split(QUESTION_DIVIDER) ] def parse_into_sections(text): # Breaks a single question into is primary sections: # question, options, answer. top, asection, rest = text.split(ANSWER_TEXT_MARK, 2) qsection, osection = top.split(OPTION_MARK, 1) return (qsection.strip(), osection.strip(), asection.strip())
{ "domain": "codereview.stackexchange", "id": 44581, "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 def parse_question_section(qsection): # Extracts the question text from the question-section. q = '\n'.join(to_lines(qsection)[1:]) return q.lstrip(QUESTION_PREFIX).strip() def parse_options_section(osection): # Extracts the options from the options-section. return [ dict( option = line.strip(OPTION_MARK).strip(), is_answer = line.startswith(ANSWER_MARK), ) for line in to_lines(osection) ] def to_lines(text): return text.split('\n') Next steps: model your data with proper data objects. You are currently representing a quiz as a list of question dicts. I don't know how you intend to use those dicts, but I suspect that your larger project would benefit from representing those questions as dataclass Question instances.
{ "domain": "codereview.stackexchange", "id": 44581, "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 }
c#, httpclient Title: Exponential retry handler implementing DelegatingHandler in C# Question: I am writing a small library where I don't want to include Polly since I want to keep the number of dependencies as small as possible. I also thought it was a good learning exercise to do this on my own since I'm learning the language. However if my implementation is subpar, I might consider Polly instead. My goal is to have a handler I can attach to any HTTP client where the target RequestUri of the client has a recommendation on this type of retry policy. I don't want to throw exceptions, and I want to return the last failed status if retries are exhausted. If retries are not exhausted, I want to return the result I received. I would like to know if this is safe to use, if I have missed something or if there are other improvements to be made. I would also like to know if I'm following the conventions of the language properly. It should work like this: Retry a maximum of MaxRetries times if the response status is in RetryableStatusCodes or if the client throws HttpRequestException If the HttpRequestException contains status code, also verify that it should be retried If HttpRequestException does not contain a status, retry anyway If retries are exhausted, return the last HttpResponseMessage If only receiving exceptions, return a custom HttpResponseMessage to have something to return Here's what I have: using System.Net; namespace MyNamespace.Http; public abstract class ExponentialBackoffHandler : DelegatingHandler { public abstract int MaxRetries { get; } public abstract int MinBackoffMs { get; } public abstract int MaxBackoffMs { get; } public abstract List<int> RetryableStatusCodes();
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken ct) { Func<HttpRequestMessage, Task<HttpResponseMessage>> func = async (req) => { var backoff = new ExponentialBackoff(MinBackoffMs, MaxBackoffMs); HttpResponseMessage? response = null; for (int i = 0; i < MaxRetries; i++) { try { response = await base.SendAsync(request, ct); if (response.IsSuccessStatusCode) { return response; } if (ShouldRetry(i, response.StatusCode)) { await backoff.Delay(ct); } } catch (HttpRequestException e) { // Force the return of the custom response on the last attempt if (ShouldRetry(i + 1)) { await backoff.Delay(ct); } else { response = new HttpResponseMessage { StatusCode = e.StatusCode ?? HttpStatusCode.InternalServerError, Content = new StringContent(e.Message) }; break; } } } return response!; }; return await func(request); } private bool ShouldRetry(int attempt, HttpStatusCode? status = null) { bool hasRetriesLeft = attempt < MaxRetries; bool isStatusRetryable = status != null ? RetryableStatusCodes().Contains((int)status) : true; return hasRetriesLeft && isStatusRetryable; } }
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient struct ExponentialBackoff { private readonly int _delayMilliseconds; private readonly int _maxDelayMilliseconds; private int _retries; public ExponentialBackoff(int delayMilliseconds, int maxDelayMilliseconds) { _delayMilliseconds = delayMilliseconds; _maxDelayMilliseconds = maxDelayMilliseconds; _retries = 0; } public Task Delay(CancellationToken ct) { var delay = TimeSpan.FromMilliseconds( Math.Min(_delayMilliseconds * Math.Pow(2, ++_retries) / 2, _maxDelayMilliseconds) ); return Task.Delay(delay, ct); } } You implement it like this: class MyExponentialBackoffHandler : ExponentialBackoffHandler { public override int MaxRetries => 3; public override int MinBackoffMs => 1; public override int MaxBackoffMs => 10; public override List<int> RetryableStatusCodes() { return new() { 404 }; } } And then in the DI wiring: services .AddTransient<MyExponentialBackoffHandler>() .AddHttpClient<MyHttpClient>() .AddHttpMessageHandler<MyExponentialBackoffHandler>(); I also have a bunch of tests for this if that would be useful. Thank you for your time, looking forward to your input. Answer: In this post I would like to focus on correctness, extensibility and composability. Correctness Most of the time whenever we want to make sure that a given implementation works correctly then we write unit (and integration) tests to assure that the observed and expected behaviours are the same. Which is good, but sometimes it is not enough. Currently that's the case. You have written a generic retrier which nicely integrates with HttpClient. What's the problem with this from correctness point of view? In order to be able to answer the above question, let's see the prerequisites of retry:
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient The potentially introduced observable impact is acceptable The operation can be redone without any irreversible side effect The introduced complexity is negligible compared to the promised reliability Does your implementation satisfy all these? Let's see one-by-one: Because you did not specify explicitly any time-cap for each retry attempt, that's why it might happen that 3 retries could take several minutes (downstream having hard-time to respond to requests). If you are using the decorated HttpClient for a background operation then it might be acceptable. If you are using the decorated HttpClient for user-facing operation most probably (but depends on the use case) it is not acceptable and tolerable. Possible solution: Use timeout and/or circuit breaker. Because you have decorated the entire HttpClient with the retrier that's why all operations can (and will) be retried. Which can be problematic if the downstream's endpoint is not implemented in an idempotent way. Like many times the POST verb is not idempotent. Possible solution: Use typed client. You can decorate the underlying HttpClient with the retrier and use it only for idempotent operations (mostly GETs) In order to keep your logic simple, you've made the retry logic "dumb". It performs a retry whenever you receive HRE or whenever the status code is one of the retriable ones. But what if the server exposes throttling? It communicates to the client when should they perform retry with a custom 429 response. At the current stage your code complexity is negligible compared to the promised reliability. But as you start to add more and more sophisticated logic to add resiliency to your communication protocol the answer might change.
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient The jitter If you look at the best practices regarding retry logic you can easily bump into exponential backoff. Which is a good start, but it is just half of the story. With any retry logic (regardless it is linear or exponential or other) it can happen that they synchronise clients. All clients start to perform retry at the exact same time against the recovered downstream service. Which might bring down again the service due to the flood of the requests. If you would add a jitter to the sleep duration between retry attempts that could spread the clients in time. A jitter can be as simple as a random number between [-1.0, 1.0] or much more sophisticated. I highly recommend to read the following article by AWS. Extensibility How easily can you extend the current implementation to support slightly different use cases? We are looking for answer to this question here. Let me provide a couple of example use cases. This won't be an exhaustive list rather than just a couple of examples. Using RetryAfter header As I have already mentioned under the correctness section it might happen that the server is implemented in the way that it does support rate-limiting / throttling. The service might respond with a 429 (Too Many Requests) status code and sets the RetryAfter response header to indicate when should the client issue the next retry attempt (to give space for self-healing for the service). Your current handler can't be easily extended to support this scenario with inheritance. Conditional retry There are situations where you need to have branching logic to handle different circumstances differently. Even though at first glance retry does not fall under this category, but in reality it does. :D Let's image the following scenario:
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient If the response's status code is 429 then retry only once by respecting RetryAfter If the response's status code is 408 then retry 3times with exponential backoff If the response's status code is 502/504 then retry indefinitely (until is succeeds) with fix interval The current design does not support this. Custom fallback In your current implementation if all attempts failed then you return either with the last response or with a made-up HttpResponseMessage (depending on the control flow). You might need to know consistently that all the retry attempts failed. Users of your retrier might want to provide custom fallback response in this case. Observability For observability purposes it might be useful to extend your current implementation with logging to know the distribution of the retries in time and which downstream service is the least reliable. These were just a couple of examples. Adding support for all of these greatly increase complexity. So, you should evaluate again whether the introduced complexity is still negligible compared to the promised reliability. Composability IMHO the greatest feature of Polly is composability. You can chain multiple policies together to define resiliency strategies. A resiliency strategy is nothing more than a predefined protocol between clients and server to overcome transient failure (without causing harm to the other side). A pretty common resiliency strategy looks like this: Having a global timeout which overarches all retry attempts Having a retry policy which is aware of the underlying circuit breaker's state Having a circuit breaker which monitors the responses' "healthiness" to detect over-flooded/degraded downstream services Having a local timeout for each request attempt What I want to emphasize here is that retry is a good start, but please do not stop here. In order to have more robust solution to overcome transient errors you need to combine multiple primitives to achieve the desired behaviour.
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c#, httpclient Huh ... that's a lots of information. Thanks for reading it all. I hope it helped (at least a bit).
{ "domain": "codereview.stackexchange", "id": 44582, "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#, httpclient", "url": null }
c, mathematics, bitwise Title: Compute the sum of even numbers between two values Question: Recently I was watching two YouTube videos criticizing a function which sums the even elements in an inclusive range, the original function looks like this: int calculate(int bottom, int top) { if (top > bottom) { int sum = 0; for (int number = bottom; number <= top; number++) { if (number % 2 == 0) { sum += number; } } return sum; } else { return 0; } } original source video While I agree the original function could be formatted better with less indentation and early returns, it seems the solutions proposed in C++, Rust & Haskell are making heavy use of their variations of .filter & .reduce like functional programming which seems like a lot of overhead for something like this... Which led to me spending a bit too much time writing the following functions, with the intent to make the function blazingly fast, more concise and removing all layers of nesting (as intended by the source video). The Math Approach I remember learning a math formula for summing numbers in a sequence which I looked up for quick refresher, and found an even better solution for summing only even numbers: n • (n + 1) Where n is the number of numbers in the range. My initial attempts at just subtracting the total sum of evens from the top and bottom failed (more on this later), which led me to trying a different formula: and after a bit more time than I like to admit, I arrived at the following solution: int sumOnlyEvenNumbersInRange(int bottom, int top) { int x = bottom + (bottom & 1); // next even if odd int y = top + (top & 1); // previous even if odd return (y - x + 2) * 0.25 * ((x ^ y) + ((x & y) << 1)); }
{ "domain": "codereview.stackexchange", "id": 44583, "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, mathematics, bitwise", "url": null }
c, mathematics, bitwise Which I'll admit looks a lot worse than it really is, but was the product of me combing the math terms and then substituting bitwise operators where applicable. The issue I realized I encountered earlier is that when bottom is odd we need to start the sequence at the next even and likewise if top is odd we need to end at the previous even number. After discovering this I revisited my first attempt, and finally got the following to work: int sumOnlyEvenNumbersInRange(int bottom, int top) { int x = (bottom + (bottom & 1)) >> 1; int y = (top - (top & 1)) >> 1; return y * (y + 1) - x * (x - 1); } Which to be honest I'm pretty happy about, even though I still dream of an inline function. Anyways, I would be pretty upset if I saw this in a code-review the way it is and I realize it still doesn't account for when top < bottom, so here is the finalized version: int sumOnlyEvenNumbersInRange(int bottom, int top) { if (bottom > top) return 0; // edge case int x = (bottom + (bottom & 1)) >> 1; // first even number in range divided by 2 int y = (top - (top & 1)) >> 1; // last even number in range divided by 2 return y * (y + 1) - x * (x - 1); // difference of evens between x and y } I know it isn't the most readable code, but that wasn't really the goal here. This won't be used in production and is just for fun, so I'm pretty happy with it, but it would be awesome if there was a way to Handle the first / last even in range more elegantly. Inline the entire function.
{ "domain": "codereview.stackexchange", "id": 44583, "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, mathematics, bitwise", "url": null }