question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
79,564,155 | 2025-4-9 | https://stackoverflow.com/questions/79564155/how-to-decorate-the-enter-and-exit-instance-methods | I would like to use the decorator deco to reshape the __enter__ and __exit__ instance methods. The code runs but the wrapper is not executed in the with section. Find the actual output below, followed by expected output and finally the code. Current output: In __init__ ------------------- In __enter__ -----------------... | The short answer As others have pointed out, the problem is that it's the __enter__ and __exit__ methods of the class that will get called, not those of the instance. But you said this is for testing purposes, and you don't want the decorators to be there permanently, so the solution is to alter the class methods tempo... | 2 | 0 |
79,565,465 | 2025-4-9 | https://stackoverflow.com/questions/79565465/python-subprocess-run-error-filenotfounderror | I am currently creating an application in python which uses the Youtube Data API and includes the following code block: import os from subprocess import run os.chdir(os.path.dirname(__file__)) command = 'python3.10 uploadYoutube.py --file="blank.mp4" --title="Blank" --description="THIS IS YOUR BLANK VIDEO" --keywords="... | as Adon Bilivit stated, this is due to the first argument you pass to the command subprocess.run. As stated in the subprocess documentation, when you provide a string there is a platform dependent interpretation. On POSIX, providing a string is interpreted as the name or path of the program to execute. Solution The f... | 1 | 3 |
79,565,937 | 2025-4-10 | https://stackoverflow.com/questions/79565937/click-help-text-shows-dynamic-when-an-option-has-the-default-set-to-a-lambda | I have this code in a CLI: @click.option( "--username", default=lambda: os.environ.get("USER", None), show_default=True, help="User name for SSH configuration.", ) When I invoke the CLI with --help option, I get this: --username TEXT User name for SSH configuration. [default: (dynamic)] Is there a way to make click ... | The Option.get_default method has a call option to call the default value when it's a callable. The option is True by default but is passed False only when generating help, so you can make the help generator call the the callable simply by overriding Option.get_default with a wrapper that forces the call option to be T... | 2 | 2 |
79,565,568 | 2025-4-10 | https://stackoverflow.com/questions/79565568/interoperability-between-two-crates-with-pyo3-bindings | I have two Rust crates lib1 and lib2, for which I use pyo3 to generate bindings. I import the crate lib1 in lib2. In a separate crape lib1-py, I create a python class MyClass, and in lib2, I try to use MyClass as a parameter for a Python function, using : fn foo(param: PyRef<MyClass>) I separately use maturin to build... | In general, this is impossible. Rust does not even guarantee MyClass will have the same memory layouts in both builds. It is possible to design lib1-py to allow this, though. For example, if the entirety of MyClass is #[repr(C)] (that is, it and all of its fields are, recursively), you can take a Bound<PyAny> and conve... | 2 | 1 |
79,565,260 | 2025-4-9 | https://stackoverflow.com/questions/79565260/dynamically-script-conditional-statements-in-python | I have a fixed table with (name,value) pairs that are known. I.e.: Bob.age: 47 Bill.age: 44 Jane.age: 36 Steve.age: 22 I'd like a user to be able to write in a json file, a statement to dynamically generate a conditional statement to evaluate to true/false for a report: (Bob.age == Jane.age) || (Bob.age < Bill.age) I... | There are many template languages implemented in Python. There are whole list of "tried and tested libraries": https://www.fullstackpython.com/template-engines.html , https://wiki.python.org/moin/Templating . Additionally, you can execute arbitrary strings as python with eval. Sky is the limit. An example solution woul... | 1 | 2 |
79,562,908 | 2025-4-8 | https://stackoverflow.com/questions/79562908/permutations-problem-on-python-i-cant-understand-where-i-am-wrong | Hi I have made this code. Τhe code generates all binary permutations of a string with a given number of zeros and ones, checks for adjacency based on a specific homogeneity condition (differing by exactly two consecutive bits), builds a graph of these permutations, and prints the graph with nodes sorted by their decima... | You claim to expect 46 and 15 to be adjacent in the graph. But 46 represents 101110 and 15 represents 001111. Those are not adjacent by the adjacency rule that you've described (and coded). Therefore either your expectation is wrong, or your adjacency rule is wrong. (Spot checking, 23 represents 010111, which indeed sh... | 1 | 3 |
79,562,856 | 2025-4-8 | https://stackoverflow.com/questions/79562856/python-flask-server-405-error-for-a-specific-path-when-hosted-on-azure-works-fi | I'm building a flask app to process images uploaded from a mobile device, before sending results back to the mobile app. I've successfully deployed the flask app on Azure, and can confirm it works with certain paths, /test for one. The path my mobile app uses to upload an image, is /upload-data. When I run my flask app... | I notice you're making your requests over HTTP not HTTPS, I imagine Azure is stricter on the POST requests rather than GET due to encrypting the body of the request. Make sure you have HTTPS only turned off in Azure Portal. | 1 | 3 |
79,561,979 | 2025-4-8 | https://stackoverflow.com/questions/79561979/regex-replace-numbers-between-to-characters | I have a string 'manual__2025-04-08T11:37:13.757109+00:00' and I want 'manual__2025-04-08T11_37_13_00_00' I know how to substitute the : and + using 'manual__2025-04-08T11:37:13.757109+00:00'.replace(':','_').replace('+','_') but I also want to get rid of the numbers between the two characters '.' and '+'. I'm using p... | You could do a regex substitution using re.sub: >>> import re >>> s = 'manual__2025-04-08T11:37:13.757109+00:00' >>> new_s = re.sub(r'\.\d+(?=\+)', '', s).replace(':', '_').replace('+', '_') >>> new_s 'manual__2025-04-08T11_37_13_00_00' | 1 | 1 |
79,561,367 | 2025-4-8 | https://stackoverflow.com/questions/79561367/how-to-disable-robot-framework-automatically-logging-kubelibrary-response-to-deb | I am utilizing robot framework's KubeLibrary to interact with my k8s cluster. By default, any function and response is automatically logged to DEBUG in robot framework, meaning that it's response will be visible in the log.html that robot framework generates. I want to disable this logging for some parts of my code or ... | I've been dealing with this exact issue in Robot Framework + KubeLibrary. After trying several approaches, here's what actually worked for me: import logging from contextlib import contextmanager @contextmanager def suppress_debug_logging(): """Temporarily suppress DEBUG level logging to keep secrets out of Robot logs.... | 1 | 3 |
79,561,773 | 2025-4-8 | https://stackoverflow.com/questions/79561773/how-to-export-data-frame-with-color-to-csv | I want to add color to cells of Status Pass and Fail. I tried following code it will print a colored data frame but exported csv was not colored. And when I applied two rules (green and red), only green shows. df = pd.DataFrame([{'Status':'Pass', 'Value': '0'}, {'Status':'Pass', 'Value': '1'}, {'Status':'FAIL', 'Value'... | You can't export colors to a text/CSV file. Furthermore, you ran your command after to_csv, which wouldn't affect it if this was supported. You can export as xlsx by chaining the style.map to to_excel: ( df.style.map( lambda x: 'background-color: green' if x == 'Pass' else '', subset=['Status'], ).to_excel('color_test.... | 1 | 2 |
79,561,147 | 2025-4-8 | https://stackoverflow.com/questions/79561147/change-column-type-in-polars-dataframe | I have a Polars DataFrame below. import polars as pl df = pl.DataFrame({"a":["1.2", "2.3", "5.4"], "b":["0.4", "0.03", "0.12"], "c":["AA", "BB", "CC"]}) >>> df a b c str str str ------------------------- "1.2" "0.04" "AA" "2.3" "0.3" "BB" "3.5" "0.12" "CC" How can I convert the columns to specific types? In this case,... | There are multiple approaches in Polars to convert column type. Using the cast method with with_columns is one of the most efficient approach: df = df.with_columns([ pl.col("a").cast(pl.Float64), pl.col("b").cast(pl.Float64) ]) Another approach: df = df.select([ pl.col("a").cast(pl.Float64), pl.col("b").cast(pl.Float6... | 2 | 3 |
79,561,013 | 2025-4-8 | https://stackoverflow.com/questions/79561013/is-it-ok-to-not-use-the-value-of-the-index-i-inside-a-for-loop | Would it be frowned upon if the index variable i were not used inside a for loop? I have never come across a code that didn't use the value of the index while it iterates through the loop. def questionable(): for i in range(3): print('Is this OK?') # (or do something more complicated) # as opposed to: def proper(): for... | When you want to perform an action a certain number of times without caring about the loop variable, the convention is to use an underscore (_) instead of a named variable like i. This signals to readers of your code: "I'm not going to use this variable." So your questionable function can be rewritten in a more Pythoni... | 4 | 10 |
79,582,846 | 2025-4-19 | https://stackoverflow.com/questions/79582846/the-python-mcp-server-with-stdio-transport-throws-an-error-sse-connection-not | I've been trying to run an example from the official repo of Model Context Protocol for Python (https://github.com/modelcontextprotocol/python-sdk). But it keeps giving me Error in /message route: Error: SSE connection not established", when I click the "Connect" button in the webpage of MCP Inspector. The problem is t... | Here's what worked for me: I was only able to run the Inspector correctly in VS Code's Simple Browser (Ctrl + Shift + P → Simple Browser: Show → Paste your Inspector link—in my case, it was running on http://127.0.0.1:6274). I still have no idea what the problem is. I couldn't make the Inspector work in Edge or Chrome.... | 2 | 1 |
79,583,320 | 2025-4-20 | https://stackoverflow.com/questions/79583320/same-size-of-text-labels-and-buttons | I am not really a programmer. I asked an AI to generate a matrix of buttons, with rows and columns having text-labels on top and left side of the window. I wanted the matrix to be scrollable but the labels on top/left should always remain visible. The code the AI gave me is actually doing what I described (sort of), bu... | I improved your code and solved the scrolling issue. I also improved performance. I made a numerous changes and added new features. If I go to write them all, it will occupy a lot of space. However, if you require, I could provide the list of changes. Here is the full code: import tkinter as tk class OptimizedScrollabl... | 1 | 2 |
79,583,654 | 2025-4-20 | https://stackoverflow.com/questions/79583654/logits-dont-change-in-a-custom-reimplementation-of-a-clip-model-pytorch | The problem The similarity scores are almost the same for texts that describe both a photo of a cat and a dog (the photo is of a cat). Cat similarity: tensor([[-3.5724]], grad_fn=<MulBackward0>) Dog similarity: tensor([[-3.4155]], grad_fn=<MulBackward0>) The code for CLIP model The code is based on the checkpoint of o... | The issue was in the EncoderLayer where the residual calculations were done wrong. The correct way of calculating: def forward(self, x: torch.Tensor, src_pad_key = None): residual = x x = self.layer_norm1(x) if src_pad_key is not None: x = self.self_attn(x, src_pad_key = src_pad_key, use_self_attention = True) else: x... | 2 | 1 |
79,585,301 | 2025-4-21 | https://stackoverflow.com/questions/79585301/matplotlib-vertical-grid-lines-not-match-points | Could you please explain why vertical grid lines not match points? Here is my data for plot: {datetime.datetime(2025, 4, 15, 19, 23, 50, 658000, tzinfo=datetime.timezone.utc): 68.0, datetime.datetime(2025, 4, 16, 19, 31, 1, 367000, tzinfo=datetime.timezone.utc): 72.0, datetime.datetime(2025, 4, 17, 19, 34, 21, 507000,... | There are multiple solutions for it. I think using ax.set_xticks(df['Дата']) "to force the ticks to match your actual datetimes" might be better for you when the time of day matters, not just the date. The full code: import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd from datetime imp... | 1 | 3 |
79,584,062 | 2025-4-21 | https://stackoverflow.com/questions/79584062/userwarning-figurecanvasagg-is-non-interactive-and-thus-cannot-be-shown | I am trying to show a matplotlib.pyplot figure on Python 3.10 but can't. I am aware of this question and tried their answers but is still unsuccessful. The default OS distribution is Ubuntu 24.04 using Python 3.12 as a default. Here is how I setup the Python 3.10 project venv and installed numpy and matplotlib: $ uv in... | I uses Linux Mint 22 based on Ubuntu 24.04. Code works for me with uv and Python 3.10 when I install PyQt6 but not with PyQt5 And it doesn't need line matplotlib.use('Qt5Agg') nor matplotlib.use('QtAgg') (but it works also with those lines) As for tkinter: normally tkinter is intalled directly with Python but on Ubunt... | 1 | 2 |
79,584,014 | 2025-4-21 | https://stackoverflow.com/questions/79584014/how-to-render-power-bi-slicer-items-with-python-selenium | I'd like to scrape the second page of this Power BI dashboard. In order to get the data from a specific month, I must set the date in a slicer: However, when I expand a year element to display the month elements, some are out of sight and thus unrendered. Therefore, I must scroll down the slicer. However, I have yet t... | ActionChains with scrolling via move_to_element, click_and_hold, and move_by_offset, It is key when interacting with complex UIs like Power BI embedded dashboards or custom dropdowns. move_to_element(): Ensures you're hovering over the correct scrollable area. click_and_hold(): Simulates a mouse drag. Without this, the... | 1 | 4 |
79,583,755 | 2025-4-20 | https://stackoverflow.com/questions/79583755/how-to-build-a-nested-adjacency-list-from-an-adjacency-list-and-a-hierarchy | I have a simple adjacency list representation of a graph like this { 1: [2, 3, 4], 2: [5], 3: [6, 9], 4: [3], 5: [3], 6: [7, 8], 7: [], 8: [], 9: [] } which looks like this But each node also has a "type ancestry" which tells us what "type" of node it is, and this is completely different from the hierarchy present in... | Basing this off of @trincot's answer (who wanted me to write my own answer instead of editing theirs as the change is non-trivial) with a critical change on how edges are made. Create a node (a dict) for each distinct node that can be found in ancestry list, so including the ancestry groups. A node looks like this: { ... | 1 | 1 |
79,584,797 | 2025-4-21 | https://stackoverflow.com/questions/79584797/how-to-cast-polars-decimal-to-int-or-float-depending-on-scale-parameter | executing a polars.read_database() resulted in columns with the Decimal data type, which I'd like to cast to either Int or Float, depending on the value of the scale parameter in Decimal. Alternatively, I'd be happy if there is a way to instruct polars to not use the Decimal data type as an option and during schema inf... | A fairly explicit solution that works is: int_dec_cols = [c for c, dt in df.schema.items() if isinstance(dt, pl.Decimal) and dt.scale == 0] flt_dec_cols = [c for c, dt in df.schema.items() if isinstance(dt, pl.Decimal) and dt.scale > 0] df = df.with_columns( pl.col(int_dec_cols).cast(pl.Int64), pl.col(flt_dec_cols).cas... | 4 | 2 |
79,584,546 | 2025-4-21 | https://stackoverflow.com/questions/79584546/how-to-correct-a-parsererror-when-respecting-the-csv-delimiter-and-a-second-pars | I'm new here so I hope that I will put all needed information As the CSV is a huge one (10Go), the URL link is in the code below if needed URL link to the data description (column type...) Delimiter is \t but they call it CSV (describe in the "data description file"). After replacing wrong delimiter (replace '\n\t' b... | The problem appears to be that the file uses the " character not to quote items but to indicate a measurement in inches. For example, I found this in one cell of the file: fluted shell round sweet 2.5" The fix is straightforward: add quoting=csv.QUOTE_NONE to your call to pd.read_csv. (You'll need to add import csv as... | 2 | 2 |
79,583,650 | 2025-4-20 | https://stackoverflow.com/questions/79583650/mount-type-cache-doesnt-speed-up-pip-install-during-docker-build | I'm using --mount=type=cache in my Dockerfile to cache pip packages between builds, but it doesn't seem to have any effect on build speed. I expected pip to reuse cached packages and avoid re-downloading them, but every build takes the same amount of time. Here is the relevant part of my Dockerfile: FROM python:3.13-sl... | The pip cache is relative to the user's home directory. Just above the RUN pip install line you set ENV HOME=/app, and so the pip cache is in /app/.cache/pip (you also see that directory in the error message). Use that directory as the cache location RUN --mount=type=cache,target=/app/.cache/pip pip ... # ^^^^^ the dir... | 1 | 2 |
79,584,468 | 2025-4-21 | https://stackoverflow.com/questions/79584468/how-to-represent-ranges-of-time-in-a-pandas-index | I have a collection of user data as follows: user start end John Doe 2025-03-21 11:30:35 2025-03-21 13:05:26 ... ... ... Jane Doe 2023-12-31 01:02:03 2024-01-02 03:04:05 Each user has a start and end datetime of some activity. I would like to place this temporal range in the index so I can quickly query t... | Here is your solution: import pandas as pd data = { 'user': ['John Doe', 'Jane Doe'], 'start': [pd.Timestamp('2025-03-21 11:30:35'), pd.Timestamp('2023-12-31 01:02:03')], 'end': [pd.Timestamp('2025-03-21 13:05:26'), pd.Timestamp('2024-01-02 03:04:05')], } df = pd.DataFrame(data) interval_index = pd.IntervalIndex.from_a... | 2 | 1 |
79,583,908 | 2025-4-21 | https://stackoverflow.com/questions/79583908/how-can-i-automatically-run-a-command-immediately-after-git-add | I'm working on a side project to make my git commit message better and make the process faster, but I cant seem to figure out how to trigger the scripts after git add, without manually doing it. This is the flow I want: I run git add. My script kicks in immediately. It fetches the staged diff. AI generates a commit me... | If you don't want to use a prepare-commit-msg hook, you can use a CLI script like this: Add specified files git add "$@" Get diff diff=$(git diff --cached) Generate commit message commit_msg=$(echo "$diff" | your_ai_commit_generator) Ask for confirmation echo "Suggested commit message:" echo "$commit_msg" read -... | 1 | 2 |
79,583,707 | 2025-4-20 | https://stackoverflow.com/questions/79583707/adding-text-file-attachments-to-keepass-with-pykeepass-in-python | I am trying to create and save KeePass entries using pykeepass and saving a .txt file as an attachment. However I get a type-error: Traceback (most recent call last): File "c:\Users\Simplicissimus\Documents\coding\directory\attachment.py", line 15, in <module> entry.add_attachment('attachment.txt', f.read()) ~~~~~~~~~~... | I can't test it but examples on page pykeepass show # add attachment data to the db >>> binary_id = kp.add_binary(b'Hello world') >>> kp.binaries [b'Hello world'] # add attachment reference to entry >>> a = e.add_attachment(binary_id, 'hello.txt') So maybe it needs first add it as add_binary() and later attache it to ... | 3 | 1 |
79,583,700 | 2025-4-20 | https://stackoverflow.com/questions/79583700/pandass-gt-and-lt-not-working-when-chained-together | I'm playing around with the pipe | and ampersand & operators, as well as the .gt() and .lt() built-in functions to see how they work together. I'm looking at a column in a DataFrame with values from 0.00 to 1.00. I can use the >, <, and & operators together and find no problem, same with using .gt(), .lt(), and &. Howe... | The misunderstanding is that in Python True == 1 and False == 0 (see bool). Suppose we have: import pandas as pd data = {'col': [0.5, 0.8, 1]} df = pd.DataFrame(data) df['col'].gt(0.7) When we chain .lt(0.9), this check takes place on the result of .gt(0.7): 0 False # 0 < 0.9 (True) 1 True # 1 < 0.9 (False) 2 True # 1... | 3 | 4 |
79,583,142 | 2025-4-20 | https://stackoverflow.com/questions/79583142/broadcasting-a-b-1-tensor-to-apply-a-shift-to-a-specific-channel-in-pytorch | I have a tensor p of shape (B, 3, N) in PyTorch: # 2 batches, 3 channels (x, y, z), 5 points p = torch.rand(2, 3, 5, requires_grad=True) """ p: tensor([[[0.8365, 0.0505, 0.4208, 0.7465, 0.6843], [0.9922, 0.2684, 0.6898, 0.3983, 0.4227], [0.3188, 0.2471, 0.9552, 0.5181, 0.6877]], [[0.1079, 0.7694, 0.2194, 0.7801, 0.8043... | In PyTorch, tensors directly created by users are termed leaf tensors, and their views share the same underlying storage. Performing in-place assignments on a view can modify the storage of the original tensor midst in the computational graph, leading to undefined behavior. Thus, directly assigning values to views shou... | 3 | 2 |
79,582,880 | 2025-4-19 | https://stackoverflow.com/questions/79582880/why-isnt-packages-installed-in-my-multi-stage-docker-build-using-pip | I'm working on a Python project with a multi-stage Docker build and running into an issue where pydantic (just example) isn't installed, even though pip is present and working in the final image. Here's my project structure: project-root/ ├── docker-compose.yml ├── vector_db_service/ │ ├── app/ │ │ └── __init__.py │ ├─... | Try to copy project files which you need to install FROM python:3.13-slim AS compile-image RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN pip install --no-cache-dir --upgrade pip setuptools wheel WORKDIR /app COPY pyproject.toml ./ COPY vector_db_service ./vector_db_service RUN pip install --no-cache-... | 3 | 0 |
79,581,767 | 2025-4-18 | https://stackoverflow.com/questions/79581767/problems-creating-a-generator-factory-in-python | I'd like to create a generator factory, i.e. a generator that yields generators, in python using a "generator expression" (generator equivalent of list comprehension). Here's an example: import itertools as it gen_factory=((pow(b,a) for a in it.count(1)) for b in it.count(10,10)) In my mind this should give the follow... | You can prevent the closure by capturing b with for b in [b] (Attempt This Online!): gen_factory=((pow(b,a) for b in [b] for a in it.count(1)) for b in it.count(10,10)) As documented: the iterable expression in the leftmost for clause is immediately evaluated, so that an error produced by it will be emitted at the po... | 2 | 2 |
79,580,890 | 2025-4-18 | https://stackoverflow.com/questions/79580890/how-to-select-element-from-two-complex-number-lists-to-get-minimum-magnitude-for | I have two python lists(list1 and list2),each containing 51 complex numbers. At each index i, I can choose either list1[i] or list2[i]. I want to select one element per index(Total of 51 elements) such that magnitude of sum of the selected complex number list is minimized. Sample code I have tried below: import random ... | Let's slightly reinterpret your problem. Instead of strictly choosing one element from either of the two lists, start with an initial state where you've selected all elements from list1. The sum of this selection is your offset value, which we'll call C. Next, create a new list called list3, defined as list3 = list2 - ... | 5 | 6 |
79,581,422 | 2025-4-18 | https://stackoverflow.com/questions/79581422/how-to-plot-4sin2x-cos2x3-using-sympy | I am trying to plot the expression 4*sin(2*x)/cos3(2*x) in Sympy: from sympy import * from sympy.plotting import plot x = symbols('x') expr = 4*sin(2*x)/cos(2*x)**3 plot(expr) But all I get is: when it should look a bit like a horizontally-squished tangent graph: | SymPy's plotting module doesn't handle very well functions with poles. But SymPy Plotting Backends (which is a more advanced plotting module) is up for the task: from spb import plot plot(expr, (x, -2*pi, 2*pi), detect_poles=True, ylim=(-3, 3)) In particular: detect_poles=True: run the algorithm to detect poles (sin... | 1 | 4 |
79,579,619 | 2025-4-17 | https://stackoverflow.com/questions/79579619/why-does-32-bit-bitmasking-work-in-python-for-leetcode-single-number-ii-when-p | I'm trying to understand why the following solution for LeetCode's Single Number II works in Python: class Solution: def singleNumber(self, nums: List[int]) -> int: number = 0 for i in range(32): count = 0 for num in nums: if num & (1 << i): count += 1 if count % 3: number |= (1 << i) if number & (1 << 31): number -= (... | Think of positive ints having infinitely many zero-bits in front and of negative ints having infinitely many one-bits in front: 3 = ...00000011 2 = ...00000010 1 = ...00000001 0 = ...00000000 -1 = ...11111111 -2 = ...11111110 -3 = ...11111101 -4 = ...11111100 That's how Python treats them, which is why for example (-... | 1 | 2 |
79,581,533 | 2025-4-18 | https://stackoverflow.com/questions/79581533/find-pairs-of-keys-for-rows-that-have-at-least-one-property-in-common | I'm using polars with a data frame whose schema looks like this: Schema({'CustomerID': String, 'StockCode': String, 'Total': Int64}) interpreted as "Customer CustomerID bought Total of product StockCode." I'm looking for an efficient way to generate all unique pairs of customer IDs such that the two customers purchase... | Use a self-join: (df.lazy() .join_where(df.lazy(), ((pl.col.StockCode == pl.col.StockCode_right) & (pl.col.CustomerID < pl.col.CustomerID_right))) .select("^CustomerID.*$") .unique() .collect(engine="streaming")) ┌────────────┬──────────────────┐ │ CustomerID ┆ CustomerID_right │ │ --- ┆ --- │ │ str ┆ str │ ╞═════════... | 2 | 1 |
79,580,670 | 2025-4-18 | https://stackoverflow.com/questions/79580670/fast-calculation-of-nth-generalized-fibonacci-number-of-order-k | How can I calculate Nth term in Fibonacci sequence of order K efficiently? For example, Tribonacci is Fibonacci order 3, Tetranacci is Fibonacci order 4, Pentanacci is Fibonacci order 5, and Hexanacci is Fibonacci order 6 et cetera. I define these series as follows, for order K, A0 = 1, Ai = 2i-1 (i ∈ [1, k]), Ak+1 = 2... | Yes, there is a faster way to compute this. Matrix Diagonalisation The matrix exponentiation can be optimised if the matrix is diagonalisable. It turns out it is diagonalisable. Indeed, we know that the n-order Fibonacci matrix M is a square matrix and all its rows and columns are linearly independent (by design). Thi... | 8 | 5 |
79,581,784 | 2025-4-18 | https://stackoverflow.com/questions/79581784/python-editing-file-in-loop-how-to-keep-changes-after-each-xml | I need to clean few xml files from not needed elements, came up with this wild card replacement for nothing to get rid of not needed <EmbeddedImage>, but I'm missing how to store each change in the loop, looks like it overwrites it each time. Thought that Python will keep it, but it's not the case. Do I need to create ... | Try to operate directly with Bs.data from bs4 import BeautifulSoup as bs xml = ''' <Images> <EmbeddedImage Name="Brand_1"> <ImageData>/9j/4AAQSkZJB//2Q==</ImageData> </EmbeddedImage> <EmbeddedImage Name="Brand__2XX"> <ImageData>/9j/4AAQSkZJB//2Q==JB//2</ImageData> </EmbeddedImage> <EmbeddedImage Name="Brand___3XX"> <Im... | 3 | 4 |
79,581,369 | 2025-4-18 | https://stackoverflow.com/questions/79581369/why-does-python-allow-for-multiple-methods-with-the-same-name | Python does not allow overloading. I therefore expect it to only allow a single class method with the same name. This is not the case. This code runs without issue. class DoubleTest: def __init__(self): self._generate_thing() def _generate_thing(self, entry): print(entry) def _generate_thing(self): print("do the thing"... | Python doesn't allow multiple methods with the same name, but it does allow you to redefine methods and functions. As a result, only the last method with the duplicate name is effective, the other one is effectively ignored because it has been replaced by the time the class definition is completed. | 1 | 5 |
79,576,800 | 2025-4-16 | https://stackoverflow.com/questions/79576800/numpy-sort-n-dimensional-array-similar-to-pythons-list-sort | I am trying to sort a list of 3D coordinates. The target is to get the same order that the basic Python list sort produces, which is the same as the meshgrid + column_stack order. Python sorts by the first value of each element first; in case of ties, the second element is checked, and so on. I would like to do the sam... | You could use lexsort on the reversed columns: import numpy as np num = 10 x = np.linspace(1, 3, num) y = np.linspace(4, 6, num) z = np.linspace(7, 9, num) xg, yg , zg = np.meshgrid(x, y, z, indexing='ij', sparse=False) test = np.column_stack((xg.ravel(), yg.ravel(), zg.ravel())) print('Target ordering\n', test) np.ran... | 1 | 2 |
79,574,572 | 2025-4-15 | https://stackoverflow.com/questions/79574572/powershell-subprocess-launched-via-debugpy-doesn-t-inherit-environment-variables | Problem I'm encountering an issue where launching PowerShell via Python’s subprocess.Popen() works as expected during normal execution, but in debug mode (using debugpy/cursor) key environment variables (e.g. PROGRAMFILES and LOCALAPPDATA) are empty. In contrast, when I run a CMD command (e.g. echo %PROGRAMFILES%), the... | Self‑Answer: Root Cause and Fix Apologies for the confusion and for taking up your time with this—it was my own mistake. I really appreciate your help. After all the investigation above, I finally discovered the true culprit: a project‑root .env file that I had added for other tooling (e.g. to set JAVA_HOME for a Proce... | 3 | 0 |
79,580,208 | 2025-4-17 | https://stackoverflow.com/questions/79580208/how-to-add-jitter-to-plotly-go-scatter-in-python-when-mode-lines | I have a dataframe as such: Starting point Walking Driving Lunch 0 8 4 Shopping 0 7 3 Coffee 0 5 2 Where I want to draw, for each index, a green line from "Starting point" -> "Walking", and a red line from "Starting point" -> "Coffee". To do this, I loop through both the columns and the index, as such: for column in d... | Try to use offset and then enumerate import pandas as pd import plotly.graph_objects as go from itertools import cycle df7 = pd.DataFrame({ 'Starting point': [0, 0, 0], 'Walking': [8, 7, 5], 'Biking': [4, 3, 2] }, index=['Lunch', 'Shopping', 'Coffee']) fig9 = go.Figure() color_cyc = cycle(["#888888", "#E2062B"]) symbol... | 2 | 2 |
79,579,904 | 2025-4-17 | https://stackoverflow.com/questions/79579904/why-is-there-a-complex-argument-in-the-array-here-trying-to-do-dtfs | I have a window signal, which i calculate it's Fourier coefficients but then in the output i get a small complex value [3 order of magnitude less in the origin and the same order of magnitude in the edges of my sampling (from -1000 to 1000)] where the output should be purely real, if it was just a floating point approx... | the imaginary part you see is correct, your textbook definition speaks of a signal symmetric around 0, your signal is only from -100 to 99 as python range is end exclusive, it is not symmetric around 0, hence there's a phase error, which translates to an imaginary component in the signal Fourier transform. correcting t... | 2 | 5 |
79,580,115 | 2025-4-17 | https://stackoverflow.com/questions/79580115/proper-python-type-hinting-for-this-function-in-2025 | I'm using VS Code with Pylance, and having problems correctly writing type hints for the following function. To me, the semantics seem clear, but Pylance disagrees. How can I fix this without resorting to cast() or # type ignore? Pylance warnings are given in the comments. I am fully committed to typing in Python, but ... | This is just fundamentally unsafe, due to ambiguity. Suppose you have a generic function that uses listify: def caller[T](x: T): y = listify(x) What's the proper annotation for y? The obvious answer is list[T]. But there's no guarantee listify will return a list[T]. If T is list[Something], or tuple[Something, ...], o... | 2 | 2 |
79,579,955 | 2025-4-17 | https://stackoverflow.com/questions/79579955/check-corresponding-columns-for-null-data | Imagine I have a dataframe like so: ID, place, stock 1, 1, 4 2, NaN, 2 3, NaN, NaN 4, 1, 1 I wish to find all the rows for which place is null and check the corresponding stock column to see, for instance, if place is Null but stock is >0. I've implemented this by iterating over the dataframe like so: for idx, x in en... | You can use something vectorized like that count = df[df['place'].isnull() & (df['stock'] > 0)].shape[0] | 2 | 1 |
79,578,736 | 2025-4-17 | https://stackoverflow.com/questions/79578736/python-for-xml-parsing-how-to-track-correct-tree | I try to parse XML file to get NeedThisValue!!! for one of the element tagged <Value>. But there are several tags <Value> in file. How I can get the right one under <Image> branch? This is example of my XML: <Report xmlns=http://schemas.microsoft.com> <AutoRefresh>0</AutoRefresh> <DataSources> <DataSource Name="DataSou... | As an alternative to the accepted solution from @Igel, you can reach it also with lxml and xpath(): from lxml import html broken_xml = """<Report xmlns=http://schemas.microsoft.com> <AutoRefresh>0</AutoRefresh> <DataSources> <DataSource Name="DataSource2"> <Value>SourceAlpha</Value> <rd:SecurityType>None</rd:SecurityTy... | 1 | 1 |
79,579,461 | 2025-4-17 | https://stackoverflow.com/questions/79579461/why-no-floating-point-error-occurs-in-print0-1-100000-vs-decimal0-1100000 | I am studying numerical analysis and I have come across this dilemma. Running the following script, from decimal import Decimal a = 0.1 ; N = 100000 ; # product calculation P = N*a # Print product result with no apparent error print(' %.22f ' % P) # Print product result with full Decimal approximation of 0.1 print(Deci... | a = 0.1 ; Assuming your Python implementation uses IEEE-754 binary641, this converts 0.1 to 0.1000000000000000055511151231257827021181583404541015625, because that is the representable value that is nearest to 0.1. P = N*a The real-number arithmetic product of 100,000 and 0.10000000000000000555111512312578270211815... | 4 | 8 |
79,579,642 | 2025-4-17 | https://stackoverflow.com/questions/79579642/arranging-three-numbers-into-a-specified-order-in-python-3 | Problem: You will be given three integers A, B and C. The numbers will not be given in that exact order, but we do know that A < B < C. In order to make for a more pleasant viewing, we want to rearrange them in the given order. The first line of the input contains three positive integers A, B and C, not necessarily in... | The order input apparently has extra whitespace around the letters, so it doesn't exactly equal any of the strings you're comparing with. Your friend's solution ignores any characters that aren't in ABC, so it ignores the extra spaces. You can remove this extraneous whitespace with order = input().strip() I'd say this... | 1 | 5 |
79,577,208 | 2025-4-16 | https://stackoverflow.com/questions/79577208/subclassing-a-generic-class-with-constrained-type-variable-in-python-3-12-witho | I would like to subclass a generic class that is using a constrained type variable. This is fairly easy with pre-3.12 syntax as shown in this minimal example: from typing import Generic, TypeVar T = TypeVar("T", int, float) class Base(Generic[T]): pass class Sub(Base[T]): pass But I am struggling with writing this in ... | Unfortunately, you cannot reuse type variables defined with PEP 695 syntax. The type variable must have the correct bound to parametrize the superclass (in other words, bounds and constraints can't be inferred or magically "pushed down" from the superclass, that has soundness problems if you consider multiple inheritan... | 4 | 1 |
79,579,330 | 2025-4-17 | https://stackoverflow.com/questions/79579330/python-multiprocessing-queue-strange-behaviour | Hi I'm observing a strange behaviour with python multiprocessing Queue object. My environment: OS: Windows 10 python: 3.13.1 but I observed the same with: OS: Windows 10 python: 3.12.7 and: OS: Windows 10 python: 3.10.14 while I could not reproduce it in Linux Redhat. I have this short script: from multiprocessing i... | when you put an item in the queue, you are only putting it in an internal list, and a worker thread is incrementally adding items to the IPC pipe, the process won't exit until the worker empties this list into the pipe, the pipe has a small internal buffer, which is why small sizes work fine, this is done so that queue... | 2 | 4 |
79,578,785 | 2025-4-17 | https://stackoverflow.com/questions/79578785/why-is-my-asyncio-task-not-executing-immediately-after-asyncio-create-task | import asyncio async def worker(): print("worker start") await asyncio.sleep(1) print("worker done") async def main(): # Schedule the coroutine asyncio.create_task(worker()) # Give control back to the event loop for a moment await asyncio.sleep(0.1) print("main exiting") asyncio.run(main()) Expected behavior I thought... | asyncio.create_task(coro) does not result in the immediate execution of coroutine coro. According to the docs: asyncio.create_task(coro, *, name=None, context=None) Wrap the coro coroutine into a Task and schedule its execution. Return the Task object. asyncio.create_task(coro) only schedules the task for execution. ... | 2 | 3 |
79,577,035 | 2025-4-16 | https://stackoverflow.com/questions/79577035/how-can-i-get-the-name-of-svg-element-when-i-click-on-it-in-nicegui | I have a NiceGUI page with an SVG image consisting of two elements (a circle and a square). I need to check which element of this image was clicked when the SVG image is clicked, so that I can handle it. I want the event "circle clicked" to be triggered when the circle is clicked, and the event "square clicked" to be t... | If you want to use JavaScript then you have to use the same name event in (event) => { console.log(event.target) } I think you could use it to emit custom event with information what object was clicked emitEvent(`clicked_${event.tagerg.tagName}`) and it should send event clicked_circle or clicked_rect (and maybe even... | 2 | 1 |
79,578,293 | 2025-4-17 | https://stackoverflow.com/questions/79578293/python-how-to-check-for-missing-values-not-represented-by-nan | I am looking for guidance on how to check for missing values in a DataFrame that are not the typical "NaN" or "np.nan" in Python. I have a dataset/DataFrame that has a string literal "?" representing missing data. How can I identify this string as a missing value? When I run usual commands using Pandas like: missing_va... | You can use df.replace("?", pd.NA) to properly encode "?" as missing value. This will ensure that those are properly handled in all operations. import pandas as pd data = {"x": [1, 2, "?"], "y": [3, "?", 5]} df = pd.DataFrame(data) print(df.isnull().sum()) # x 0 # y 0 df = df.replace("?", pd.NA) print(df.isnull().sum()... | 1 | 5 |
79,577,512 | 2025-4-16 | https://stackoverflow.com/questions/79577512/pytest-caplog-not-capturing-logs | See my minimal example below for reproducing the issue: import logging import logging.config def test_logging(caplog): LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s", }, }, "handlers": { "console": { "clas... | You're not supposed to configure logging during a test. Further, if any real code under test tries to configure loggers, you should probably patch that out. The way caplog fixture works is by adding a capturing handler, so if you've already configured the logging framework, or attempt to reconfigure it during test, the... | 3 | 3 |
79,577,827 | 2025-4-16 | https://stackoverflow.com/questions/79577827/polars-pandas-like-groupby-save-to-files-by-each-value | Boiling down a bigger problem to its essentials, I would like to do this: import numpy as np import pandas as pd df = pd.DataFrame({'a': np.random.randint(0, 5, 1000), 'b': np.random.random(1000)}) for aval, subdf in df.groupby('a'): subdf.to_parquet(f'/tmp/{aval}.parquet') in Polars using LazyFrame: import numpy as n... | You could use a partitioning scheme e.g. PartitionByKey() lf.sink_parquet( pl.PartitionByKey("/tmp/output", by="a"), mkdir = True ) For your example this creates: /tmp/output /tmp/output/a=0 /tmp/output/a=0/0.parquet /tmp/output/a=1 /tmp/output/a=1/0.parquet /tmp/output/a=2 /tmp/output/a=2/0.parquet /tmp/output/a=3 /t... | 2 | 2 |
79,577,779 | 2025-4-16 | https://stackoverflow.com/questions/79577779/how-do-we-use-numpy-to-create-a-matrix-of-all-permutations-of-three-separate-val | I want to make a pandas dataframe with three columns, such that the rows contain all permutations of three columns, each with its own range of values are included. In addition, I want to sort them asc by c1, c2, c3. For example, a = [0,1,2,3,4,5,6,7], b = [0,1,2], and c= [0,1]. The result I want looks like this: c1 c2 ... | You can use pandas MultiIndex (the doc) import pandas as pd a = range(8) b = range(3) c = range(2) multi_index = pd.MultiIndex.from_product([a, b, c], names=['c1', 'c2', 'c3']) df = multi_index.to_frame(index=False) print(df) Output: c1 c2 c3 0 0 0 0 1 0 0 1 2 0 1 0 3 0 1 1 4 0 2 0 5 0 2 1 6 1 0 0 7 1 0 1 8 1 1 0 9 1... | 5 | 4 |
79,575,456 | 2025-4-15 | https://stackoverflow.com/questions/79575456/is-a-lock-needed-when-multiple-tasks-push-into-the-same-asyncio-queue | Consider this example where I have 3 worker tasks that push results in a queue and a tasks that deals with the pushed data. async def worker1(queue: asyncio.Queue): while True: res = await do_some_work(param=1) await queue.put(res) async def worker2(queue: asyncio.Queue): while True: res = await do_some_work(param=2) ... | No - there is no need to locks to put or read items from asyncio Queues. Keep in mind that Python multithreaded code will already require much less locks than most code in other languages, as the data-structures themselves are thread-safe - so, even with a free-threading build (without the GIL) if you have several thre... | 2 | 1 |
79,577,490 | 2025-4-16 | https://stackoverflow.com/questions/79577490/how-to-fit-scaler-for-different-subsets-of-rows-depending-on-group-variable-and | I have a data set like the following and want to scale the data using any of the scalers in sklearn.preprocessing. Is there an easy way to fit this scaler not over the whole data set, but per group? My current solution can't be included in a Pipeline: import pandas as pd import numpy as np from sklearn.preprocessing im... | You can create custom transformer, using BaseEstimator and TransformerMixin for example: import pandas as pd import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import StandardScaler class GroupScaler(BaseEstimator, TransformerMixin): def __init__(self, group_column, s... | 2 | 1 |
79,577,365 | 2025-4-16 | https://stackoverflow.com/questions/79577365/making-file-hidden-in-windows-using-python-blocks-file-writing | I am trying to make a hidden file in Windows using Python, but after I make it hidden it becomes impossible to write. However, reading this file is possible. import ctypes with open("test.txt", "r") as f: print('test') ctypes.windll.kernel32.SetFileAttributesW("test.txt", 0x02) # adding h (hidden) attribute to a file w... | I haven't seen specific Python documentation on this behavior, but believe it is because at the implementation level, 'w' eventually is calling The Windows API CreateFileW which has this note: If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if t... | 1 | 1 |
79,577,437 | 2025-4-16 | https://stackoverflow.com/questions/79577437/why-is-my-python-code-displaying-csv-file-with-right-sided-alignment | I have written this code just to read a csv file: import pandas as pd df = pd.read_table('C:\\XXXXX\\Python_Learn\\pandas.csv') print(df.to_string()) and output to this is coming as below: Date|Invoice ID|Customer Name|Product|Category|Quantity|Unit Price|Total Amount|Region|Salesperson 0 2025-04-01|INV1001|John Smit... | You need to use pd.read_csv() with the correct delimiter. You can read more about it here import pandas as pd df = pd.read_csv('C:\\XXXXX\\Python_Learn\\pandas.csv', delimiter='|') print(df.to_string()) | 1 | 2 |
79,577,224 | 2025-4-16 | https://stackoverflow.com/questions/79577224/redis-py-not-returning-consistent-results-for-match-all-query | I'm attempting to add 100 documents to a Redis index, and then retrieving them with a match all query: import uuid import redis from redis.commands.json.path import Path import redis.commands.search.aggregation as aggregations import redis.commands.search.reducers as reducers from redis.commands.search.field import Tex... | Try to use pipe and add some time.sleep() import uuid import time import redis from redis.commands.json.path import Path from redis.commands.search.field import TextField, NumericField, TagField from redis.commands.search.indexDefinition import IndexDefinition, IndexType from redis.commands.search.query import NumericF... | 1 | 1 |
79,577,143 | 2025-4-16 | https://stackoverflow.com/questions/79577143/pyserial-doesnt-read-full-line | I want to read data from my arduino and show it on a tkinter window, it works nicely but when I sent the Data on the arduino faster then every 10ms it resevieses many lines that are not full like this: 'Malik'] ⚠️ Invalid line, skipped: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 'Malik'] ⚠️ Invalid l... | You're reading data too fast, and the serial input is not guaranteed to end cleanly with \n before your code tries to process it, and that’s why you are getting incomplete or "corrupted" lines. 1. Use a dedicated thread for serial reading Tkinter is single-threaded. If you read from a serial in the same thread as the G... | 2 | 3 |
79,575,363 | 2025-4-15 | https://stackoverflow.com/questions/79575363/how-to-force-numba-to-return-a-numpy-type | I find this behavior quite counter-intuitive although I suppose there is a reason for it - numba automatically converts my numpy integer types directly into a python int: import numba as nb import numpy as np print(f"Numba version: {nb.__version__}") # 0.59.0 print(f"NumPy version: {np.__version__}") # 1.23.5 # Explici... | Why don't you just return np.uint32(a*b): @nb.njit(nb.uint32(nb.uint32, nb.uint32)) def func(a, b): return np.uint32(a * b) It is faster and more readable than the other solutions: import numba as nb import numpy as np @nb.njit(nb.types.Array(nb.uint32, 0, "C")(nb.uint32, nb.uint32)) def test_fn(a, b): res = np.empty(... | 3 | 2 |
79,576,300 | 2025-4-16 | https://stackoverflow.com/questions/79576300/how-to-display-metadata-in-scatter-plot-in-matplotlib | I have a scatter plot. I want to add some metadata to each point in my scatter plot. looking at documentation , i found annotate function( matplotlib.pyplot.annotate) , has anyone use this or some other function , such that we can add metadata to each point or are there are similar libraries, like matplotlib, which can... | Matplotlib does not offer a built-in function in its core library to enable hover effects. For this functionality, you may consider using the mplcursor library. Kindly try running the code below after installing mplcursors. import matplotlib.pyplot as plt import numpy as np import mplcursors x = np.random.rand(20) y = ... | 1 | 2 |
79,576,828 | 2025-4-16 | https://stackoverflow.com/questions/79576828/get-a-grouped-sum-in-polars-but-keep-all-individual-rows | I am breaking my head over this probably pretty simply question and I just can't find the answer anywhere. I want to create a new column with a grouped sum of another column, but I want to keep all individual rows. So, this is what the docs say: import polars as pl df = pl.DataFrame( { "a": ["a", "b", "a", "b", "c"], "... | All you need is a window function: df.with_columns( b_sum=pl.col("b").sum().over(pl.col("a")) ) shape: (5, 3) ┌─────┬─────┬───────┐ │ a ┆ b ┆ b_sum │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═════╪═════╪═══════╡ │ a ┆ 1 ┆ 2 │ │ b ┆ 2 ┆ 5 │ │ a ┆ 1 ┆ 2 │ │ b ┆ 3 ┆ 5 │ │ c ┆ 3 ┆ 3 │ └─────┴─────┴───────┘ | 2 | 3 |
79,576,316 | 2025-4-16 | https://stackoverflow.com/questions/79576316/exceptions-being-hidden-by-asyncio-queue-join | I am using an API client supplied by a vendor (Okta) that has very poor/old examples of running with async - for example (the Python documentation says not to use get_event_loop()): from okta.client import Client as OktaClient import asyncio async def main(): client = OktaClient() users, resp, err = await client.list_u... | For printing the error, pythons traceback module is especially helpful. Add import traceback to your imports and then use it like so: async def handle_queue(name, queue: asyncio.Queue, okta_client: OktaClient): """Handle queued API requests""" while True: try: # REST OF THE FUNCTION except Exception as e: print(repr(e)... | 2 | 1 |
79,576,352 | 2025-4-16 | https://stackoverflow.com/questions/79576352/is-it-possible-to-use-the-closed-form-of-fibonacci-series-to-generate-the-nth-fi | The closed-form of the Fibonacci series is the following: As you can see the expression contains square roots so we cannot use it directly to generate Nth Fibonacci number exactly, as sqrt(5) is irrational, we can only approximate it even in pure mathematics, and floating point inaccuracies introduces a whole other lo... | I have done it, I have made the closed form spit out Nth Fibonacci number exactly efficiently. Now instead of doing all that inefficient binomial expansion, we can reduce the problem to the most basic part. Since we are doing exponentiation, we are really just doing multiplications repeatedly, we first need to find a w... | 3 | 6 |
79,575,935 | 2025-4-15 | https://stackoverflow.com/questions/79575935/trying-to-exeute-the-dbms-stats-function-in-a-python-script | I inherited a 1000+ line query the works in oracle's sql developer. When I try running the query in a python script, I get an error (An error occurred: ORA-00900: invalid SQL statement) at the line: EXEC DBMS_STATS.gather_table_stats('SSS', 'YYY'). I have very little experience with databases and a Google search of the... | The script can be converted into a single PL/SQL anonymous block. The advantage of this conversion is that it allows the exact same block to run on all environments. (Although the slash at the end should probably be excluded when running from Python.) The disadvantage of this conversion is that all the DDL statements n... | 1 | 0 |
79,576,073 | 2025-4-15 | https://stackoverflow.com/questions/79576073/can-you-create-multiple-columns-based-on-the-same-set-of-conditions-in-polars | Is it possible to do something like this in Polars? Like do you need a separate when.then.otherwise for each of the 4 new varialbles, or can you use struct to create multiple new variables from one when.then.otherwise? Regular Python example: if x=1 and y=3 and w=300*z and z<100: tot = 300 work = 400 sie = 500 walk = '... | If you remove the .struct.field() call you will see the issue. # DuplicateError: multiple fields with name 'literal' found You need to give names to the struct fields you are creating. df.with_columns( pl.when(pl.col('Movie') == 'Up') .then(pl.struct(pl.lit(0).alias('a'), pl.lit(2).alias('b'))) .otherwise(pl.struct(pl... | 1 | 2 |
79,576,094 | 2025-4-15 | https://stackoverflow.com/questions/79576094/whats-the-best-way-to-group-by-more-than-one-column | Essentially, I want to group all records that match either key Input: |id|key1|key2| |-|-|-| |1|a|x| |2|a|y| |3|b|y| |4|c|z| Desired output: (The first 3 rows are grouped together) |key1 (or any identifier, I only care about the final counts)|len| |-|-| |a|3| |c|1| My attempted (incomplete) solution: import polars as... | If I understand you correctly, you want to create equivalence relationships between key1 and key2, and keep merging things into groups if there exists a relationship chain that connects the two? So in this case since there is a row a, y any rows which have a or y in them should be merged? In this case it's hard to expr... | 2 | 2 |
79,575,941 | 2025-4-15 | https://stackoverflow.com/questions/79575941/why-does-randomforestclassifier-in-scikit-learn-predict-even-on-all-nan-input | I am training a random forest classifier in python sklearn, see code below- from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=42) rf.fit(X = df.drop("AP", axis =1), y = df["AP"].astype(int)) When I predict the values using this classifier on another dataset that has NaN value... | In the most recent version of scikit-learn (v1.4) they added support for missing values to RandomForestClassifier when the criterion is gini (default). Source: https://scikit-learn.org/dev/whats_new/v1.4.html#id7 | 1 | 2 |
79,575,632 | 2025-4-15 | https://stackoverflow.com/questions/79575632/why-do-i-get-get-http-1-1-404-not-found-with-fastapi-server | I am trying to create a token with FastAPI: > import json > import os > import aiohttp > import asyncio > from fastapi import FastAPI > from fastapi import APIRouter, Request > from fastapi.responses import JSONResponse > > token = APIRouter(prefix="/management/api", tags=["API Apl token"]) > > app=FastAPI() > app.incl... | The reason of your issue is that you're trying to run a FastAPI APIRouter instance (token) directly with uvicorn, instead of the actual FastAPI application (app). Your uvicorn command: uvicorn peg:token --reload is trying to start the app using the token router as the main app, which won’t work since token is not a Fa... | 3 | 4 |
79,591,487 | 2025-4-24 | https://stackoverflow.com/questions/79591487/roll-back-a-commit | Note: This question focuses on web apps utilising MySQL's transactions - commit and rollback. Even though the code samples below use Python, the problem itself is not limited to the choice of programming language building the web app. Imagine I have two files: main.py and my_dao.py. main.py acts as the starting point o... | I don't do transaction commit or rollback in DAO class methods, because of the nesting problem you identified. Some people "fake" transactions using a counter. If a nested DAO called by another DAO starts a transaction, it doesn't really start a transaction, it just increments the nesting counter. And it doesn't really... | 2 | 4 |
79,591,152 | 2025-4-24 | https://stackoverflow.com/questions/79591152/root-mean-square-linearisation-for-linear-programming | I am trying to linearise the function root mean square to use it in a linear optimisation or Mixed integer linear optimisation. Any idea how I could do this? For instance with the example below, if I wanted to maximize P*100, the model would give P=10, Q = 0 and S=10. Many thanks import numpy as np import pulp S = np.s... | It cannot be linearised with an exact problem. It can be linearised with an approximate problem, and depending on a few things, to a decent degree of accuracy. It cannot be linearised with a continuous solver. It must be linearised with a mixed integer solver because the upper parabolic constraint is non-convex; only t... | 1 | 1 |
79,595,678 | 2025-4-28 | https://stackoverflow.com/questions/79595678/how-can-i-store-ids-in-python-without-paying-the-28-byte-per-int-price | My Python code stores millions of ids in various data structures, in order to implement a classic algorithm. The run time is good, but the memory usage is awful. These ids are ints. I assume that since Python ints start at 28 bytes and grow, there's a huge price there. Since they're just opaque ids, not actually mathem... | Your use case is for IDs to be stored as keys and values of a dict. But since keys and values of a dict have to be Python objects, they must each be allocated an object header as well as a pointer from the dict. To be able to actually store keys and values at 4 bytes each you would have to implement a custom hash table... | 1 | 3 |
79,594,689 | 2025-4-27 | https://stackoverflow.com/questions/79594689/python-asyncio-lock-release-object-nonetype-cant-be-used-in-await-expressi | Code & Context I'm building a multithreaded program to automate API calls, to retrieve all the information I need based off of a list of unique IDs. To do this, I ended up creating my own Lock class to allow threads either concurrent read access to specific variables, or one single thread to read and write. # Read-Writ... | In the function release_write, you've mentioned asyncio.Lock.release(). asyncio.Lock.release() is a synchronous method, but you're trying to await it. When you await it, Python tries to treat the return value (which is None) as an awaitable, causing TypeError. So remove await from release_write() At present, you're a... | 2 | 3 |
79,595,929 | 2025-4-28 | https://stackoverflow.com/questions/79595929/warm-up-huggingface-transformers-models-efficiently-to-reduce-first-token-latenc | In production deployment of Hugging Face LLMs, the first inference call often has very high latency ("cold start"), even on a machine where the model is already loaded into memory. Subsequent calls are much faster. I want to implement a model warm-up strategy that: Primes the model and GPU memory before real user requ... | You could use a dummy inference immediately after loading the model. For pipeline: # Warmup _ = generator("Warm up prompt", max_new_tokens=1) For raw model.generate(): from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-7b-instruct") model = AutoModelFo... | 2 | 0 |
79,594,983 | 2025-4-27 | https://stackoverflow.com/questions/79594983/why-does-np-fromfile-fail-when-reading-from-a-pipe | In a Python script, I've written: # etc. etc. input_file = args.input_file_path or sys.stdin arr = numpy.fromfile(input_file, dtype=numpy.dtype('f32')) when I run the script, I get: $ cat nums.fp32.bin | ./myscript File "./myscript", line 123, in main arr = numpy.fromfile(input_file, dtype=numpy.dtype('f32')) OSError:... | This error happens because np.fromfile() is implemented in a fairly counterintuitive way. You might assume that this is implemented by repeatedly calling e.g. file.read(4096), then copying the resulting buffer to the appropriate place in the array. It does not work like this. Instead, it is following roughly this proce... | 1 | 1 |
79,596,631 | 2025-4-28 | https://stackoverflow.com/questions/79596631/convert-month-abbreviation-to-full-name | I have this function which converts an English month to a French month: def changeMonth(month): global CurrentMonth match month: case "Jan": return "Janvier" case "Feb": return "Février" case "Mar": return "Mars" case "Apr": return "Avril" case "May": return "Mai" case "Jun": return "Juin" case "Jul": return "Juillet" ... | Question seems a bit unclear to me, Do you want to replace the month column in dataframe itself? If yes something like this can work: def changeMonth(month): if month=="Jan": return "Janvier" elif month=="Feb": return "Février" elif month=="Mar": return "Mars" elif month=="Apr": return "Avril" elif month=="May": return... | 3 | 0 |
79,596,399 | 2025-4-28 | https://stackoverflow.com/questions/79596399/how-to-log-display-app-name-host-and-port-upon-startup | In my simple Flask app, I've created the following .flaskenv file: FLASK_APP=simpleflask.app FLASK_RUN_HOST=127.0.0.1 FLASK_RUN_PORT=60210 Now, I would like my app to log the following message upon startup: Running my.flask.app on http://127.0.0.1:60210 ... The message should be logged just once, not per each request... | app = Flask(__name__) # ... with app.app_context(): app.logger.info(f"Running {os.environ.get('FLASK_APP')} on http://{os.environ.get('FLASK_RUN_HOST')}:{os.environ.get('FLASK_RUN_PORT')} ...") | 1 | 0 |
79,596,838 | 2025-4-28 | https://stackoverflow.com/questions/79596838/scipy-sparse-one-subarray-at-many-locations-in-a-larger-array | Say I have a sparse subarray whose contents and shape are known: import scipy.sparse as sp sub = sp.coo_array([[a, b], [c, d]]) I'd like to place this subarray at many locations, according to some known pattern, in a larger sparse array of arbitrary size. The code can compute the size of the large array (say NxN) but ... | Thanks to Reinderien's comment, I was able to figure this out - I had no idea what a Kronecker product was until now. sp.kron does exactly what I want, with the added benefit of being able to multiply each block by a coefficient. For the contrived example, the code to specify the pattern would be: import scipy.sparse a... | 1 | 3 |
79,596,227 | 2025-4-28 | https://stackoverflow.com/questions/79596227/finding-numerical-relationships-between-columns | I have selected a subset of numerical columns from a database and I want to iterate through the columns selecting a target_column and comparing it with the result of a numerical operation between two other columns in the dataframe. However, I am unsure as to how to compare the result (e.g. col1 * col2 = target_column).... | To solve your problem I strongly suggest you to vectorize your data and use as few Pandas operations as possible, since a lot of operations are required and, consequently, the more we can rely solely on NumPy the faster the code will run (NumPy's core is written in C). Since there are multiple operations to take in acc... | 1 | 1 |
79,596,493 | 2025-4-28 | https://stackoverflow.com/questions/79596493/generate-rtdb-key-without-creating-node | I'm trying to create a Python function that generates a valid key in my Firebase Realtime Database (using the same logic as other keys, ensuring no collision and chronological order). Something like this: def get_new_key() -> str: return db.reference(app=firebase_app).push().key print(get_new_key()) # output: '-OOvws9u... | You're right, each time you call push(value='') a child node in the Realtime Database will be created. If you are calling the function without passing a value, the default string that will be used for writing the data will be an empty string. As far as I know, the Firebase SDKs for Python does not publicly expose a pus... | 2 | 2 |
79,596,418 | 2025-4-28 | https://stackoverflow.com/questions/79596418/django-the-page-refreshed-when-i-click-on-import-file-and-no-message-appears | i am working on a django powered web app, and i want to customize admin view of one of my models. i have made a custom template for the add page and overrides save function in admin class to process input file before saving. here i have the admin class of RMABGD: @admin.register(RMABGD) class RMABGDAdmin(BaseModelAdmin... | Problem: Your custom <form> never hits Django admin’s add_view/changeform_view, so save_model/process_excel_import isn’t called and no messages ever display. Option 1: Override the Admin View Intercept your “Import Excel” POST, run process_excel_import, then redirect so messages render: from django.contrib import admi... | 1 | 2 |
79,595,840 | 2025-4-28 | https://stackoverflow.com/questions/79595840/why-doesnt-multiprocessing-process-start-in-python-guarantee-that-the-process | Here is a code to demo my question: from multiprocessing import Process def worker(): print("Worker running") if __name__ == "__main__": p = Process(target=worker) p.start() input("1...") input("2...") p.join() Note, ran on Python 3.13, Windows x64. And the output I got is (after inputting Enter twice): 1... 2... Work... | This is normal behaviour, and it's usually exactly what you want when you choose multiprocessing over, say, threading, i.e., the processes continue in parallel and do not block each other. As mentioned in the comments, here's an example how you can make sure the worker is running before proceeding: import time from mul... | 1 | 3 |
79,595,836 | 2025-4-28 | https://stackoverflow.com/questions/79595836/generating-key-value-map-from-aggregates | I have raw data that appears like this: ┌─────────┬────────┬─────────────────────┐ │ price │ size │ timestamp │ │ float │ uint16 │ timestamp │ ├─────────┼────────┼─────────────────────┤ │ 1697.0 │ 11 │ 2009-09-27 18:00:00 │ │ 1697.0 │ 5 │ 2009-09-27 18:00:00 │ │ 1697.0 │ 5 │ 2009-09-27 18:00:00 │ │ 1697.0 │ 5 │ 2009-09... | Use this query to calculate the total size (sum_size) for each price at every timestamp in your dataset. WITH aggregated_data AS ( SELECT timestamp, price, SUM(size) AS sum_size FROM tickdata GROUP BY timestamp, price ) SELECT timestamp, MAP(ARRAY_AGG(price), ARRAY_AGG(sum_size)) AS histogram FROM aggregated_data GROUP... | 1 | 1 |
79,593,802 | 2025-4-26 | https://stackoverflow.com/questions/79593802/notimplementederror-gets-triggered-unexpectedly-when-tring-to-define-an-abstr | This question is related to a question about the implementation of class property in Python which I have asked yesterday. I received a working solution and wrote my classProp and ClassPropMeta as the solution suggests. However, when I want to use class property together with @abstractmethod, problem occurs. Below is a ... | This is slihghtly tricky at first glance. The problem occurs during class creation, when Python runs thru initialization of your B class. At this point, the __new__() method of ABCMeta class needs to figure out which methods are abstract and it does so by actually accessing the X descriptor on B. That in turn triggers ... | 1 | 1 |
79,594,903 | 2025-4-27 | https://stackoverflow.com/questions/79594903/gathering-and-change-multiple-excel-files-columns-based-on-another-excel-file-wi | I'm working on a work project that requires the data of multiple excel files, which needed to be upload to the database. There is another file name "table_name" that contains the current columns data name, with the file name as the sheet name. I'm trying to code in python in order to change the columns name based on "t... | Still not 100% on what your doing but perhaps this will help; From your updated details seems the XLSX file "table_name.xlsx" has two sheets with the name changes; 'chung1' & 'nganh' and you want to apply the changes to all XLSX files in the List 'list' So perhaps what you want to do is create one dictionary 'renamee_d... | 2 | 1 |
79,595,753 | 2025-4-28 | https://stackoverflow.com/questions/79595753/sql-alchemy-generates-integer-instead-of-int-for-sql-lite | Python Sql Alchemy generates table with VARCHAR for sql lite instead of INTEGER so select for sql lite ordered by with alphabet number Given City Table in Sql lite generated from sql alchemy: class City(Base): __tablename__ = "city" id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True) city_name: Mappe... | In SQLite, if the id column is stored as TEXT instead of INTEGER, the ORDER BY will sort alphabetically, not numerically. That's why '100567' can come before '15470'. To fix it, you should cast id to an integer when ordering: SELECT id, city_name FROM city WHERE city_name = 'Paris' ORDER BY CAST(id AS INTEGER) LIMIT 1;... | 1 | 1 |
79,595,744 | 2025-4-28 | https://stackoverflow.com/questions/79595744/why-does-init-requires-an-explicit-self-as-an-argument-when-calling-it-as-ba | I know of two ways to call a superclass's constructor from a derived class: super().__init__() and base.__init__(self). Why does the second require me to explicitly supply self as an argument? Here's a snippet that demonstrates the difference: class base: def __init__(self,/): print("initializing") class der(base): def... | TL;DR: super() is an instance. der is a class. To undersand this properly, you have to understand how instance methods in Python work. When you write an instance method, you have to include self as the first parameter like this: class Foo: def bar(self): ... This is because when you call an instance method, Python aut... | 1 | 2 |
79,594,922 | 2025-4-27 | https://stackoverflow.com/questions/79594922/how-to-add-function-parameter-kwargs-during-runtime | I have hundreds of functions test1, test2, ... Function testX may or may not have kwargs: def test1(x, z=1, **kwargs): pass def test2(x, y=1): pass def test3(x, y=1, z=1): pass ... and I have a function call_center: tests = [test1, test2, test3] def call_center(**kwargs): for test in tests: test(**kwargs) call_center... | To add variable keyword parameters (kwargs) to a function that does not have it you can re-create the function with types.FunctionType but with the code object replaced with one that has the inspect.CO_VARKEYWORDS flag enabled in the co_flags attribute, the kwargs name added to the co_varnames attribute, and the number... | 2 | 3 |
79,595,603 | 2025-4-28 | https://stackoverflow.com/questions/79595603/sketch-partial-regression-chart-using-dash | i have dataframe, in which we are given x and y columns and between them i want to sketch regression model, main idea is that i should use dash framework, as according chow test , there could be difference between two regression model at different instance value,based on following link : dash models i wrote following c... | It may need to add all code in one function and return both figures fig = px.scatter(selected, x=x, y=y) fig.add_traces(px.line(selected, x=x, y=y_predicted).data) return fig Full working code with random data. import pandas as pd from dash import Dash,html,dcc,callback,Output,Input from sklearn.linear_model import ... | 1 | 3 |
79,593,505 | 2025-4-26 | https://stackoverflow.com/questions/79593505/cant-close-cookie-pop-up-on-website-with-selenium-webdriver | I am trying to use selenium to click the Accept all or Reject all button on a cookie pop up for the the website autotrader.co.uk, but I cannot get it to make the pop up disappear for some reason. This is the pop up: and here is the html: <button title="Reject All" aria-label="Reject All" class="message-component messa... | As you can see, the pop-up window is embedded within an <iframe>Selenium must first switch the driver's context to that iframe before attempting to locate or interact with any elements contained within it. wait for the desired iframe element to be available to switch to it: iframe = wait.until(EC.frame_to_be_available_... | 1 | 2 |
79,595,515 | 2025-4-27 | https://stackoverflow.com/questions/79595515/urlparse-urlsplit-and-urlunparse-whats-the-pythonic-way-to-do-this | The background (but is not a Django-only question) is that the Django test server does not return a scheme or netloc in its response and request urls. I get /foo/bar for example, and I want to end up with http://localhost:8000/foo/bar. urllib.parse.urlparse (but not so much urllib.parse.urlsplit) makes gathering the re... | If you need it in Django then I found request.build_absolute_uri() in question How can I get the full/absolute URL (with domain) in Django? - Stack Overflow I didn't test it but maybe it resolves this problem in Django. Other modules/frameworks may have also own functions for this. As I rembeber module scrapy for scrap... | 1 | 2 |
79,595,283 | 2025-4-27 | https://stackoverflow.com/questions/79595283/how-to-properly-extract-all-duplicated-rows-with-a-condition-in-a-polars-datafra | Given a polars dataframe, I want to extract all duplicated rows while also applying an additional filter condition, for example: import polars as pl df = pl.DataFrame({ "name": ["Alice", "Bob", "Alice", "David", "Eve", "Bob", "Frank"], "city": ["NY", "LA", "NY", "SF", "LA", "LA", "NY"], "age": [25, 30, 25, 35, 28, 30, ... | The error is not .filter() specific. and I don't think it's a bug. Expressions allow you to use Series on the RHS, and it will return an expression. pl.lit(True) & pl.Series([1, 2]) # <Expr ['[(true) & (Series)]'] at 0x134D05F90> But the other way round doesn't make sense, and errors. pl.Series([1, 2]) & pl.lit(True) ... | 3 | 3 |
79,595,292 | 2025-4-27 | https://stackoverflow.com/questions/79595292/how-can-i-delete-a-row-from-a-csv-file | enter image description here enter image description here When I try to delete a row from my csv file, it deletes everything else and then turns that row sideways and separates the characters into their own columns. I have no idea what is happening. Above are pictures that show the before and after of my csv file when ... | avoid shadowing Use singular and plural identifiers where appropriate. The usual idiom is for x in xs: You wrote: for i, guests in enumerate(guests, start=1): if name == guests[0]: del guests[i] What you wanted to write was for i, guest in ... When testing name equality, you intended to refer to guest[0], the first c... | 2 | 2 |
79,595,244 | 2025-4-27 | https://stackoverflow.com/questions/79595244/does-py-cord-support-discords-new-user-install-commands-feature | I recently learned that Discord has updated with a feature called "User Install" that allows users to install bots to their personal accounts, not just servers. As I understand it, this enables users to use certain bot commands in servers where the bot isn't officially present. I'm developing a Discord bot using py-cor... | As of Pycord v2.6, this is supported. if you want your command to be available in both guilds and to users who have installed your bot, you can specify both guild_install and user_install in an integration types parameter inside a @bot.slash_command() decorator: @bot.slash_command( name="hello", description="say hello"... | 1 | 1 |
79,589,289 | 2025-4-23 | https://stackoverflow.com/questions/79589289/is-it-good-practice-to-override-an-abstract-method-with-more-specialized-signatu | Background information below the question. In Python 3, I can define a class with an abstract method and implement it in a derived class using a more specialized signature. I know this works, but like many things work in many programming languages, it may not be good practice. So is it? from abc import ABC, abstractmet... | Your first example would be completely fine, as everything the abstract parent accepts is also accepted by the derived class, the argument types are identical (<s>a</s>, <s>b</s> untyped). See comment for why the first snippet isn't quite type-correct, only an override with def foo(self, a:Any=default, b:Any=default, *... | 1 | 1 |
79,595,094 | 2025-4-27 | https://stackoverflow.com/questions/79595094/why-is-flask-sqlalchemy-giving-me-an-error-no-such-table-users | import os from flask import Flask, render_template, redirect, url_for, request from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') app.config["SQLALCHEMY_DAT... | The error about no such column: location mentioned in your question is different from the actual traceback, which is showing a no such table: users error. However I see the issue. You're initializing Flask-SQLAlchemy after defining routes, but before initializing app context. You need to move your configuration setting... | 2 | 5 |
79,594,776 | 2025-4-27 | https://stackoverflow.com/questions/79594776/python-abstract-methods-for-children-but-such-that-dont-prohibit-instances-of | I'm currently using ABC's to ensure that my child classes implement a specific method (or property, in this particular case). I want to make it impossible to create children of Entity without implementing similar_entities: class Entity(ABC): @property @abstractmethod def similar_entities(self) -> list[str]: return [] c... | Here is my code that fits: Implementing similar_entities on subclasses is allowed. Entity can be instantiated. Subclasses defined without similar_entities property raise TypeError. class MyMeta(type): def __init__(self, classname, superclasses, attributedict): super().__init__(classname, superclasses, attributedict) ... | 2 | 3 |
79,594,789 | 2025-4-27 | https://stackoverflow.com/questions/79594789/issue-with-reading-a-csv-file-with-all-columns-as-string-using-polars | I have below Python code using polars, and I do not want Python to auto parse values as dates or integers unless explicitly stated. schema_overrides doesn't prevent auto conversion either. import polars as pl # Read the CSV file with all columns as strings using schema_overrides file_path = "./xyz.csv" df = pl.read_csv... | This is what infer_schema=False is for. When False, the schema is not inferred and will be pl.String if not specified in schema or schema_overrides. pl.read_csv(b"""a,b,c 1,2,3""") # shape: (1, 3) # ┌─────┬─────┬─────┐ # │ a ┆ b ┆ c │ # │ --- ┆ --- ┆ --- │ # │ i64 ┆ i64 ┆ i64 │ # ╞═════╪═════╪═════╡ # │ 1 ┆ 2 ┆ 3 │ #... | 4 | 4 |
79,594,764 | 2025-4-27 | https://stackoverflow.com/questions/79594764/increasing-the-size-of-the-model | Recently I trained two MLP model and saved weights for future work. I develop one module for loading model and use these model in another module. Load model module contain this code to load models: def creat_model_extractor(model_path, feature_count): """ This function create model and set weights :param model_path: ad... | Every time you call model.inference_step(), TensorFlow creates a new computation graph, because your @tf.function is dynamically bound inside your model object. TensorFlow is trying to trace and cache the @tf.function, but it can't re-use the existing trace properly, because model.inference_step is reattached dynamical... | 1 | 1 |
79,593,358 | 2025-4-25 | https://stackoverflow.com/questions/79593358/how-do-you-efficiently-find-gaps-in-one-list-of-datetimes-relative-to-another | I have datasets from multiple instruments with differing, but hypothetically concurrent datetime stamps. If date from instrument A does not correspond to any data from instrument B within some interval, I want to flag those data for removal later. The current way I handle this is to loop over A and test against B with ... | Faster code with Numpy A simple way to make this faster is to vectorise the code with Numpy: def findGaps_faster(dTM,dTT): bTs = [] start = -1 i, index, stop = 0,0,0 tThreshold = timedelta(seconds=30) dTT = np.array(dTT, dtype=np.datetime64) for index, esTimeI in enumerate(dTM): esTimeI = np.datetime64(esTimeI) tDiff =... | 1 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.