text
stringlengths
1
2.12k
source
dict
javascript Better to use Number to parse a string to a number. Prefer id to uniquely identify DOM elements. Don't add comment that state the obvious. Generally good code is self documenting (meaningful naming, structured, etc...) and thus does not need comments Don't leave console output in release code. Use the spread operator ... to convert from iterable array like objects to array. Eg Array.from(checkboxes) is the same as [...checkboxes] Rewrite The rewrite adds a span to accept a single click event that is used to calculate the sum. The listener only iterates the checkboxes once per click to calculate the sum. The element used to display the sum is identified by its id rather than a className The code assumes that all the data set values are correctly setup and thus only need to check if the checkbox is checked. const checkboxes = document.querySelectorAll("input[type=checkbox]"); sumCheckboxes.addEventListener('click', () => { var total = 0; for (const {checked, dataset} of checkboxes) { total += checked ? Number(dataset.amount) : 0; } runningTotal.textContent = total; }); <span id="sumCheckboxes"> <input type="checkbox" data-amount="100"> 100 <input type="checkbox" data-amount="150"> 150 <input type="checkbox" data-amount="-50"> -50 <input type="checkbox" data-amount="10.50"> 10.50 <input type="checkbox" data-amount="0"> 0 </span> <div id="runningTotal"></div> Alternative implementation using a Array.reduce to sum the checkboxes. Note that the array like result of querySelectorAll needs to be converted to an array. This is done once using the spread operator.
{ "domain": "codereview.stackexchange", "id": 43875, "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 }
javascript const checkboxes = [...document.querySelectorAll("input[type=checkbox]")]; sumCheckboxes.addEventListener('click', () => { runningTotal.textContent = checkboxes.reduce((total, el) => total + (el.checked ? Number(el.dataset.amount) : 0), 0 ) }); <span id="sumCheckboxes"> <input type="checkbox" data-amount="100"> 100 <input type="checkbox" data-amount="150"> 150 <input type="checkbox" data-amount="-50"> -50 <input type="checkbox" data-amount="10.50"> 10.50 <input type="checkbox" data-amount="0"> 0 </span> <div id="runningTotal"></div>
{ "domain": "codereview.stackexchange", "id": 43875, "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 }
beginner, android, kotlin, graphics Title: Android + Kotlin advanced color picker (HSV and RGB) Question: For almost the past year, I have been working on a pixel art editor for Android. My pixel art editor was relying on an external library for its color picker. For 0.2.0, I wanted to change this by working on my own color picker. This was quite a challenging task, but I got it done in the end. Here were my objectives for the end user: Create a simple looking yet complex color picker RGB and HSV support Give the user the option of editing individual HSV and RGB channel values (similar to how it's done in GIMP/Photoshop) Spectrum mode Good performance, the user should not notice any delays when changing channel values Here were my objectives for the codebase: The codebase should be as clean/readable as possible There shouldn't be any duplicated pieces of code in the codebase The codebase should be optimized for performance The codebase isn't perfectly polished, but it's good enough that it's usable. Below is the finished code for the color picker (enjoy!): /* * Color Picker * Copyright 2022 therealbluepandabear * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.example.colorpicker import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics class ColorPicker @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private lateinit var colorPickerViewBitmap: Bitmap private lateinit var boundingRect: Rect private val circlePickerPaint = Paint().apply { style = Paint.Style.FILL } private val whiteCirclePaint = Paint().apply { style = Paint.Style.FILL color = Color.WHITE } private val hsvArr = FloatArray(3) private var prevHue = -1f private var hue = 0f private var prevSaturation = -1f private var saturation = 0f private var prevValue = -1f private var value = 0f private var prevRed = -1f private var red = 0f private var prevGreen = -1f private var green = 0f private var prevBlue = -1f private var blue = 0f private var currentChannel: ColorChannel = ColorChannel.Hue private var touchCoordinates = Coordinates(0, 0) private var colorAtTouchCoordinates = Color.WHITE private var scaleWidth = 0f private var scaleHeight = 0f private var pixelsArr: IntArray = IntArray(0) private var onColorTapped: (Int) -> Unit = { } fun setOnColorTapped(onColorTapped: (Int) -> Unit) { this.onColorTapped = onColorTapped } private fun getCurrentChannelValue() = when (currentChannel) { ColorChannel.Hue -> hue ColorChannel.Saturation -> saturation ColorChannel.Value -> value ColorChannel.Red -> red ColorChannel.Green -> green else -> blue } private fun getPrevChannelValue() = when (currentChannel) { ColorChannel.Hue -> prevHue ColorChannel.Saturation -> prevSaturation ColorChannel.Value -> prevValue ColorChannel.Red -> prevRed ColorChannel.Green -> prevGreen else -> prevBlue }
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics private fun getBitmapSpec(): Pair<Int, Int> = when (currentChannel) { ColorChannel.Hue -> Pair(101, 101) ColorChannel.Saturation, ColorChannel.Value -> Pair(361, 101) ColorChannel.Red, ColorChannel.Green, ColorChannel.Blue -> Pair(256, 256) else -> Pair(361, 201) } private fun resetChannelValues() { prevHue = -1f hue = 0f prevSaturation = -1f saturation = 0f prevValue = -1f value = 0f } private fun initPixelsArr() { pixelsArr = IntArray(colorPickerViewBitmap.width * colorPickerViewBitmap.height) } private fun updateColorAtTouchCoordinates() { colorAtTouchCoordinates = colorPickerViewBitmap.getPixel((touchCoordinates.x / scaleWidth).toInt(), (touchCoordinates.y / scaleHeight).toInt()) } private fun setScaleWidthHeight() { scaleWidth = measuredWidth.toFloat() / colorPickerViewBitmap.width.toFloat() scaleHeight = measuredHeight.toFloat() / colorPickerViewBitmap.height.toFloat() } fun updateHue(hue: Float) { this.hue = hue updateColorAtTouchCoordinates() invalidate() } fun updateSaturation(saturation: Float) { this.saturation = saturation updateColorAtTouchCoordinates() invalidate() } fun updateValue(value: Float) { this.value = value updateColorAtTouchCoordinates() invalidate() } fun updateRed(red: Float) { this.red = red updateColorAtTouchCoordinates() invalidate() } fun updateGreen(green: Float) { this.green = green updateColorAtTouchCoordinates() invalidate() } fun updateBlue(blue: Float) { this.blue = blue updateColorAtTouchCoordinates() invalidate() } fun updateCurrent(current: ColorChannel) { colorPickerViewBitmap.recycle()
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics fun updateCurrent(current: ColorChannel) { colorPickerViewBitmap.recycle() this.currentChannel = current val spec = getBitmapSpec() colorPickerViewBitmap = Bitmap.createBitmap(spec.first, spec.second, Bitmap.Config.ARGB_8888) resetChannelValues() initPixelsArr() setScaleWidthHeight() invalidate() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) if (::colorPickerViewBitmap.isInitialized) { colorPickerViewBitmap.recycle() } colorPickerViewBitmap = Bitmap.createBitmap(101, 101, Bitmap.Config.ARGB_8888) boundingRect = Rect(0, 0, measuredWidth, measuredHeight) initPixelsArr() setScaleWidthHeight() } private fun doOnTouchEvent(event: MotionEvent) { touchCoordinates.x = event.x.toInt() touchCoordinates.y = event.y.toInt() val coordinatesX = touchCoordinates.x / scaleWidth val coordinatesY = touchCoordinates.y / scaleHeight when { coordinatesX < 0 && coordinatesY < 0 -> { touchCoordinates.x = 0 touchCoordinates.y = 0 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(0, 0) } coordinatesX < 0 && coordinatesY >= colorPickerViewBitmap.height -> { touchCoordinates.x = 0 touchCoordinates.y = height - 1 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(0, colorPickerViewBitmap.height - 1) } coordinatesX >= colorPickerViewBitmap.width && coordinatesY >= colorPickerViewBitmap.height -> { touchCoordinates.x = width - 1 touchCoordinates.y = height - 1 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(colorPickerViewBitmap.width - 1, colorPickerViewBitmap.height - 1) }
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics coordinatesX >= colorPickerViewBitmap.width && coordinatesY < 0 -> { touchCoordinates.x = width - 1 touchCoordinates.y = 0 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(colorPickerViewBitmap.width - 1, 0) } coordinatesX < 0 -> { touchCoordinates.x = 0 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(0, coordinatesY.toInt()) } coordinatesX >= colorPickerViewBitmap.width -> { touchCoordinates.x = width - 1 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(colorPickerViewBitmap.width - 1, coordinatesY.toInt()) } coordinatesY < 0 -> { touchCoordinates.y = 0 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(coordinatesX.toInt(), 0) } coordinatesY >= colorPickerViewBitmap.height -> { touchCoordinates.y = height - 1 colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(coordinatesX.toInt(), colorPickerViewBitmap.height - 1) } else -> { colorAtTouchCoordinates = colorPickerViewBitmap.getPixel(coordinatesX.toInt(), coordinatesY.toInt()) } } onColorTapped.invoke(colorAtTouchCoordinates) invalidate() } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { doOnTouchEvent(event) } MotionEvent.ACTION_MOVE -> { doOnTouchEvent(event) } } return true }
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics return true } override fun onDraw(canvas: Canvas) { if (::colorPickerViewBitmap.isInitialized) { if (getCurrentChannelValue() != getPrevChannelValue()) { prevHue = hue prevValue = value prevSaturation = saturation prevRed = red prevGreen = green prevBlue = blue colorPickerViewBitmap.getPixels(pixelsArr, 0, colorPickerViewBitmap.width, 0, 0, colorPickerViewBitmap.width, colorPickerViewBitmap.height) for (i in pixelsArr.indices) { val x = i % colorPickerViewBitmap.width val y = (i / colorPickerViewBitmap.width) when (currentChannel) { ColorChannel.Hue -> { hsvArr[0] = hue hsvArr[1] = x / 100f hsvArr[2] = (100 - y) / 100f } ColorChannel.Saturation -> { hsvArr[0] = x.toFloat() hsvArr[1] = saturation / 100f hsvArr[2] = (100 - y) / 100f } ColorChannel.Value -> { hsvArr[0] = x.toFloat() hsvArr[1] = (100 - y) / 100f hsvArr[2] = value / 100f } ColorChannel.Red -> { pixelsArr[i] = Color.argb(255, red.toInt(), x, (255 - y)) } ColorChannel.Green -> { pixelsArr[i] = Color.argb(255, x, green.toInt(), (255 - y)) } ColorChannel.Blue -> { pixelsArr[i] = Color.argb(255, x, (255 - y), blue.toInt()) }
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics else -> { hsvArr[0] = x.toFloat() if (y < 101) { hsvArr[1] = y.toFloat() / 100f } else { hsvArr[1] = 1f } if (y < 101) { hsvArr[2] = 1f } else { hsvArr[2] = (200 - y).toFloat() / 100f } } } if (currentChannel.colorSpace == ColorChannel.ColorSpace.HSV) { pixelsArr[i] = Color.HSVToColor(hsvArr) } } } val spec = getBitmapSpec() colorPickerViewBitmap = Bitmap.createBitmap(pixelsArr, spec.first, spec.second, Bitmap.Config.ARGB_8888) canvas.drawBitmap(colorPickerViewBitmap, null, boundingRect, null) circlePickerPaint.color = colorAtTouchCoordinates canvas.drawCircle(touchCoordinates.x.toFloat(), touchCoordinates.y.toFloat(), 60f, whiteCirclePaint) canvas.drawCircle(touchCoordinates.x.toFloat(), touchCoordinates.y.toFloat(), 50f, circlePickerPaint) } } } About the code Throughout the code I utilize getPixels for good performance. I am weighing whether or not to switch to an NDK based implementation for iterating over the bitmap and whether or not the performance gains are worth it with the added cost of having to write lower level C/C++ code. I am also curious whether or not there are faster methods of doing what I want without an NDK based implementation. I only update the current HSV/RGB values in the onDraw method if the previous channel value is different than the current channel value. This is to ensure that when the user moves their finger across the canvas it doesn't update the channel values.
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics Performance I have used the measureTimeMillis function from Kotlin to measure the speed of the color picker. Whether or not this is a wise choice for measuring performance is something I'm also willing to get feedback on. Changing hue value (bitmap size: 101x101) Around 1000 onDraw iterations give an average time value of 8.412 milliseconds Changing saturation value (bitmap size: 361x101) Around 1000 onDraw iterations give an average time value of 28.878 milliseconds (not so good) Changing 'value (V)' value (bitmap size: 361x101) Around 1000 onDraw iterations give an average time value of 29.875 milliseconds (not so good) Changing red value (bitmap size: 256x256) Around 1000 onDraw iterations give an average time value of 3.068 milliseconds (this is fast because there is no HSV conversion) Changing green value (bitmap size: 256x256) Around 1000 onDraw iterations give an average time value of 2.92 milliseconds Changing blue value (bitmap size: 256x256) Around 1000 onDraw iterations give an average time value of 3.297 milliseconds The spectrum speed is irrelevant as should only be drawn once to the canvas. Screenshots Here are the two types of feedback I am looking for: I am interested to know how the code quality can be improved so it's as readable as possible. I am interested to know ways that I can optimize this code so it works as quickly as possible -- currently it's fast, but not extremely fast. If there are any issues with this question or room for improvement, do let me know. Answer: Reduce nesting of if's, that surround whole method, I suggest you instead use negative if's with return in onDraw. Or you can at least merge them into single if (or combine as I did): if (!(::colorPickerViewBitmap.isInitialized) || getCurrentChannelValue() == getPrevChannelValue()) return
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
beginner, android, kotlin, graphics onTouchEvent can be simplified. Either using in operator (you can also extract this set into static constant), or simpler when: if (event.actionMasked in setOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE)) { doOnTouchEvent(event) } //OR when (event.actionMasked) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { doOnTouchEvent(event) } } I would extract the contents of your for loop in onDraw. It's hard to keep track of what are local variables and what are class variables in this big method. This will nicely show, what are actual parameters in every loop (not giving example, because I don't know the parameters of the method :) ). You can use inline keyword on the extracted function to ensure performance won't get worse. Your updateXX methods with 1 parameter are basically setters. You can use kotlin properties to make it more obvious and easier to read your API. Duplicate last 2 lines in those updateXX methods, I would consider extracting them to a method. Consider putting integer values for colour numbers into data structures. Either structure, that can hold "hue, saturation, value, red,.." and then have 2 instances of "current" and "previous". Or a structure, that can hold 2 values - current and previous.
{ "domain": "codereview.stackexchange", "id": 43876, "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": "beginner, android, kotlin, graphics", "url": null }
c++, programming-challenge, time-limit-exceeded, c++20 Title: Find the best couple of an array in 1.5 seconds Question: I faced this exercise. Given a sequence \$S\$ (\$2 <= |S| <= 10^6\$) of numbers (\$1 <= S_x <= 10^7\$), determine \$max(abs(S_i - S_j) + abs(i -j))\$. Here is the solution I found: int main(){ ios::sync_with_stdio(false); int N; cin >> N; vector<int> S(N); for(int i = 0; i < N; i++) { cin >> S[i]; } int interestingness = 0; int val = 0; for (int i=0; i < N; i++){ int item = S[i]; for (int j=i+1; j < N; j++){ val = abs(item - S[j]) + j - i; if (val > interestingness){ interestingness = val; } } } cout << interestingness << endl; return 0; } But there is a problem. When the data in input increase their sizes, the program take more than 1.5s to run (about 1.5500s). How can optimize the program to make it run in 1.5 seconds? Answer: The posted algorithm is a brute force solution, computing the "interestingness" for all pairs of values. In programming competitions in general, a brute-force solution is unlikely to get full credit. It's important to look for alternative algorithms. Consider this linear algorithm: Process the items from left to right. Track the index of the most relevant low and high items, let's call them min_index and max_index, both initialized to 0. What I mean by "most relevant": a value simply being lower than the previous lowest value is alone not enough, we also need to account for the distance from the previous lowest value. Consider for example when we process a sequence that starts with the values 5 5 4. Even though 4 is lower than 5, we want to keep min_index = 0, because the longer distance makes the first 5 a better candidate for the low value to consider in computations. It is the most relevant low item. Starting with the second item, for each item at index i:
{ "domain": "codereview.stackexchange", "id": 43877, "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++, programming-challenge, time-limit-exceeded, c++20", "url": null }
c++, programming-challenge, time-limit-exceeded, c++20 Starting with the second item, for each item at index i: Update interestingness, if i - min_index + item - S[min_index] is higher. That is, the difference of the current item and the most relevant low item + the difference of these items is more interesting. Update interestingness, if i - max_index + S[max_index] - item is higher. The analogy here is the same. Update min_index if the current item is low enough, when offset by the relative distance from the last most relevant low item. Update max_index if the current item is high enough, when offset by the relative distance from the last most relevant high item. In code: int interestingness = 0; int min_index = 0; int max_index = 0; for (int i = 1; i < N; i++) { int item = S[i]; interestingness = max(interestingness, i - min_index + item - S[min_index]); interestingness = max(interestingness, i - max_index + S[max_index] - item); if (item < S[min_index] - i + min_index) { min_index = i; } else if (item > S[max_index] + i - max_index) { max_index = i; } }
{ "domain": "codereview.stackexchange", "id": 43877, "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++, programming-challenge, time-limit-exceeded, c++20", "url": null }
python, python-requests Title: Single API call with authentication in Python Question: I've written a small script for Zabbix to check the status of our ESXi Hosts. The request needs to be authenticated, so I went for this process: Read auth token from file If file does not exist, authenticate and store token into file Run request to get the information If I get permission denied, authenticate, store the token into file and try again Is there a better way to handle this? It bothers me a little to have the get_host_state() call twice, but placing the handling of the permission error into the function would make it recursive, which would then need additional parameters to prevent an endless loop and which would make it more complex. Could the functions themselves be improved? Notes: I'm aware that there are existing python modules to access the API, but I want to avoid the hassle and overhead of setting up a virtualenv and installing countless python modules on the Zabbix server for a simple check I disabled the traceback on purpose because I get the first line of the output of the script directly in Zabbix when an error occurs and this way I see directly the error instead of the pretty useless first line of the stacktrace. The response from the API is json, which is then parsed and handled in Zabbix. full script: import requests import sys vc_url = "vcenter.example.com" vc_user = "readonly@vsphere.local" vc_password = "aHR0cDovL2JpdC5seS8xVHFjd243Cg==" auth_store = "/tmp/zbx_esxi_connstate_auth" esx_name = sys.argv[1] session_id = '' sys.tracebacklimit = 0 def vc_auth(): response = requests.post(f"https://{vc_url}/api/session", auth=(vc_user, vc_password)) if response.ok: session_id = response.json() with open(auth_store, "w") as file: file.write(session_id) return session_id else: raise PermissionError("Unable to retrieve a session ID.")
{ "domain": "codereview.stackexchange", "id": 43878, "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, python-requests", "url": null }
python, python-requests def read_auth(): try: with open(auth_store, "r") as file: session_id = file.read() return session_id except FileNotFoundError: vc_auth() def get_host_state(): response = requests.get(f"https://{vc_url}/api/vcenter/host?names={esx_name}", headers={"vmware-api-session-id": session_id}) if response.status_code == 401: raise PermissionError("Authentication required.") if response.ok: print(f"{response.text}") else: raise ValueError(response.text) session_id = read_auth() try: get_host_state() except PermissionError: session_id = vc_auth() get_host_state() Here is the response from the API for the authentication request: HTTP/2 201 date: Thu, 15 Sep 2022 13:28:26 GMT vmware-api-session-id: 39efaf9c1c0ababc005ce63795b773bc content-type: application/json x-envoy-upstream-service-time: 169 server: envoy "39efaf9c1c0ababc005ce63795b773bc" Answer: Instead of using: esx_name = sys.argv[1] prefer the argparse library which is more flexible and allows for variable argument positioning. In read_auth you have: except FileNotFoundError but this is an exception that is preventable so it would be easier to just check that the file does exist eg: from os.path import exists if not exists(auth_store)... or better yet: from pathlib import Path if not Path(auth_store).is_file()
{ "domain": "codereview.stackexchange", "id": 43878, "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, python-requests", "url": null }
python, python-requests or better yet: from pathlib import Path if not Path(auth_store).is_file() Instead of doing plain plain requests.get or requests.post prefer requests.Session(). One benefit is that the session instance can contain predefined headers including the auth token, so there is no need to repeat those headers in every subsequent request. Just do session.post() etc, and you can still provide additional headers on a per request basis if needed. This will come in handy when and if you add more methods. Have you considered writing a small class to wrap this all up? The session ID could be made a class property with an initial value of None. There is one challenge in your program, it is that the token may expire after some time but you don't know when. Since the requests library has callbacks (called event hooks), it could be interesting to use the functionality to handle automatic and transparent re-authentication whenever needed. This could easily turn into another bigger challenge but that's an idea though. Have a look here for a possible solution: Python Requests - retry request after re-authentication. Another option is to use the retry on failure capabilities of the requests lib. This is more advanced stuff and it requires you to tinker with HTTPAdapter but it's worth it for bigger projects surely. Let's note that response.ok actually does not match a HTTP/200 (OK) response: Returns True if status_code is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.
{ "domain": "codereview.stackexchange", "id": 43878, "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, python-requests", "url": null }
python, python-requests Source: Developer Interface It may be a convenient shorthand to handle both 200 and 201 though, as long as you are aware of how it works. You can also use predefined codes for HTTP errors, for example for 401: requests.codes.unauthorized and 201: requests.codes.created. Use response.status_code to get the actual HTTP response code. And you can indeed use requests.codes.ok if you really want to check for HTTP/200. Instead of using PermissionError it would make more sense to use the set of native requests exceptions. Or just use raise_for_status().
{ "domain": "codereview.stackexchange", "id": 43878, "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, python-requests", "url": null }
c++, performance, interview-questions, c++20 Title: Goats up hills II: revenge of the goat Question: This is a continuation of Goat racing up a hill (C++ hiring take-home) . This is an interview take-home challenge that has been translated to avoid compromising the company's question. Problem statement You are a goat that needs to race up a hill. Designated waypoint rocks on the hill must each be visited in sequence (only in the order provided) or skipped and a score penalty incurred. For the goat to get its balance, it must pause ten seconds on each rock. Travel between rocks occurs on a straight line at two metres per second. Coordinates and penalties per rock are all integral and exist in the open interval (0, 100). Rock designations are spatially unique*. The start rock at (0, 0) and the finish rock at (100, 100) are implied and not included in input. Minimise the total cost of the goat's chosen path, calculated as the sum of all time spent and all penalties incurred. Input is specified on stdin as one or more races followed by a final 0. Each race is specified by an integer n on one line - the number of rocks (excluding the start and finish) - followed by n lines, each an integer triple x y p, the coordinates of the rock and the penalty incurred if it is skipped. Output on stdout is a single line per race, the path cost to three digits after the decimal. *Problem statement promises uniqueness but is contradicted by sample input that contains duplicates, so algorithm must work equally well in the presence of duplicates. Test cases Input (sample_input_small.txt): 1 50 50 20 3 30 30 90 60 60 80 10 90 100 3 30 30 90 60 60 80 10 90 10 0 Output (sample_output_small.txt): 90.711 156.858 110.711
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 Output (sample_output_small.txt): 90.711 156.858 110.711 Implementation I have a long-winded explainer that I might not paste here, but suffice to say that the implementation is amortised O(n). I used C++ because I need to catch up on best practices for versions 11+. The current compiler invocation looks like g++ -Ofast -s -march=native -NDEBUG --std=c++20 -Wall -Wextra -pedantic It's pretty fast - for the biggest well-formed input of 9801 rocks, it executes in 5ms. For a randomly-generated input of 1,000,000 waypoints, it's about 54 ms. Review Any feedback welcome, but I'm particularly interested in idiomatic use of modern C++ and associated data structures, and performance. I am not satisfied with a number of things: Whereas this is much faster with the current heap approach than a prior iteration that used a multimap, the map was more elegant because it only required emplace and erase, not swapping. Consequences are numerous; I now need: assignment operators copy constructors mutable members special treatment of the case where the heap only contains one item
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 I'm sure there's a better way to do this; move semantics, rvalue references and auto constructors are still kind of black magic to me. I took the most relevant parts of the first review, which were quite helpful. In a larger project I'd certainly cut out the tests to their own translation unit, but for the time being I'm preserving this as a single-file application. To clarify some more: <algorithm> and <vector> were implied by other headers, and this does compile without them, but in a future version they will be reintroduced for better explicit dependency documentation. sqrt, push_heap and pop_heap being non-qualified references missing std:: was an oversight, and frankly I'm a little disappointed that g++ didn't complain at me for doing so. (Is there a compiler flag to enforce this more strictly?) Code #include <cassert> #include <charconv> #include <cmath> #include <fstream> #include <iomanip> #include <iostream> #include <queue> #include <ranges> using namespace std::string_view_literals; namespace { constexpr int delay = 10, // seconds speed = 2, // metres per second edge = 100; // metres /* These are theoretical bounds; we get narrower than this during the pruning step. We cannot use dist_min = 1, due to waypoints such as (4, 2) in sample_input_large.txt that violate the uniqueness constraint */ constexpr double dist_min = 0, dist_max = edge*std::numbers::sqrt2, time_min = dist_min / speed, time_max = dist_max / speed; constexpr std::errc success = std::errc(); double time_to(int dx, int dy) { assert(-edge <= dx); assert(dx <= edge); assert(-edge <= dy); assert(dy <= edge); // std::hypot(dx, dy) makes better use of the library but is much slower double time = sqrt(dx*dx + dy*dy) / speed; assert(!std::isnan(time)); assert(time_min <= time); assert(time <= time_max); return time; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 return time; } int coord_min(int x) { return std::min(edge-x, x); } int coord_max(int x) { return std::max(edge-x, x); } // Direct representation of waypoints parsed from the input class Waypoint { private: int x, y, penalty; public: Waypoint(int x, int y, int penalty = 0): x(x), y(y), penalty(penalty) { } Waypoint(const Waypoint &other): x{other.x}, y(other.y), penalty(other.penalty) { } double time_to(const Waypoint &other) const { return ::time_to(other.x - x, other.y - y); } double time_min() const { return ::time_to(coord_min(x), coord_min(y)); } double time_max() const { return ::time_to(coord_max(x), coord_max(y)); } void output(std::ostream &out) const { out << '(' << x << ',' << y << ") penalty=" << penalty; } bool is_sane() const { return x >= 0 && x <= edge && y >= 0 && y <= edge; } int get_penalty() const { return penalty; } Waypoint &operator=(const Waypoint &other) { x = other.x; y = other.y; penalty = other.penalty; return *this; } }; std::ostream &operator<<(std::ostream &out, const Waypoint &w) { w.output(out); return out; } // Parser to replace the quite-slow istream << method class WaypointReader { private: static const std::invalid_argument parse_error; const std::string body_mem; const std::string_view body_view; long pos = 0; public: WaypointReader(const std::string &body_str): body_mem(body_str), body_view(body_mem) { } static WaypointReader from_stream(std::istream &in) { std::stringstream incopy; incopy << in.rdbuf(); return WaypointReader(incopy.str()); }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 int get_case_size() { size_t next_pos = body_view.find('\n', pos), substr_len = next_pos - pos; std::string_view line = body_view.substr(pos, substr_len); const char *line_start = line.data(), *line_end = line_start + substr_len; pos = next_pos + 1; int size; std::from_chars_result r = std::from_chars(line_start, line_end, size); if (r.ec != success || r.ptr != line_end) throw parse_error; return size; } Waypoint get_next() { size_t next_pos = body_view.find('\n', pos), substr_len = next_pos - pos; std::string_view line = body_view.substr(pos, substr_len); const char *line_start = line.data(), *line_end = line_start + substr_len; pos = next_pos+1; int x, y, penalty; std::from_chars_result r = std::from_chars(line_start, line_end, x); if (r.ec != success) throw parse_error; r = std::from_chars(r.ptr+1, line_end, y); if (r.ec != success) throw parse_error; r = std::from_chars(r.ptr+1, line_end, penalty); if (r.ec != success || r.ptr != line_end) throw parse_error; return Waypoint(x, y, penalty); } }; const std::invalid_argument WaypointReader::parse_error("Invalid input line"); // A sidekick to Waypoint that includes optimiser data. Only one "visited" Waypoint is held // in memory at a time, but a small handful of OptimisedWaypoints are held in a working map. class OptimisedWaypoint { public: Waypoint waypoint; double cost_invariant, // Sum of invariant costs incurred by skipping from this waypoint cost_min; // Lowest possible cost incurred by skipping from this waypoint to anywhere
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 // cost_best is the cost of the optimal path from the beginning all the way here OptimisedWaypoint(const Waypoint &waypoint, double cost_best = 0): waypoint(waypoint), cost_invariant(cost_best - waypoint.get_penalty() + delay), cost_min(waypoint.time_min() + cost_invariant) { } OptimisedWaypoint(const OptimisedWaypoint &copy): waypoint(copy.waypoint), cost_invariant(copy.cost_invariant), cost_min(copy.cost_min) { } double cost_to(const Waypoint &visited) const { double time = visited.time_to(waypoint); return time + cost_invariant; } double cost_max() const { return waypoint.time_max() + cost_invariant; } void output(std::ostream &out) const { out << waypoint << " cost_inv=" << cost_invariant << " cost_min=" << cost_min; } bool is_sane() const { return waypoint.is_sane(); } OptimisedWaypoint &operator=(const OptimisedWaypoint &other) { waypoint = other.waypoint; cost_invariant = other.cost_invariant; cost_min = other.cost_min; return *this; } bool operator<(const OptimisedWaypoint &other) const { return cost_invariant < other.cost_invariant; } }; std::ostream &operator<<(std::ostream &out, const OptimisedWaypoint &ow) { ow.output(out); return out; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 // Erase all heap waypoints whose minimum cost is greater than to_exceed. to_exceed is the maximum cost of the // heap's front waypoint, having the lowest minimum cost of any optimised waypoint. void prune(std::vector<OptimisedWaypoint> &opt_heap, double to_exceed) { while (!opt_heap.empty()) { if (opt_heap.front().cost_min <= to_exceed) break; if (opt_heap.size() > 1) pop_heap(opt_heap.begin(), opt_heap.end()); opt_heap.pop_back(); } } double get_best_cost( const Waypoint &visited, const std::vector<OptimisedWaypoint> &opt_heap ) { double cost_best = std::numeric_limits<double>::max(); for (const OptimisedWaypoint &skip_from: opt_heap) cost_best = std::min(cost_best, skip_from.cost_to(visited)); assert(cost_best < std::numeric_limits<double>::max()); return cost_best; } double solve(WaypointReader &reader, int n) { int total_penalty = 0; const OptimisedWaypoint head(Waypoint(0, 0)); // Max-heap of optimised waypoints with the first element // guaranteed to have highest minimum possible skip-from cost std::vector<OptimisedWaypoint> opt_heap { head }; // The maximum acceptable cost, set as the maximum possible cost of the lowest-minimum-cost waypoint. // Any waypoints costing more than this are discarded. double cost_acceptable = std::numeric_limits<double>::max(), cost_front = head.cost_min; for (int i = 0; i < n; ++i) { Waypoint visited = reader.get_next(); assert(visited.is_sane()); total_penalty += visited.get_penalty(); double cost_best = get_best_cost(visited, opt_heap); OptimisedWaypoint new_opt(visited, cost_best); assert(new_opt.is_sane());
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 if (cost_acceptable >= new_opt.cost_min) { if (cost_front >= new_opt.cost_min) { cost_front = new_opt.cost_min; cost_acceptable = new_opt.cost_max(); // Only prune if the new waypoint has been accepted and has become the lowest-minimum-cost waypoint. // Otherwise, the cost bounds will not have changed. prune(opt_heap, cost_acceptable); } opt_heap.emplace_back(new_opt); push_heap(opt_heap.begin(), opt_heap.end()); } } static const Waypoint tail(edge, edge); double cost_best = get_best_cost(tail, opt_heap); // Since waypoint costs are calculated with a negative relative penalty, // compensate by adding the total penalty to get the true cost return cost_best + total_penalty; } void process_streams(std::istream &in, std::ostream &out) { constexpr std::ios::iostate mask = std::ios::failbit | std::ios::badbit; in.exceptions(mask); out.exceptions(mask); out << std::fixed << std::setprecision(3); WaypointReader reader = WaypointReader::from_stream(in); for (;;) { int n = reader.get_case_size(); if (n == 0) break; double time = solve(reader, n); out << time << '\n'; } } void compare(std::istream &out_exp, std::istream &out_act) { for (;;) { std::string time_exp, time_act; if (!std::getline(out_exp, time_exp)) { if (out_exp.eof()) break; throw std::ios::failure("getline"); } out_act >> time_act; std::cout << time_exp << " == " << time_act << std::endl; if (time_exp != time_act) { std::cerr << "Assertion failure" << std::endl; exit(1); } } }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 void test() { constexpr const char *cases[] = {"small", "medium", "large"}; for (const char *const case_name: cases) { std::stringstream out_act; { std::ostringstream fnin; fnin << "samples/sample_input_" << case_name << ".txt"; std::ifstream in; in.open(fnin.str()); process_streams(in, out_act); } std::ostringstream fnout; fnout << "samples/sample_output_" << case_name << ".txt"; std::ifstream out_exp; out_exp.exceptions(std::ios::badbit); out_exp.open(fnout.str()); out_act.seekp(0); compare(out_exp, out_act); } } void process_std() { std::ios::sync_with_stdio(false); // Critical to fast handling of stdin process_streams(std::cin, std::cout); } } int main(int argc, const char **argv) { try { if (argc > 1 && argv[1] == "-t"sv) test(); else process_std(); } catch (const std::exception &ex) { std::cerr << ex.what() << std::endl; return 1; } return 0; } Answer: I’m going to assume the algorithm works correctly, and focus on the code structure. So, let’s start at the top. using namespace std::string_view_literals; The literals namespaces are generally okay to expose globally via a using directive, but I would still suggest limiting them as much as possible, only putting them in function scopes. In this case, you use literally one string view literal, in main(), so I would put this line in main(). namespace {
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 I don’t really see the point of putting the entire program in an anonymous namespace. I assume your thinking is that this makes everything statically scoped, which means it can be aggressively inlined, but it doesn’t really make any difference in reality. Anything that can be inlined, will (assuming even a moderately decent optimizer), regardless of whether it’s statically scoped or not. All that really happens is (for example) Waypoint just becomes __secret_compiler_name::Waypoint, and is consequently mangled as such. That’s literally it. Nothing else happens. Nothing. So it’s really not worth doing. (If you’re thinking “but the names won’t be exported then!”… wrong. Imagine you have a class foo in an anonymous namespace in a translation unit, and a function in that translation unit throws an instance of foo. How could that be possible if foo were truly not exported from the translation unit?) In any case, it doesn’t really make a lot of sense to indent the entire contents of a namespace… and especially in a situation like this, when the content of the namespace is literally the entire program. All it does is cost you \$4 \times N\$ horizontal spaces of readability. For nothing. I would suggest not indenting code within a namespace. Even in this simple case with a simple namespace, it will give you 4 more horizontal spaces, but in a case with multiple nested namespaces, indenting every namespace gets pathological. constexpr int delay = 10, // seconds speed = 2, // metres per second edge = 100; // metres This is an anti-pattern. Declare only one variable per line. It’s not only more readable, it avoids whole classes of typo-created bugs. constexpr std::errc success = std::errc();
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 This kind of thing isn’t a good idea. This is an example of a coding quirk designed to coddle clueless coders while frustrating experienced coders… exactly the opposite of what you want to be doing, because the people who are going to find the bugs in your code are far more likely to be the experiences coders, so they’re the ones you want to make things easy for. For example, as someone who knows C++ fairly well, I just know that r.ec == std::errc{} is checking for success, as any moderately competent C++ coder does… but when I see r.ec == success, I have to stop, curse a bit, then search the entire freaking codebase for success (all while making sure it isn’t being shadowed in some sneaky way). These kinds of aliases don’t make code more readable, they make it less readable. If you really MUST use a success alias, because you just can’t stand that std::errc{} means success, then fine, but in that case, the alias should be scoped to the function, not global. At least in that case, reviewers don’t need to go hunting through the entire codebase to figure out your disguise. double time_to(int dx, int dy) { assert(-edge <= dx); assert(dx <= edge); assert(-edge <= dy); assert(dy <= edge); // std::hypot(dx, dy) makes better use of the library but is much slower double time = sqrt(dx*dx + dy*dy) / speed; assert(!std::isnan(time)); assert(time_min <= time); assert(time <= time_max); return time; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 return time; } This entire function doesn’t really make a lot of sense, because you already have a time_to() function in the Waypoint class… where it belongs… although, oddly, you have it call out to this function. That’s kinda back-asswards. The whole point of strong typing and encapsulation is that, assuming everything is done properly, you shouldn’t need to reduce everything to ints and doubles. And, in fact, the very structure of this function is pretty much screaming that it’s a bad idea. You shouldn’t need a wash of assert()s to validate the input. The input should be valid by default. There should be no possible way—assuming no shenanigans—to have dx and dy be out of range. When more than 2∕3 of the function is assert()s… that’s a sign that something is smelly. And if dx and dy are always in range, then there should be no possible way for time to be NaN or out of range. (Also, don’t put multiple statements on the same line.) int coord_min(int x) { return std::min(edge-x, x); } int coord_max(int x) { return std::max(edge-x, x); } These two functions are hinting at a failure in your abstraction, but let’s put a pin in that and come back to them later. class Waypoint { private: int x, y, penalty; public: Waypoint(int x, int y, int penalty = 0): x(x), y(y), penalty(penalty) { } Waypoint(const Waypoint &other): x{other.x}, y(other.y), penalty(other.penalty) { } // ... [snip] ... void output(std::ostream &out) const { out << '(' << x << ',' << y << ") penalty=" << penalty; } Waypoint &operator=(const Waypoint &other) { x = other.x; y = other.y; penalty = other.penalty; return *this; } }; std::ostream &operator<<(std::ostream &out, const Waypoint &w) { w.output(out); return out; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 All of the above can be simplified to this: struct Waypoint { int x; int y; int penalty = 0; // ... [snip] ... friend auto operator<<(std::ostream& out, Waypoint const& w) -> std::ostream& { out << '(' << w.x << ',' << w.y << ") penalty=" << w.penalty; return out; } };
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 First, note that I’ve ditched the output() function, and just made the stream inserter a friend. Also, a hidden friend. Second, I ditched the manual copy constructor and assignment. These serve no purpose, and in fact, defining them creates problems: it inhibits move operations, and now the copy ops are no longer trivial ops. The rule is to never define any of the copy constructor, copy assignment operator, move constructor, move assignment operator, or destructor unless you absolutely need to… and if you define any of them, you must define all of them. Third, and this will probably be the only controversial move, I made all the data members public. Here’s my rationale: If there is no class invariant that can be broken by fuggering with any of a class’s data members, then they should all be public. For example, consider a 3D point class with x, y, and z members. There is no possible way to “break” a point. No matter what value you set x to, it’s still a valid point. Doesn’t matter what y and z are. In other words, it is impossible to set any of the data members to any valid value and break the class, and not have a valid point. Thus, there is no reason to make those data members private. By contrast, consider a date class with year, month, day members. It is possible to break the class invariant and create an invalid date by—for example—setting the day to 30 when the month is February. In other words, it is possible to set one of the data members to a valid value (30 is a perfectly cromulent day value), yet break the class. To protect the class invariant, you can’t allow free access to the individual data members. Thus, those data members should be private. (See also here.)
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 Now let’s consider your way point class. It’s basically a 2D point plus a penalty value. As with the 3D point, there is no possible way to break the class invariant by messing with any of those individual data members. So long as you set any of x, y, or penalty to any valid value, the entire way point object is valid. Ah, but there’s a catch, right? There are invalid values for x, y, and penalty. Both x and y have to be between 0 and edge, right? And penalty can’t be less than zero, presumably. So while it is true that it is impossible to set any data member to a valid value and end up with an invalid way point… there are invalid values. So how do we guard against that? There are two options. Option 1 is less elegant. This is where you make all the data members private, and provide constructors and accessors to prevent invalid values. This… “works”, and is probably the “easy way”. It requires a lot more code in the class, and hence, a lot more testing of the class. But it’ll do the job. Option 2 is more interesting. Here’s where I call back to those coord_min() and coord_max() functions, and all those assert()s, and point out that there is an object in your abstraction screaming out to be noticed. You have values… specifically coordinates (for now!)… that are basically ints… but that must be restricted to certain value ranges. Right off the bat, that means you really need a coordinate_value type… you shouldn’t be using bare ints for things that are clearly not bare ints (because they must be restricted to a certain range). So, to start, you should have this: using coordinate_value = int;
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 That’s just the most absolute basic starting point. But with that, you should be defining things like Waypoint like this: struct Waypoint { coordinate_value x; coordinate_value y; penalty_value penalty; // ... etc. ... }; Now, using an alias of a bare int is only slightly better than using a bare int. So, the next step is this: class coordinate_value { int _value = /* optional sensible default */; public: constexpr coordinate_value() noexcept = default; // Explicit conversion from int. constexpr explicit coordinate_value(int v) : _value{v} { // Validate here. } // Implicit conversion to int. constexpr operator int() const noexcept { return _value; } };
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 And you can build it up from there with whatever else you need: comparisons, arithmetic operations, stream inserters/extractors, whatever. With that (and a similar class for penalty_value, your way point class is trivial, as shown above—just a simple struct with a few public members—yet is perfectly safe, and maximally efficient. You can’t possibly create an invalid way point, and you can’t make an extant way point invalid… so you can just always assume that your way point is valid. Which means you no longer need assert()s and other sanity checks all over the place. And, in fact, the compiler can leverage the knowledge that way points and their data are always valid (possibly with some help from you via something like the proposed [[assume(expr)]]) to do more aggressive optimizing. But, hang on a sec. We have coordinate_value, which is basically an int clamped to the range [0, 100]. And we also have penalty_value, which is basically an int clamped to the range [0, ∞] (well, not really infinity, but std::numeric_limits<int>::max(), but, yanno). So, what we really need is a clamped_value type, that might look something like this to start: // Some helper concepts that are just generally useful. template <typename T> concept character = std::same_as<T, char> or std::same_as<T, char8_t> or std::same_as<T, char16_t> or std::same_as<T, char32_t> or std::same_as<T, wchar_t>; template <typename T> concept number = std::integral<T> or std::floating_point<T> and (not character<T> and not std::same_as<T, bool>); template <number auto Min, number auto Max> requires std::same_as<decltype(Min), decltype(Max)> and (Min <= Max) class clamped_value { T _value = Min; public: constexpr coordinate_value() noexcept = default; // Explicit conversion from value. constexpr explicit coordinate_value(T v) : _value{std::move(v)} { // Validate here. }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 // Implicit conversion to value. constexpr operator T() const noexcept { return _value; } }; And you can jazz up that type as much you need, such as adding support for open and closed ranges, and special casing having no minimum or no maximum, or whatever. Getting this type right has such an enormous payoff, it probably deserves to be its own project. With that, coordinate_value becomes: using coordinate_value = clamped_value<0, edge>; And, of course, the way point class is just a struct with public coordinate_value (and penalty_value members), and everything Just Works™. Which turns all this: double time_to(int dx, int dy) { assert(-edge <= dx); assert(dx <= edge); assert(-edge <= dy); assert(dy <= edge); // std::hypot(dx, dy) makes better use of the library but is much slower double time = sqrt(dx*dx + dy*dy) / speed; assert(!std::isnan(time)); assert(time_min <= time); assert(time <= time_max); return time; } int coord_min(int x) { return std::min(edge-x, x); } int coord_max(int x) { return std::max(edge-x, x); } // Direct representation of waypoints parsed from the input class Waypoint { private: int x, y, penalty; public: Waypoint(int x, int y, int penalty = 0): x(x), y(y), penalty(penalty) { } Waypoint(const Waypoint &other): x{other.x}, y(other.y), penalty(other.penalty) { } double time_to(const Waypoint &other) const { return ::time_to(other.x - x, other.y - y); } double time_min() const { return ::time_to(coord_min(x), coord_min(y)); } double time_max() const { return ::time_to(coord_max(x), coord_max(y)); } void output(std::ostream &out) const { out << '(' << x << ',' << y << ") penalty=" << penalty; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 bool is_sane() const { return x >= 0 && x <= edge && y >= 0 && y <= edge; } int get_penalty() const { return penalty; } Waypoint &operator=(const Waypoint &other) { x = other.x; y = other.y; penalty = other.penalty; return *this; } }; std::ostream &operator<<(std::ostream &out, const Waypoint &w) { w.output(out); return out; } into something like this: struct waypoint { using coordinate_value = clamped_value<0, edge>; using penalty_value = clamped_value<clamp_minimum{0}>; coordinate_value x; coordinate_value y; penalty_value penalty; // Can be constexpr as of C++23. auto time_to(waypoint const& w) const { auto const dx = w.x - x; auto const dy = w.y - y; return std::sqrt((dx * dx) + (dy * dy)) / speed; } friend auto operator<<(std::ostream& out, Waypoint const& w) -> std::ostream& { out << '(' << w.x << ',' << w.y << ") penalty=" << w.penalty; return out; } }; (with the reusable clamped_value type separately defined in some other module/header, of course). And ironically, this much shorter code should be faster, because all the fundamental ops except construction are trivial. Oh, one more thing: Waypoint(const Waypoint &other): x{other.x}, y(other.y), penalty(other.penalty) { } The norm in C++ is to put the type modifier with the type… not the identifier. In other words: const Waypoint &other: this is C style. const Waypoint& other: this is C++ style. Waypoint const& other: also C++ style. // Parser to replace the quite-slow istream << method class WaypointReader { private: static const std::invalid_argument parse_error; const std::string body_mem; const std::string_view body_view; long pos = 0;
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 const std::string body_mem; const std::string_view body_view; long pos = 0; public: WaypointReader(const std::string &body_str): body_mem(body_str), body_view(body_mem) { } static WaypointReader from_stream(std::istream &in) { std::stringstream incopy; incopy << in.rdbuf(); return WaypointReader(incopy.str()); } int get_case_size() { size_t next_pos = body_view.find('\n', pos), substr_len = next_pos - pos; std::string_view line = body_view.substr(pos, substr_len); const char *line_start = line.data(), *line_end = line_start + substr_len; pos = next_pos + 1; int size; std::from_chars_result r = std::from_chars(line_start, line_end, size); if (r.ec != success || r.ptr != line_end) throw parse_error; return size; } Waypoint get_next() { size_t next_pos = body_view.find('\n', pos), substr_len = next_pos - pos; std::string_view line = body_view.substr(pos, substr_len); const char *line_start = line.data(), *line_end = line_start + substr_len; pos = next_pos+1; int x, y, penalty; std::from_chars_result r = std::from_chars(line_start, line_end, x); if (r.ec != success) throw parse_error; r = std::from_chars(r.ptr+1, line_end, y); if (r.ec != success) throw parse_error; r = std::from_chars(r.ptr+1, line_end, penalty); if (r.ec != success || r.ptr != line_end) throw parse_error; return Waypoint(x, y, penalty); } }; const std::invalid_argument WaypointReader::parse_error("Invalid input line");
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 const std::invalid_argument WaypointReader::parse_error("Invalid input line"); I’m truly baffled by this class. The comment says its purpose is to be faster than using multiple istream extraction operations, which… fine… but… the way it’s done is by reading the ENTIRE input into another stream… and then copying the contents of that stream into a string… and then copying that string into another string… all to eventually get a string view you can work with. I’m actually impressed that all that works out faster than using istream extractors (but not shocked, because the costs of locale-awareness in istreams is really high). I think you need to take a step back and rethink all this. First, you need a type to store each race, which is really just a vector of waypoints, but, again, this is C++, so you really need a bespoke type for this: class race { std::vector<waypoint> _waypoints; public: // ... etc. ... friend auto operator>>(std::istream& in, race& r) -> std::istream& { // ... TODO ... } }; With that, your actual main loop is just: for (auto r = race{}; (in >> r); ) { auto const best_time = race.solve(); out << best_time << "\n"; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 out << best_time << "\n"; } That’s it. You see, there’s no real reason to make the loading of multiple races efficient as a whole. Once loading a single race is as efficient as can be, you’re hardly going to notice the comparatively microscopic extra cost of loading additional races. Where the efficiency magic happens, then, is in that single race loading operation. And for that, all you need is this: friend auto operator>>(std::istream& in, race& r) -> std::istream& { // We put this here, outside of all loops, so we can reuse its memory. // In other words, in theory, the only time a reallocation will be // necessary is when we're reading a line that is longer than any // previously read line. Which should be a rare occurrence after the // first few lines. // // We could do even better by noting the maximum expected length of a // valid line, which would be "100 100 100\n", which is 12 chars, and // reserve that up front. (Though that's within SSO range.) auto line = std::string{}; if (std::getline(line, in)) { auto size = int{}; if (auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), size); ec != std::errc{}) { if (size == 0) { in.setstate(std::ios_base::failbit); return in; } // could do further validation of size and p here... auto waypoints = std::vector<waypoint>{}; waypoints.resize(size); for (auto& wp : waypoints) { if (not std::getline(line, in)) { in.setstate(std::ios_base::failbit); return in; } auto p_next_char = line.data(); auto const p_end = line.data() + line.size()
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 auto x = int{}; if (auto [p, ec] = std::from_chars(p_next_char, p_end, size); ec != std::errc{}) { // validate x here... p_next_char = p; if (p_next_char != p_end) ++p_next_char; // ignore space } else { in.setstate(std::ios_base::failbit); return in; } // exactly the same as above for y and penalty (yeah, // iostreams code is always ugly, verbose, and repetitive) wp = waypoint{x, y, penalty}; } r._waypoints = std::move(waypoints); } else { in.setstate(std::ios_base::failbit); return in; } } return in; } The above is fairly restrictive on the input format (just like your code), but I doubt you can get much faster than that. (Of course, if you are actually going to write an istream extractor, there is a lot you can do to avoid a lot of the repetition.) With that, you can throw the whole WaypointReader class out completely. But I’ll review it anyway. static const std::invalid_argument parse_error;
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 As with success, I really don’t see the point of this. Presumably, parse errors will be very rare… exceptionally rare, even… and when they happen, everything is about to come crashing down anyway, so what’s the point of bailing out of the program efficiently? For all valid and successful runs of the program you will never need this exception. So why pay the cost for it? Also, std::invalid_argument is not the correct exception to use in any case. std::invalid_argument is a logic error… meaning it signals an error in the logic of the program. (Specifically, an invalid argument was passed to a function.) But there is nothing wrong with the program… the problem here is that the program’s input data is bad. This is a run-time error. There isn’t really a standard error that is purpose specific for malformed input data, though you could use either std::runtime_error or std::ios_base::failure or, perhaps better, std::system_error with a domain-specific error code. const std::string body_mem; const std::string_view body_view;
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 Don’t make data members const. I know, I know, I’ve seen a lot of well-meaning but confused people spreading misinformation about how data members should be const. I’ve seen arguments about safety and correctness… which are silly, because if you want const data, you make the object const, not the object’s data members… and I’ve seen arguments about efficiency and optimization… which are flat-out wrong, and easily disproved. I’ve linked to the part of the core guidelines—peer-reviewed by the top C++ experts in the world, and edited by two of the best, including Bjarne Stroustrup himself—that explains why this is a bad idea. The other big problem here is having a std::string_view data member. That’s just juggling lit dynamite. std::string_view is what’s referred to by the experts as a “parameter-only type”, which means that it is really intended for use only as a function parameter, and using it for anything else is extremely dangerous. (Though, obviously having a local variable string view of a string that is in scope and unmodified (ie, const) for the entire scope is fine.) In this particular case, consider what would happen if you ever copied a WaypointReader class. You’d copy the string, but the string view would still be viewing the original string, not the copy. If the original now goes out of scope, boom, there goes your program. WaypointReader(const std::string &body_str): body_mem(body_str), body_view(body_mem) { }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 First, this constructor should be explicit. Second, when taking an object as a sink value—as you are here with the string—the best way to do it is to take it by value and move it. Consider what happens in this case. Somehow someone has constructed a string containing the input data… you take it by const&… and because it a const&, you have to copy it into body_mem. If you took it by value, you could move it into body_mem, which could be massively faster for very large strings, and save a lot of memory. static WaypointReader from_stream(std::istream &in) { std::stringstream incopy; incopy << in.rdbuf(); return WaypointReader(incopy.str()); } As I mentioned above, I’m actually impressed that this is noticeably faster than doing stream extractions manually, because what you’re doing here is copying an entire stream… and then again copying that entire stream’s data into a string. Yikes. If you are determined to read the entire stream into a string, well, there’s no way to avoid copying the entire stream of course. However, you can avoid the second copy, and just yank the string right out of the string stream, like so: return WaypointReader(std::move(incopy).str()); On to get_case_size(): size_t next_pos = body_view.find('\n', pos), substr_len = next_pos - pos; Oh, please don’t write code like this. This is just ghastly. There is absolutely no benefit of the above over: auto const next_pos = body_view.find('\n', pos); auto const substr_len = next_pos - pos; And the latter is much less bug-prone. (Also, for the record, it’s std::size_t. But there’s no reason not to just use auto.) std::string_view line = body_view.substr(pos, substr_len);
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 As far as I can tell, this (and the identical line in get_next()) is the only reason for body_view. But if all you want is a view of part of the string, you could just do: auto const next_pos = body_mem.find('\n', pos); auto const substr_len = next_pos - pos; auto const line = std::string_view{body_mem.data() + pos, substr_len}; Of course, that raises the question of whether you even need the view at all, since you just end up working with pointers anyway. You could just ditch the line view, and change the following (ghastly) line to get this: auto const next_pos = body_mem.find('\n', pos); auto const substr_len = next_pos - pos; auto const line_start = body_mem.data() + pos; auto const line_end = line_start + substr_len; And from there the rest of the function is unchanged. get_next() is almost the same, except there’s this: int x, y, penalty; First, don’t declare multiple variables like this. Second, don’t declare variables until you need them. You don’t need either y or penalty until later in the function. And third, avoid declaring variables like type name;. That is a dangerous pattern, because it leaves some variables uninitialized. You can get away with it here, because you go on to set those variables with std::from_chars(), but it’s still bad practice. Also, as an aside, reusing a std::from_chars_result seems a bit pathological. Those are intended to be throwaway objects that you check-and-discard… not the type of thing you usually truck around and reuse for 3∕4 of a function. Reusing variables is also an anti-pattern. class OptimisedWaypoint {
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 So this class is just an implementation detail of the solve algorithm; it doesn’t need to (and shouldn’t) be part of the public interface. For that reason, I wouldn’t bother spending too much time spiffing it up. (Indeed, personally I wouldn’t bother making a class at all. I’d just use a tuple<Waypoint, double, double>.) Everything that applied to Waypoint applies here: you don’t need the copy constructor or copy assignment operator. Since you don’t change the waypoint at any time after initialization, there is no need to check whether it’s “sane”; if it was sane at construction time, it will be sane always. // Erase all heap waypoints whose minimum cost is greater than to_exceed. to_exceed is the maximum cost of the // heap's front waypoint, having the lowest minimum cost of any optimised waypoint. void prune(std::vector<OptimisedWaypoint> &opt_heap, double to_exceed) { while (!opt_heap.empty()) { if (opt_heap.front().cost_min <= to_exceed) break; if (opt_heap.size() > 1) pop_heap(opt_heap.begin(), opt_heap.end()); opt_heap.pop_back(); } } I have to admit I have no idea what the logic here is. From the comment, and as far as I can tell from the actual code, all you’re doing is removing every way point whose minimum cost is above a certain value. Yet, bizarrely, you do so by checking the first element, and if that’s above the limit, you rearrange the entire data set to remove it… then do that again, checking the first element, and if it’s above the limit, rearranging the entire data set… and so on. Surely there’s a better way to do this. It seems like all you have to do is remove all costly way points, then remake the heap, like so: auto const num_erased = std::erase_if(opt_heap, [to_exceed](auto&& wp) { return wp.cost_min > to_exceed; });
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 // Only need to bother remaking the heap if something was actually erased. if (num_erased != 0) std::ranges::make_heap(opt_heap); Now if it actually turns out remaking the heap is more expensive than repeatedly popping, you can still do better by counting the number of offending way points first, then popping as many times as necessary: auto const n = std::ranges::count_if(opt_heap, [to_exceed](auto cost_min) { return cost_min > to_exceed; }, &Waypoint::cost_min); auto p_end = std::ranges::end(opt_heap); for (auto i = decltype(n){}; i != n; ++i) std::ranges::pop_heap(std::ranges::begin(opt_heap), p_end--); opt_heap.erase(p_end, std::ranges::end(opt_heap); Either way is probably both simpler and more efficient. (One wonders if you even need a heap in the first place. It seems like you could achieve the same effect, and probably more efficiently, by just sorting by the cost and using binary search algorithms. But, as I said, I’m not reviewing the algorithm, just the structure.) double get_best_cost( const Waypoint &visited, const std::vector<OptimisedWaypoint> &opt_heap ) { double cost_best = std::numeric_limits<double>::max(); for (const OptimisedWaypoint &skip_from: opt_heap) cost_best = std::min(cost_best, skip_from.cost_to(visited)); assert(cost_best < std::numeric_limits<double>::max()); return cost_best; }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 assert(cost_best < std::numeric_limits<double>::max()); return cost_best; } Is it ever possible for cost_to() to return std::numeric_limits<double>::max()? If not, then the assert() is unnecessary, because all it’s checking is assert(not opt_heap.empty()). In any case, you should avoid raw loops like this, and prefer algorithms. In this case, reduce() would probably be the best choice, if it were properly integrated with ranges: // Not C++20 code, unfortunately: auto const cost_best = std::ranges::reduce( opt_heap | std::views::transform([&visited](auto&& wp) { return wp.cost_to(visited); }), std::numeric_limits<double>::max(), [](auto c1, auto c2) { return std::min(c1, c2); } ); If you could do that, you could even use an execution policy like std::execution::par_unseq to possibly parallelize or vectorize the algorithm. But because the numerics algorithms haven’t been spiffied up yet, you’re stuck with accumulate(), and no reordering, parallelization, or vectorization: auto const cost_best = std::accumulate( std::ranges::begin(opt_heap), std::ranges::end(opt_heap), std::numeric_limits<double>::max(), [&visited](auto const& skip_from, auto cost) { return std::min(cost, skip_from.cost_to(visited)) }); There’s not much more to add for the rest of the code. I’ve already covered the important stuff (like doing input), and everything else is just going to be repeating stuff mentioned previously. Extension (2022-09-16) Anonymous namespaces and exported symbols So, the issue here is I claimed that things in anonymous namespaces can still be exported from translation units, and the OP called me on that, saying: Removing the namespace introduces an additional 9 entries in .symtab, including things like _Z5solveR14WaypointReaderi and _ZlsRSoRK8Waypoint. Those sure seem like exported class symbols to me, and they're very much absent from the program when compiled with the anonymous namespace.
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 The problem here is we’re talking about two different things. I was talking about C++ exports—that is, language-level exports—where symbols exported from one translation unit are visible in another. In C++, symbols are exported by default, unless you declare them static or put them in an anonymous namespace. Symbols from other translation units are imported using extern (for objects) or declarations (for classes/functions). (There also used to be a way to export templates, but that was removed in C++11.) What I was explaining was that even though using an anonymous namespace “hides” symbols from being accessed directly from other translation units, they’re still very much accessible indirectly. (I used the example of throwing an instance of a “hidden” class, but there are other ways, too.) What the OP is talking about is something entirely different, and completely unrelated. They probably used a tool like readelf or objdump or nm to inspect the generated executable, and saw a bunch of stuff in .symtab or .dynsym. Those are not C++ exports. Those are linker exports. In fact, they have no relation to C++ at all, and could have been generated by other languages. And, in fact, even when using C++, what gets generated has nothing at all to do with C++, but is rather a function of the linker (and compiler and optimizer, all working together). To prove the point, take the source code from the OP, put it in a file called src.cpp, and compile it with this command: g++ --std=c++20 -pedantic -Wall -Wextra -Ofast src.cpp Then list the symbols with: readelf -CWs a.out
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 Then list the symbols with: readelf -CWs a.out That shows you everything in .dynsym and .symtab. I have 86 entries in .dynsym, and 132 entries in .symtab. Nothing from the source code in the file is in .dynsym, so let’s focus on the entries in .symtab with “Waypoint”. You can do that with readelf -CWs a.out | grep Waypoint. This is what I get: 6: 0000000000004140 302 FUNC LOCAL DEFAULT 16 (anonymous namespace)::get_best_cost((anonymous namespace)::Waypoint const&, std::vector<(anonymous namespace)::OptimisedWaypoint, std::allocator<(anonymous namespace)::OptimisedWaypoint> > const&) 8: 000000000000a3a0 8 OBJECT LOCAL DEFAULT 28 guard variable for (anonymous namespace)::solve((anonymous namespace)::WaypointReader&, int)::tail 9: 000000000000a3a8 12 OBJECT LOCAL DEFAULT 28 (anonymous namespace)::solve((anonymous namespace)::WaypointReader&, int)::tail 11: 000000000000a3c0 16 OBJECT LOCAL DEFAULT 28 (anonymous namespace)::WaypointReader::parse_error
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 (For reference, that’s 1 function, and 3 global or function static variables. Only 2 “real” variables are exported: the WaypointReader::parse_error exception object, and tail in solve(). The “guard” variable is necessary because tail has to only be initialized once, even if the function is called multiple times; it’s basically just a (probably atomic) flag.) It’s important to understand that these symbols have no effect on the actual program. Their presence or absence does not make the program run any faster, or use any less memory while running. Maybe they affect the cost of the kernel loading the program—maybe that takes a little longer or uses more memory—but if you’re worried about that kind of cost… you probably should be coding in ASM and not C++. (To be clear, I’m pretty sure .symtab is not loaded into memory when a program is run, but I’m saying that its mere existence may require a little more work on the part of the loader to spot it and work around it. Not much work, but maybe non-zero.) It’s also important to understand that these symbols are actually only local symbols. They are in .symtab… not .dynsym. They are not “exported” in the sense that symbols exported from a shared library that you can call are. Now, as the OP noted, if you remove the anonymous namespace and compile again, you will now get 12 symbols with Waypoint. So, the anonymous namespace really matters, right? Wrong. Take the original code, and instead of using the compile command above, use this one: g++ --std=c++20 -pedantic -Wall -Wextra -O0 src.cpp
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 The only difference from the previous compile command is -O0 instead of -Ofast. Now try listing the symbols, and…: 24: 0000000000003b7e 49 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::Waypoint(int, int, int) 25: 0000000000003b7e 49 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::Waypoint(int, int, int) 26: 0000000000003bb0 55 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::Waypoint((anonymous namespace)::Waypoint const&) 27: 0000000000003bb0 55 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::Waypoint((anonymous namespace)::Waypoint const&) 28: 0000000000003be8 69 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::time_to((anonymous namespace)::Waypoint const&) const 29: 0000000000003c2e 67 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::time_min() const 30: 0000000000003c72 67 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::time_max() const 31: 0000000000003cb6 129 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::output(std::ostream&) const 32: 0000000000003d38 66 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::is_sane() const 33: 0000000000003d7a 17 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::get_penalty() const 34: 0000000000003d8c 58 FUNC LOCAL DEFAULT 16 (anonymous namespace)::Waypoint::operator=((anonymous namespace)::Waypoint const&) 35: 0000000000003dc6 45 FUNC LOCAL DEFAULT 16 (anonymous namespace)::operator<<(std::ostream&, (anonymous namespace)::Waypoint const&) 36: 0000000000003df4 82 FUNC LOCAL DEFAULT 16 (anonymous namespace)::WaypointReader::WaypointReader(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 37: 0000000000003df4 82 FUNC LOCAL DEFAULT 16 (anonymous namespace)::WaypointReader::WaypointReader(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) 38: 0000000000003e46 27 FUNC LOCAL DEFAULT 16 (anonymous namespace)::WaypointReader::~WaypointReader() …
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 I cut it short, but it was 130 symbols for me. So much for the anonymous namespace making any difference to what gets put in the symbol table. Now, you may say that was unfair, because I turned off all optimization. Okay. Fine. Try it with just -O instead: 13: 00000000000039aa 141 FUNC LOCAL DEFAULT 16 (anonymous namespace)::get_best_cost((anonymous namespace)::Waypoint const&, std::vector<(anonymous namespace)::OptimisedWaypoint, std::allocator<(anonymous namespace)::OptimisedWaypoint> > const&) 14: 0000000000003a38 33 FUNC LOCAL DEFAULT 16 std::_Vector_base<(anonymous namespace)::OptimisedWaypoint, std::allocator<(anonymous namespace)::OptimisedWaypoint> >::~_Vector_base() 16: 000000000000a3c0 16 OBJECT LOCAL DEFAULT 28 (anonymous namespace)::WaypointReader::parse_error 17: 000000000000a3a0 8 OBJECT LOCAL DEFAULT 28 guard variable for (anonymous namespace)::solve((anonymous namespace)::WaypointReader&, int)::tail 18: 000000000000a3a8 12 OBJECT LOCAL DEFAULT 28 (anonymous namespace)::solve((anonymous namespace)::WaypointReader&, int)::tail
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 So, 5 symbols, not 4 (as you get with -Ofast). I just used different optimization levels to prove the point, but any compiler/linker options could have any effect. (Give -fwhole-program a try without the anonymous namespace, for example.) What controls which symbols get put in the symbol table by the linker is a complex dance between the code, the compiler, the optimizer, and the linker. The anonymous namespace happens to work in your favour here (for this particular version of the compiler and linker)… but it is not actually controlling what does and does not end up in the symbol table. What actually controls that is the options you give to the compiler and linker (and, indirectly, the optimizer). Changing your C++ code to control what the linker puts in the symbol table is like an author changing the plot of their novel to work around the fact that the “W” key on their typewriter is faulty (“And the murderer is… William! No, wait, shit. Can’t type that name, so, uh, I guess Steve did it instead.”). Do not be a slave to the limitations of your tools. Just write good C++ code. It’s not only silly to uglify your code as an underhanded way of controlling the linker, it’s actually self-defeating, because maybe the next version of GCC will work in an entirely different way, making your hack at least pointless, and possibly making things worse. (Caveat: If you are targeting a specific compiler/linker, then okay, sure, fine, you can tweak your code to satisfy that. But understand that doing so may improve codegen for that particular compiler/linker, but actually make things worse for other tools. This comes up often when having to work around bugs in tools, too. It’s quite common that you have to write worse code to make older/buggy compilers work, instead of good code that has better codegen properties in newer/better compilers.) If you want to control what the linker generates… just control the linker directly. Don’t try to do so indirectly by warping your code.
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 In this particular case, what’s in .symtab has absolutely no relevance to how your program runs… but if you’re really bothered by the fact that there’s crap in there: just strip it out. Just add -s to your link command, or use strip. Problem solved. Never, ever use exit() I made a mental note to mention this, but then forgot about it. In compare() you call exit(1). Now, first, that should be std::exit(1). But the real problem is that std::exit() is extremely dangerous to use in C++, because it can cause destructors to not be run… which can be catastrophic. You should never, ever use std::exit() in a C++ program. And in this case, there’s no need for it anyway. Instead of: if (time_exp != time_act) { std::cerr << "Assertion failure" << std::endl; exit(1); }
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
c++, performance, interview-questions, c++20 you can just do: if (time_exp != time_act) throw std::runtime_error{"Assertion failure"}; That’s not only better, it’s also less code. Incidentally, “1” is not a portable exit code. The only portable return codes from main() are EXIT_SUCCESS, EXIT_FAILURE, and 0 (which means success, but is not necessarily the same as EXIT_SUCCESS). Miscellaneous other stuff auto operator<<(std::ostream& out, Waypoint const& w) -> std::ostream& This is trailing return style. It has nothing to do with the return type being ambiguous. In this case, it means the same thing as the “classic” function style: std::ostream& operator<<(std::ostream& out, Waypoint const& w) However, trailing return style has several benefits over the “classic” style (which is why they created it in the first place), and no real downsides (other than that it’s a few chars longer). As for the unused function warning comment… you are expecting too much of that warning. It isn’t a tool to detect functions that are never used in the program. It will only fire for functions that are absolutely and utterly impossible to be used anywhere other than the immediate scope they are in (and, obviously, aren’t used in that scope). In other words, it doesn’t mean “this function is never used”, it means “this function can never BE used”, which is subtly different, but different. In this case, it was firing because the anonymous namespace means that anything in that namespace cannot be called outside of the translation unit. So anything in that namespace that isn’t used in the translation unit cannot possibly be used… anywhere… ever. If you want to find actually unused functions (as in, not just “can’t possibly be used”, but also “could possibly be used, but isn’t”), you need to use a proper tool for that, like a static analyzer.
{ "domain": "codereview.stackexchange", "id": 43879, "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++, performance, interview-questions, c++20", "url": null }
go, aws-cdk Title: A Go endpoint to get all items from DynamoDB and return them as a JSON response Question: Let me start by stating that I am currently in the process of learning Go and AWS CDK. What better way to learn than building a Serverless Todo API!? Using the Go AWS CDK (v2) I have built my infrastructure using the following AWS components: API Gateway (HTTP) AWS Lambda (Go) DynamoDB All code is open-source. It is a Todo API, so I have a Task entity with some properties, these are: type Task struct { TaskId string `dynamodbav:"task_id" json:"task_id"` UserId string `dynamodbav:"user_id" json:"user_id"` Content string `dynamodbav:"content" json:"content"` CreatedAt string `dynamodbav:"created_at" json:"created_at"` IsDone bool `dynamodbav:"is_done" json:"is_done"` } So far, I only have one endpoint coded. It is the getitems endpoint. This endpoint is responsible for returning all tasks from the database, here is the code: package getitems import ( "context" "encoding/json" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue" "github.com/aws/aws-sdk-go-v2/service/dynamodb" "log" "net/http" "os" ) func GetItemsHandler(w http.ResponseWriter, r *http.Request) { const dynamodbTableNameEnvKey = "DYNAMODB_TABLENAME" dynamodbTableName, ok := os.LookupEnv(dynamodbTableNameEnvKey) if !ok { log.Fatalf("the %v variable was not set!", dynamodbTableNameEnvKey) } else { log.Printf("The %v variable is set to: %v", dynamodbTableNameEnvKey, dynamodbTableName) } log.Println("Running the GetItemsHandler!") // using the sdk's default configuration, loading additional config // and credentials values from the environment variables, shared // credentials, and shared configuration files cfg, err := config.LoadDefaultConfig(context.TODO())
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk if err != nil { log.Fatalf("unable to load sdk config, %v", err) } // using the config value, create the dynamodb client dynamodbService := dynamodb.NewFromConfig(cfg) var tasks []Task // build the required scan params scanInput := &dynamodb.ScanInput{ TableName: aws.String(dynamodbTableName), } response, err := dynamodbService.Scan(context.TODO(), scanInput) if err != nil { log.Printf("could not scan the dyanmodb table! error: %v", err) } else { err = attributevalue.UnmarshalListOfMaps(response.Items, &tasks) if err != nil { log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err) } } w.Header().Set("Content-Type", "application/json") jsonResponse, err := json.Marshal(tasks) if err != nil { log.Fatalf("Error happened in JSON marshal. Err: %s", err) } w.Write(jsonResponse) } Since I am new to Go, I suspect I am making some mistakes here, or perhaps I could improve things a little. The code right now "works", here is the response when I call the endpoint: [{ "task_id": "4d4b9d9f-760f-4f63-9b89-27750dfec9e2", "user_id": "aae30f8e-aabe-4e38-918f-0f5a2223f589", "content": "Clean the car", "created_at": "2022-09-12T14:44:03Z", "is_done": false }, { "task_id": "299c1283-5704-4170-8196-b43742007e4d", "user_id": "aae30f8e-aabe-4e38-918f-0f5a2223f589", "content": "Tidy the office", "created_at": "2022-09-12T14:42:38Z", "is_done": false }] Also, right now I have no tests and I'd like to know what should I be testing in this endpoint? And how can I write the tests (mocking ...etc). Right now, I have a handler_test.go file that simply has: package getitems import "testing" func TestHandler(t *testing.T) { got := "foo" want := "bar" if got != want { t.Errorf("got %q want %q", got, want) } }
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk if got != want { t.Errorf("got %q want %q", got, want) } } Answer: First up, I'll admit to being a pedantic arse at times, but there's a few things that just jump out (in an OCD triggering kind of way) that I'll cover first: There's some stylistic issues that kind of "show" that you're relatively new to golang. The official golang repo for the longest time had a list of code review recommendations/comments covering things beyond your standard gofmt stuff. One of those is naming, in particular stutter. You have a package called getitems. A package starting with a verb just doesn't make sense. Functions are verbs, packages are, well, ... packages. Collections of functions and types (verbs and nouns if you will). Changing the package "getitems" to package "items" makes a lot more sense, but then you have this GetItems function, which in turn leads to stutter in the form of: items.GetItems. This reads to me as "from items, get items". Why not simply have items.GetAll(), which would read as "get everything from items".
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk Moving on You are doing everything in a single handler function. Whether it be: getting config, connecting to a database, fetching data, converting/marshalling it, etc... This is really rather messy and above all: slow. It's much better to connect to the database in your main function, create a repository that takes this connection as a dependency, and expose some methods to get the data via this repository, and pass that on to your handler (which will be much more simplified as a result, and should only occupy itself with request/response actions). As an added bonus, you no longer need to load the config and establish a DB connection on every request. AFAIK, the dynamodb package can be used concurrently. Considering you are dealing with items (which seem to be simple task objects), You can just have the repo object interact with dynamodb, scan the results into a Task type you declare in yet another package that your handler and repository packages both import, and as far as your handler is concerned: this is what it needs: package handlers import ( "context" "encoding/json" "net/http" ) type Repo interface { GetAll() ([]*Task, error) GetByID(id string) (*Task, error) // etc... } type svc struct { repo Repo } func New(r Repo) *svc { return &svc{ repo: r, } } // GetItems. This is the handlers package, so GetItemsHandler is stutter func (s *svc) GetItems(w http.ResponseWriter, r *http.Request) { tasks, err := s.repo.GetAll() if err != nil { // write error response return } resp, err := json.Marshal(tasks) if err != nil { // again: handle error return } w.Header().Set("Content-Type", "application/json") w.Write(resp) }
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk This, to my eye, is a hell of a lot cleaner. It is also a lot easier to test. Simply mock the repository interface, inject the interface, and you can run tests where the repository returns the results you expect, an error, or no results at all, and ensure the handler behaves correctly. Because this handler can only marshal data returned by a dependency that returns a slice of Task objects, there's less errors to even consider. The list of maps unmarshalling is something handled by the repository, not the handler. The repository lives in its own package, so it handles errors at that point. It also means the handler can stay unchanged, should you move away from dynamodb. The repository would still expose the same methods, you'd just have to update its internals to cope with the new data source... As for testing, like I mentioned above: you can mock the dependencies, but doing this all by hand is a right PITA. Below is a bare-bones example of how you can write this repository package. I've replaced the dynamodb dependency with a more generic interface for brevity sake, but the principles remain the same: Testing & Mocking You have unit tests, which is great to see, but there's an issue IMO. A unit test, at its core, has to approach the code it tests as "here's input X, I expect output Y. Dependencies that are used along the way should be called with argument Z, etc...". Essentially, unit tests should cover the API the tested unit provides/exposes. Golang allows you to ensure you do this by adding a _test suffix to the package name: package foo import ( "errors" ) var ( InvalidSourceDataErr = errors.New("database returned incompatible data") ) // Database is the interface this package needs - go packages declare their own dependency interfaces type Database interface { Get() ([]any, error) // for example } type Data struct {} // some data-type this package deals with type Repo struct { db Database }
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk type Data struct {} // some data-type this package deals with type Repo struct { db Database } // New creates the instance the external world will use, pass in the dependency here (injection). Packages don't return interfaces in golang (generally speaking) func New(db Database) *Repo { return &Repo{ db: db, } } func (r *Repo) GetAll() ([]*Data, error) { all, err := r.db.Get() // get the data if err != nil { return nil, err } dat := make([]*Data, 0, len(all)) for _, v := range all { d, err := r.toData(v) if err != nil { return nil, err } dat = append(dat, d) // mapped to the expected type } return dat, nil } // converts data from DB (any) to the relevant type - error if fails // this should not be exposed to the outside world func (r *Repo) toData(v any) (*Data, error) { dm, ok := v.(map[string]any) if !ok { return nil InvalidSourceDataErr // can't map this } ret := Data{} // iterate over dm, map keys onto fields, if types don't match, return error return &ret, nil // mapping worked } For packages like this, you can use tools like mockgen to generate a mock Database interface like so: //go:generate go run github.com/golang/mock/mockgen -destination mocks/db_mock.go -package mocks your.module/path/to/foo Databse type Database interface { Get() ([]any, error) } Now you can test this package like this: package foo_test // _test suffix, so toData is not exposed even on the unit-test level import ( "testing" "your.module/path/to/foo" // import the package you're testing "your.module/path/to/foo/mocks" // import generated mocks "github.com/golang/mock/gomock" // mock stuff ) type testFoo struct { *foo.Repo ctrl *gomock.Controller db *mocks.MockDatabase // mocked dependency }
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk func getRepo(t *testing.T) testFoo { t.Helper() ctrl := gomock.NewController(t) db := mocks.NewMockDatabase(ctrl) return testFoo{ Repo: foo.New(db), // inject mock ctrl: ctrl, db: db, } } func TestNoData(t *testing.T) { repo := getRepo(t) defer repo.ctrl.Finish() // signals gomock to check if the expected calls to the mocked dependencies have indeed been made // we specify what call we expect to be made, how many times to make it, and what to return repo.db.EXPECT().Get().Times(1).Return(nil, nil) // no error, no data got, err := repo.GetAll() if err != nil { t.Fail("Expected no errors, got one") } if len(got) > 0 { t.Fail("Expected nothing to be returned") } } To check the output of the function, check out packages like require or assert, so you can just write stuff like: require.NoError(t, err) require.Empty(t, got) To test the private mapping function, you simply add tests where your mocked DB actually returns data: func TestInvalidData(t *testing.T) { repo := getRepo(t) defer repo.ctrl.Finish() repo.db.EXPECT().Get().Times(1).Return([]interface{}{1}, nil) // 1 is not a map... got, err := repo.GetAll() require.Error(t, err) // or specifically, we expect this error: require.Equals(t, foo.InvalidSourceDataErr, err) require.Empty(t, got) } func TestValidData(t *testing.T) { repo := getRepo(t) defer repo.ctrl.Finish() repo.db.EXPECT().Get().Times(1).Return([]interface{}{map[string]interface{}}, nil) // populate map with valid data got, err := repo.GetAll() require.NoError(t, err) // this should not produce an error require.NotEmpty(t, got) // check values in the result, should match what we passed in through the mock }
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
go, aws-cdk Bringing it all together So now we have: a handlers package, a repository package, and we have moved the initialisation of everything to the main function (ie we bootstrap everything at startup). Our main function would look something like this now: func main() { ctx, cfunc := context.WithCancel(context.Background()) defer cfunc() // add handler for kill/term signal to call cfunc cfg, err := config.LoadDefaultConfig(ctx) if err != nil { panic(err) // crash, log.Fatal, whatever } dyndb := dynamodb.NewFromConfig(cfg) repo := repository.New(dyndb) // create repo hdl := handlers.New(repo) // handler object // set up routing using `hdl.GetItems` for the route to get all etc.. } Now we have one place to set up everything, one place to handle config, handlers that just read requests, and write responses, and a repository that makes it very clear (and easy) to see what a given handler does. The overal code is more efficient (as we no longer re-connect to dynamodb on each request), very easy to test, and a lot easier to maintain. The trade-off is that there's a bit more code to write if all you have is a single handler function, but the moment you add basic things like getting tasks by user id or by task ID, there's less duplication overall...
{ "domain": "codereview.stackexchange", "id": 43880, "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": "go, aws-cdk", "url": null }
python, object-oriented, rock-paper-scissors Title: Rock, Paper, Scissors game in object-oriented Python Question: I would like to learn Python and (maybe...) someday become a developer. Nevertheless... I've written a small "Rock, Paper, Scissors" game. Can you please take a look at the code and write the feedback? All types of feedback is highly appreciated! import random from enum import Enum class Hand(Enum): ROCK = 1 PAPER = 2 SCISSORS = 3 class Player: def __init__(self, name, no_of_lives): self.name = name self._no_of_lives = no_of_lives self.is_alive = True @property def no_of_lives(self): return self._no_of_lives @no_of_lives.setter def no_of_lives(self, no_of_lives): self._no_of_lives = no_of_lives if self._no_of_lives == 0: self.is_alive = False class Game: def __init__(self): while True: try: no_of_lives = int(input('Please enter amount of lives: ')) if not 0 < no_of_lives <= 11: print('Not allowed number of lives. Please enter value between 1 and 10') else: break except ValueError: print("Ups! It seems that you did not enter the number. Please try again") self.computer = Player('Computer', no_of_lives) player_name = input("Please enter your name: ") self.player = Player(player_name, no_of_lives)
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors def check_result(self, player_action, computer_action): if player_action == computer_action: print('Draw! Please continue') elif player_action == Hand.ROCK and computer_action == Hand.SCISSORS: self.computer.no_of_lives -= 1 if self.computer.is_alive: print(f'{self.computer.name} chose {computer_action.name}. You won this part!') else: self.player.no_of_lives -= 1 if self.player.is_alive: print(f'{self.computer.name} chose {computer_action.name}. Computer won this part!') def take_action(self): action = input().upper() if action not in Hand.__members__.keys(): print("Unknown action.") else: computer_action = random.choice(list(Hand)) self.check_result(Hand[action], computer_action) def print_final_result(self): if self.player.is_alive: print(f"Congratulation {self.player.name}! You won with {self.player.no_of_lives} live(s) remaining.") else: print(f"Unfortunately. {self.computer.name} won with {self.computer.no_of_lives} live(s) remaining.") def start_game(self): print("""Let's start! Please select action:' - ROCK - PAPER - SCISSORS""") while self.computer.is_alive and self.player.is_alive: self.take_action() self.print_final_result() if __name__ == '__main__': print(""" Hello to the "Rock paper scissors" game! You will have opportunity to play with the computer. Each of you have 5 lives. Will you be able to win? Good luck! Let's start with selection of the amount of lives each player shall have. Please enter the number between 1 and 10. Each time someone is losing the amount of lives decrease. Draw will not change amount of lives. User won't receive additional live for winning. """)
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors while True: game = Game() game.start_game() print("Do you want to play one more time? Please enter 'YES' to continue") decision = input() if decision.upper() != 'YES': break ``` Answer: Welcome to codereview! First of all: that was quite good already! Your use of classes was appropriate making Hand an Enum was appropriate! You tried to make your functions short and gave them a descriptive name, which you didn't manage to do in all places, but the intent was already there! Formatting was good! Pyright was fully satisfied with the code! The choice of rock-paper-scissors to get to know OOP better was excellent! Not too difficult, but it introduces you to the important concepts. What would I improve?
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors Your startup message and the "make a choice" message each span multiple lines and make it hard to read within a function. Extract a constant for either of the two. Define a main method that you can put at the very top of the file. That way the entrypoint is more obvious when you first look at the file. "do you want to play one more time" can be a prompt for input(), which saves one line. As @Richard Neumann pointed out, Player.is_alive is closely tied to no_of_lives, and therefore doesn't need to be a field, but can be a property instead. That prevents you from having to set is_alive manually. show the flow of information. Game.__init__ currently asks the user for the number of lives per player. It would be better to ask that in main, and then forward that to Game. Furthermore, asking the player for the number of lives and the player name should be separate functions. You had a logic error: You ask for numbers between 1 and 10, but you allowed numbers up to 11. Use type hints. Optional here because of the limited complexity of the exercise, and it was very easy to guess the correct types, but they make your life so much easier when dealing with more complex code. Your try block in Game.__init__ is a bit too large. You want only the actual part that can fail in the try block. I would replace the while True loop in the main function with something more expressive. Reading while True I ask myself "How long is the loop going to continue?". If you use a bool and call it user_wants_to_play, the main loop becomes clearer. Asking the user if he wants to continue is another candidate for a function ask_wants_to_continue start_game is probably better called play_game, since you don't only start it, but the whole game happens there.
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors check_result does a lot more than the name implies. It determines the winner, and subtracts one life from the looser. Also you see that deducting one live from the computer and the player is exactly the same code, so this should be a method to avoid repetition (DRY principle) Same thing for the naming goes for take_action. This should be called play_round. There are no tests, which makes refactoring more difficult, because I cannot be sure that I did not break anything during refactoring. I have added tests using pytest, which is the de-facto standard test-framework in Python. The core logic of determining the winner is wrong, which you could have caught with tests. To run the tests, open a shell and type pytest [your script]. Return early where possible:
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors if action not in Hand.__members__.keys(): print("Unknown action.") else: computer_action = random.choice(list(Hand)) ... in cases like this you should just return early. That saves one level of identation in the code, and frees the programmer from keeping in mind why this indentation is there. Rule of thumb: the less indentation, the better. if action not in Hand.__members__.keys(): print("Unknown action.") return computer_action = random.choice(list(Hand)) ... Here is my final code. import random from enum import Enum from typing import Optional import pytest MAKE_CHOICE_MESSAGE = """Let's start! Please select action:' - ROCK - PAPER - SCISSORS""" STARTUP_MESSAGE = """ Hello to the "Rock paper scissors" game! You will have opportunity to play with the computer. Each of you have 5 lives. Will you be able to win? Good luck! Let's start with selection of the amount of lives each player shall have. Please enter the number between 1 and 10. Each time someone is losing the amount of lives decrease. Draw will not change amount of lives. User won't receive additional live for winning. """ def main(): print(STARTUP_MESSAGE) user_wants_to_play = True while user_wants_to_play: number_of_lives = ask_number_of_lives() computer = Player("Computer", number_of_lives) player = Player(input("Please enter your name: "), number_of_lives) game = Game(computer, player) game.play_game() user_wants_to_play = ask_wants_to_continue() def ask_wants_to_continue() -> bool: decision = input( "Do you want to play one more time? Please enter 'YES' to continue: " ) return decision.upper() == "YES" class Hand(Enum): ROCK = 1 PAPER = 2 SCISSORS = 3 class Player: def __init__(self, name: str, no_of_lives: int): self.name = name self._no_of_lives = no_of_lives
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors @property def no_of_lives(self) -> int: return self._no_of_lives @no_of_lives.setter def no_of_lives(self, no_of_lives: int): self._no_of_lives = no_of_lives @property def is_alive(self) -> bool: return self.no_of_lives > 0 def deduct_one_life(self): self.no_of_lives -= 1 if self.is_alive: print(f"{self.name} lost this part.") def ask_number_of_lives() -> int: no_of_lives = 0 while not 0 < no_of_lives <= 10: try: no_of_lives = int(input("Please enter amount of lives between 1 and 10: ")) except ValueError: print("Ups! It seems that you did not enter the number. Please try again") return no_of_lives class Game: def __init__(self, computer: Player, player: Player): self.computer = computer self.player = player def _determine_looser( self, player_action: Hand, computer_action: Hand ) -> Optional[Player]: if player_action == computer_action: print("Draw! Please continue") return None elif ( (player_action == Hand.ROCK and computer_action == Hand.SCISSORS) or (player_action == Hand.SCISSORS and computer_action == Hand.PAPER) or (player_action == Hand.PAPER and computer_action == Hand.ROCK) ): return self.computer return self.player def play_round(self): action = input().upper() if action not in Hand.__members__.keys(): print("Unknown action.") return computer_action = random.choice(list(Hand)) print(f"{self.computer.name} chose {computer_action.name}") looser = self._determine_looser(Hand[action], computer_action) if looser: looser.deduct_one_life()
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, object-oriented, rock-paper-scissors def print_final_result(self): if self.player.is_alive: print( f"Congratulation {self.player.name}! You won with {self.player.no_of_lives} live(s) remaining." ) else: print( f"Unfortunately. {self.computer.name} won with {self.computer.no_of_lives} live(s) remaining." ) def play_game(self): print(MAKE_CHOICE_MESSAGE) while self.computer.is_alive and self.player.is_alive: self.play_round() self.print_final_result() if __name__ == "__main__": main() @pytest.mark.parametrize( "player_hand, computer_hand, correct_looser", [ # draw [Hand.ROCK, Hand.ROCK, None], # computer looses [Hand.PAPER, Hand.ROCK, "computer"], [Hand.ROCK, Hand.SCISSORS, "computer"], [Hand.SCISSORS, Hand.PAPER, "computer"], # player looses [Hand.ROCK, Hand.PAPER, "player"], [Hand.PAPER, Hand.SCISSORS, "player"], [Hand.SCISSORS, Hand.ROCK, "player"], ], ) def test_check_result(player_hand, computer_hand, correct_looser): computer = Player("computer", 1) player = Player("player", 1) g = Game(computer, player) looser = g._determine_looser(player_hand, computer_hand) if looser: assert looser.name == correct_looser else: assert looser == correct_looser Otherwise: keep it up! That was good work already!
{ "domain": "codereview.stackexchange", "id": 43881, "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, object-oriented, rock-paper-scissors", "url": null }
python, performance, python-3.x, random, playing-cards Title: blackjack dealer hand generator Question: I wrote a piece of blackjack code - for dealer dealing cards to himself (python). My question is how can I make it more efficient, faster and neater. I ran it for 1.000.000 iterations and it took 14.7 second which is quite slow, I believe. import random deck = 4 * [2,3,4,5,6,7,8,9,10,10,10,10,11] random.shuffle(deck) dealer_hand = [] dealer_hand.append(deck.pop(0)) dealer_hand.append(deck.pop(0)) hit_on_soft_17 = True exit = False while not exit: if sum(dealer_hand) == 17 and hit_on_soft_17: exit = True for i, card in enumerate(dealer_hand): if card == 11: exit = False dealer_hand.append(deck.pop(0)) break if sum(dealer_hand) < 17: exit = False dealer_hand.append(deck.pop(0)) if sum(dealer_hand) > 21: exit = True for i, card in enumerate(dealer_hand): if card == 11: exit = False dealer_hand[i] = 1 break if sum(dealer_hand) < 22 and sum(dealer_hand) > 17: exit = True print(dealer_hand)
{ "domain": "codereview.stackexchange", "id": 43882, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, random, playing-cards", "url": null }
python, performance, python-3.x, random, playing-cards print(dealer_hand) Answer: Testing One million print(dealer_hand) statements executed in 14.7 seconds would be amazing. I'm running it as I write this answer and it has yet to finish. Please be clear on exactly what you are timing. pop deck.pop(0) is inefficient, since every element in the list must be copied to a new position. Consider instead using deck.pop() to remove a card from the other end of the deck. Alternately, you could use a deque, which allows O(1) insertion/removal from either end. Finally, you could create an iterator (it = iter(deck)) and use it to deal cards (next(it)); it doesn't actually remove the cards from deck, but iterates through them one-by-one. sum If the dealer holds [10, 8], then sum(dealer_hand) is computed 5 times in the loop! Each time, the same value is returned. You could compute this once at the top of the loop, dealer_total = sum(dealer_hand), and use that variable in subsequent tests. Chained conditionals if sum(dealer_hand) < 22 and sum(dealer_hand) > 17: could be written more succinctly and more efficiently as if 17 < sum(dealer_hand) < 22: Of course, if 17 < dealer_total < 22: is better still. Reserved identifiers exit() is a function ... or it was until you redefined it as a variable. Use a different identifier, like done, instead. Bug If hit_on_soft_17 = False, then once the dealer holds [10, 7] (or equivalent), none of the if conditions will be true, exit will remain False, and the loop will never end. PEP-0008 hit_on_soft_17 is a global constant, and should be named in UPPER_CASE like HIT_ON_SOFT_17. Commas should be followed by 1 space Use functions You should always organize your code into functions.
{ "domain": "codereview.stackexchange", "id": 43882, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, random, playing-cards", "url": null }
rust Title: Implement get_or_create() with Rust and Diesel Question: I just started learning Rust, and try to implement a function like Django's get_or_create. Now my implementation looks too verbose[ I hope that rust can be neater. Therefore, how can I implement this function in less verbose way? There is probably a way to shorten nested match constructions below? use log::warn; use diesel::prelude::*; use diesel::result; use crate::db::{get_connection, PgPool}; use crate::models::{NewUser, User}; pub fn get_or_create_user(pool: &PgPool, email: &str) -> User { use crate::schema::users; let new_user = NewUser { email }; let mut conn = get_connection(pool); let result = diesel::insert_into(users::table) .values(&new_user) .get_result(&mut conn); match result { Ok(user) => return user, Err(err) => match err { result::Error::DatabaseError(err_kind, info) => match err_kind { result::DatabaseErrorKind::UniqueViolation => { warn!( "{:?} is already exists. Info: {:?}. Skipping.", new_user, info ); // another query to DB to get existing user by email let user = user_by_email(pool, new_user.email); return user; } _ => { panic!("Database error: {:?}", info); } }, _ => { // TODO: decide how to deal with unexpected errors return User { id: 0, email: "".into(), }; } }, } } pub fn user_by_email(pool: &PgPool, user_email: &str) -> User { use crate::schema::users::dsl::*; let mut conn = get_connection(pool);
{ "domain": "codereview.stackexchange", "id": 43883, "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", "url": null }
rust let mut conn = get_connection(pool); let user = crate::schema::users::dsl::users .filter(email.eq(user_email)) .first(&mut conn) .unwrap(); return user; } Answer: welcome to the Rust community! get or create You may indeed make code readable by replacing multiple nested matches with a single match that has nested patterns. For example, we match on Err(DatabaseError(UniqueViolation, info)) and that grabs all errors that contain a DatabaseError variant of Diesel Error enum, with inner UniqueViolation variant of DatabaseErrorKind. We bind the second value within DatabaseError to info, so we can print the info super easy too. If, for example, the Error is something else than UniqueViolation, we fall through to the next match arm. The pattern sublanguage is like a language within a language -- you have to learn it and build your intuition about it. The result of our effort is super readable: match result { Ok(user) => return user, Err(DatabaseError(UniqueViolation, info)) => { warn!( "{:?} is already exists. Info: {:?}. Skipping.", new_user, info ); // another query to DB to get existing user by email user_by_email(new_user.email) } Err(DatabaseError(_, info)) => { panic!("Database error: {:?}", info); } _ => { // TODO: decide how to deal with unexpected errors User { id: 0, email: "".into(), } } } I had an idea that you may only build one query, which would use ON CONFLICT, and kill two birds with one stone. Unfortunately, Diesel dsl does not seem to support ON CONFLICT (...) DO NOTHING RETURNING *. Other concerns Syntax nitpick: let user = schema::users::dsl::users .filter(email.eq(user_email)) .first(&mut conn) .unwrap(); return user;
{ "domain": "codereview.stackexchange", "id": 43883, "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", "url": null }
rust You may just return the user value directly, replacing the above code with this: schema::users::dsl::users .filter(email.eq(user_email)) .first(&mut conn) .unwrap() Result The result is available on my github: https://github.com/pczarn/codereview/tree/81d3fcddd3921bf1b4df4bb347be5dcad3de743f/2022/9/get_or_create I cleaned up your code, migrated to sqlite for local testing and this is what I got: extern crate diesel; mod schema; use diesel::sqlite::SqliteConnection; use diesel::prelude::*; use dotenvy::dotenv; use std::env; use log::warn; use diesel::prelude::*; use schema::users; #[derive(Debug, Insertable)] #[diesel(table_name = users)] struct NewUser<'a> { email: &'a str, } #[derive(Queryable)] pub struct User { id: i32, email: String, } pub fn get_or_create_user(email: &str) -> User { use diesel::result::{Error::DatabaseError, DatabaseErrorKind::UniqueViolation}; let new_user = NewUser { email }; let mut conn = get_connection(); let result = diesel::insert_into(users::table) .values(&new_user) .get_result(&mut conn); match result { Ok(user) => return user, Err(DatabaseError(UniqueViolation, info)) => { warn!( "{:?} is already exists. Info: {:?}. Skipping.", new_user, info ); // another query to DB to get existing user by email user_by_email(new_user.email) } Err(DatabaseError(_, info)) => { panic!("Database error: {:?}", info); } _ => { // TODO: decide how to deal with unexpected errors User { id: 0, email: "".into(), } } } } pub fn user_by_email(user_email: &str) -> User { use schema::users::dsl::*; let mut conn = get_connection();
{ "domain": "codereview.stackexchange", "id": 43883, "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", "url": null }
rust let mut conn = get_connection(); let user = schema::users::dsl::users .filter(email.eq(user_email)) .first(&mut conn) .unwrap(); return user; } pub fn get_connection() -> SqliteConnection { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); SqliteConnection::establish(&database_url) .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) } fn main() { get_or_create_user("example@example.com"); get_or_create_user("example@example.com"); }
{ "domain": "codereview.stackexchange", "id": 43883, "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", "url": null }
beginner, datetime, reinventing-the-wheel, rust Title: Simple ISO date, time and datetime implementation Question: I am getting started with rust. To get familiar with the language I implemented a datetime library: main.rs mod datetime; use datetime::DateTime; use datetime::Date; use datetime::Time; fn main() { let date_time = DateTime::create(2022u16, 09, 17, 02, 53, 00); println!("Datetime: {}", date_time); println!("Date: {}", date_time.date); println!("Time: {}", date_time.time); let date = Date::new(2022u16, 09, 17); println!("Date: {}", date); let time = Time::new(03, 51, 00); println!("Time: {}", time); } datetime.rs use std::fmt; mod date; pub use self::date::Date; mod time; pub use self::time::Time; pub struct DateTime { pub date: Date, pub time: Time } impl DateTime { pub fn new(date: impl Into<Date>, time: impl Into<Time>) -> DateTime { DateTime { date: date.into(), time: time.into() } } pub fn create( year: impl Into<u16>, month: impl Into<u8>, day: impl Into<u8>, hour: impl Into<u8>, minute: impl Into<u8>, second: impl Into<u8> ) -> DateTime { DateTime::new(Date::new(year, month, day), Time::new(hour, minute, second)) } pub fn isoformat(&self) -> String { format!("{}T{}", self.date.isoformat(), self.time.isoformat()) } } impl fmt::Display for DateTime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.isoformat()) } } datetime/date.rs use std::fmt; pub struct Date { pub year: u16, pub month: u8, pub day: u8 } impl Date { pub fn new(year: impl Into<u16>, month: impl Into<u8>, day: impl Into<u8>) -> Date { Date { year: year.into(), month: month.into(), day: day.into() } } pub fn isoformat(&self) -> String { format!("{:0>4}-{:0>2}-{:0>2}", self.year, self.month, self.day) } }
{ "domain": "codereview.stackexchange", "id": 43884, "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": "beginner, datetime, reinventing-the-wheel, rust", "url": null }
beginner, datetime, reinventing-the-wheel, rust impl fmt::Display for Date { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.isoformat()) } } datetime/time.rs use std::fmt; pub struct Time { pub hour: u8, pub minute: u8, pub second: u8 } impl Time { pub fn new(hour: impl Into<u8>, minute: impl Into<u8>, second: impl Into<u8>) -> Time { Time { hour: hour.into(), minute: minute.into(), second: second.into() } } pub fn isoformat(&self) -> String { format!("{:0>2}:{:0>2}:{:0>2}", self.hour, self.minute, self.second) } } impl fmt::Display for Time { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.isoformat()) } } Since I'm completely new to rust, I'd like to have feedback on code style and proper use of language concepts. Answer: welcome to the Rust community! Your code is quite good. There are a couple areas where the code could be improved, but not by much. It would be helpful if you implement more code for review all at once, for example datetime parsing code. DateTime::create pub fn create( year: impl Into<u16>, month: impl Into<u8>, day: impl Into<u8>, hour: impl Into<u8>, minute: impl Into<u8>, second: impl Into<u8> )
{ "domain": "codereview.stackexchange", "id": 43884, "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": "beginner, datetime, reinventing-the-wheel, rust", "url": null }
beginner, datetime, reinventing-the-wheel, rust The function name is not descriptive. It is idiomatic to name constructors e.g. with_date_and_time. I do not like that your arguments are impl Into<u16> or impl Into<u8>. Why is it better to accept precisely u16 or u8 here? See the following error to figure out why. Very little convenience is lost -- the caller can do .into() if needed. // error[E0283]: type annotations needed // --> src/main.rs:17:16 // | // 17 | let time = Time::new("03".parse().unwrap(), "51".parse().unwrap(), "00".parse().unwrap()); // | ^^^^^^^^^ cannot infer type for type parameter `impl Into<u8>` declared on the associated function `new` // | // = note: cannot satisfy `_: Into<u8>` // note: required by a bound in `Time::new` let time = Time::new("03".parse().unwrap(), "51".parse().unwrap(), "00".parse().unwrap()); println!("Time: {}", time); Basically, impl Trait in argument position does not inform type inference. Some functions such as str::parse return generic results parameterized by a free parameter, so it may be best to guide inference. Accepting impl Trait in argument position is usually unidiomatic. Furthermore, impl Into<u16> is why you have to write 2022u16 and can't write just 2022. So we have: pub fn with_date_and_time( year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8 ) public fields My recommendation is to add accessor methods and make fields private. If you want to change inner representation someday, you wouldn't need to break backwards compatibility. This is important in library code. But in binary code, you may change representation without breaking other modules, so this is beneficial as well. pub struct Time { hour: u8, minute: u8, second: u8 } impl Time { fn hour(&self) -> u8 { self.hour } // .. }
{ "domain": "codereview.stackexchange", "id": 43884, "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": "beginner, datetime, reinventing-the-wheel, rust", "url": null }
beginner, datetime, reinventing-the-wheel, rust impl Time { fn hour(&self) -> u8 { self.hour } // .. } isoformat I recommend a better method name such as to_iso_format or to_rfc3339. The name to_rfc3339 is consistent with chrono's DateTime. more Your code is not formatted with rustfmt. I recommend cargo fmt. For lints, I recommend cargo clippy. github https://github.com/pczarn/codereview/tree/7a1952ec0bf9c5c813802becff27785ed57178de/2022/9/datetime edit Your impl Display allocates a String twice. It is better to implement isoformat that calls self.to_string() rather than the other way around. derive Debug Most library users expect types to implement Debug.
{ "domain": "codereview.stackexchange", "id": 43884, "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": "beginner, datetime, reinventing-the-wheel, rust", "url": null }
python, file, classes Title: A simple and fast library/code to store & manage variable data Question: I've been searching through the different ways to store data and found some helpful and actually great libs like: JSON XML And some neh: text file basic write and read some binary type data storing? some other database types... Yet still I didn't find an easy and light library with basic storing mechanism/way (In my whole search; tell me others if you know :) So I wanted to create a type of library to store and manage data in special file type extension which I call '.var'. The lib will provide access to all sorts of the specified file type data manipulation methods. lib pros: single light file lib faster than JSON, XML... Easily understood by humans and reads by robots/computers can be very flexible when commenting('--', '//', '#') or initializing a variable('tab', '=', ':') example '.var' file looks like: #This is a comment using '#' --This is a comment using '--' //This is a comment using '//' NAME alex IP = 127.0.0.1 port: 1024 lib py file code: from dataclasses import replace
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes class varFile: isKey_CaseSensitive = None varFileLocation = None varFileText = None varFileLines = None def __init__(self, file_location='', file_text='', isKey_CaseSensitive=False): self.varFileLocation = file_location self.varFileText = file_text self.isKey_CaseSensitive = isKey_CaseSensitive def SplitLines(self): self.varFileLines = self.varFileText.split('\n') #print(self.varFileLines) # used to output the list of 'varFileLines' def readVarFile(self, file_location=''): file = None if(file_location != ''):# if file_location parameter was provided file = open(file_location, "rt") else:# if file_location parameter was NOT provided file = open(self.varFileLocation, "rt") self.varFileText = file.read() file.close() self.SplitLines() def writeVarFile(self, file_location=''): file = None if(file_location != ''):# if file_location parameter was provided file = open(file_location, "wt") else:# if file_location parameter was NOT provided file = open(self.varFileLocation, "wt") file.read(self.varFileText) file.close() def getVarFileText(self):# also regenerates 'varFileText' from the list 'varFileLines' self.varFileText = '' for var_line in self.varFileLines: self.varFileText += var_line + '\n' return self.varFileText def getVarParts(self, var_line_text): if('=' not in var_line_text and ':' not in var_line_text and '\t' not in var_line_text): #check variable line if may not be properly formated raise Exception("varFile: var_line_text has no initializer(e.g. '=')\n" + "var_line_text: " + var_line_text) #three sections_parts: # 1 = key # 2 initializer
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes #three sections_parts: # 1 = key # 2 initializer # 3 value section_part='1' part_key='' part_initializer='' part_value='' for i in range(len(var_line_text)): if(section_part=='1'): if(var_line_text[i] != '=' and var_line_text[i] != ':' and var_line_text[i] != '\t'): part_key += var_line_text[i] else: #section_part='2' part_initializer=var_line_text[i] # here section part 2 is completed, then proceed to section part 3 section_part='3' elif(section_part=='3'): part_value+=var_line_text[i] return [part_key.strip(), part_initializer, part_value.strip()]
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes # # # HERE starts the ".var" file data mainpulation functions # # def getValueByKey(self, key): if(self.isKey_CaseSensitive==False):key=key.lower()#if option 'isKey_CaseSensitive' false, then the search will be case-INsensitive value = None for variable_line in self.varFileLines: variable_line = variable_line.lstrip()#trim line for unwanted starting space if(self.isKey_CaseSensitive==False):variable_line=variable_line.lower()#if option 'isKey_CaseSensitive' false, then the search will be case-INsensitive
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes if(variable_line.startswith(key)): #print(variable_line) value = self.getVarParts(variable_line)[2] break return value def getValueByLineNumber(self, line_number): return self.getVarParts(self.varFileLines[line_number-1])[2] def setValueByKey(self, key, value): for i in range(len(self.varFileLines)): if(self.isKey_CaseSensitive==False):#if option 'isKey_CaseSensitive' false, then the search will be case-INsensitive if(self.varFileLines[i].lower().startswith(key.lower())): self.varFileLines[i] = value break else:#else then the search will be case-sensitive if(self.varFileLines[i].startswith(key)): self.varFileLines[i] = value break self.getVarFileText(self)#regenerate 'varFileText' from the list 'varFileLines' def setValueByLineNumber(self, line_number, value): self.varFileLines[line_number-1] = value self.getVarFileText(self)#regenerate 'varFileText' from the list 'varFileLines' def getVarByLineNumber(self, line_number): return self.getVarParts(self.varFileLines[line_number-1]) def getAbsLineAt(self, line_number): return self.varFileLines[line_number-1] # absolute line (e.g. "name: alex" OR can be a comment "--this' a comment" ) def appendAbsLineAt(self, abs_line, line_number=0): if(line_number==0):#if 'line_number' is 0 then append to the end(this is a special case number) self.varFileLines.append(abs_line)
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes self.varFileLines.append(abs_line) else:# if 'line_number' is > 0 then make it at the specified position line (e.g. 'line_number' is 1, then it will be the fist line..., and so for 2, second line) self.varFileLines.insert(line_number-1, abs_line)
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes self.getVarFileText(self)#regenerate 'varFileText' from the list 'varFileLines' def replaceAbsLineByLineNumber(self, line_number, replace_with): self.varFileLines[line_number-1] = replace_with self.getVarFileText(self) def removeAbsLineByKey(self, key):# can be only used to remove variables(e.g. "name=alex") for i in range(len(self.varFileLines)): if(self.isKey_CaseSensitive==False):#if option 'isKey_CaseSensitive' false, then the search will be case-INsensitive if(self.varFileLines[i].lower().startswith(key.lower())): del self.varFileLines[i] break else:#else then the search will be case-sensitive if(self.varFileLines[i].startswith(key)): del self.varFileLines[i] break self.getVarFileText(self)#regenerate 'varFileText' from the list 'varFileLines' def removeAbsLineByLineNumber(self, line_number):# can be used to remove either variables(e.g. "name=alex") OR comments del self.varFileLines[line_number-1] self.getVarFileText(self)#regenerate 'varFileText' from the list 'varFileLines'
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes # no need for this any more since function 'appendAbsLineAt()' exists and is all comprehensive and shiny lol # var line (e.g. ['name'],[':'],['alex']) #def appendVarLine(self, var_line, line_number=''): # pass # # # HERE ends the ".var" file data mainpulation functions # # def convertValueToInt(self, value): return int(''.join(value.split())) def convertValueToBoolean(self, value): boolean_value = None if(value.lower() in ('true', 't', 'yes', 'y', '1')): boolean_value=True#if 'boolean_value' was detected as TRUE elif(value.lower() in ('false', 'f', 'no', 'n', '0')): boolean_value=False#if 'boolean_value' was detected as FALSE return boolean_value #not yet implemented! def convertValueToBytes(self, value): pass def clear():# note the function DOESNT clear the variable 'varFileLocation' varFile.varFileText = '' varFile.varFileLines = '' Reference file in github Interface using the lib interface/methods to print data: from varFile import varFile test_varFile = varFile('../test.var') test_varFile.readVarFile() #variable value is retrieved by its key(name), which is e.g. 'NAME' print('My name is ' + test_varFile.getValueByKey('NAME')) #variable value is retrieved by the line number, which is e.g. 7 print('My Ip is ' + test_varFile.getValueByLineNumber(7)) #entire variable line is retrieved by the line number, which is e.g. 8 print('\nfull variable line:\n' + test_varFile.getAbsLineAt(8)) Currently the lib is written in python only, but if you think it's good and worth using, I'll write it in different languages. The source is on GitHub. Answer: Incorrect Python Some parts of the code is incorrect Python, and will raise exceptions when executed. I guess you missed these because your tests don't execute these lines.
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes Calls like this, passing self as parameter, which is unexpected: self.getVarFileText(self) The self parameter should be removed. In writeVarFile, this line is most certainly an error: file.read(self.varFileText) The file.read function expects an int, and self.varFileText is a str. Suspicious Python In code like this: class VarFile: varFileLocation = None def __init__(self, file_location='', file_text='', isKey_CaseSensitive=False): self.varFileLocation = file_location foo = VarFile() Be aware that VarFile.varFileLocation and foo.varFileLocation are not the same thing. The first one is a class variable, the second is an instance variable. All the class variables in the posted code seem to be unintended. A related issue is this clear function inside the class: def clear(): varFile.varFileText = '' varFile.varFileLines = '' Since the function doesn't take self as argument, it looks like a class function, which some tools report as an error. I believe the intention was more like this: def clear(self): self.varFileText = '' self.varFileLines = '' Python style I suggest to read and follow PEP 8 – Style Guide for Python Code The posted code doesn't follow the style guide well, which makes it difficult to read. I call out a few bigger points, but please do read that doc and follow it. Classes should use PascalCase naming, for example VarFile Functions should use snake_case, for example read_var_file There should not be large blocks of blank lines Avoid foo == False, the idiomatic Python is to write not foo Always break the line after :, for example in if cond: pass Avoid redundant parentheses, for example in if (cond): Use inline comments sparingly. Most of not all inline comments in the posted code would be better on their own line. if (file_location != ''): should be written simpler as if file_location:
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes I suggest to use a code editor such as PyCharm, which has built in tools to re-format the code nicely, and also calls out practices and violations of PEP8. Consider encapsulation and information hiding A class should hide implementation details are not relevant for its users. It makes the API easier to understand, and it helps ensure the integrity of the class. These functions are for internal use, therefore they should have a name starting with _, to signal to readers that they are private: SplitLines, getVarFileText, getVarParts, and all the convert* functions. What are the interesting functions for users of the class? The ones that get or set values. Those are the only functions that should be non-private. Consider the essential data of a class The class has varFileText and varFileLines. Judging by their names, both could contain the relevant data parsed from the storage file, but which one is the canonical source? After reading the code, it turns out that self.varFileText is just a middle man: the get* methods use self.varFileLines as the source, and self.varFileText is repeatedly overwritten. There's no need for self.varFileText, remove it. The code will be simpler, it will be clear where the relevant data is. Consider the cost of flexibility The API allows different kinds of comment symbols, in the name of flexibility. Be aware that flexibility can lead to complexity, and to religious wars. The support for flexibility requires more code, more test code, and with that it opens opportunities for more bugs. Some users will prefer one commenting style over another, some will use inconsistent commenting style with or without reason. Style guides will emerge recommending one writing style over another. Religious wars. Sometimes it's good to have an opinion, and be unburdened by the responsibility of choice. I suggest to choose one commenting style to support. Whichever one. Use context manager for file operations
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes Whichever one. Use context manager for file operations The recommended idiom to work with files looks like this: with open(path) as fh: ...
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, file, classes When the code leaves the with block, the file will get closed correctly, and no need to call fh.close(). When not using with, you must remember to call fh.close(), and also to handle exceptions. It's a lot easier to just use with. Other issues file = None is unnecessary, remove it. This import is not used, remove it: from dataclasses import replace Don't use empty string to mean "not provided". It's better to use None for that. For example instead of this: def readVarFile(self, file_location=''): if file_location != '': # if file_location parameter was provided file = open(file_location, "rt") else: # if file_location parameter was NOT provided file = open(self.varFileLocation, "rt") self.varFileText = file.read() file.close() self.varFileLines = self.varFileText.split('\n') A better way to write would be (including some other suggestions above): def readVarFile(self, path=None): if not path: path = self.varFileLocation with open(path, "rt") as fh: self.varFileLines = fh.readlines() Instead of this: def getVarFileText(self): # also regenerates 'varFileText' from the list 'varFileLines' self.varFileText = '' for var_line in self.varFileLines: self.varFileText += var_line + '\n' return self.varFileText Use join: def getVarFileText(self): return '\n'.join(self.varFileLines) + '\n'
{ "domain": "codereview.stackexchange", "id": 43885, "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, file, classes", "url": null }
python, game, pygame, basic-lang Title: Conversion of ZX81 BASIC Game to Pygame Question: I got the idea for this code from an article on converting ZX81 BASIC to Pygame. Although some code was provided in the article, I implemented this myself. I'm pretty dubious about the approach of using nested for loops inside the main game loop to make the game work, but at the same time I'm curios to see how well the BASIC paradigm maps onto the more event driven approach of Pygame, and would like to convert other games listed here for example: http://www.zx81stuff.org.uk/zx81/tape/10Games so I'd welcome any comments on the pros and cons of this approach. Here's a few questions I have about my code: Is there somewhere I can put the exit code if event.type == pygame.QUIT where it will work during game rounds, without having to repeat the code elsewhere? How would this game be implemented if I were to avoid the use of for loops/ nested for loops? Are there any points of best practice for pygame/Python which I have violated? What improvements can you suggest, bearing in mind my purpose is to write good Pygame code while maintaining the "spirit" of the ZX81 games. Any input much appreciated. I'm also curious to see full listings implementing some of the ideas arising from my initial attempt. Listing below: import pygame import random import sys # Define colors and other global constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) TEXT_SIZE = 16 SCREEN_SIZE = (16 * TEXT_SIZE, 13 * TEXT_SIZE) NUM_ROUNDS = 5 def print_at_pos(row_num, col_num, item): """Blits text to row, col position.""" screen.blit(item, (col_num * TEXT_SIZE, row_num * TEXT_SIZE)) # Set up stuff pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption("Dropout") game_font = pygame.font.SysFont('consolas', TEXT_SIZE) # Create clock to manage how fast the screen updates clock = pygame.time.Clock() # initialize some game variables player_pos, new_player_pos, coin_row, score = 0, 0, 0, 0
{ "domain": "codereview.stackexchange", "id": 43886, "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, pygame, basic-lang", "url": null }
python, game, pygame, basic-lang # initialize some game variables player_pos, new_player_pos, coin_row, score = 0, 0, 0, 0 # -------- Main Program Loop ----------- while True: score = 0 # Each value of i represents 1 round for i in range(NUM_ROUNDS): coin_col = random.randint(0, 15) # Each value of j represents one step in the coin's fall for j in range(11): pygame.event.get() pressed = pygame.key.get_pressed() if pressed[pygame.K_RIGHT]: new_player_pos = player_pos + 1 elif pressed[pygame.K_LEFT]: new_player_pos = player_pos - 1 if new_player_pos < 0 or new_player_pos > 15: new_player_pos = player_pos # --- Game logic player_pos = new_player_pos coin_row = j if player_pos + 1 == coin_col and j == 10: score += 1 # --- Drawing code # First clear screen screen.fill(WHITE) player_icon = game_font.render("|__|", True, BLACK, WHITE) print_at_pos(10, new_player_pos, player_icon) coin_text = game_font.render("O", True, BLACK, WHITE) print_at_pos(coin_row, coin_col, coin_text) score_text = game_font.render(f"SCORE: {score}", True, BLACK, WHITE) print_at_pos(12, 0, score_text) # --- Update the screen. pygame.display.flip() # --- Limit to 6 frames/sec maximum. Adjust to taste. clock.tick(8) msg_text = game_font.render("PRESS ANY KEY TO PLAY AGAIN", True, BLACK, WHITE) print_at_pos(5, 0, msg_text) pygame.display.flip() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) if event.type == pygame.KEYDOWN: waiting = False Image of ZX81 listing:
{ "domain": "codereview.stackexchange", "id": 43886, "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, pygame, basic-lang", "url": null }
python, game, pygame, basic-lang Image of ZX81 listing: Answer: Fun and interesting. You have too many magic numbers. Things like 13 and 16 need constants. Better yet make those dimensions parametric. Don't leave code laying around in the global namespace. Move code to functions, and variables at least to parameters if not to a class. A class in this case is easy and clean. You have an important coordinate system error. TEXT_SIZE is not the pixel dimensions of your character! You have to call .size() on your font to get that. print_at_pos should take over responsibility for rendering via the font, since that's done in the exact same way every time. Once you have clearer variable names and add more functions, all of your comments can go away. Your if new_player_pos < 0 or new_player_pos > 15: is better-expressed by a compound expression using min/max. It's very important that you check for quit events during your main loop - currently your game cannot quit. You have another coordinate system bug - you allow the player to move off the screen and miss some coin match events, both because you ignore the width of the player's symbol string. Suggested import pygame from random import randrange BLACK = (0, 0, 0) WHITE = (255, 255, 255) TEXT_SIZE = 16 TEXT_ANTIALIAS = True TEXT_FOREGROUND = BLACK TEXT_BACKGROUND = WHITE PLAYER_SYMBOL = '|__|' PLAYER_WIDTH = len(PLAYER_SYMBOL) class DropoutGame: def __init__(self, n_rows: int = 11, n_cols: int = 16, n_rounds: int = 5, fps: int = 6) -> None: self.player_pos, self.coin_row, self.coin_col, self.score = 0, 0, 0, 0 self.n_rows, self.n_cols, self.n_rounds, self.fps = n_rows, n_cols, n_rounds, fps self.n_display_cols = self.n_cols self.n_display_rows = self.n_rows + 3 pygame.init() pygame.display.set_caption('Dropout')
{ "domain": "codereview.stackexchange", "id": 43886, "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, pygame, basic-lang", "url": null }
python, game, pygame, basic-lang pygame.init() pygame.display.set_caption('Dropout') self.game_font = pygame.font.SysFont('Consolas', TEXT_SIZE) self.char_w, self.char_h = self.game_font.size('W') screen_size = (self.n_display_cols*self.char_w, self.n_display_rows*self.char_h) self.screen = pygame.display.set_mode(screen_size) self.clock = pygame.time.Clock() def run(self) -> None: while self.play_rounds(): if not self.should_play_again(): break pygame.quit() def play_rounds(self) -> bool: self.score = 0 for i_round in range(self.n_rounds): self.coin_col = randrange(self.n_cols) for self.coin_row in range(self.n_rows): self.move() self.score += self.scored self.draw() self.clock.tick(self.fps) if self.should_quit: return False return True @property def should_quit(self) -> bool: for event in pygame.event.get(): if event.type == pygame.QUIT: return True return False def should_play_again(self) -> bool: self.print(y=self.n_rows//2, x=0, text='PRESS ANY KEY TO PLAY AGAIN') pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.KEYDOWN: return True def move(self) -> None: pressed = pygame.key.get_pressed() if pressed[pygame.K_RIGHT]: delta = 1 elif pressed[pygame.K_LEFT]: delta = -1 else: return self.player_pos = max(0, min(self.n_cols - PLAYER_WIDTH, self.player_pos + delta))
{ "domain": "codereview.stackexchange", "id": 43886, "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, pygame, basic-lang", "url": null }
python, game, pygame, basic-lang self.player_pos = max(0, min(self.n_cols - PLAYER_WIDTH, self.player_pos + delta)) @property def scored(self) -> bool: return ( self.player_pos <= self.coin_col <= self.player_pos+PLAYER_WIDTH and self.coin_row == self.n_rows-1 ) def draw(self) -> None: self.screen.fill(WHITE) self.print(y=self.n_rows-1, x=self.player_pos, text=PLAYER_SYMBOL) self.print(y=self.coin_row, x=self.coin_col, text='0') self.print(y=self.n_display_rows-1, x=0, text=f'SCORE: {self.score}') pygame.display.flip() def print(self, y: int, x: int, text: str) -> None: rendered = self.game_font.render(text, TEXT_ANTIALIAS, TEXT_FOREGROUND, TEXT_BACKGROUND) self.screen.blit(rendered, (x*self.char_w, y*self.char_h)) if __name__ == '__main__': DropoutGame().run()
{ "domain": "codereview.stackexchange", "id": 43886, "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, pygame, basic-lang", "url": null }
c++, performance, reinventing-the-wheel, cryptography, c++20 Title: Improving the speed of an MD5 implementation from scratch in C++ Question: I wrote an implementation of the MD5 hashing algorithm from scratch in C++, following the original RFC: https://www.ietf.org/rfc/rfc1321.txt . It works as expected, and the outputs match all the test cases mentioned in the RFC as well. I timed this for a couple of test cases, and it seems it takes around 0.25 msecs on average for a 26 character text (or 1 block essentially). This, admittedly, is not bad. But given that I was able to scrounge together an implementation of the same in Python relatively easily, which is actually faster (nanosecond range), I feel there are obviously some implementation mistakes or inefficiencies that are present here. This is literally the first C++ program that I have written (except for hello world of course), as I am primarily a Python developer, so I'm looking for ways to improve the code structure and efficiency. I would like to know where I could improve here, and what exactly is causing it to be slow in the first place. Please excuse my naming conventions. Just borrowed from Python! I would also like to point out that there are possibly some things in this code that are specifically only C++20. Here is the code: pstl_cryptography.h #pragma once #include <string> #include <array> #include <vector>
{ "domain": "codereview.stackexchange", "id": 43887, "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++, performance, reinventing-the-wheel, cryptography, c++20", "url": null }