QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
79,523,897
1,719,931
SQLAlchemy add a table to an automapped Base results in `object has no attribute '_sa_instance_state'`
<p>I'm mirroring a remote MS SQL into a local SQLite db.</p> <p>Here is the relevant code:</p> <pre><code>eng_str = rf&quot;mssql+pymssql://{user_domain}\{username}:{password}@{hostip}/{dbname}&quot; engine_remote = create_engine(eng_str, echo=False) dbfp = Path(&quot;../../data/mydb.sqlite3&quot;) engine_local = crea...
<python><sqlalchemy>
2025-03-20 19:15:27
2
5,202
robertspierre
79,523,835
1,178,960
python socket streaming (yield) llm response seems to be blocking everything
<p>I am learning llm recently and trying to build a simple chatbot, where multiple clients can connect to this chatbot and chat with the model. I created a simple python code below, but I noticed when multiple clients are connected, and 1 client is receiving the stream, other clients are blocked.</p> <p>I tried chatgpt...
<python><websocket><stream><large-language-model>
2025-03-20 18:37:39
0
842
Dongminator
79,523,764
856,588
using asyncio in Streamlit
<p>many frameworks use <code>asyncio</code> internally so there is no way get around it. is there a reliable recommended way of dealing with <code>asyncio</code> in Streamlit apps? i often get <code>Event loop is closed</code> or something similar when using it. not providing any code because it is basically anything w...
<python><python-asyncio><streamlit>
2025-03-20 18:03:57
0
4,085
Maxim Volgin
79,523,708
395,857
How can I resolve the 403 Forbidden error when deploying a fine-tuned GPT model in Azure via Python?
<p>I follow Azure's <a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/tutorials/fine-tune?tabs=python-new%2Ccommand-line" rel="nofollow noreferrer">tutorial</a> on fine-tuning GPT. I'm stuck at the deployment phase.</p> <p>Code:</p> <pre><code># Deploy fine-tuned model import json import requests to...
<python><azure><azure-openai><fine-tuning><gpt-4>
2025-03-20 17:31:33
2
84,585
Franck Dernoncourt
79,523,703
720,300
Indexing issue in python script for detection of hairpin curves in road gpx
<p>I have a working script that will process gpx files in the same folder as the script, detect hairpin curves and make a report, with length and gradient statistics, for straight and for curved portions of the track.</p> <p>The algorithm looks for cumulative changes in bearings in a look ahead search distance along th...
<python><distance><gpx><bearing>
2025-03-20 17:29:32
0
2,874
Kay
79,523,696
6,471,140
how to modify a step or a prompt of an existing langchain chain (customize SelfQueryRetriever)?
<p>I need to customize a SelfQueryRetriever(the reason is: the generated target queries in OpenSearch are being generated incorrrectly so we need to tune prompts + we need to add some custom behavior such as multi-tenancy) but we don't want to re-write the whole chain, just the parts what we need to customize. How can ...
<python><nlp><artificial-intelligence><langchain><large-language-model>
2025-03-20 17:26:35
0
3,554
Luis Leal
79,523,622
7,483,211
Python Intellisense tooltip forever "Loading" in Cursor AI Editor
<p>I'm trying out the Cursor &quot;AI&quot; editor with a Python repository.</p> <p>Cursor offered to import all my VS Code extensions to ease onboarding.</p> <p>But now Intellisense doesn't seem to work at all. In VS Code, when I hover over a variable or method, I get type information and/or method documentation. This...
<python><intellisense><cursor-ide>
2025-03-20 16:55:53
0
10,272
Cornelius Roemer
79,523,584
169,947
Use a single pyproject.toml for 'poetry' & 'uv': dev dependencies
<p>I'm trying to let people on my project (including myself) migrate to <code>uv</code> while maintaining compatibility with people who still want to use <code>poetry</code> (including some of our builds). Now that <a href="https://python-poetry.org/blog/announcing-poetry-2.0.0/#supporting-the-project-section-in-pypro...
<python><python-poetry><pyproject.toml><uv>
2025-03-20 16:40:17
1
24,277
Ken Williams
79,523,536
5,602,104
Can you raise an AirflowException without dumping the entire traceback into the logs?
<p>In Airflow, you're suppose to raise an AirflowException if you want a task to be marked as a failure. But the raised error doesn't seem to be caught in the top-level Airflow module, and so it results in the entire stacktrace being dumped into the logs. If you do your error handling properly, it should be possible to...
<python><airflow>
2025-03-20 16:24:10
1
729
jcgrowley
79,523,500
1,570,985
RMSNorm derivative using sympy -- problem with summation over fixed number of elements
<p>I have following sympy equation for RMSNorm (easier to see in Jupyter notebook)</p> <pre class="lang-py prettyprint-override"><code>import sympy as sp # Define the symbols x = sp.Symbol('x') # Input variable n = sp.Symbol('n') # Number of elements gamma = sp.Symbol('gamma') epsilon = sp.Symbol('epsilon') # Small...
<python><sympy>
2025-03-20 16:09:07
1
730
algoProg
79,523,375
3,815,773
max() output depends on order when nan is present
<p>I am puzzled by this behaviour of Python's max() function:</p> <pre><code>&gt;&gt;&gt; a = 100 &gt;&gt;&gt; n = float(&quot;nan&quot;) &gt;&gt;&gt; a 100 &gt;&gt;&gt; n nan &gt;&gt;&gt; max(a, n) 100 &gt;&gt;&gt; max(n, a) nan </code></pre> <p>That is the ORDER of the parameters determines the outcome?</p>
<python><math><comparison><nan>
2025-03-20 15:16:25
0
505
ullix
79,523,183
10,658,339
Why are date and time data not mapping/uploading to PostgreSQL with the correct datatype?
<p>I'm working with a PostgreSQL database in Python using psycopg2 and pandas. My workflow involves reading data into Python, uploading it to the database, retrieving it back into Python, and then updating the database. To ensure data integrity, I aim to create a comprehensive mapping between pandas data types and Post...
<python><pandas><database><postgresql><dtype>
2025-03-20 13:59:56
0
527
JCV
79,523,161
5,506,912
Connect to socket.io xhr request with python
<p>I'm trying to retrieve some data from <a href="https://www.winamax.fr/paris-sportifs/sports/1/7/4" rel="nofollow noreferrer">here</a>, namely games and odds. I know the data is in the response of this GET request as shown in the network tab below:</p> <p><a href="https://i.sstatic.net/ykrU3Pk0.png" rel="nofollow nor...
<python><web-scraping><socket.io>
2025-03-20 13:52:29
1
521
M.O
79,523,159
4,875,766
How do I type a generic subclass correctly?
<p>Here is some example code:</p> <p>I have my underlying generic object.</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar(&quot;T&quot;, str, int, bytes) class MyObj(Generic[T]): id: T </code></pre> <p>and some implementations</p> <pre class="lang-py prettyprint-override"><code>class MyObjImplInt(...
<python><oop><generics><python-typing>
2025-03-20 13:51:34
2
331
TobyStack
79,522,949
5,060,208
Adding time-series logging to tensorboard
<p>Tensorboard provides access plotting <a href="https://www.tensorflow.org/tensorboard/scalars_and_keras" rel="nofollow noreferrer">scalars, histograms and images</a>. I am trying to add model predictions as simple vectors to tensorboard. Currently I am doing that through adding matplotlib images, which works great to...
<python><machine-learning><logging><tensorboard>
2025-03-20 12:33:41
0
331
Merk
79,522,829
357,024
Python type hints with default value as Type
<p>Below is a simplified example of an object factory in my Python application.</p> <pre><code>from typing import Type class Animal: def speak(self): assert False class Dog(Animal): def speak(self): print(&quot;bark&quot;) def make_animal[T : Animal](animal_class: Type[T] = Animal) -&gt; T: ...
<python><python-typing><mypy>
2025-03-20 11:46:32
0
61,290
Mike
79,522,783
12,040,751
NonExistentTime error caused by pandas.Timestamp.floor with localised timestamp
<p>I need to calculate the floor of a localized timestamp with daily resolution, but I get an exception when the daylight saving time starts.</p> <pre><code>&gt;&gt;&gt; pd.Timestamp('2024-09-08 12:00:00-0300', tz='America/Santiago').floor(&quot;D&quot;) NonExistentTimeError: 2024-09-08 00:00:00 </code></pre> <p>I unde...
<python><pandas><datetime><timestamp>
2025-03-20 11:27:10
1
1,569
edd313
79,522,749
11,863,823
How to change the title of a DataFrameSchema in pandera?
<p>I've been going through the <code>pandera</code> docs and I cannot find a way to change the title of an existing <code>pandera.DataFrameSchema</code>. Currently I do the following, which seems to work but <em>feels</em> weird because usually APIs define methods that cleanly change the properties (for instance, I hav...
<python><dataframe><pandera>
2025-03-20 11:15:43
0
628
globglogabgalab
79,522,677
364,088
How to pass an argument to a 'dependencies' function in FastAPI?
<p>Is there a way to pass an argument to a function defined within the <code>dependencies</code> argument of, for instance, <code>app.get</code>? If there isn't, what other options exist ?</p> <p>I can do the following to test a request, including examining the bearer token, before it reaches the endpoint handler:</p> ...
<python><fastapi>
2025-03-20 10:45:52
2
8,432
shearichard
79,522,584
9,729,847
{{ ds }} isn't interpreted in my airflow dag
<p>My goal is to dynamically create some <code>SFTPToS3Operator</code> to retrieve files from a server to Amazon S3.</p> <p>For instance, ,my filename is <code>xxx_date_hours_minutes_seconds.csv</code>, so I want to fetch filename from the server to use it in the <code>SFTPToS3Operator</code> operator.</p> <p>The main ...
<python><airflow>
2025-03-20 10:17:55
1
1,798
maxime G
79,522,491
13,158,157
Error opening Excel file in python edited on Excel Web Interface
<p><strong>Problem</strong>:</p> <p>I'm encountering issues when trying to open Excel files (.xlsx) with pandas that was edited on SharePoint Online (Microsoft 365) via the web Excel interface and then downloaded.</p> <p><strong>Code and Errors</strong>:</p> <pre><code>import pandas as pd # Attempt to read the Excel f...
<python><excel><pandas>
2025-03-20 09:38:40
0
525
euh
79,522,367
4,080,181
How do I read a string as if it were bytes
<p>I have a string in a file encoded in utf-8. It contains escape sequences that should not be interpreted as Unicode code points, but rather as binary numbers. How can I convert it to bytes?</p> <p>For example, consider the string 'abc \x00\x01\xff'. If I were to type this in to the Python interpreter as a bytes lit...
<python>
2025-03-20 08:54:45
2
548
August West
79,522,011
2,854,673
Python PIL image text overlay not displayed with expected color on white background image (RGB vs RGBA mode)
<p>Python PIL Image not working properly with overlay text image. I am trying to use FPDF image to convert an overlayed text png image to pdf file. However, the overlay text is not in expected colour (looks transparent) on a white background image. However, the same logic works in a zebra pattern background image.</p> ...
<python><image><python-imaging-library><overlay>
2025-03-20 05:52:06
1
334
UserM
79,521,913
577,288
python 3 - audio effect - pedalboard cannot export file
<p>I'm trying to add some reverb to an audio file. Pedalboard says it has succeeded, yet there is no file in the output directory</p> <p>I have taken the example directly from the official site</p> <p><a href="https://pypi.org/project/pedalboard/0.4.1/" rel="nofollow noreferrer">official site</a></p> <pre><code>import ...
<python><pyaudio>
2025-03-20 04:47:24
0
5,408
Rhys
79,521,805
2,469,032
Shift+enter inserts extra indents
<p>I have a Python source file with some dummy code:</p> <pre><code>a = 3 if a == 1: print(&quot;a = 1&quot;) elif a == 2: print(&quot;a = 2&quot;) else: print(&quot;Other&quot;) </code></pre> <p>When I submit the code to terminal with shift+enter, I get the following error. It looks like VS Code changed th...
<python><visual-studio-code><indentation><read-eval-print-loop>
2025-03-20 03:09:10
2
1,037
PingPong
79,521,599
3,084,178
Python Kivy Button text_size = self.size wraps in button way before it should
<p>I'm coding an application in Kivy (seriously impressive library).</p> <p>I'm coming up against an interesting issue, and wondering if I'm missing something and/or if there's a fix.</p> <p><a href="https://i.sstatic.net/XIBd9nNc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XIBd9nNc.png" alt="Screens...
<python><android><kivy>
2025-03-19 23:43:03
1
1,014
Dr Xorile
79,521,249
927,039
Advice on using Wagtail (e.g. RichTextField) with Pylance type checking
<p>Nearly all my Wagtail models files are full of errors according to Pylance and I'm not sure how to silence them without either adding <code># type: ignore</code> to hundreds of lines or turning off Pylance rules that help catch genuine bugs. The errors often come from <code>RichTextField</code> properties on my mode...
<python><python-typing><wagtail><pyright>
2025-03-19 19:46:07
1
525
phette23
79,521,147
774,575
How to manage QLineEdit.returnPressed signal from multiple QLineEdit?
<p>Using <code>qtpy</code> (and the actual <code>Qt5</code> behind):</p> <pre><code>from qtpy.QtWidgets import QApplication, QMainWindow, QLineEdit class MainWindow(QMainWindow): def __init__(self): super().__init__() widget = QLineEdit() widget.setPlaceholderText(&quot;Enter your text&quot...
<python><qt><pyqt><qlineedit>
2025-03-19 18:57:31
0
7,768
mins
79,521,127
4,043,845
filedialog doesn't return anything on second run
<p>I'm working on a tkinter/customtkinter app to load data to MySQL. Below are the relevant classes. When I run this code to load a single file, I have no issues. The problem comes when I click <code>self.load_another_button</code> in the class <code>loading_window</code>. It properly brings me back to <code>file_selec...
<python><tkinter><customtkinter><filedialog>
2025-03-19 18:47:58
0
2,545
Kyle
79,521,003
1,443,801
How to install CPU only version of pytorch using setuptools backed pyproject.toml
<p>Consider the following pyproject.toml</p> <pre><code>[build-system] requires = [&quot;setuptools&gt;=75&quot;, &quot;wheel&quot;] build-backend = &quot;setuptools.build_meta&quot; [project] name = &quot;test&quot; version = &quot;0.0.1-dev&quot; requires-python = &quot;&gt;=3.9&quot; dependencies = [ &quot;tens...
<python><pytorch><setuptools><pyproject.toml>
2025-03-19 17:51:51
0
1,321
Paagalpan
79,520,985
16,383,578
How to simplify the generation process of these boolean images?
<p>I have written code that generates <a href="https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence" rel="nofollow noreferrer">Thue-Morse sequence</a>, its output is a NumPy 2D array containing only 0s and 1s, the height of the array is 2<sup>n</sup> and the width is n. More specifically, each intermediate result ...
<python><numpy><image><opencv><image-processing>
2025-03-19 17:43:36
1
3,930
Ξένη Γήινος
79,520,972
5,215,538
FastAPI hosted on Lambda does not serve static content
<p>I have a FastAPI app hosted on AWS Lambda + Api Gateway using Mangum. However it seems not to be able to serve static content returning 404 error.</p> <p>Here is how static directory is mounted</p> <pre class="lang-py prettyprint-override"><code>application = FastAPI(title=&quot;MyApp&quot;) static_directory = Path...
<python><amazon-web-services><aws-lambda><fastapi><mangum>
2025-03-19 17:32:56
0
4,109
Sergii Gryshkevych
79,520,909
2,410,558
What's necessary for the `keras` tag to populate on TensorBoard?
<p>I'm trying to view the conceptual graph of a fairly complex TensorFlow model in TensorBoard. However, the option is greyed out. (I have no issue viewing the op graph).</p> <p>My understanding is that in TensorBoard, the <code>keras</code> tag is necessary to view the conceptual graph. However, there are no tags a...
<python><tensorflow><keras><tensorboard>
2025-03-19 17:03:33
1
674
Brandon Sherman
79,520,845
2,130,515
How can I get bot response using Messaging API
<p>This is my first attempt to build a chatbot using Botpress. To start, my bot is so simple and consists of: start node and autonomous node (&quot;country name extraction&quot;). The latter node receive a text and return the extracted countries.</p> <p>Everything is working well on the emulator.</p> <p>I setup the mes...
<python><bots><botpress>
2025-03-19 16:38:34
0
1,790
LearnToGrow
79,520,843
1,593,077
Am I using a "backported module"?
<p>I'm trying to use the Python <a href="https://github.com/netromdk/vermin" rel="nofollow noreferrer">vermin</a> utility to determine the minimum version needed to run a script of mine. Running it, I get:</p> <pre class="lang-none prettyprint-override"><code>$ vermin --no-parse-comments foo.py Tips: - You're using pot...
<python><pip><python-module><backport>
2025-03-19 16:37:24
1
137,004
einpoklum
79,520,697
7,687,981
Dynamic dependency install with pyproject.toml
<p>Is there a way to dynamically check the version of a package installed system wide and set that as a package dependency in the pyproject.toml? Specially, I need to check if a person already has GDAL installed system wide and if they do, set the python gdal version to that. If I were manually installing the gdal pyth...
<python><gdal><toml>
2025-03-19 15:44:32
1
815
andrewr
79,520,460
2,854,673
Python Image AttributeError: 'ImageDraw' object has no attribute '__array_interface__'
<p>Getting this issue while saving and writing text over image using python image library. I am trying to write a text over a png image using Pillow imaging library, however after trying previous answers in stack overflow, still face this issue.</p> <pre><code>from pickle import FALSE import sys #keep sys import and in...
<python><numpy><image><python-imaging-library>
2025-03-19 14:15:50
1
334
UserM
79,520,442
432,691
How do I detect a database timeout in python?
<p>I have some code that executes database queries, like so:</p> <pre><code>self.db_cursor = self.db_conn.cursor(buffered=False) self.db_cursor.execute(query) </code></pre> <p>Now I want to add a timeout, so that long queries are killed. I can do this in MYSQL like this:</p> <pre><code>self.db_conn.reset_session(sessio...
<python><mysql><timeout>
2025-03-19 14:07:03
1
340
pecks
79,520,380
4,634,965
Coloring Python VTK PolyData by additional attribute values in the dataset
<p>Utilizing the <a href="https://pypi.org/project/vtk/" rel="nofollow noreferrer">vtk python library</a> I am trying to color vtk polydata by a defined attribute (atype). So far I did not succeed. The renderer does not color by the specified attribute (atype) but instead by other date specified (position_and_radii).</...
<python><vtk>
2025-03-19 13:43:55
1
693
bue
79,520,326
10,161,091
Shap text plot does not show properly in notebook
<p>I am running the demo code provided <a href="https://github.com/shap/shap/blob/master/notebooks/text_examples/sentiment_analysis/Emotion%20classification%20multiclass%20example.ipynb" rel="nofollow noreferrer">here</a>. But I do not get the same plots with the nice coloring and highlights.</p> <p>Here is how it look...
<python><plot><jupyter><shap>
2025-03-19 13:20:34
1
2,750
SaTa
79,520,314
4,681,187
Why does tqdm mess up cProfile output?
<p>When profiling some Python code, I've been frustrated by functions like <code>threading.py:637(wait)</code> appearing high in cProfile output instead of the hot functions I want to see. After some tests I realized that the problem is that I've been using tqdm to monitor the overall progress of the program. Here is a...
<python><python-multithreading><tqdm><cprofile>
2025-03-19 13:14:49
1
1,565
Imperishable Night
79,520,271
11,062,613
Can you wrap NumPy functions in Numba-jitted code using llvmlite?
<p>This is a follow up question to: <a href="https://stackoverflow.com/questions/79514906/how-to-wrap-numpy-functions-in-numba-jitted-code-with-persistent-disk-caching">How to wrap NumPy functions in Numba-jitted code with persistent disk caching?</a></p> <p>Background: In general Numba's implementations of Numpy funct...
<python><numpy><llvm><numba><llvmlite>
2025-03-19 12:58:30
0
423
Olibarer
79,520,098
7,245,066
Using pyarrow back end with custom dtype
<p>I have a custom dtype in Pandas as well as an extension array. I would like to use the <code>pyarrow</code> back end over the default <code>numpy</code> backend.</p> <p>See: <a href="https://www.practicaldatascience.org/notebooks/class_3/week_2/50_pandas_pyarrow.html#is-this-something-to-worry-about-now" rel="nofol...
<python><pandas><pyarrow><dtype>
2025-03-19 11:47:47
0
403
JabberJabber
79,520,072
11,227,857
Azure Function (python) won't trigger from Azure IoT Hub event
<p>I have an IoT Hub and an Azure Function App written in Python. I want the Azure function to trigger on messages received by the hub.</p> <p>The IoT Hub is publicly accessible and I can successfully send messages to it. I have confirmed the JSON payloads are being received by using the Azure CLI.</p> <p>I've deployed...
<python><azure><azure-functions><azure-iot-hub>
2025-03-19 11:32:02
1
530
gazm2k5
79,520,044
18,002,913
How to measure the length of image from a masked image using OpenCV?
<p>I am new in image processing and I am trying to improve myself by doing some projects and I have a problem about my project. I have an image dataset containing lakes with their corresponding binary mask images. I want to calculate the perimeter (boundary length) and area of the lake in each image using OpenCV.</p> <...
<python><opencv><image-processing><contour>
2025-03-19 11:20:38
1
1,298
NewPartizal
79,519,937
12,730,925
Azure Batch Python SDK - 5 - 10% Chance to encounter "CreateTasksErrorException"
<p>I have a python service running that is starting azure batch pools and adds a single job + task on user requests. In ~90% of the time, everything works fine, but sometimes i get the following error message:</p> <pre><code>Traceback (most recent call last): [...] azure.batch.custom.custom_errors.CreateTasksErrorExc...
<python><azure><azure-batch>
2025-03-19 10:40:08
1
504
SebSta
79,519,871
3,813,371
How to make Visual Studio 2022 Python CLI project launch Windows Terminal instead of Python.exe?
<p>This is a Windows 11 machine. I have 2 projects in a Visual Studio 2022 solution.</p> <ol> <li>A Python CLI.<br /> When I run this app, it opens the <code>python.exe</code> terminal.</li> </ol> <p><a href="https://i.sstatic.net/YjZajfpx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YjZajfpx.png" alt...
<python><visual-studio-2022>
2025-03-19 10:19:28
1
2,345
sukesh
79,519,830
10,200,497
What is the best way to get the last non zero value in a window of N rows?
<p>This is my dataframe:</p> <pre><code>df = pd.DataFrame({ 'a': [0, 0, 1, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0] }) </code></pre> <p>Expected output is creating column <code>b</code>:</p> <pre><code> a b 0 0 0 1 0 0 2 1 0 3 -1 1 4 -1 -1 5 0 -1 6 0 -1 7 0 -1 8 0 0 9 0 0 10 -1 0 11 0 -1...
<python><pandas>
2025-03-19 10:04:07
6
2,679
AmirX
79,519,665
5,838,180
Overploting healpy gnomview with data points ignores the data points
<p>I am trying to create a figure in Python containing subplots with a gnomview map inside and data points overplotted. I am using this code:</p> <pre><code>import healpy as hp import matplotlib.pyplot as plt import numpy as np nside = 32 npix = hp.nside2npix(nside) rot = [0, 0] xsize = 500 reso = 1.0 fig, axs = plt....
<python><matplotlib><plot><healpy>
2025-03-19 09:06:57
0
2,072
NeStack
79,519,597
17,148,835
python API wait for .cmm script to finish (Practice stack depth error)
<p>I am using python with the lauterbach.trace32.rcl library to control a trace32 instance. I am getting sporadic 'Practice stack depth error' while calling multiple cmm files My goal is to call a .cmm script and wait for the script to complete before calling another one.</p> <p>My current python script looks like this...
<python><trace32><lauterbach>
2025-03-19 08:42:09
1
1,045
BeanBoy
79,519,395
1,079,907
How to skip, if starts with, but match other strings
<p>I want to match and substitute for strings as shown in the example below, but not for some strings which start with <code>test</code> or <code>!!</code>. I have used negative lookahead to skip matching unwanted strings but <code>(Street|,)(?=\d)</code> matching for <code>Street</code> &amp; comma replacing group 1 w...
<python><regex>
2025-03-19 07:04:19
6
12,828
Sunil Bojanapally
79,519,353
28,063,240
How to cache python pip requirements of docker build progress?
<p>I'm on a very slow internet connection, and the</p> <pre><code>RUN pip install -r requirements.txt </code></pre> <p>step of <code>docker compose up --build</code> keeps timing out halfway through.</p> <p>When I run <code>docker compose up --build</code> again, it looks like it restarts from the very beginning. All o...
<python><django><docker><celery><django-celery>
2025-03-19 06:45:29
1
404
Nils
79,519,074
3,604,745
Do Python version issues with TTA lead to fasttransform vs. fastcore bugs in Python >= 3.10?
<p>Test Time Augmentation (TTA) in FastAI should be easily applied with <code>learn.tta</code>, yet has led to numerous issues in my Cloud Run deployment. I have a working Cloud Run deployment that does base learner and metalearner scoring as a prediction endpoint using <code>load_learner</code> from FastAI.</p> <p>I w...
<python><pytorch><prediction><fast-ai>
2025-03-19 03:41:56
1
23,531
Hack-R
79,519,059
3,099,733
provision a custom python virtualenv with apptainer
<p>In order to run a software that require 32 bit environment on HPC, I have to build a container with Apptainer.</p> <p>The problem is, I need to run a python script with extra dependencies in the container. I don't want to rebuild the container whenever I add/remove python packages, so I am thinking of building a vi...
<python><singularity-container><apptainer>
2025-03-19 03:27:33
0
1,959
link89
79,518,999
8,444,568
Why std(skipna=False) and std(skipna=True) yield different results even when there are no NaN or null values in the Series?
<p>I have a pandas Series <code>s</code>, and when I call <code>s.std(skipna=True)</code> and <code>s.std(skipna=False)</code> I get different results even when there are no NaN/null values in <code>s</code>, why? Did I misunderstand the <code>skipna</code> parameter? I'm using pandas 1.3.4</p> <pre class="lang-py pret...
<python><pandas>
2025-03-19 02:39:54
1
893
konchy
79,518,840
19,537,838
Forward slash ```/``` and the backslash ```\``` following a quote disappear when typing the third following chacter (Sublime Text/Python editor)
<p>Sublime Text / Python editor: When I type the third character after a slash character that follows and opening quotation mark (double <code>&quot;/...</code> or single <code>'/...</code> OR <code>&quot;\...</code> <code>'\...</code>) the slash disappears. How can I stop this behavior?</p> <p>When typing:<br /> <cod...
<python><autocorrect><sublimetext4>
2025-03-19 00:01:05
1
795
rich neadle
79,518,764
4,463,825
How to load a Neural Network Model along with MinMaxScalar?
<p>I have a simple neural network model, of 4 layers, that I trained on a numerical dataset of 25K data points.</p> <p>It takes a good time to load the data, whenever I want to evaluate new features to python code. So how could I save the model in my project folder, and just load it as required?</p> <p>It is a sequenti...
<python><keras><scikit-learn><neural-network><minmax>
2025-03-18 22:49:01
0
993
Jesh Kundem
79,518,643
2,698,266
pre-commit is failing due to virtualenv
<p>pre-commit is failing on all invocations due to an upstream dependency failure with virtualenv. I get the following error:</p> <pre><code>[INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Initializing environment for https://github.com/psf/black. [INFO] Initializing environme...
<python><macos><virtualenv>
2025-03-18 21:05:03
0
972
Wold
79,518,604
3,566,606
Python Typing: Put Constraint on Annotated
<p>I would like to do some meta-programming with python type annotations.</p> <p>I want to define a certain type of <code>Annotated</code>, constraining the type for the metadata of the Annotated special form.</p> <p>For example, I want to write a function, which only allows for Annotated types whose first metadata ent...
<python><metaprogramming><python-typing>
2025-03-18 20:41:49
1
6,374
Jonathan Herrera
79,518,434
16,891
Trying to deploy my first modal app with a chrona database but the data is not being used. Need help debugging retrieveInfoForQuery function?
<p>I am having trouble figuring out why I can't see the print statements in the terminal for my retrieveInfoForQuery function and trying to figure out what is wrong. I have verified the chroma db is on the volume. Here is the code.</p> <pre><code>from langchain_core.tools import tool from langchain_core.messages i...
<python><py-langchain><rag>
2025-03-18 18:59:00
0
2,130
Chris Westbrook
79,518,393
835,073
Can we get "-x^{2}+1" instead of "1-x^{2}" with sympy.latex(-x**2+1)?
<p>I need <code>-x^{2}+1</code> rather than <code>1-x^{2}</code> with <code>sympy.latex(-x**2+1)</code>.</p> <pre class="lang-py prettyprint-override"><code>from sympy import symbols, latex x = symbols('x') print(-x**2+1) print(latex(-x**2+1)) </code></pre> <h4>Output:</h4> <pre><code>1 - x**2 1 - x^{2} </code></pre> <...
<python><sympy>
2025-03-18 18:39:56
2
880
D G
79,518,311
1,980,208
Arrange consecutive zeros in panda by specific rule
<p>I have panda series as the following :</p> <pre><code> 1 1 2 2 3 3 4 4 5 0 6 0 7 1 8 2 9 3 10 0 11 0 12 0 13 0 14 1 15 2 </code></pre> <p>I have to arrange this in following format :</p> <pre><code> 1 1 2 2 3 3 ...
<python><pandas><numpy>
2025-03-18 17:52:20
2
439
prem
79,518,189
13,806,869
Why is my Winsorization code telling me it has too many arguments?
<p>I have an array that looks like this:</p> <pre><code>[ 3.4 0. 10.6 ... -0.4 -0.4 0. ] </code></pre> <p>The array has around 13.5m values in it. I want to winsorize the top and bottom 5% to deal with outliers. This is the code I'm using:</p> <pre><code>from scipy.stats.mstats import winsorize winsorized_array = wi...
<python><scipy>
2025-03-18 17:00:39
1
521
SRJCoding
79,518,161
2,893,712
Pyhon Telegram Bot Multiple Bots
<p>I have multiple bots that utilize Python Telegram Bot module. Each bot has code like:</p> <pre><code>from telegram.ext import Updater, CommandHandler def start(update, context): update.message.reply_text(&quot;Command List:\n/start - Display this message&quot;) def main(): updater = Updater(token='XXXXXXX:...
<python><telegram><telegram-bot><python-telegram-bot>
2025-03-18 16:49:41
1
8,806
Bijan
79,518,142
16,563,251
Implement the __getitem__ method of a minimal collections.abc sequence with type hints
<p>How does a minimal implementation of a <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence" rel="nofollow noreferrer"><code>Sequence</code></a> from <a href="https://docs.python.org/3/library/collections.abc.html" rel="nofollow noreferrer"><code>collections.abc</code></a>, togeth...
<python><python-typing><pyright><python-collections>
2025-03-18 16:41:30
1
573
502E532E
79,518,011
1,858,864
WebP support not enabled in Pillow 2.9.0 on CentOS 7 despite installing libwebp
<p>I’m trying to enable WebP support in Pillow 2.9.0 on CentOS 7. I can only use yum to install packages (I cannot use pip). Here’s what I’ve done so far:</p> <p>Installed libwebp and libwebp-devel using yum:</p> <pre><code>yum install libwebp libwebp-devel </code></pre> <p>The installed version of libwebp is 0.3.0:</p...
<python><python-imaging-library><webp>
2025-03-18 15:47:11
0
6,817
Paul
79,517,991
3,621,143
Using "no challenge" to create a certificate with private CA?
<p>I am working on a python script that performs the same SSL certificate generation using the ACME protocol as I accomplished with an Ansible playbook (<a href="https://stackoverflow.com/questions/77902933/acme-certificates-in-ansible-using-incommon-sectigo-ca">ACME certificates in Ansible using InCommon/Sectigo CA</a...
<python><acme>
2025-03-18 15:38:15
1
1,175
jewettg
79,517,632
16,563,251
Type hint private member variable of subclass more specific than superclass
<p>I have some private field of a class that is type hinted as a <code>Collection</code>. Now, I want to inherit from this class, changing the type to a <code>Sequence</code>, which itself inherits from <code>Collection</code>. Thus, everything the superclass was doing before is still supported by the type hint. Nevert...
<python><python-typing><pyright>
2025-03-18 13:42:37
0
573
502E532E
79,517,500
12,859,833
z3py threshold Optimization results in worse performance than unoptimized solution
<p>In a <a href="https://stackoverflow.com/questions/79506894/constraint-based-optimizing-the-decision-threshold-of-a-prediction-model">previous question</a>, I asked about optimizing the decision threshold of a prediction model. The solution led me to the <code>z3py</code> library.</p> <p>I am now trying a similar set...
<python><z3><z3py>
2025-03-18 12:57:02
1
343
emil
79,517,387
21,446,483
Dependency error when using a cloud storage connector with Hadoop 3
<p>I'm trying to set up a simple PySpark project which writes a DataFrame to a cloud storage bucket, but I keep getting errors related to incorrect dependency management. I have tried multiple versions of the cloud storage connector without any success.</p> <p>I've also tried adding additional configuration options I'v...
<python><pyspark><google-cloud-storage>
2025-03-18 12:15:06
1
332
Jesus Diaz Rivero
79,517,202
1,751,393
Define a custom tree splitter from sklearn
<p>I'm trying to define a custom splitter using sklearn Classification Trees classes, but I'm getting no results so far. I got no errors but the tree is not developed. How to achieve this?</p> <p>My strategy is largely inspired by this approach: <a href="https://stackoverflow.com/questions/47624000/cinit-takes-exactly-...
<python><scikit-learn><classification><decision-tree>
2025-03-18 11:11:56
0
356
Jojo
79,517,158
16,563,251
Test event handler registration using pytest
<p>Consider a module that allows to register event handlers and fires them at some condition:</p> <pre class="lang-py prettyprint-override"><code># mymodule/myfile.py _event_handlers = [] def register_event_handler(handler): _event_handlers.append(handler) def fire_event_handlers(): for handler in _event_handl...
<python><event-handling><pytest><function-call>
2025-03-18 10:56:19
1
573
502E532E
79,516,990
7,662,164
General way to define JAX functions with non-differentiable arguments
<p>For a particular JAX function <code>func</code>, one can define non-differentiable arguments by using the decorator <code>@partial(jax.custom_jvp, nondiff_argnums=...)</code>. However, in order to make it work, one must also explicitly define the differentiation rules in a custom <code>jvp</code> function by using t...
<python><function><jax><automatic-differentiation>
2025-03-18 09:55:30
1
335
Jingyang Wang
79,516,928
2,307,441
swifter module causing my executable to fail which built by pyinstaller
<p>I am building an onefile exe using pyinstaller with my python file.</p> <p>my <code>testing.py</code> file contains following code:</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd import swifter file = &quot;D:/Testing/file1.csv&quot; if __name__ == '__main__': try: df = p...
<python><pyinstaller>
2025-03-18 09:37:04
0
1,075
Roshan
79,516,854
4,872,540
Can a metaclass be used as a type hint for a class instance in Python 3.12+?
<p>The project I'm working on uses a somewhat complex typing system, I have a base class called RID which uses the metaclass RIDType. Custom RID types are classes which derive from RID:</p> <pre class="lang-py prettyprint-override"><code>class RIDType(ABCMeta): ... class RID(metaclass=RIDType): ... class Custo...
<python><metaprogramming><python-typing>
2025-03-18 09:03:46
0
1,086
Aeolus
79,516,763
1,256,529
Method decorators which "tag" method - prevent overwriting by other decorators
<p>I'm investigating the pattern whereby you have a method decorator which annotates the method in some way, and then once the class is defined it looks through its methods, finds the annotated methods, and registers or processes them in some way. e.g.</p> <pre><code>def class_decorator(cls): for name, method in cls...
<python><metaprogramming>
2025-03-18 08:21:17
1
3,817
samfrances
79,516,714
6,730,854
Viterbi Decoding Returns -Incorrect State Sequence with One-Hot Observations in MultinomialHMM (Tried v0.3.0, v0.3.2, and v0.3.3)
<p>I'm experiencing unexpected behavior with the MultinomialHMM in hmmlearn. When using one-hot encoded observations (with n_trials=1), the Viterbi algorithm returns the state sequence incorrectly.</p> <p>In my minimal reproducible example, the decoded state sequence consists entirely of state 0, even though the parame...
<python><markov-chains><hidden-markov-models><hmmlearn>
2025-03-18 07:59:36
0
472
Mike Azatov
79,516,463
4,451,521
A timeout exception is not caught as such
<p>I have a function that calls an API</p> <pre><code>def somefunction(): #.... try: response = requests.post(api_url, json=payload, timeout=timeout) response.raise_for_status() result = response.json() # # Handle response # if response.status_code == 200: ...
<python><python-requests><connection><timeout>
2025-03-18 06:22:16
1
10,576
KansaiRobot
79,516,316
1,635,450
psycopg_pool.ConnectionPool conninfo WARNING error connecting in 'pool-1': [Errno -2] Name or service not known
<pre><code>with ConnectionPool( conninfo = app.config[&quot;POSTGRESQL_DATABASE_URI&quot;], max_size = app.config[&quot;DB_MAX_CONNECTIONS&quot;], kwargs = connection_kwargs, ) as pool: </code></pre> <p>With a connection string of <code>postgresql://username:password@ipaddress:5432/database</code>, I ge...
<python><postgresql><connection-string><psycopg3><connection-pool>
2025-03-18 04:40:46
1
4,280
khteh
79,516,194
9,951,273
Typing a generic iterable
<p>I'm creating a function that yields chunks of an iterable.</p> <p>How can I properly type this function so that the return value <code>bar</code> is of type <code>list[int]</code>.</p> <pre><code>from typing import Any, Generator, Sequence def chunk[T: Any, S: Sequence[T]](sequence: S, size: int) -&gt; Generator[S,...
<python><python-typing>
2025-03-18 03:19:23
2
1,777
Matt
79,516,082
219,153
Is there a simpler way to write this Numpy structured array query?
<p>This Python 3.12 script</p> <pre><code>import numpy as np a = np.array([('Rex', 9, 18), ('Fido', 3, 22), ('Fido', 7, 42), ('Fluffy', 1, 30), ('Fido', 5, 19)], dtype=[('name', 'U10'), ('age', 'f4'), ('weight', 'f4')]) b = a[np.where((a['name'] == 'Fido') &amp; (a['weight'] &lt; 30))] oldestFidoUnder30 ...
<python><numpy><structured-array>
2025-03-18 01:35:29
2
8,585
Paul Jurczak
79,515,992
16,674,436
Correctly Assign Street Sectors Based on Even/Odd Street Numbers and Street Segment Ranges
<p>Ok I cannot wrap my head around that.</p> <p>I have two dataframes, <code>first_df</code> and <code>second_df</code>, where <code>first_df</code> contains information about street segments, including the street name, start and end numbers of street segments, and whether the segment is for even or odd numbers. <code>...
<python><pandas><dataframe><sorting>
2025-03-17 23:59:52
3
341
Louis
79,515,822
12,415,855
Reading emails with imap_tools getting wrong sort-output
<p>i want to read the emails from an email-account from the newsest to the oldest mail in the inbox using the following code:</p> <pre><code>from imap_tools import MailBox import os import sys from dotenv import load_dotenv path = os.path.abspath(os.path.dirname(sys.argv[0])) fn = os.path.join(path, &quot;.env&quot;)...
<python><imap-tools>
2025-03-17 21:46:46
1
1,515
Rapid1898
79,515,814
13,971,251
Photomosaic library raising TypeError: slice indices must be integers or None or have an __index__ method
<p>I have the following code (a slightly modified version of <a href="https://www.tutorialspoint.com/implementing-photomosaics-in-python" rel="nofollow noreferrer">this</a>) to create a mosaic from many individual images:</p> <pre class="lang-py prettyprint-override"><code>import sys import photomosaic as phmos from sk...
<python><scikit-image>
2025-03-17 21:43:32
1
1,181
Kovy Jacob
79,515,692
1,934,800
How to reference class static data in decorator method
<p>Is it possible to make the global variable <code>handlers</code> a static class variable?</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable, Self # dispatch table with name to method mapping handlers:dict[str, Callable[..., None]] = {} class Foo: # Mark method as a handler for a p...
<python>
2025-03-17 20:27:36
4
4,817
TrentP
79,515,585
10,242,281
how to install python package in 2025 ? Datascience
<p>I'm trying to install python package and still getting errors after trying all options for online and offline installation. Is this package still valid? maybe there is some license restrictions? I'm using terminal windows in <code>pyCharm</code></p> <p><code>https://github.com/data-8/datascience</code></p> <p>Thanks...
<python><package>
2025-03-17 19:31:29
0
504
Mich28
79,515,499
5,678,653
Categorize 3D points into octants based on their signs in numpy
<p>I have the set of all <em>8</em> possible signs that non-zero 3D (euclidean). I want to efficiently categorise 3D points <code>pts</code> into octants based on their signs, as part of an ongoing project on octahedral spaces, as per <a href="https://stackoverflow.com/questions/79498948">this and many other questions<...
<python><numpy><binning>
2025-03-17 18:54:34
3
2,248
Konchog
79,515,343
850,781
How to compare objects based on their superclass
<p>How do I check for equality using super-class-level comparison?</p> <pre><code>from dataclasses import dataclass @dataclass(order=True) class Base: foo: int @dataclass(order=True) class X(Base): x: str @dataclass(order=True) class Y(Base): y: float x = X(0, &quot;x&quot;) y = Y(1, 1.0) </code></pre> ...
<python><python-dataclasses>
2025-03-17 17:30:34
4
60,468
sds
79,515,167
2,266,881
Filtering polars dataframe by row with boolean mask
<p>I'm trying to filter a Polars dataframe by using a boolean mask for the rows, which is generated from conditions on an specific column using:</p> <pre><code>df = df[df['col'] == cond] </code></pre> <p>And it's giving me an error because that filter is meant for column filter:</p> <blockquote> <p>expected xx values w...
<python><dataframe><python-polars><polars>
2025-03-17 16:26:30
1
1,594
Ghost
79,515,104
13,440,165
Sliding window Singular Value Decomposition
<p>Throughout the question, I will use Python notation. Suppose I have a matrix <code>A</code> of shape <code>(p, nb)</code> and I create a sliding window, taking the submatrix of <code>p</code> rows and <code>n</code> columns <code>Am = A[:, m : m + n]</code>. Now I want to compute it <strong>singular value decomposit...
<python><algorithm><svd>
2025-03-17 16:04:41
1
883
Triceratops
79,515,072
2,893,712
Pandas Join Two Series Based on Conditions
<p>I have a dataframe that has information about employee's employment info and I am trying to combine with another dataframe that has their Employee ID #.</p> <p><code>df</code></p> <pre><code>Name SSN Doe, John A XXXX-XX-1234 Doe, Jane B XXXX-XX-9876 Test, Example XXXX-XX-0192 </code></pre> <...
<python><pandas>
2025-03-17 15:54:57
2
8,806
Bijan
79,515,028
9,422,807
find the min of int value mixed with string value in a nested list in Python
<p>I have a nested li below, I wanted to return a nested li with the string with and min of the int value within the same string value. Any idea?</p> <pre><code>li=[['a', 10], ['a', 20], ['a', 20], ['a', 40], ['a', 50], ['a', 60] , ['b', 10], ['b', 20], ['b', 30], ['b', 40] , ['c', 10], ['c', 10], ['c', 20]] </code></p...
<python><nested-lists>
2025-03-17 15:32:56
2
413
Liu Yu
79,514,922
20,895,654
Most performant approach to find closest match from unordered collection
<p>I'm wondering what the best approach for finding the closest match to a given value from a collection of items is. The most important part is the lookup time relative to the input size, the data can be shuffled and moved around as much as needed, as long as the lookup is therefore faster.</p> <p>Here the initial scr...
<python><algorithm><hash><lookup><closest>
2025-03-17 14:48:01
1
346
JoniKauf
79,514,906
11,062,613
How to wrap NumPy functions in Numba-jitted code with persistent disk caching?
<p>Numba reimplements many NumPy functions in pure Python and uses LLVM to compile them, resulting in generally efficient performance. However, some Numba implementations show slower performance compared to their optimized NumPy counterparts, such as numpy.sort().</p> <p>A quick approach to wrap NumPy's optimized funct...
<python><numpy><numba>
2025-03-17 14:40:03
0
423
Olibarer
79,514,805
65,424
Having trouble in posit great_tables formatting with whitespace sensitive text , fmt_markdown, cols_width ignored
<p>I am using the great_tables python library from Posit and am trying to format some long text for a particular column in a html table derived from a pandas DataFrame inside a Jupyter Notebook .</p> <p>The text represents a Protein Sequence alignment and these are best showed with a fixed width font and with column wi...
<python><markdown><great-tables><posit>
2025-03-17 13:59:41
2
11,935
harijay
79,514,802
8,079,611
Have a 3D Effect on Y-axis of a Matplotlib Graph
<p>I have been trying to mimic this bar graph style that I found online. I was able to mimic several different parts, however, I am unable to mimic this 3D feel on the Y-axis. Using Python, any ideas of how could I make this happen? I am happy to use a different library if needed (tried Seaborn but same problem, no 3D ...
<python><matplotlib><seaborn>
2025-03-17 13:58:54
0
592
FFLS
79,514,742
6,382,434
Llama Index AgentWorkflow WorkflowRuntimeError: Error in step 'run_agent_step': 'toolUse'
<p>I have a simple llama-index AgentWorkflow based on the first example from this <a href="https://docs.llamaindex.ai/en/stable/examples/agent/agent_workflow_basic/" rel="nofollow noreferrer">llama-index doc example notebook</a>:</p> <pre class="lang-py prettyprint-override"><code>from llama_index.core.agent.workflow i...
<python><llama-index>
2025-03-17 13:35:51
1
19,000
LMc
79,514,688
3,648,768
python requests on URL with bad certificate [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE]
<p>I need to get data from a URL that has some certificate problems. It works with <code>curl -k</code> (that skips verification). So I tried with <code>verify=False</code> in python <code>requests</code> but I'm still getting [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE]. Any idea how to bypass this?</p> <p>I'm using python 3....
<python><ssl>
2025-03-17 13:11:01
1
630
Daniel
79,514,684
17,551,958
Encountering Flet Build APK Issue on Windows Machine
<p>I am trying to build the android apk of a simple python flet application on my Windows 10 machine. However, despite the fact that I have installed Android Studio, flutter, Java SDK, gradle, accepted all the licences, and set all the system paths, I am still encountering the error below:</p> <pre><code>[13:08:01] 1 F...
<python><android><flutter><apk><flet>
2025-03-17 13:10:00
0
1,392
Ifeanyi Idiaye
79,514,574
4,000,073
How to create set with values 1, 0, True, False along with other values in the same set
<p>I am trying to create a set having different values along with True, False, 1, 0.</p> <p>I am aware that Python treats 1 as True and 0 as False. Imperatively, since the set keeps only the <em>unique</em> values, my set stores either of 1 or True, and of 0 or False.</p> <p>Is there any workaround to deal with the abo...
<python><data-structures><set>
2025-03-17 12:28:05
1
311
Venkata