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,763,222
811,299
How can one python script launch another python script using a different virtual environment?
<p>I have researched this question and found <a href="https://stackoverflow.com/questions/8052926/running-subprocess-within-different-virtualenv-with-python">Running subprocess within different virtualenv with python</a>, but my situation is a little different.</p> <p>I have an astrophotography application which I run ...
<python><python-venv>
2025-09-12 17:48:06
1
4,909
Steve Cohen
79,763,157
667,355
apply function versus vectorised operation in pandas dataframe
<p>I am working with a DataFrame of almost 1M rows and want to compute a column as a function of two others. My first idea was to use <code>.apply(axis=1)</code> with a lambda function to do the operation, but it was extremely slow compared to when I do vectorized operation.</p> <p>An example of the task:</p> <pre><cod...
<python><pandas><dataframe>
2025-09-12 16:10:14
0
3,491
amiref
79,763,094
10,686,658
Change contravariant tensor to covariant tensor in einsteinpy package
<p>Using einsteinpy package of Python, I am defining the electromagnetic tensor (or any other arbitrary tensor). While defining, I am defining it as 'uu' tensor using the BaseRelativityTensor class file. I want the 'll' version from this, ie. F_covariant from F_contravariant. But the package seems not to provide any .c...
<python><tensor>
2025-09-12 15:09:53
0
559
ASarkar
79,762,824
1,688,726
Mock patch sys.stdout to StringIO as a decorator
<p>I am trying to mock.patch sys.stdout to StringIO as a decorator to record the output for testing.</p> <p>As a 'with' statement it works this way:</p> <pre><code>with mock.patch('sys.stdout', new_callable = StringIO) as recorded_output: print('OUTPUT') r = recorded_output.getvalue() print(r) </code></pre> <p>...
<python><mocking><stdout>
2025-09-12 10:36:50
1
359
user1688726
79,762,810
3,486,078
Fatest way to convert float array to string in python
<p>This question came up while I was saving a large number of model-inferred embeddings to plain text. To do so, I needed to convert lists of float embeddings into strings, and I found this conversion to be surprisingly time-consuming.</p> <p>Inspired by <a href="https://discuss.python.org/t/faster-float-string-convers...
<python><profiling><orjson>
2025-09-12 10:14:23
0
474
K_Augus
79,762,788
5,103,620
How to transform callable argument types?
<p>Assume I have a callable type with some arbitrary set of argument types:</p> <pre class="lang-py prettyprint-override"><code>Callable[[T1, T2, T3, &lt;etc&gt;, Tn], str] </code></pre> <p>Is there a way (presumably using <code>TypeVarTuple</code> or <code>ParamSpec</code>) to statically generate the following callabl...
<python><python-typing>
2025-09-12 09:53:07
0
4,886
Sebastian Lenartowicz
79,762,675
2,105,307
MS-Graph returns 404 and 412 when uploading attachments concurrently
<p>I have the following python script which is sending emails through MS-Graph using (partly) msgraph-sdk in python. The problem I see is that if I try to upload multiple attachments of the email concurrently I get a lot of 404 and 412 errors from ms-graph when trying to upload the attachment chunks. But if I set the s...
<python><microsoft-graph-api><microsoft-graph-mail><microsoft-graph-files>
2025-09-12 08:15:28
0
1,548
NikosDim
79,762,332
2,112,193
How to do batched matrix vector multiplication with np.matvec
<p>I have rotation matrix, for the sake of a simple example, <code>np.ndarray(..., shape=(3, 2))</code>, and I want to multiply it by an nd-array of vectors, say <code>np.mgrid[:4, :5]</code>, how do I do that with the new <code>np.matvec</code> function? I guess the signature I want from this generalized ufunc is <cod...
<python><numpy><numpy-ufunc>
2025-09-11 20:11:40
1
522
DBS4261
79,761,797
6,618,051
We could not find a project publisher for the project at {DIR}
<p>I'm trying to configure an application (Kivy framework, Python language, <a href="https://github.com/lyskouski/app-language" rel="nofollow noreferrer">https://github.com/lyskouski/app-language</a>) distribution via</p> <pre><code>msstore reconfigure --tenantId *** --clientId *** --clientSecret *** --sellerId *** mss...
<python><kivy><github-actions><msstore>
2025-09-11 10:22:50
1
1,939
FieryCat
79,761,794
228,804
Airflow tasks in sequence: dag file is parsed again?
<p>I'm writing a DAG script for Apache Airflow and I'm running into behaviour that I didn't expect. If you take a look at my example script I was expecting the same timestamp to be printed. Instead, when running this dag, the timestamp gets re-evaluated and prints the date-time of the second task.</p> <pre><code>import...
<python><airflow><task><directed-acyclic-graphs>
2025-09-11 10:21:53
2
333
Cesar
79,761,695
3,938,402
Copy directory and its contents
<p>In the below I'm copying a directory from a remote machine to local. Instead of copying the directory and its contents (files and directories), it's copying only the contents (files and directories). How do I make Paramiko SCP create a directory first and then copy the contents (files and directories) to it.</p> <p>...
<python><paramiko><scp>
2025-09-11 09:01:43
1
4,026
Harry
79,761,589
17,580,381
How to install torch on MacOS (Intel)
<p>On my M2-based Mac I can install torch simply with:</p> <pre class="lang-shell prettyprint-override"><code>pip install torch </code></pre> <p>(pip is an alias for pip3)</p> <p>However, on my Xeon-based iMac I get this error:</p> <pre class="lang-none prettyprint-override"><code>ERROR: Could not find a version that s...
<python><pytorch>
2025-09-11 07:19:56
1
28,997
Ramrab
79,761,576
1,559,401
mlflow unable to generate input output schema when using log_model()
<p>I am using the latest mlflow <strong>3.3.2</strong> with a simple PyTorch implementation of SRCNN. I am able to log the parameters as well as the metrics for the training process as well as generate custom visualizations for the losses and PSNR alongside the model with all auxilliary files required for exporting as ...
<python><pytorch><mlflow>
2025-09-11 07:14:43
0
9,862
rbaleksandar
79,761,328
1,429,450
Accessing any object type from multiprocessing shared_memory?
<p>Suppose I create a shared memory object:</p> <pre><code>from multiprocessing import shared_memory shm_a = shared_memory.SharedMemory(create=True, size=1024) buffer = shm_a.buf </code></pre> <p>and put a generic object of a generic class, such as:</p> <pre><code>class GenericClass: def __init__(self, a, b): ...
<python><casting><multiprocessing><shared-memory><void-pointers>
2025-09-10 22:00:24
1
5,826
Geremia
79,761,289
1,604,008
Trying to understand mocking in python
<p>using pytest - given the following:</p> <pre><code>class Bar: def wtf(self): return 1 class Foo: def __init__(self, bar): self.bar = bar def huh(self): return self.bar.wtf() def test_huh(): bar = Bar() foo = Foo(bar) assert foo.huh() == 1 def test_huh2(mocker): ...
<python><pytest><pytest-mock>
2025-09-10 21:07:16
1
1,159
user1604008
79,761,286
13,968,392
write_database(..., engine="adbc") with autocommit=False
<p>In polars, I would like to use <code>pl.write_database</code> multiple times with <code>engine=&quot;adbc&quot;</code> in the same session and then commit all at the end with <code>conn.commit()</code>, i.e. do a manual commit.</p> <pre class="lang-py prettyprint-override"><code>import adbc_driver_postgresql.dbapi a...
<python><database><postgresql><python-polars><adbc>
2025-09-10 21:04:12
1
2,117
mouwsy
79,761,269
20,789
Best way to assign a scalar to a new DataFrame column with a specific dtype
<p>I am writing a routine to load a large dataset into a Pandas <code>DataFrame</code> from a bespoke text format.</p> <p>As part of this process, I need to add new columns to a <code>DataFrame</code>. Sometimes I need to broadcast a scalar value into the whole column, and I use <a href="https://pandas.pydata.org/docs/...
<python><pandas><dataframe><numpy><series>
2025-09-10 20:28:05
2
80,378
Dan Lenski
79,761,246
1,750,498
Can I create a sphere in matplotlib with all inputs 3d (e.g. x**2 + y**2 + z**2 = 0)
<p>I want to create a fun (for me ;-)) Python project where I plot mathematical formulas in 3d using matplotlib and I was especially looking to print a sphere, since a line is a quite boring formula (y = x + z) and even parabolas can be boring (y = x^2 + z^2). But a sphere x^2 + y^2 + z^2 = 0 directly interested me.</p...
<python><matplotlib>
2025-09-10 19:54:57
1
5,562
Nemelis
79,761,125
8,765,709
Python Convert List Image to multiple PDF
<p>In the case</p> <p>I have a folder of image list and list name file with csv</p> <p>I want to write a python script to convert list of PNG's to multiple pdf file with name file of pdf from csv file at column D</p> <p>like this: <a href="https://i.sstatic.net/91J4d6KN.png" rel="nofollow noreferrer"><img src="https://...
<python><csv><img2pdf>
2025-09-10 17:24:56
1
339
dede.brahma
79,760,973
2,203,144
How to make an async setup and teardown fixture in Pytest
<p>I have a working basic example of a setup and teardown fixture in <a href="https://docs.pytest.org/en/stable/" rel="nofollow noreferrer">Pytest</a>:</p> <pre><code> @pytest.fixture() def setup_and_teardown(): # Setup print('setup') # Yield some variable to the test yield 'v' # Teardown ...
<python><testing><async-await><pytest><teardown>
2025-09-10 14:29:35
1
3,988
mareoraft
79,760,899
1,023,928
Memory efficient sorting/removing duplicates of polars dataframes
<p>I am trying to import very large csv files into parquet files using polars. I stream data, use lazy dataframes and sinks. No problem until...</p> <p>...sorting the dataframe on a column and removing duplicates. Requirement that can't be skipped is that the data written to parquet must be unique by the 'datetime' col...
<python><dataframe><datetime><parquet><python-polars>
2025-09-10 13:18:33
1
7,316
Matt
79,760,853
2,125,110
Is there a decorator for attrs factory sugar?
<p>Similar to <a href="https://stackoverflow.com/questions/63625357/decorator-for-attrs-converter">Decorator for attrs converter</a>, please see this case:</p> <pre><code>from attrs import define, field, Factory @define class MyClass: name = field(default = Factory(_name_factory, takes_self=True), init=False) ...
<python><python-attrs>
2025-09-10 12:17:48
1
3,596
Daemon Painter
79,760,561
7,465,516
Python equivalent of java-regex Pattern.quote ( \Q and \E )?
<p>In Java the regular expression <code>\Q\s\E</code> will match the literal string <code>&quot;\s&quot;</code> and not whitespace because <code>\Q</code> and <code>\E</code> quote the part of the regex inside them. For quoting a whole string conveniently and with care of the edge-case that the string contains an <code...
<python><regex><escaping><match>
2025-09-10 07:12:02
1
2,196
julaine
79,760,254
3,866,585
Why do I keep getting a 400 Bad Request trying to import a private GitHub repo into an Azure Devops repo using the API?
<p>I am trying to make API calls to import a repo from a private GitHub repo to an Azure Devops repo in Python using a PAT. I tried using the SDK with no luck. My code DOES work with a public GitHub repo, just not a private one. I have tried adding the username/PAT in the GitHub repo url and tried creating my own servi...
<python><github><azure-devops>
2025-09-09 20:16:52
0
332
Hydromast
79,760,189
13,172,864
Why isn't my keras model throwing and error when different sizes are passed to the dense layer?
<p>I am working on a dynamic time series multi-class segmentation problem with keras (tensorflow version 2.12.0), and I wanted to see what would happen when I dropped in a dense layer into the network architecture. My expectation is that for any situation where the input size changes (e.g., dynamic time series), you'll...
<python><tensorflow><machine-learning><keras><deep-learning>
2025-09-09 18:53:16
3
403
jjschuh
79,760,030
1,145,666
How can I find out if Google AI API used the tool that I provided?
<p>How can I use the <em>Python Gemini API</em> to find out whether the model used the Google Search tool for grounding (and what the results of it were)?</p> <p>I am using the following code to run a prompt (with some images and text) to Google Gemini. The system instruction clearly states to 1) use the tool, and 2) p...
<python><google-gemini>
2025-09-09 15:15:15
1
33,757
Bart Friederichs
79,759,686
467,083
python requests response.text logging "Encoding detection: utf_8 is most likely the one."
<p>(my solution below)</p> <p>I have a python script that uses a REST API to get XML files from a tool. This is the heart of it:</p> <pre><code>def get_output(self, url, output_filename): xml_response = self.client.get_request(url) if not xml_response: self.logger.error(f&quot;no xml_response:{output_fi...
<python><utf-8>
2025-09-09 08:57:10
1
757
oaklodge
79,759,628
10,197,791
How to Bypass "Grant Access" when using Xlwings
<p>I am in the process of porting over some python excel automation scripts to work on MacOS (previously they were run on windows, and used the pywin32 library to &quot;refresh&quot; an excel file - the purpose of this was to make sure that all formulas were computed before using pandas to read the excel file to a data...
<python><excel><xlwings>
2025-09-09 07:49:52
1
375
NicLovin
79,759,341
1,747,834
How to create kwargs from tuple?
<p>I have a function with lots of optional arguments. I want to apply it to an enumeration of tuples, that'd specify only the non-default values for each parameter. Something like:</p> <pre class="lang-py prettyprint-override"><code>def myf(foo = 11, bar = 17): print(foo + bar) for tup in [(foo = 1), (bar = 2)]: ...
<python>
2025-09-08 21:05:46
1
4,246
Mikhail T.
79,759,280
1,747,834
How to use multiprocessing module with interdependent tasks?
<p>The existing examples of the <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer"><code>multiprocessing</code></a>-module assume, the tasks are independent, but my situation is &quot;hairier&quot;.</p> <p>I need to process several hundred thousands of <em>widgets</em>. These are...
<python><python-multiprocessing><message-queue>
2025-09-08 19:37:08
2
4,246
Mikhail T.
79,759,200
4,799,172
Using pybabel to translate tooltip text inside a HTML tag
<p>I've basically finished translating my flask frontend into a lot of different languages but there are a couple of tooltips that I just can't seem to figure out. Technically, these need to be strings against the <code>title=</code> property, so the <em>unmodified</em> version would look like:</p> <pre class="lang-htm...
<python><flask><python-babel>
2025-09-08 17:46:24
1
13,314
roganjosh
79,759,016
13,132,728
Change the decimal value of each value in each column to 0.5 while maintaining the same leading integer python pandas
<h1>CONTEXT</h1> <p>I am NOT trying to round to the nearest 0.5. I know there are questions on here that address that. Rather, I am trying to change the decimal value of each value in each row to 0.5 while maintaining the same leading integer. For example, I have <code>df</code>:</p> <pre><code>df = pd.DataFrame({'foo'...
<python><pandas><dataframe><apply><rounding>
2025-09-08 14:20:55
1
1,645
bismo
79,758,933
2,386,113
How to efficiently create an array from a list containing arrays of different lengths
<p>I have a list containing 2D arrays with same number of rows but different number of columns. I need to create a padded array of arrays with same shape. My current code is below but due to the for loop, the code is very inefficient for large lists. How can I create a padded array more efficiently?</p> <p><strong>MWE:...
<python><arrays><list><numpy>
2025-09-08 13:19:45
1
5,777
skm
79,758,868
1,815,054
QGIS headless + Python - exporting PDF with XYZ tiles layer
<p>I have a script that generates a PDF file from QGIS headless running on Ubuntu. The script generates a map view from a geojson feature which is centered on the view and a Mapbox XYZ tile layer is put behind it.</p> <p>When running the script for the first time, I get a segmentation error and a faulty PDF is generate...
<python><qgis><pyqgis>
2025-09-08 12:21:25
0
3,508
Dusan
79,758,809
3,486,078
Does head(n) in Polars agg guarantee alignment across multiple columns within the same group
<p>When using <code>group_by().agg()</code> in Polars to apply <code>head(n)</code> on multiple columns simultaneously, is it guaranteed that the returned elements come from the same original rows?</p> <p>For example, when grouping by code and applying <code>.head(2)</code> to several columns (e.g., 'interest', 'embedd...
<python><dataframe><python-polars>
2025-09-08 11:05:51
2
474
K_Augus
79,758,806
11,863,823
Trying to reduce the verboseness of __post_init__ in a python dataclass
<p>I am writing a Python config script that creates an array of input files in a domain-specific language (DSL), so my use case is a bit unusual. In this scenario, we want medium-level users to be able to edit the <code>RandomRequest</code> class / create various other classes following similar patterns, that will be u...
<python><enums><python-dataclasses>
2025-09-08 11:03:24
1
628
globglogabgalab
79,758,737
5,121,448
Error when trying to access data in h5 file using h5py
<p>I am trying to read an h5 file using python</p> <pre><code>with h5py.File(filename, 'r') as file: print(&quot;file.keys() = &quot;, file.keys()) a_group_key = list(file.keys())[0] data = list(file[a_group_key]) print(data) </code></pre> <p>but the code above leads to the error</p> <pre><code> File &...
<python><hdf5><h5py>
2025-09-08 10:00:51
1
4,478
carl
79,758,380
4,966,317
How to add objects/links to a set of links in beanie?
<p>Assume that I have these <code>Beanie Document</code>s which are based, by the way, on <code>Pydantic Model</code>s:</p> <p><strong>File name:</strong> <code>models.py</code></p> <pre class="lang-py prettyprint-override"><code>from beanie import Document, Link class A(Document): first: int second: str clas...
<python><mongodb><fastapi><pydantic><beanie>
2025-09-07 22:15:29
1
2,643
Ambitions
79,758,337
11,986,368
Using Sphinx autosummary to generate documentation for class instances stored as attributes during instantiation of another class
<p>I have a class called <code>WebAPI</code> that instantiates and stores a <code>UserEndpoints</code> object inside its constructor:</p> <pre class="lang-py prettyprint-override"><code># /src/minim/api/spotify/_core.py ... # other imports from .._shared import OAuth2API from ._web_api.users import UserEndpoints cla...
<python><python-sphinx><autosummary>
2025-09-07 20:05:31
0
528
Benjamin Ye
79,757,853
4,701,426
Manipulating a large dataframe most efficiently
<p>Imagine I have this dataframe called temp:</p> <pre><code>temp = pd.DataFrame(index = [x for x in range(0, 10)], columns = list('abcd')) for row in temp.index: temp.loc[row] = default_rng().choice(10, size=4, replace=False) temp.loc[1, 'b'] = np.nan temp.loc[3, 'd'] = np.nan </code></pre> <p>df:</p> <p><a ...
<python><pandas><numpy><pytorch>
2025-09-06 23:41:28
1
2,151
Saeed
79,757,564
12,871,587
Nested Window Expression
<p>I'm building some feature generation expressions and I'd like to build an expression that:</p> <ol> <li>Calculates account_length as cumulative count of records per account</li> <li>Then calculate the median of account_length per status_date</li> </ol> <p>Is there a way to do this in single expression, without using...
<python><dataframe><python-polars>
2025-09-06 13:06:49
1
713
miroslaavi
79,757,357
1,890,413
custom filter for filter_horizontal admin in django
<p>I have the following models where a deck have a many to many relationship with problems and problems can have tags</p> <pre><code>from django.utils import timezone from django.db import models from taggit.models import TaggedItemBase from taggit.managers import TaggableManager # Create your models here. class Tag...
<python><django>
2025-09-06 05:50:56
1
1,114
angvillar
79,757,210
1,604,008
Python unittest fails with No module loaded in VScode
<p>I have the following directory structure</p> <p><img src="https://i.sstatic.net/3KGwRt0l.png" alt="directory structure" /></p> <p>when I use the test runner I get</p> <p><code> File &quot;/home/kyle/dev/tests/test_foo.py&quot;, line 2, in &lt;module&gt; import foo ModuleNotFoundError: No module named 'foo'</code></p...
<python><visual-studio-code><python-unittest>
2025-09-05 22:31:47
1
1,159
user1604008
79,757,125
422,953
When did numpy change the behavior of A = B[slice]?
<p>I know that if I have a numpy array <code>A</code>, then a statement like <code>B = A</code> will make a &quot;shallow&quot; copy, i.e., B will point to the same memory address as A. However, before some numpy version, <code>B = A[slice]</code> used to create a new array <code>B</code> such that changing <code>B</co...
<python><numpy>
2025-09-05 20:16:09
2
340
TM5
79,756,828
6,691,914
Pass python location to Rscript in Azure Devops
<p>I need to create an Azure Devops pipeline to build and deploy an R Shiny app (not python-shiny). The main problem in my case is that I don't have admin rights on the build agents. To mitigate this, I use a folder where I have full sudo rights ($(Pipeline.Workspace)/R/library).</p> <p>And for app restore and snapshot...
<python><r><azure-devops><rscript><renv>
2025-09-05 13:25:39
0
1,652
Vasyl Stepulo
79,756,763
8,037,521
Python VTK RAM usage
<p>I am using VTK Python in my application for point cloud visualization. I would like to be able to support rather big point clouds but, as I have noticed in my app, the high RAM usage does not make it possible. Of course, there is always some limit to what we can visualize, based on the available RAM of the PC, but I...
<python><vtk>
2025-09-05 12:14:06
0
1,277
Valeria
79,756,625
7,321,700
Using a column value to find the Column header name in Pandas
<p><strong>Scenario:</strong> I have a pandas dataframe. I am trying to use the values in a given column (year) to find the relevant header name and add it to a new column (year_name). For example, if the dataframe looks like this:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>itemName</th...
<python><pandas>
2025-09-05 09:46:17
1
1,711
DGMS89
79,756,594
1,750,612
How do I capture missing nan values from Pandas 2.3.0 using Pydantic 2.11.7
<p>Prerequisites:</p> <ul> <li>Python 3.11.7</li> <li>Pandas 2.3.0</li> <li>Numpy 2.1.3</li> <li>Pydantic 2.11.7</li> </ul> <p>In the pandas documentation, it states that missing values for numeric data types are filled in with <code>numpy.nan</code>:</p> <p><a href="https://pandas.pydata.org/docs/user_guide/missing_da...
<python><pandas><numpy><python-typing>
2025-09-05 09:07:53
1
359
MikeFenton
79,756,402
2,153,235
vobject.readcomponents(...) : Is it a generator or does it *return* a generator?
<p>This is a question about technical terminology.</p> <p>The <a href="https://github.com/skarim/vobject" rel="nofollow noreferrer">vobject documentation</a> says &quot;readComponents is a generator&quot;, which is consistent with its doc string &quot;Generate one Component at a time from a stream&quot;.</p> <p>However...
<python><generator>
2025-09-05 04:35:59
2
1,265
user2153235
79,756,235
4,057,053
Why doesn't MCP server expose my resources?
<p>here's the MCP code I have:</p> <pre class="lang-py prettyprint-override"><code>from mcp.server.fastmcp import FastMCP # Create an MCP server mcp = FastMCP(&quot;Demo&quot;) # Add a dynamic greeting resource @mcp.resource(&quot;greeting://{name}&quot;) def get_greeting(name: str) -&gt; str: &quot;&quot;&quot;...
<python><model-context-protocol>
2025-09-04 21:27:45
0
8,822
kurtgn
79,756,233
1,233,376
`google.auth` python SDK not reading granted scopes from credentials file
<p>I've run:</p> <pre><code>gcloud auth application-default login --client-id-file google_oauth_client_id.json --scopes=&quot;https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/calendar.calendars.readonly&quot; </code></pre> <p>successfully. My browser opened, I granted the calendar and clou...
<python><google-oauth><google-calendar-api><gcloud>
2025-09-04 21:22:07
1
1,092
Ian Burnette
79,756,149
5,096,103
Pandas does not fail, warn, or skip when rows have more columns than the header
<p>I'm new to Python and to Pandas, and I am desperately trying to understand how or why this is happening.</p> <p>I have a CSV file with some data, which has some rows which have extra commas <code>,</code> which are not escaped. So there are 4 column headers, but some rows have 5 fields due to the improperly escaped ...
<python><pandas><dataframe><csv>
2025-09-04 19:25:11
2
764
Cillian Myles
79,756,115
1,700,890
Installing python package from zip file offline
<p>I am working in Kaggle notebook. I need to install transformers package offline. Normally I would install it like this (online):</p> <pre><code>!pip install git+https://github.com/huggingface/transformers </code></pre> <p>Here is what I did to accomplish the same, but offline.</p> <p>I created snapshot of installed ...
<python><pip><kaggle>
2025-09-04 18:41:20
1
7,802
user1700890
79,756,072
6,433,136
AI Foundry - Remote MCP Server - Failure: Error - RequiresAction on ToolCall
<p>I have a custom Remote MCP Server hosted on Azure written in Rust leveraging the &quot;rmcp&quot; crate. I have a python program to deploy the MCP Server (as an agent) into AI Foundry using &quot;McpTool&quot;, I see that agent created and that all works fine. The Python program tests connectivity during the deploy...
<python><model-context-protocol><azure-ai-foundry>
2025-09-04 18:04:59
2
575
mazecreator
79,756,013
1,390,639
turn Python float argument into numpy array, keep array argument the same
<p>I have a simple function that is math-like:</p> <pre><code>def y(x): return x**2 </code></pre> <p>I know the operation <code>x**2</code> will return a <code>numpy</code> array if supplied a numpy array and a float if supplied a float.</p> <p>for more complicated functions that include an integral I want it to retu...
<python><arrays><numpy><floating-point>
2025-09-04 17:04:47
2
1,259
villaa
79,755,894
1,742,777
Can I find out if an instance of a SQL Alchemy Model meets the filter requirements without scanning the entire table?
<p>Suppose I have the SQLAlchemy code shown below. It retrieves all the users who are older than 28 years old.</p> <p>Now suppose I create a new User <code>u2 = User(name='Bart', age=66)</code>.</p> <p>I want to find out if <code>u2</code> matches the filter of <code>my_query</code> without going back to the DB and sca...
<python><database><postgresql><sqlalchemy>
2025-09-04 15:11:27
1
12,798
Saqib Ali
79,755,800
1,700,890
Downloading "BigQuery_Helper" wheels locally results in error "Multiple top-level modules discovered in a flat-layout"
<p>I am trying to download all packages from <code>requirements.txt</code> file.</p> <p>I ran</p> <pre class="lang-none prettyprint-override"><code>! pip download -r requirements.txt -d ./wheels --verbose </code></pre> <p>It generated error:</p> <pre class="lang-none prettyprint-override"><code>Obtaining bq_helper from...
<python><pip><setuptools>
2025-09-04 13:50:48
1
7,802
user1700890
79,755,748
24,332,077
Is iteration order of a set in Python preserved until that set is modified?
<p>According to <a href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset" rel="nofollow noreferrer">the Python documentation</a>, <code>set</code> is a mutable unordered collection.</p> <p>Usually, it's implemented as a hash table that stores references to objects as its keys. Comparing to <code...
<python><set><iteration>
2025-09-04 12:51:54
2
353
SLebedev777
79,755,548
2,218,321
Why only creating a task will run the coroutine in python?
<p>There is something I can't understand in this code</p> <pre><code>import asyncio async def fetch_data(param): print(f&quot;Do something with {param}...&quot;) await asyncio.sleep(param) print(f&quot;Done with {param}&quot;) return f&quot;Result of {param}&quot; async def main(): task1 = async...
<python><async-await><python-asyncio><coroutine>
2025-09-04 09:52:53
4
2,189
M a m a D
79,755,358
7,176,676
How to deploy a Databricks App with tesseract-ocr
<p>I am trying to deploy a Databricks app that uses PyMUPDF library to extract text from PDF files. Under the hood, it tries to use an OS dependency called 'tesseract-ocr'. Please note that this is not the pytesseract library, but a dependency that need to be installed on the system.</p> <p>My understanding is that whe...
<python><databricks><ocr>
2025-09-04 06:34:28
0
395
flow_me_over
79,755,351
6,186,822
How to have a parent terminal view and pilot a child pseudo-terminal
<p>Goal: In Python have a parent terminal start a program in a child pseudo-terminal (PTY), see its outputs and provide its inputs. At any given time, the parent terminal should be able to query what's on the child's screen at any character index</p> <p>So in pseudocode the parent would do:</p> <pre><code>child_termina...
<python><tty><pty>
2025-09-04 06:29:17
1
1,590
GenTel
79,755,132
16,563,251
Create recursive TypeAlias at runtime
<p>For use with <a href="https://docs.pydantic.dev/latest" rel="nofollow noreferrer">pydantic</a>, I want to create recursive type aliases at runtime. &quot;Normal&quot; <a href="https://typing.python.org/en/latest/spec/aliases.html" rel="nofollow noreferrer">type aliases</a> are possible like this:</p> <pre class="lan...
<python><python-typing><pydantic>
2025-09-03 22:29:10
0
573
502E532E
79,755,062
13,014,864
Best method to create generator for TensorFlow with list of array inputs
<p>I am using TensorFlow/Keras to create a deep learning model. The network is built as follows:</p> <pre class="lang-py prettyprint-override"><code>inps = [] features = [] for i in range(number_windows): inp = Input(shape=(window_length,), name=f&quot;input_{i}&quot;) inps.append(inp) feat = Dense(25)...
<python><tensorflow><keras><dataloader>
2025-09-03 20:29:53
1
931
CopyOfA
79,754,617
17,569,967
Pyside environment variable doesn't apply in Pycharm's run configuration
<p>I'm trying to diagnose missing <code>Slot</code> decorators as specified in the end of the section <a href="https://doc.qt.io/qtforpython-6/tutorials/basictutorial/signals_and_slots.html#the-slot-class" rel="nofollow noreferrer">https://doc.qt.io/qtforpython-6/tutorials/basictutorial/signals_and_slots.html#the-slot-...
<python><pycharm><pyside6>
2025-09-03 12:51:29
0
412
Intolighter
79,754,606
13,014,864
TensorFlow data loader from generator error "Dataset had more than one element"
<p>I am trying to implement a TensorFlow dataset from a Python generator because I am having problems with my model consuming memory, inevitably resulting in a OOM crash (see my question on that <a href="https://stackoverflow.com/questions/79727623/tensorflow-keras-model-accumulates-system-and-gpu-ram-during-training">...
<python><tensorflow><keras><dataloader>
2025-09-03 12:40:39
1
931
CopyOfA
79,754,535
4,882,126
Permutation of list in python with one or multiple fixed items
<p>I have a list of <code>a = [5,6,7,9]</code> I want all the possible permutations, with one or more entry fixed.</p> <p>e.g. If I want to fix third element <code>7</code>, then in all permutations I want to see <code>7</code> in the third place of the list.</p> <p>The code I wrote works well.</p> <pre><code>from iter...
<python><list><permutation>
2025-09-03 11:31:29
2
512
Zeryab Hassan Kiani
79,754,233
9,021,547
How to change order and number of tasks to be executed in airflow
<p>I want to create a dag workflow with 5 different branches as follows: <a href="https://i.sstatic.net/lG5LPdG9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lG5LPdG9.png" alt="enter image description here" /></a></p> <p>The base dag is this:</p> <pre><code>from datetime import datetime, timedelta, da...
<python><airflow>
2025-09-03 07:02:32
1
421
Serge Kashlik
79,754,148
11,790,637
How should I install CUDA dependencies in readthedocs build with apidoc autodoc
<p>I have a python project which uses readthedocs and its apidoc/autodoc to build API documents automatically. The project uses a third-party tool that can only be installed from source like this: <code>pip install git+https://github.com/xxx/yyy.git</code> (no published prebuilt wheel). Furthermore, the third-party too...
<python><python-sphinx><read-the-docs><autodoc>
2025-09-03 05:05:55
0
2,337
ihdv
79,753,801
6,271,889
Pyparsing ParseResults attributes type hinting
<p>I'm using Pyparsing and I'm getting a <code>reportArgumentType</code> error from Pyparse:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass import pyparsing as pp @dataclass class Foo: value: int def parse_foo(line: str) -&gt; Foo: grammar = pp.Keyword(&quot;FOO&quot;) ...
<python><python-typing><pyparsing><pyright>
2025-09-02 17:54:17
0
2,021
Leonardo
79,753,551
4,367,177
Why is Airflow Bash operator not passing XCom to another operator?
<p>I'm working on a task group that needs to pass a variable from a <code>BashOperator</code> to another <code>BashOperator</code>. Each bash operator is invoking Python, and the first Python script needs to return a string in a variable that the second bash operator will take and continue with:</p> <pre><code>first_st...
<python><airflow><airflow-xcom>
2025-09-02 13:22:15
2
302
BMac
79,753,458
3,611,164
Configure ruff to ignore environment-provided globals
<p>How can we configure the Ruff linter to ignore environment-provided global variables?</p> <p>I have a python codebase which contains notebooks, that run in a databricks environment. The environment provides globals such as <code>spark</code>.</p> <p>A perfectly valid example in that context would be:</p> <pre class=...
<python><ruff>
2025-09-02 11:47:10
1
366
Fabitosh
79,753,424
6,045,397
Is it necessary to recreate conda environments for python on a different version of Linux-64?
<p>I use a High Performance Computing cluster that has moved between Linux versions (RedHat to Rocky). The file system is the same so my home directory is identical. Do I need to reinstall my conda environments for python? The versions of gcc and other system libraries are different, but won't conda download the same p...
<python><linux><conda>
2025-09-02 11:16:13
0
844
tiagoams
79,753,356
799,812
mypy fails with mixed types in variable length tuple
<p>mypy fails on code where a variable length tuple contains different types. What should I be doing here?</p> <pre><code>for i, *s in [(1, 'a'), (2, 'b', 'c')]: print(hex(i), '_'.join(s)) </code></pre> <pre><code>main.py:2: error: Argument 1 to &quot;hex&quot; has incompatible type &quot;int | str&quot;; expected ...
<python><python-typing><mypy>
2025-09-02 10:13:45
3
317
grahamstratton
79,753,263
12,519,771
Pytest-django database not rolled back with pytest-asyncio
<p>For context, I am trying to test a WebSocket connection made through Django, so I need to set up some async tests with database support.<br /> To do so, I have set up pytest-django and I have some trouble understanding the <code>django_db</code> decorator's behavior in async contexts.</p> <p><code>django_db</code> h...
<python><django><pytest><pytest-django><pytest-asyncio>
2025-09-02 08:34:48
1
957
RobBlanchard
79,753,068
5,118,421
Which way is faster way to create Decimal?
<p>Which way is faster to create <code>Decimal</code> - from float or from string?</p> <pre><code>Decimal(1.2) </code></pre> <p>vs</p> <pre><code>Decimal('1.2') </code></pre> <p>How does the difference in speed of the to cases?</p>
<python>
2025-09-02 04:12:35
3
1,407
Irina
79,752,914
27,596,369
How can I make all attributes in a Python dataclass optional without rewriting each one?
<p>I have this data class:</p> <pre><code>@dataclass class User: id: str name: str pwd: str picture: str url: str age: int # many, many more attributes </code></pre> <p>Now, I have to make all of the attributes of my data class optional because of a change in the data I am receiving.</p> <p>...
<python><metaprogramming><python-dataclasses>
2025-09-01 21:23:24
2
1,512
Aadvik
79,752,222
219,153
How to pretty-print a tuple of NumPy scalars?
<p>This NumPy 2.2.6 script:</p> <pre><code>import numpy as np a = np.arange(24).reshape(2, 2, 2, 3) idx = np.unravel_index(np.argmax(a, axis=None), a.shape) print(idx) </code></pre> <p>will print:</p> <pre><code>(np.int64(1), np.int64(1), np.int64(1), np.int64(2)) </code></pre> <p>which is hard to read. What is a sim...
<python><numpy><printing>
2025-09-01 06:41:19
2
8,585
Paul Jurczak
79,751,873
8,964,393
Combine separate plots into one plot in Python
<p>I have created the following pandas dataframe:</p> <pre><code>ds = { 'Date' : ['2025-08-22 16:00:00', '2025-08-22 16:01:00', '2025-08-22 16:02:00', '2025-08-22 16:03:00', '2025-08-22 16:04:00', '2025-08-22 16:05:00', '2025-08-22 16:06:00', '2025-08-22 16:07:00', '2025-08-22 16:08:00', '2025-08-22 16:0...
<python><pandas><dataframe><matplotlib><combinedchart>
2025-08-31 15:57:28
1
1,762
Giampaolo Levorato
79,751,781
9,985,445
Why Does Sympy Say This Derivative Is Constant When It's Obviously Not?
<p>I am trying to make a Jacobian matrix using sympy.</p> <p>I want to make a matrix of 2nd order derivatives, which I will call a 2nd order Jacobian.</p> <p>I did this:</p> <pre><code>gk_letters = [&quot;Δ&quot;, &quot;Γ&quot;, &quot;v&quot;] def greek_symbols(): return symbols(&quot; &quot;.join(gk_letters)) de...
<python><sympy><symbolic-math>
2025-08-31 13:38:26
1
869
James Strieter
79,751,467
9,251,158
Why does flake8 flag E226 only when whitespace is missing on both sides of operator?
<p>Here is a minimal reproducible example:</p> <pre><code>j = 0*0 # Flagged for E226. j = 0* 0 # Not flagged for E226. j = 0 *0 # Not flagged for E226. </code></pre> <p>As the comments suggest, <code>flake8</code> flags only the first line, not the others, for E226:</p> <pre><code>$ flake8 tmp.py --ignore=E225,E231,...
<python><pep8><flake8>
2025-08-30 22:25:55
2
4,642
ginjaemocoes
79,751,457
905,814
Diagnosing duplicate inserts after merge/upsert with deltalake (Python)
<p>I’d really appreciate your help with a duplication issue I’m hitting when using deltalake merges (Python).</p> <p><strong>Context</strong></p> <ol> <li>Backend: Azure Blob Storage</li> <li>Libraries: deltalake 1.1.4 (Python), Polars 1.31.0 (source is a LazyFrame/DataFrame)</li> <li>Goal: Idempotent upsert (re-runnin...
<python><merge><python-polars><delta-lake><delta-rs>
2025-08-30 22:18:27
1
456
Octavio
79,751,371
2,856,552
Sorting a column of max values from a multicolumn pandas data frame
<p>I have a multi-column pandas data frame of years and corresponding cumulative rainfall values from 1 to 183 (October to March). That means in each column the last value is the maximum column value, being the cumulative total from 1. I then create a new data frame which contains the years (col1) and the max values in...
<python><pandas><dataframe>
2025-08-30 19:16:09
1
1,594
Zilore Mumba
79,751,257
703,421
Python search in a sorted list if key is a part of a string using bisect
<p>I have a list of pathnames (dirname+filename), sorted by filenames.</p> <p>How to use bisect if I want to find a filename in this list ?</p> <p>Example :</p> <pre><code>import os, bisect lst=[] for (dp, dn, fn) in os.walk(rep): for name in fn: lst.append(os.path.join(dp, name) # sort list by filenames ls...
<python><list><sorting><bisect>
2025-08-30 15:54:44
1
2,279
Eric H.
79,751,217
9,063,378
Compute Eigenvalues for matrix when each element is a disjoint array
<p>I have some 2x2 covariance matrix represented as 3 disjoint arrays, meaning 3 Nx1 arrays. The N is this case represents time so the covariance of some measurements over time. I would like to be able to compute the eigenvalues at each time step without copying the individual arrays in a square matrix.</p> <p>I could ...
<python><numpy><eigenvalue>
2025-08-30 14:36:01
2
514
Melendowski
79,751,060
3,938,402
How to make a ssh connection from another ssh connected machine
<p>I have 3 linux machines <code>(hostA, hostB, hostC)</code>, from <code>hostA</code> I will remote login into <code>hostB</code> via ssh and transfer some file/directory from <code>hostA</code> to <code>hostB</code>. Once transfer is done from <code>hostA</code> to <code>hostB</code>, I would like to login and transf...
<python><ssh><paramiko>
2025-08-30 09:55:38
0
4,026
Harry
79,751,053
633,961
Django OneToOneField, Pyright: Cannot access attribute (reportAttributeAccessIssue)
<p>I try to check my Django project with <a href="https://github.com/microsoft/pyright" rel="nofollow noreferrer">pyright</a>.</p> <p>There is this OneToOneField, which pyright does not detect, when I use it:</p> <pre class="lang-py prettyprint-override"><code>user.lala </code></pre> <p>Error message of pyright:</p> <b...
<python><django><python-typing><pyright>
2025-08-30 09:46:23
0
27,605
guettli
79,751,006
1,230,724
Custom numpy element type with arithmetic functions without overloading `np.ndarray`
<p>Is it possible to implement a custom class (say, <code>class Foo</code>) with <code>__add__</code>, <code>__mul__</code>, etc. methods defined and add it into a normal <code>np.ndarray</code> (<code>np.asarray([Foo(1), Foo(2)])</code>) and have numpy delegate to methods <code>Foo.__add__</code>/<code>Foo.__mul__</co...
<python><arrays><numpy>
2025-08-30 07:50:23
1
8,252
orange
79,750,812
405,017
Creating git subtree repo that can import Python files as from "fake" namespace
<p>tl;dr: What are the minimal changes needed to make a standalone folder work in Python runtime, and get modules resolved in VS Code, as though it's part of a parent module namespace? Simple example at the end of the question.</p> <h2>Background/Motivation</h2> <p>I have a git repo I develop on with a structure like:<...
<python><git><git-subtree><pyright>
2025-08-29 22:09:38
1
304,256
Phrogz
79,750,735
27,596,369
How to use the data class itself as the type of its attribute
<p>I have a data class:</p> <pre><code> from dataclasses import dataclass from typing import Any @dataclass class Url: http: bool params: dict[str: Any] body: str # More stuff here </code></pre> <p>Here I have a <code>Url</code> data class with three attributes, <code>http</code> which is a boolean, ...
<python><python-typing><python-dataclasses>
2025-08-29 20:03:26
0
1,512
Aadvik
79,750,725
3,138,436
Variable type-hinted to to be a dictionary that accept list as value is also taking sets as valid value
<p>I am experimenting with type-hinting in Python 3.12. I've declared a variable that is type-hinted to be a dictionary whose keys are string and values will be a list of string.</p> <pre><code>mydict : dict[str,list[str]] = { &quot;d&quot;:[&quot;k&quot;,&quot;t&quot;,&quot;k&quot;] } #output : mydict ----&gt; d:[...
<python><python-typing>
2025-08-29 19:54:33
1
9,194
AL-zami
79,750,684
396,373
How to detect pipe close when reading text by line in Python
<p>I have been having a lot of trouble reading text a line at a time from a pipe in Python and determining when the socket has been closed on the writing end. I have had the problem when communicating with a subprocess, but to for testing, I wrote some code that reads text lines from the pipe in a thread while code in ...
<python><io><pipe>
2025-08-29 18:51:54
1
12,777
Steve Jorgensen
79,750,682
2,807,964
Is it possible to install submodules of a python package dynamically?
<p>I have a very complex Python library that is used by several people/projects for different purposes.</p> <p>The structure is basically the same as many Python libraries, but I would like to give the ability of a partial install.</p> <pre><code>project_name/ |__ package | |__ submodule1 | | |__ ...
<python><pip><python-import><setuptools><python-packaging>
2025-08-29 18:50:24
1
880
jcfaracco
79,750,548
629,186
Using PyTest and Playwright, run one method before loading all the test files
<p>This question seems to be asked a lot, but I'm not finding any answers that work, or at least that work for what I'm looking for.</p> <p>The premise is simple: I have a website I need to automate testing on (using Playwright with PyTest). I can use <code>browser.new_context(storage_state=auth_file)</code>, which put...
<python><pytest><playwright><playwright-python>
2025-08-29 16:29:18
1
1,817
MivaScott
79,750,369
1,029,469
Pycharm recognizes package installed with -e (editable), but does not recognize/show the package content
<p>I've installed my own custom package with <code>-e 'git+https://.....@main#egg=package'</code>. I build my dependencies with pip-tools (pip-compile), and install them with pip-sync.</p> <p>The package shows as &quot;installed&quot; when I look at the installed packages of the interpreter in Pycharm. But it's content...
<python><pip><pycharm>
2025-08-29 13:52:51
1
1,957
benzkji
79,750,217
2,377,238
How to make Numpy.where() return only the first match?
<p>I'm trying to optimize the performance of a script, which is full of Numpy's <a href="https://numpy.org/doc/stable/reference/generated/numpy.where.html" rel="nofollow noreferrer">where()</a> after which only the first returned element is actually used. Example:</p> <pre><code>F = np.where(Y&gt;p/100)[0] </code></pre...
<python><numpy>
2025-08-29 11:25:09
3
319
chris_cm
79,750,038
5,121,448
SyntaxError in flask_humanify
<p>I get this Syntax error after installing flast_humanify</p> <pre><code>Traceback (most recent call last): File &quot;once.py&quot;, line 29, in &lt;module&gt; from flask_humanify import Humanify File &quot;/usr/local/lib/python3.6/site-packages/flask_humanify/__init__.py&quot;, line 9, in &lt;module&gt; ...
<python><flask><flask-humanify>
2025-08-29 08:54:54
2
4,478
carl
79,750,033
12,411,536
polars `write_parquet` to S3 with partitions makes local copy
<p>I am observing an unintuitive behavior when writing to S3 from polars with specifying partitions. Namely,</p> <ul> <li>with <code>use_pyarrow=False</code> a copy of the files is created locally before uploading, and not cleanup up afterwards automatically</li> <li>with <code>use_pyarrow=True</code> I am getting <cod...
<python><dataframe><python-polars>
2025-08-29 08:50:09
1
6,614
FBruzzesi
79,750,003
5,121,448
python module not found after installation
<p>I installed a python package using</p> <pre><code>/usr/local/bin/python3.6 -m pip install flask_Humanify </code></pre> <p>and it gave me the output below, indicating that everything worked. Now, when I run my code</p> <pre><code>/usr/local/bin/python3.6 test.py </code></pre> <p>I get</p> <pre><code>Traceback (most r...
<python>
2025-08-29 08:24:30
1
4,478
carl
79,749,945
492,034
Python - ThemedTKinterFrame - grid_columnconfigure weight does not work
<p>I'm using ThemedTKinterFrame to beautify my python app but I'm facing a problem with grid_columnconfigure that does not work as supposed. Infact, does not work at all.</p> <p>Code:</p> <pre><code>import tkinter as tk import TKinterModernThemes as TKMT class App(TKMT.ThemedTKinterFrame): def __init__(self, theme...
<python><tkinter>
2025-08-29 07:26:42
1
1,776
marco
79,749,841
5,400,385
How to get the MCPO Proxy command working correctly
<p>Just trying to setup a basic MCP Server and put it behind MCPO proxy.</p> <p>This MCP server copied from: <a href="https://github.com/modelcontextprotocol/python-sdk/tree/main" rel="nofollow noreferrer">https://github.com/modelcontextprotocol/python-sdk/tree/main</a></p> <pre><code>&quot;&quot;&quot; FastMCP quickst...
<python><model-context-protocol><mcpo>
2025-08-29 05:20:51
0
2,112
PGHE