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,670,945
285,777
Parsing question for Python with LXML and Requests (Soap)
<p>This is an example response:</p> <pre><code>&lt;soap-env:Envelope xmlns:soap-env=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt; &lt;soap-env:Header /&gt; &lt;soap-env:Body&gt; &lt;api:PlexViewResponse xmlns:api=&quot;http://alu.com/plexwebapi/api&quot; Command=&quot;ACT-USER&quot; SwitchName=&quot;...
<python><lxml>
2025-06-18 15:52:00
1
409
Kelso
79,670,944
6,843,153
Adding text to gdoc using Google API sets random paragraph style
<p>I have the following method that adds formatted text to a data structure for it to be used in a <code>batchUpdate</code> request:</p> <pre><code> def add_text( self, text, bold=None, color=None, font_size=None, bg_color=None, italic=None, ): if te...
<python><google-api><google-docs-api>
2025-06-18 15:50:32
0
5,505
HuLu ViCa
79,670,825
2,666,289
Index array using boolean mask with a "broadcasted" dimension?
<p>I have two arrays <code>a1</code> and <code>a2</code> of shape <code>M1xM2x...xMPx3</code> and <code>N1xN2x...xNQx3</code>, and a mask <code>m</code> (boolean array) of shape <code>M1xM2x...xMPxN1xN2x...xNQ</code> (you can assume that <code>a1</code> and <code>a2</code> are at least 2D).</p> <pre class="lang-py pret...
<python><numpy>
2025-06-18 14:35:52
1
38,048
Holt
79,670,668
6,500,048
marimo switches to global python instead of using uv venv
<p>running marimo with uv as I have done with other projects, but for some reason it switches from the venv created using uv to the global version of python and nothing I do can seem to make it run in uv.</p> <p>Is there some metadata or path environment I am missing to get this working?</p> <p>Here is my <code>project...
<python><uv><marimo>
2025-06-18 12:51:05
1
1,279
iFunction
79,670,587
24,696,572
pytorch: torch.bucketize with not-strictly increasing sequence
<p>I am working with a batched interpolation class where a typical task is to find the knot index for each evaluation point in the batch. This sounds like a job for <code>torch.bucketize</code>, but the knot vector is not strictly increasing but has repeated vals. See the example below.</p> <p>The documentation of <cod...
<python><pytorch>
2025-06-18 11:56:58
0
332
Mathieu
79,670,289
221,166
Type-hinting a dynamic, asymmetric class property
<p>I'm currently working on removing all the type errors from my Python project in VS Code.</p> <p>Assume you have a Python class that has an asymmetric property. It takes any kind of iterable and converts it into a custom list subclass with additional methods.</p> <pre class="lang-py prettyprint-override"><code>class ...
<python><python-typing><pyright>
2025-06-18 08:44:59
2
3,203
Torben Klein
79,670,265
1,023,928
When importing python library, package is sometimes found, at other times not found due to location of file in the project
<p>I have the following project structure:</p> <pre class="lang-none prettyprint-override"><code>PYTHON_DEVELOPMENT [WSL: UBUNTU2504] ├── mattlibrary ├── test_bench │ └── testme.ipynb └── test.ipynb </code></pre> <p>My problem is that when I <code>import mattlibrary</code> inside <code>testme.ipynb</code> the module ...
<python><import><package>
2025-06-18 08:26:34
0
7,316
Matt
79,670,247
6,702,598
How to tell pylint about type checks
<p>The example below does a type check inside a function in order to keep the <em>foo</em> function cleaner. However,the last <code>return values.a</code> gets a static type check error. Pylint does not understand that <code>values.a</code> was already tested for <code>None</code> and it's actually safe to return <code...
<python><python-typing>
2025-06-18 08:07:24
0
3,673
DarkTrick
79,670,214
2,537,394
Type hinting optional properties in python 3.10+
<p>Suppose I have a Car class with the properties <code>color</code> and <code>owner</code>. Thinking from a seller's perspective, a new car doesn't have an owner yet. Therefore I'd like to make owner optional, as with the following code:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import datac...
<python><python-typing><pyright>
2025-06-18 07:44:28
3
731
YPOC
79,670,155
15,468,624
Executorch v. 0.6 -- Failed build of apple-ios example
<p>I have an issue when trying building the apple-ios example app using XCode. I am working on a MacBook Pro 2021 with M1 processor.</p> <p>When opening the XCode project I have the following two issues in LLaMaRunner:</p> <blockquote> <p>Undefined symbol: executorch::extension::llm::load_tokenizer(std::__1::basic_stri...
<python><pytorch>
2025-06-18 06:57:11
0
307
alirek
79,670,111
19,459,262
Why does expressify not show calculations that require an input?
<p>I have a Shiny app in two sections - app.py, the main app, and page.py, because my code is rather long and I don't want it all in one file where I can accidentally nuke the whole thing. The problem is, I have interactive elements. Since I'm using expressify, I think it's refusing to display values if calculations ar...
<python><shiny-reactivity><py-shiny>
2025-06-18 06:26:07
1
784
Redz
79,669,954
1,060,209
regex to match uuid4 not working with f-string
<p>Working:</p> <pre><code>#!/usr/bin/python3 import re path = &quot;/a/b/c/e72cc82c-e83a-431c-9f63-c8d80eec9307&quot; if re.match(r&quot;/a/b/c/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$&quot;, path): print(&quot;matched&quot;) else: print(&quot;didn't match anything&quot;) </cod...
<python><uuid><f-string>
2025-06-18 02:22:17
2
4,881
Qiang Xu
79,669,932
10,242,281
Python how to load SQL Server table with sqlalchemy?
<p>I'm trying to load table using Python in most effective way, and learned that <code>sqlalchemy / engine</code> is the best tool for that. But I really struggle to make this construction work for SQL Server as my target, I did exactly like in <a href="https://docs.sqlalchemy.org/en/20/dialects/mssql.html#module-sqlal...
<python><sql-server><pyodbc>
2025-06-18 01:45:53
0
504
Mich28
79,669,881
17,246,545
Is there a problem with the connection code to PLC?
<p>I try to connect to Mitsubishi QJ71E71 PLC with python code.</p> <p>I already set the GX_works2's open setting.</p> <p>But when i connect to PLC with below code, it got a timed out error.</p> <pre class="lang-py prettyprint-override"><code>import pymcprotocol pymc3e = pymcprotocol.Type3E() # Q series pymc3e.setacce...
<python><network-programming><server><plc><lan>
2025-06-18 00:05:58
0
389
SecY
79,669,876
2,266,881
Process detachment
<p>This may be a very basic question..</p> <p>I made a simple python script that launches mpv with certain url with a:</p> <pre><code>p = subprocess.Popen([&quot;/usr/bin/mpv&quot;, link], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) </code></pre> <p>Now, i'm having the following situation; if i:</p> <p>A) Open...
<python><linux><arch>
2025-06-17 23:50:57
1
1,594
Ghost
79,669,473
794,329
Exhaustively check for all literals while allowing for type inference of the return type
<p>I’m trying to write a Python function that satisfies three goals simultaneously:</p> <ol> <li>Exhaustively checks all possible values of a <code>Literal</code> argument.</li> <li>Avoids linter warnings like Ruff’s &quot;too many return statements&quot;.</li> <li>Preserves precise return type inference, e.g., inferri...
<python><python-typing><literals>
2025-06-17 16:29:13
2
441
Danilo Horta
79,669,389
2,893,712
Pandas Subtract One Dataframe From Another (if match)
<p>I have a pandas dataframe that has information about total attendance for schools grouped by School, District, Program, Grade, and Month #. The data looks like the following (<code>df</code>):</p> <pre><code>School District Program Grade Month Count 123 456 A 9-12 10 ...
<python><pandas>
2025-06-17 15:41:46
2
8,806
Bijan
79,669,262
794,329
How to associate a literal label with a type and extract it to define another type in Python?
<p>I’m trying to associate a string label with each class and then use those labels to define a <code>Literal</code> type for validation or type checking purposes. Here’s a simplified example of what I’m trying to do:</p> <pre class="lang-python prettyprint-override"><code>from typing import Literal class Apple: l...
<python><python-typing>
2025-06-17 14:25:10
0
441
Danilo Horta
79,669,216
5,439,470
access denied on smbclient.register_session
<p>i try to connect from my mac to a smb server using this</p> <pre><code>smbclient.register_session( &quot;smbserver.net&quot;, username=&quot;domain\\username&quot;, password=&quot;secret&quot;, port=445 ) </code></pre> <p>but i allways get this error</p> <p...
<python><python-3.x><smb>
2025-06-17 13:56:16
0
1,303
jan-seins
79,669,210
624,900
Python http library that supports trailers
<p>Do any Python http libraries support <em>both</em> request and response trailers?</p> <p>For example, some other languages have:</p> <ul> <li>libcurl: <a href="https://curl.se/libcurl/c/CURLOPT_TRAILERFUNCTION.html" rel="nofollow noreferrer">https://curl.se/libcurl/c/CURLOPT_TRAILERFUNCTION.html</a></li> <li>go: <a ...
<python><http>
2025-06-17 13:50:56
0
67,435
jterrace
79,669,095
16,527,170
sqlalchemy.exc.OperationalError: (2003, "Can't connect to MySQL server on '123@localhost' ([Errno -2] Name or service not known)")
<p>I am using python to Connect with DB.</p> <pre><code>from sqlalchemy import create_engine import pymysql db_password = &quot;abc@123&quot; db_user = &quot;test_user&quot; db_name = &quot;xyz&quot; db_host = &quot;127.0.0.1&quot; # or 127.0.0.1 # Create SQLAlchemy engine engine = create_engine(f'mysql+pymysql://{db_...
<python><mysql><sqlalchemy><pymysql>
2025-06-17 12:46:31
0
1,077
Divyank
79,668,978
11,092,636
In the context of Key-Sharing Dictionaries, what does sys.getsizeof measure?
<p>If I understand correctly, <a href="https://peps.python.org/pep-0412/" rel="nofollow noreferrer">Key-Sharing dictionaries</a> make it so that if we have loads of instances of an object, we have a Shared Keys Table, and each instance then has a Value Array. What does <a href="https://docs.python.org/3/library/sys.htm...
<python><cpython>
2025-06-17 11:28:55
1
720
FluidMechanics Potential Flows
79,668,663
6,930,340
How to create a heatmap from a tidy / long polars dataframe
<p>I need to create a heatmap on the basis of a tidy/long <code>pl.DataFrame</code>. Consider the following example, where I used <code>pandas</code> and <code>plotly</code> to create a heatmap.</p> <pre><code>import plotly.express as px import polars as pl tidy_df_pl = pl.DataFrame( { &quot;x&quot;: [10, ...
<python><dataframe><plotly><heatmap><python-polars>
2025-06-17 07:53:12
3
5,167
Andi
79,668,219
1,115,716
issues installing PyTorch in a new virtual environment
<p>I'm testing some models and have created virtual environments for them. One of them required <code>PyTorch</code> which I was able to install with no issues. However, for another one, I've made a new virtual environment and when installing <code>flash-attn</code>, it complains about missing <code>pytorch</code>, so ...
<python><pytorch><flash-attn>
2025-06-16 20:45:57
0
1,842
easythrees
79,668,207
14,909,621
Why is contextlib._RedirectStream implemented as a reentrant context manager?
<p>While reading the code of the <a href="https://github.com/python/cpython/blob/f33a5e891a03df416dde7afa7e3bfb2ac800f5a4/Lib/contextlib.py#L393-L408" rel="nofollow noreferrer"><code>_RedirectStream</code></a> class from the <code>contextlib</code> module, I couldn't understand the purpose of defining <code>_old_target...
<python>
2025-06-16 20:29:21
1
7,606
Vitalizzare
79,668,121
2,153,235
PyPlot's ylim and yticks change for no reason
<p>I am following some online code to add major yticks to a bar chart. However, I'm finding that the major yticks and the ylim changes for no reason, even though I <em>don't</em> add new major yticks:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt plt.close('all') ax = pd.Series([600,1e3,1e4],index...
<python><matplotlib><logarithm>
2025-06-16 19:16:13
1
1,265
user2153235
79,667,918
13,860,719
Fastest way to find the indices of two Numpy arrays that meet a condition
<p>Say I have two large numpy arrays <code>a1</code> and <code>a2</code> (each with 10000 numbers). I want to find the indices in each array that meet the condition of <code>f(x1, x2) &gt; 0</code>. To be clear, for each number in <code>a1</code> (or <code>a2</code>), if there's <strong>any</strong> number in <code>a2<...
<python><arrays><algorithm><numpy><performance>
2025-06-16 16:14:49
2
2,963
Shaun Han
79,667,814
2,576,703
Is there a ReadSessionAsync or similar in BigQuery Storage Python API
<p>My (working) code roughly does the following:</p> <pre><code> read_session = bigquery_storage.ReadSession(...) request = bigquery_storage.CreateReadSessionRequest(...) session = client.create_read_session(request=request) iterator = [client.read_rows(stream.name).rows(session) for stream in session.st...
<python><google-bigquery><google-bigquery-storage-api>
2025-06-16 14:46:37
1
563
miwe
79,667,798
4,000,995
Keras AUC metric breaking on a multi-class problem
<p>I'm attempting to train a multi-class image classification model based on standardised 128x128 images. When I use &quot;accuracy&quot; alone as a metric, I have no issues. When I introduce AUC, I can't train the model.</p> <pre><code> model = tf.keras.Sequential([ tf.keras.layers.Rescaling(1./255), tf.keras.lay...
<python><tensorflow><keras><deep-learning><roc>
2025-06-16 14:35:52
1
1,019
Imran Khakoo
79,667,213
16,891,669
Join vs Lambda in pyspark
<p>Suppose I have the following dataframe of articles.</p> <pre class="lang-py prettyprint-override"><code>text_data = [ (1, &quot;I hav a dreem that one day&quot;), (2, &quot;Ths is a test of the emergncy broadcast systm&quot;), (3, &quot;Speling errors are commn in som text&quot;), ] text_df = spark.creat...
<python><pyspark>
2025-06-16 07:42:39
1
597
Dhruv
79,667,196
633,961
Kubernetes Leader Election with Lease
<p>I created a simple example for Leader Election on Kubernetes:</p> <p><a href="https://github.com/syself/pykubeleader" rel="nofollow noreferrer">syself/pykubeleader: Simpe Python Application which uses Kubernetes Leader Election</a></p> <p>But it uses the old configMap based approach:</p> <pre class="lang-py prettypr...
<python><kubernetes><leader-election>
2025-06-16 07:25:55
1
27,605
guettli
79,667,071
219,153
Why Numpy fabs is much slower than abs?
<p>This Python 3.12.7 script with Numpy 2.2.4:</p> <pre><code>import numpy as np, timeit as ti a = np.random.rand(1000).astype(np.float32) print(f'Minimum, median and maximum execution time in us:') for fun in ('np.fabs(a)', 'np.abs(a)'): t = 10**6 * np.array(ti.repeat(stmt=fun, setup=fun, globals=globals(), numb...
<python><numpy><performance>
2025-06-16 05:04:09
1
8,585
Paul Jurczak
79,666,955
19,459,262
How to access code in different files inside the main app?
<p>I have a rather large <code>app.py</code> file, so I'd like to take a nav panel out and store it in a separate file. I'm not sure how to access code from a different file and include it in the main app.</p> <p>The <code>app.py</code> file:</p> <pre><code>import page from shiny import reactive, render, req, ui from ...
<python><py-shiny>
2025-06-16 00:33:34
2
784
Redz
79,666,944
1,483,390
How to apply a high pass filter in GIMP using a python plug-in? And gaussian blur?
<p>How to apply the high-pass filter in a Python plug-in for GIMP? There is no high-pass filter in the procedure browser, and gegl:high-pass does nothing.</p> <p>Similarly, how to apply gaussian blur?</p>
<python><gimp><gaussianblur><highpass-filter>
2025-06-15 23:56:57
1
2,681
Luis A. Florit
79,666,115
9,353,682
How to select packaging files in pyproject.toml?
<p>I am trying to build a python package. I want the build package to contain only the necessary files.</p> <p>I make the build with following command: <code>python -m build</code></p> <p>My package files structure looks more or less like this:</p> <pre class="lang-none prettyprint-override"><code>project_root_director...
<python><setuptools><pyproject.toml>
2025-06-14 19:52:15
1
722
Maciek
79,666,105
444,578
Google API Call: Request had insufficient authentication scopes
<p>I have a python script that I run manually to connect to my photo library and download images. This was working for a time, and then it stopped working. Nothing changed, just time. I then let AI try to fix it and the code has changed a lot since then. From what I can tell, this is still sound... but I get the error:...
<python><google-cloud-platform><google-photos-api>
2025-06-14 19:31:06
1
16,001
David Lozzi
79,666,077
4,451,315
Cumulative count per group in PyArrow
<p>Say I have</p> <pre class="lang-py prettyprint-override"><code>data = {'a': [1,1,2], 'b': [4,5,6]} </code></pre> <p>and I'd like to get a cumulative count (1-indexed) per group.</p> <p>In pandas, I can do:</p> <pre><code>import pandas as pd pd.DataFrame(data).groupby('a').cumcount()+1 </code></pre> <p>How can I do ...
<python><pyarrow>
2025-06-14 18:58:13
2
11,062
ignoring_gravity
79,665,976
459,745
Create project with specific (downgraded) Python version
<p>At work, I am running 3.9.21. At home, I am running Python 3.13.2 on Linux, but also use <code>uv</code> install Python 3.9.21 to be in sync with work.</p> <p>In my home machine, I created a new project:</p> <pre class="lang-bash prettyprint-override"><code>uv init --package --python &quot;python==3.9.21&quot; sandb...
<python><uv>
2025-06-14 16:17:39
2
41,381
Hai Vu
79,665,724
12,439,683
How to pass any object as a classmethod's first argument - circumvent injection of class argument
<p>Passing a class, or a totally different object, as the first argument to method is easy:</p> <pre class="lang-py prettyprint-override"><code>class Foo: def method(self): ... Foo.method(object()) # pass anything to self </code></pre> <p>I wonder, is this possible with <code>classmethod</code>s as well? I assume ...
<python><methods><class-method><python-descriptors>
2025-06-14 09:30:05
1
5,101
Daraan
79,665,669
198,480
Using pattern matching with a class that inherits from str in Python 3.10
<p>In a parser library I maintain, I have some classes that inherit from <code>str</code> to manage parsed strings and parsed symbols. This has been working well for a long time, but with Python 3.10, someone requested being able to use <code>match</code> and <code>case</code> on these classes. I have constructed an ...
<python><pattern-matching><python-3.10>
2025-06-14 07:58:29
1
4,878
Joshua D. Boyd
79,665,533
3,977,292
Why my codes trigger the SettingWithCopyWarning in pandas
<p>I'm confused by this pandas warning. I'm already using the recommended <code>.loc[,]</code> format, but the warning persists. Can someone explain why this warning is appearing?</p> <pre><code>df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) sub_df = df.loc[df.A &gt; 1] sub_df.loc[:, 'C'] = sub_df.A + sub_df.B </c...
<python><pandas><warnings>
2025-06-14 03:04:26
1
315
Jiexing Wu
79,665,518
65,326
How to type hint a Python class dynamically created at runtime?
<p>I wrote a simple wrapper class to manage an sqlite database connection. I learned from <a href="https://stackoverflow.com/questions/16335772/mapping-result-rows-to-namedtuple-in-python-sqlite">another StackOverflow answer</a> how to use row_factory and recordclass so that the query results will return each row as an...
<python><python-typing>
2025-06-14 01:59:35
1
33,679
Apreche
79,665,429
395,857
Can one use DPO (direct preference optimization) of GPT via CLI or Python on Azure?
<p>Can one use DPO of GPT via CLI or Python on Azure?</p> <ul> <li><a href="https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/fine-tuning-direct-preference-optimization" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/fine-tuning-direct-preference-optimization...
<python><azure><command-line-interface><fine-tuning><gpt-4>
2025-06-13 22:22:23
1
84,585
Franck Dernoncourt
79,665,315
562,697
Using lru_cache on a class that has a classmethod
<p>I want to cache instances of a class because the constructor is complicated and repeated uses won't alter the contents. This works great. However, I want to create a classmethod to clear the cache. In the real code, <code>clear</code> will also clear file cache in addition to memory cache.</p> <p>The following is an...
<python><python-datamodel><python-lru-cache>
2025-06-13 19:49:55
3
11,961
steveo225
79,665,271
100,214
readthedocs failing on maturin builds
<p>I have a primary python project that has a dependency of another python lib which is a maturin wrapped rust crate.</p> <p>My 'readthedocs' script is failing on the lib using maturin with:</p> <pre class="lang-bash prettyprint-override"><code>Caused by: lock file version `4` was found, but this version of Car...
<python><python-sphinx><read-the-docs><maturin>
2025-06-13 18:56:27
0
8,185
Frank C.
79,665,053
9,472,203
Plot and annotate NaN values in a seaborn heatmap
<p>I have a Seaborn heatmap based on a DataFrame containing some NaN values. The heatmap turns out to just have those cells blank. However, I would like a custom color, e.g., light grey to be drawn with an 'NaN' annotation. How can I achieve this?</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt fro...
<python><seaborn><heatmap>
2025-06-13 15:12:54
1
465
Mr. Discuss
79,664,914
1,145,666
Uploading a file to SharePoint using the Office365-REST-Python-Client library
<p>I want to upload a file to my SharePoint site using Python. And the <code>Office365-REST-Python-Client</code> module is apparently the way to go. The code I am using is as follows:</p> <pre><code>def upload_document_to_sharepoint(local_file_path, sharepoint_folder_path): # Authenticate with SharePoint creden...
<python><rest><office365><sharepoint-online>
2025-06-13 13:20:24
0
33,757
Bart Friederichs
79,664,821
1,987,093
EmailClient sending duplicate email on ACS
<p><strong>REASON FOUND, NOT A BUG:</strong></p> <p>And found out the reason: I had a timer trigger running the code that sent the email once per 20s. The timer enumerated items to send from a table storage <em>which was shared between staging and prod</em>. And I had production and staging slots in the app =&gt; In 30...
<python><azure-communication-services>
2025-06-13 12:06:45
0
1,329
PetriL
79,664,325
2,469,032
How to change the uv cache directory
<p>I wanted to change the cache directory in <code>uv</code>. When I followed the documentation and typed the following command:</p> <pre><code>uv cache dir --cache-dir 'E:\Program Files\uv\cache' </code></pre> <p>It does not actually change the cache directory. What might be wrong?</p>
<python><uv>
2025-06-13 03:43:21
1
1,037
PingPong
79,664,298
2,307,441
How to ensure the results-section got refreshed after a button click using python and selenium
<p>I am doing web scraping using python selenium with the <a href="https://search.gleif.org/#/search/currentPage=1&amp;perPage=50&amp;expertMode=true#search-form" rel="nofollow noreferrer">website</a></p> <p>I am entering a value into the 'Search value' textbox and clicking the 'Search now' button within a loop. The in...
<python><selenium-webdriver>
2025-06-13 02:48:18
1
1,075
Roshan
79,664,217
18,649,992
Arbitrary Stencil Slicing in Numpy
<p>Is there a simple syntax for creating references to an arbitrary number of neighbouring array elements in numpy?</p> <p>The syntax is relatively straightforward when the number of neighbours is hard-coded. A stencil width of three for example is</p> <pre><code>import numpy as np x = np.arange(8) # Hard-coded stenc...
<python><numpy><numpy-ndarray><numpy-slicing>
2025-06-13 00:00:53
1
440
DavidJ
79,664,199
395,857
Clicking on an example so that it directly displays the expected output without requiring the user to press Enter?
<p>I have a simple Gradio interface for machine translation:</p> <p><a href="https://i.sstatic.net/LhluJsKd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LhluJsKd.png" alt="enter image description here" /></a></p> <p>How can I change it so that clicking on an example (e.g., 'Avion blanc') directly disp...
<python><gradio>
2025-06-12 23:33:11
1
84,585
Franck Dernoncourt
79,664,185
5,724,091
PCollection Objects Format for Apache Beam to write on BigQuery using CDC in Python
<p>I'm trying to write to BigQuery using Apache Beam, in python. However, I want to use the newest CDC features to write on Bigquery.</p> <p>However, I can't get the correct format of the objects in the PCollection. The <a href="https://beam.apache.org/releases/pydoc/2.61.0/apache_beam.io.gcp.bigquery.html#apache_beam....
<python><google-bigquery><apache-beam><apache-beam-io><change-data-capture>
2025-06-12 23:01:04
1
319
José Fonseca
79,664,132
10,083,382
Unable to use serverless connection in a PromptFlow pipeline
<p>I am running my prompt flow (<code>version 1.18.0</code>) code as a pipeline. However, it seems like that the connection that I created in prompt flow which is referred in <code>flow.dag.yaml</code> is not working through a pipeline. Same connection can be used in UI interface of promptflow without any issues. Note ...
<python><azure><azure-machine-learning-service><azureml-python-sdk><azure-promptflow>
2025-06-12 21:42:55
0
394
Lopez
79,663,856
1,040,323
How to uninstall or upgrade CPython?
<p>I have an install of CPython on my PC - from about 2020, version 3.8.5.</p> <p>This Windows 11 laptop is about 5 years old but I acquired it 2nd hand, 2 years ago. I discovered this CPython in an attempt to upgrade to python 3.9.2 or later, which I want to run for a specific app. The CPython has no <em>Programs and ...
<python><installation>
2025-06-12 16:23:48
1
509
user1040323
79,663,852
1,747,834
Can I specify a different directory for transient files, when invoking Python build-module?
<p>I currently build my simple Python module with a command like:</p> <pre class="lang-bash prettyprint-override"><code>python3 -m build --wheel --outdir /tmp . </code></pre> <p>This creates the <code>/tmp/mypackage-0.1-py3-none-any.whl</code> -- as one would expect. However, it <em>also</em> creates the <code>myprojec...
<python><setuptools><python-packaging><python-wheel>
2025-06-12 16:22:12
0
4,246
Mikhail T.
79,663,750
1,941,632
Call async code inside sync code inside async code
<p>I've found myself in a tricky situation which I can't seem to find my way out of:</p> <ol> <li>I've written an application which uses asyncio (and, in particular, aiohttp).</li> <li>In part of this application, I need to use a third-party library (in my case, weasyprint) which is <em>not</em> async.</li> <li>I want ...
<python><asynchronous><python-asyncio><aiohttp>
2025-06-12 15:01:51
2
888
DMJ
79,663,656
2,351,983
FastAPI state not isolated between concurrent users
<p>I have a FastAPI app. In <code>main.py</code>:</p> <pre><code>@asynccontextmanager async def lifespan(app: FastAPI): # Setup app.state.session_store = {} yield </code></pre> <p>In another file, I have the following function:</p> <pre><code>def get_user_state(request: Request, response: Response) -&gt; Ap...
<python><fastapi><starlette>
2025-06-12 13:59:49
0
356
luanpo1234
79,663,583
5,269,892
Pandera validation behavior for NaN failure cases
<p>Suppose we use a minimal example for a panderas dataframe-wide validation (cf. <a href="https://stackoverflow.com/a/77758888/5269892">this Stackoverflow post</a>):</p> <pre><code>import numpy as np import pandas as pd import pandera as pa dataframe = pd.DataFrame({'column_A': ['ABC company', 'BBB company', 'ABC com...
<python><pandas><dataframe><nan><pandera>
2025-06-12 13:01:02
0
1,314
silence_of_the_lambdas
79,663,456
7,376,511
Python Pydantic: Optional non-nullable field
<pre><code>from pydantic import BaseModel class MyModel(BaseModel): id: int name: str # this should be optional MyModel(id=1) </code></pre> <p>This raises a ValidationError. Setting <code>name: str | None = None</code> is unacceptable because the name cannot be null. It can be a string, or it can be unset, ...
<python><python-typing><pydantic>
2025-06-12 11:32:59
2
797
Some Guy
79,663,235
7,112,039
Celery 5.5.2 randomly raises RecursionError when the AsyncResult.status property is accessed
<p>I have this simple piece of code:</p> <pre class="lang-py prettyprint-override"><code>task_id = payload.task_id task_result = AsyncResult(task_id) if task_result.status == &quot;SUCCESS&quot;: print(&quot;I am happy&quot;) </code></pre> <p>Celery configuration is pretty basic. I just set the broker and the backe...
<python><celery>
2025-06-12 09:18:55
0
303
ow-me
79,663,073
17,795,398
How to apply rotations to structured numpy arrays?
<p>I'm using structured arrays to store atoms data produced by LAMMPS (I'm using a structured array that follows its format). I need to rotate the positions:</p> <pre><code>import numpy as np transform = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float64) dtype = np.dtype([(&quot;x&quot;, np.float64), (&quot...
<python><arrays><numpy>
2025-06-12 07:12:58
3
472
Abel Gutiérrez
79,662,891
605,153
Deploy python application in production with or without uv
<p>I used to work with Java for many years but in the last project I need to use python and I learn the ecosystem these days.</p> <p>We use UV and have a project with a bunch of dependencies. On my development machine I run <code>uv run main.py</code>. However I was wondering how should we prepare a deployment artifact...
<python><docker><deployment><uv>
2025-06-12 03:54:33
2
42,919
Mark Bramnik
79,662,795
3,174,075
How can I use COINBase RESTClient
<p>I went to coinbase and registered an API key</p> <p><a href="https://docs.cdp.coinbase.com/coinbase-app/docs/getting-started" rel="nofollow noreferrer">https://docs.cdp.coinbase.com/coinbase-app/docs/getting-started</a></p> <p>[!api_defined<a href="https://i.sstatic.net/f5ZgtL6t.png" rel="nofollow noreferrer">https:...
<python><coinbase-api>
2025-06-12 00:14:26
1
729
MrLister
79,662,641
3,452,708
Wrapper stripping the generic parameter of a function erases its type parameter
<p>In the following Python code, I define a generic function wrapper which takes a function of type <code>T → T</code> and replaces it by a function without arguments returning an instance of <code>Delay[T]</code>. This instance simply stores the original function so that it can be called later.</p> <pre class="lang-py...
<python><python-typing>
2025-06-11 20:39:44
1
495
matteodelabre
79,662,579
5,496,433
How to fill an existing numpy array with random normally distributed numbers
<p>I would like to generate many batches of random numbers. I only need access to one batch at a time. Naively, I could repeatedly call <code>np.random.randn(size)</code>, but that allocates an array each time. For performance, I would like to populate an existing array with something like <code>np.random.randn(size, o...
<python><numpy><random>
2025-06-11 19:56:34
2
15,467
BallpointBen
79,662,555
8,533,290
Mosek Fusion - access value of variable after timeout
<p>I have an integer optimisation problem that I want to solve with Mosek-Fusion. Since it might take too long, I want to impose a timeout of 10 seconds. The program stops after 10 seconds, but how can I access the best solution that Mosek found until this point?</p> <p>When the program terminates normally, I get the s...
<python><mosek>
2025-06-11 19:33:18
1
720
Hennich
79,662,405
1,773,367
Style a dataframe in notebook with indentation
<p>I have a table, which I have read from a database. I want to display the table in a jupyter notebook, showing the elements of totals and subtotals indented. I want the end result to look like this</p> <p><a href="https://i.sstatic.net/kcBqaGb8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kcBqaGb8.p...
<python><dataframe><format><jupyter>
2025-06-11 17:13:47
1
2,911
mortysporty
79,662,371
1,551,832
Python 365 how to pull items from a list on sharepoint online
<p>I am trying to get the row data from a SharePoint list in python.</p> <p>I am using python 365, and while I can get the field names, what I want after getting the field names is the row data to export it into excel.</p> <p>Here is what I have from the example, and I have been looking at the lists of examples but not...
<python>
2025-06-11 16:44:46
0
1,040
Gilbert V
79,662,237
5,454
How can I use web search with Gemini models in the google-generativeai package?
<p>I'm trying to utilize the <a href="https://pypi.org/project/google-generativeai/" rel="nofollow noreferrer">google-generativeai</a> Python package to call various Gemini models and also equip them with web search functionality. I can do something similar with OpenAI models and the <a href="https://pypi.org/project/o...
<python><google-gemini><web-search>
2025-06-11 15:17:42
2
10,170
soapergem
79,661,884
2,123,706
filter polars dataframe using a variable
<p>I have a polars datraframe</p> <p>I have a complex filter created, and put into a variable</p> <p>I want to use the variable to filter the polars dataframe, but receive the error: <code>TypeError: invalid predicate for filter</code>. Is there a way around this?</p> <p>MRE:</p> <pre><code>df=pd.DataFrame({'col1':[1,2...
<python><dataframe><filter><python-polars>
2025-06-11 11:11:18
1
3,810
frank
79,661,870
577,288
subprocess.Popen terminate() not stopping batch file
<p>The following code is supposed to stop the batch file counting down to ZERO when the <code>KeyboardInterrupt</code> error is called. But it is not doing so.</p> <pre><code>with open('test.bat', 'w', encoding='utf-8') as file: file.write('@echo off\nTIMEOUT /t 20') with open('test.txt', 'w', encoding='utf-8') as...
<python><subprocess><popen>
2025-06-11 10:57:49
1
5,408
Rhys
79,661,742
16,452,929
How to export plotly graphs in jupyter notebook as HTML?
<p>I am currently using PyCharm on Fedora. I have a jupyter notebook with plotly graphs. Following are my imports</p> <pre><code>import plotly.graph_objects as go fig = go.Figure( data=go.Scatter( x=simulation_results_df['expected_risk'], y=simulation_results_df['expected_return'], mode='ma...
<python><pycharm><plotly>
2025-06-11 09:40:02
1
517
CS1999
79,661,702
17,580,381
How to specify relevant columns with read_excel
<p>As far as I can tell, the following MRE conforms to the <a href="https://docs.pola.rs/api/python/dev/reference/api/polars.read_excel.html" rel="nofollow noreferrer">relevant documentation</a>:</p> <pre><code>import polars df = polars.read_excel( &quot;/Volumes/Spare/foo.xlsx&quot;, engine=&quot;calamine&qu...
<python><excel><dataframe><python-polars><polars>
2025-06-11 09:18:05
2
28,997
Ramrab
79,661,483
3,336,423
Conflicting OPENSSL versions under Linux
<p>I'm building a project linking both with QtNetwork (Qt6) and Python library (3.8).</p> <p>At runtime, I get the error:</p> <pre><code>my_prg_bin: symbol lookup error: /lib64/libk5crypto.so.3: undefined symbol: EVP_KDF_ctrl, version OPENSSL_1_1_1b </code></pre> <p>After investigating, I could finally isolate the prob...
<python><c++><qt><openssl><linker>
2025-06-11 06:24:34
1
21,904
jpo38
79,661,339
270,043
Pyspark aggregations optimization
<p>I have a huge dataframe with 3B rows. I'm running the PySpark code below with the Spark config.</p> <pre><code>spark = SparkSession\ .builder\ .appName(&quot;App&quot;)\ .config(&quot;spark.executor.memory&quot;,&quot;10g&quot;)\ .config(&quot;spark.executor.cores&quot;,&quot;4&quot;)...
<python><dataframe><apache-spark><pyspark><aggregation>
2025-06-11 03:15:33
1
15,187
Rayne
79,661,336
1,403,955
Add custom label based on endpoint with prometheus_fastapi_instrumentator
<p>I am using prometheus_fastapi_instrumentator for my service. Now I am using <code>Instrumentator().instrument(app).expose(app, include_in_schema=False)</code> to get the basic metircs. But I want to add some custom labels in the metrics based on the endpoints. For example, I have some metrics like below:</p> <pre><c...
<python><fastapi><prometheus>
2025-06-11 03:13:31
0
679
wltz
79,661,148
13,944,524
How Does Connection Pooling Work In Django?
<p>If I'm not wrong, currently there are two ways to have connection pooling in Django:</p> <ul> <li>Native Connection Pooling <a href="https://docs.djangoproject.com/en/5.2/releases/5.1/#postgresql-connection-pools" rel="nofollow noreferrer">(Django 5.x)</a></li> <li>Using <a href="https://www.pgbouncer.org/" rel="nof...
<python><django><database><connection-pooling>
2025-06-10 21:39:50
1
17,004
S.B
79,661,119
836,318
pandas apply raw / numpy apply_along_axis with function that returns Optional
<p>Trying to understand behavior in Pandas <code>apply</code> with <code>raw=True</code> and underlying numpy <code>apply_along_axis</code>.</p> <p>(More context: the reason I'm using Pandas UDF with <code>raw</code> is to make a UDF within a PySpark job, with <code>@pandas_udf</code> for performance without overhead o...
<python><pandas><numpy>
2025-06-10 20:55:29
1
18,970
wrschneider
79,661,090
3,821,009
Determine if value exists in previous rows
<p>I'm trying to do this:</p> <pre><code>import polars as pl df = pl.DataFrame({ 'j': [1, 2, 3, 4], 'k': [3, 1, 2, 2], }) df = df.with_row_index().with_columns([ pl.struct(['index', 'j']).map_elements( lambda x: df.slice(0, x['index'])['k'] .to_list().count(x['j']) &gt; 0, pl.Boolean ).alias...
<python><python-polars>
2025-06-10 20:20:44
2
4,641
levant pied
79,661,060
2,174,845
Azure Functions: get Service Bus topic_name and subscription_name from environment or Application Settings
<p>When writing an Azure Function for handling Service Bus events in Python, one decorates the handler function with <code>@service_bus_topic_trigger</code> (<a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cextensionv...
<python><azure-functions>
2025-06-10 19:49:40
1
511
MSmedberg
79,661,038
1,505,677
Unable to detect columns and rows when extracting a table
<p>I am trying to extract the information from the following but with no luck so far.</p> <p>Here is the <a href="https://drive.google.com/file/d/16hBSuoGiG7PMvP6VaXGhLVAaO6nIustp/view?usp=sharing" rel="nofollow noreferrer">link to the test PDF</a> that I am using</p> <p>I'm hoping that if I can come up with a strategy...
<python><jupyter-notebook><pdfplumber>
2025-06-10 19:25:57
0
353
M. Black
79,661,031
2,297,484
Sending Python chunks to terminal (not interactive or REPL) in VS Code
<p>I've switched to VSC over Sublime. I've figured out how to open a Terminal and then send line or selections of lines to the terminal by changing the keyboard preferences of Run Selected Text in Active Terminal to Ctrl + Enter.</p> <p><a href="https://i.sstatic.net/8Cxyc3TK.png" rel="nofollow noreferrer"><img src="ht...
<python><visual-studio-code>
2025-06-10 19:21:14
0
1,966
Nate
79,661,028
13,971,251
Python doesn't register change in timezone after being started
<p>I have the a program running on a Raspberry Pi which, for the purpose of this question, can be boiled down to the following:</p> <pre class="lang-py prettyprint-override"><code>import datetime import subprocess #Change system timzone subprocess.run('sudo timedatectl set-timezone America/Toronto', shell=True) #Prin...
<python><linux><datetime><raspberry-pi><subprocess>
2025-06-10 19:17:09
1
1,181
Kovy Jacob
79,661,002
3,294,994
Typing a callable with ParamSpec or no args (`Callable[P, Any] | Callable[[], Any]`)
<p>Here's a decorator that accepts a callable (<code>fn: Callable[P, Any]</code>) with the same signature as the function getting wrapped. It works and type checks.</p> <pre class="lang-py prettyprint-override"><code>import inspect from typing import Any, Callable, ParamSpec, TypeVar, Union P = ParamSpec(&quot;P&quot;...
<python><python-typing>
2025-06-10 18:54:48
1
846
obk
79,660,870
662,285
Azure AI Services for Phi-4-modal-instruct issue with audio - Audio Prompt Error: (Invalid input) invalid input error
<p>Audio Prompt Error: (Invalid input) invalid input error Code: Invalid input Message: invalid input error</p> <p>I am getting this above error while testing audio to text using Phi-4-modal-instruct in Azure AI foundry</p> <pre><code>import base64 import os from azure.ai.inference import ChatCompletionsClient from azu...
<python><azure><azure-ai-foundry>
2025-06-10 17:03:15
1
4,564
Bokambo
79,660,754
4,096,572
scikit-build-core ignores .pyf files when building Python modules: why?
<p>I maintain <a href="https://github.com/johncoxon/tsyganenko" rel="nofollow noreferrer">a Python module here</a> and I'm having difficulty getting it to build correctly. I'm currently trying to switch from the old numpy distutils over to <code>scikit-build-core</code> on the <code>change-setup</code> branch.</p> <p>T...
<python><numpy><cmake><f2py>
2025-06-10 15:39:16
1
605
John Coxon
79,660,435
186,202
How to use `alembic upgrade head` while requesting DB commit in between each file?
<p>Using Alembic updating an ENUM TYPE I found myself blocked because the datamigration didn't want to use the enum new values without a commit in between files.</p> <p>I tried to force the commit in the migration with no luck. And I finally ran alembic twice in order to fix it.</p> <pre><code>(alembic upgrade +1 &amp;...
<python><postgresql><sqlalchemy><alembic>
2025-06-10 12:35:28
1
18,222
Natim
79,660,164
885,650
jax.numpy profiling: time spent in "ufunc_api.py:173(__call__)"
<p>I am analyzing my numpy/python code by running it with &quot;-m cProfile&quot;. Snakeviz shows as the entry with most time spent:</p> <p>20895038 calls to <code>ufunc_api.py:173(__call__)</code> with the majority of the execution time (tottime) spent there.</p> <p>ufunc obviously refers to <a href="https://numpy.org...
<python><numpy><profiling><jax>
2025-06-10 09:30:09
1
2,721
j13r
79,659,981
11,339,315
How to use pyInstaller to package PyTorch code that includes JIT?
<p>The spec file I used is as follows, based on <a href="https://github.com/pyinstaller/pyinstaller/issues/6290" rel="nofollow noreferrer">this discussion</a>.</p> <pre><code># -*- mode: python ; coding: utf-8 -*- from PyInstaller.utils.hooks import collect_data_files datas = [] datas += collect_data_files('triton', ...
<python><pytorch><pyinstaller>
2025-06-10 07:17:35
1
779
Frontier_Setter
79,659,946
17,580,381
Pylint C0103 confusion
<p>Here's the MRE (<code>mre.py</code>):</p> <pre><code>&quot;&quot;&quot; MRE &quot;&quot;&quot; from functools import partial def func(_t, _c): &quot;&quot;&quot; NOOP &quot;&quot;&quot; for i in range(10): for j in range(10): t = &quot;Exit&quot; if i == 9 and j == 9 else f&quot;{i}, {j}...
<python><pylint>
2025-06-10 07:01:18
0
28,997
Ramrab
79,659,677
686,334
Invalid request from Google API in python
<p>I trying to write code to access the Youtube API in python. I followed the sample code get authenticated for Google API. When I run this I get a message</p> <blockquote> <p>Access blocked: MyAPP request is invalid</p> </blockquote> <p>I have no idea why I get this. Any advise would be appreciated.</p> <pre><code>fr...
<python><google-api>
2025-06-10 01:16:11
0
534
CrabbyPete
79,659,671
8,584,998
Long Running Python Program - Memory Usage Increasing Indefinitely
<p>I have a simple Python program designed to continuously plot data from a frequently-updated csv file, which is intended to run for months at a time. A simplified version of the program can be found below (there are additional pandas transformations done on the dataframe in my actual program than what I'm showing her...
<python><pandas><matplotlib><memory>
2025-06-10 00:57:50
1
1,310
EllipticalInitial
79,659,512
14,952,390
How to correctly use Psycopg3 COPY command?
<p>I have read in several places but I haven't been able to find the solution yet. I was using psycopg2 and its method copy_expert() to read a csv file and load it to a table, but I decided to switch to the newer version of the library psycopg v3.2.9. Reading their <a href="https://www.psycopg.org/psycopg3/docs/basic/c...
<python><postgresql><psycopg2><psycopg3>
2025-06-09 20:37:33
0
1,006
antusystem
79,659,409
2,153,235
What condition determines whether prettyprint (%pprint) prints a list vertically?
<p>In Spyder, <code>list(pd.DataFrame(range(22)).index)</code> causes row numbers to print horizontally but <code>list(pd.DataFrame(range(23)).index)</code> causes row numbers to print vertically. There is still plenty of horizontal space available. What determines the threshold for switching the orientation of the p...
<python><pretty-print>
2025-06-09 19:11:54
0
1,265
user2153235
79,659,380
23,260,297
Create multiple rows based on column
<p>I have a column in my dataframe that is called delivery period. The delivery period is supposed to be in the format 'Month Year' (January 2025). It shows as the string &quot;2025-01-01 to 2025-12-31&quot;.</p> <p>I need to identify where this occurs and create a new row for each month with the same data. For instanc...
<python><pandas>
2025-06-09 18:44:21
1
2,185
iBeMeltin
79,659,224
506,825
Calculating the closest intersection based upon latitude and longitude
<p>I have a geojson file containing the latitude and longitude coordinates of all of the streets and avenues in New York City - they're all formatted as either <code>LineString</code> and <code>MultiLineString</code> as follows:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;type&quot;: &quot;FeatureColl...
<python><geolocation><geopandas><haversine>
2025-06-09 16:41:04
2
4,830
Lance
79,659,209
8,512,262
Programmatically querying/toggling Windows "Show my taskbar on all displays" via Python
<p>I have an application in which I need to (at least while it's running) show the taskbar on all Windows displays, so I'm looking for a way to programmatically toggle the Windows &quot;Show my taskbar on all displays&quot; setting via Python.</p> <p>I've been able to successfully query and toggle taskbar <em>auto-hidi...
<python><ctypes><pywin32><taskbar><windows-11>
2025-06-09 16:31:32
0
7,190
JRiggles
79,658,932
7,281,675
Error while inferencing with onnx model on gpu
<pre><code>from optimum.onnxruntime import ORTModelForSequenceClassification from transformers import AutoTokenizer from optimum.pipelines import pipeline model = ORTModelForSequenceClassification.from_pretrained( &quot;t&quot;, provider=&quot;CUDAExecutionProvider&quot; ) tokenizer = AutoTokenizer.from_pret...
<python><huggingface-transformers><onnx>
2025-06-09 13:12:13
0
4,603
keramat
79,658,924
4,740,458
Why is the JAX and JAXOPT based code so slow?
<p>I am writing a <code>jax</code> and <code>jaxopt</code> based optimization. The same code takes ~3-4 seconds in <code>R</code>. I am not sure why this code takes ~90 seconds in <code>jax</code>. I am new to <code>python</code>, <code>jax</code> and <code>jaxopt</code>, any suggestions to include the code quality or ...
<python><jax>
2025-06-09 13:08:33
0
1,800
Satya