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,774,032
9,072,753
How to make a copy of stdout that does not close?
<p>I would want to copy sys.stdout such that it will not be closed.</p> <p>There is some generic code that does:</p> <pre><code>def dosomething(fd: IO[bytes], input): with fd as f: for buf in input: f.write(buf) </code></pre> <p>I would want to pass sys.stdout to it, in such a way, that it will not be...
<python><stream><stdout><python-3.7>
2025-09-24 17:58:32
2
145,478
KamilCuk
79,774,021
2,482,575
How to display local time from a UTC time
<p>I have some data with date time in UTC. My local time is usually 5 or 6 hours behind depending on standard or daylight time. I would like to print the local time.</p> <p>Is there an easy way to do that in python, or do I have to manually do a timedelta on the hours with the time offset?</p> <p>So example, I have a...
<python><datetime>
2025-09-24 17:38:02
1
439
tman
79,773,690
856,976
Building a Python extension with a local C++ library dependency using setuptools and build
<p>I have a library written in C++ for which I would like to make a Python wrapper. The directory structure of my repository is similar to the following:</p> <pre><code>. โ”œโ”€โ”€ include # C++ library headers โ”‚ย ย  โ””โ”€โ”€ โ€ฆ โ”œโ”€โ”€ Makefile โ”œโ”€โ”€ python # Python package โ”‚ โ”œโ”€โ”€ wrapper-module # C++ and Python source files โ”‚ โ”‚ โ””โ”€โ”€...
<python><python-3.x><setuptools><python-c-api><pyproject.toml>
2025-09-24 12:06:38
2
2,139
tsnorri
79,773,595
18,910,865
Does `dag.test()` in Airflow write to the metadata database?
<p>Iโ€™m debugging my DAGs in PyCharm using the <a href="https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/dag/index.html#airflow.models.dag.DAG.test" rel="nofollow noreferrer"><code>dag.test()</code></a> method (Airflow 2.9.1). I noticed that after running it a few times, my environment got into ...
<python><pycharm><airflow>
2025-09-24 10:27:52
1
522
Nauel
79,773,485
3,070,181
How to prevent uv with a tkinter application giving xcb error
<p>I am using uv to manage my python environments and I am getting a low level error message when I try to run a simple tkinter script</p> <pre><code># xxx.py import tkinter as tk def main(): root = tk.Tk() label = tk.Label(root, text=&quot;This line causes the problem&quot;) label.pack() root...
<python><tkinter><xcb><uv>
2025-09-24 08:50:57
1
3,841
Psionman
79,773,306
18,064,892
How to establish a real-time socket connection between Laravel (PHP) and Python?
<p>Iโ€™m building a real-time location tracking system with:</p> <ul> <li>Backend: Laravel 11.45.2 (PHP 8.2.29)</li> <li>Frontend: Flutter</li> <li>Hosting: cPanel</li> </ul> <p>So, how should I connect this? Am I approaching it the right way or not? Constraints</p> <ul> <li>I donโ€™t want to use Pusher because of the cost...
<python><php><laravel><flutter><websocket>
2025-09-24 06:00:09
1
406
Manish sahu
79,773,300
11,098,908
Coordinates satisfied conditions are outside of the expected area
<p>I have the following code to calculate and visualise the probability of scoring 10 points or more</p> <p>This is the Scoreboard image that I used to run the code <a href="https://i.sstatic.net/wtWE2Y8t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wtWE2Y8t.png" alt="enter image description here" /><...
<python><random><python-imaging-library>
2025-09-24 05:45:43
0
1,306
Nemo
79,773,215
1,503,005
Forward a Websocket connection using Flask
<p>Our app works as follows:</p> <ul> <li>Multiple remote machines connect to a central server using SSH connections</li> <li>The central server has various Python processes which process data sent over these SSH connections and store it in a database</li> <li>The central server also runs a bunch of Flask-based HTTP se...
<python><flask><websocket>
2025-09-24 01:48:23
1
635
macdjord
79,773,131
4,367,177
SQL Alchemy - result not bein pulled
<p>i have this class and this method of another class</p> <pre><code>import sqlalchemy as sa from sqlalchemy import Column, String, Date from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class MyTable(Base): __tablename__ = 'tablename' __table_args__ = {'schema': 'some_schema'...
<python><sqlalchemy>
2025-09-23 22:36:36
0
302
BMac
79,773,065
926,918
Optuna: Selection of parameters during k-fold CV
<p>I am using Optuna for hyperparameter tuning. I get messages as shown below:</p> <pre><code>Trial 15 finished with value: 6.226334123011727 and parameters: {'iterations': 1100, 'learning_rate': 0.04262148853587423, 'depth': 6, 'l2_leaf_reg': 6.63997127673657, 'border_count': 46, 'bagging_temperature': 4.9322542766563...
<python><hyperparameters><optuna>
2025-09-23 20:50:54
0
1,196
Quiescent
79,773,030
1,747,834
How to remove certain compiler flags, when compiling a Python extension through setup.py?
<p>My extension is built using <code>python3 setup.py build</code>, which uses all the flags Python wants to -- followed by my own, specified in <code>extra_compile_flags</code>.</p> <p>I'd like to remove certain flags. For example:</p> <ul> <li><code>-Wp,-D_FORTIFY_SOURCE=2</code></li> <li><code>-fstack-protector-stro...
<python><setup.py>
2025-09-23 20:03:25
0
4,246
Mikhail T.
79,772,987
9,357,484
python setup.py develop did not run successfully
<p>I ran the official Colab Page of GroundingDINO, but received an error while running the notebook.</p> <p>Code Block</p> <pre><code>%cd {HOME} !git clone https://github.com/IDEA-Research/GroundingDINO.git %cd {HOME}/GroundingDINO !pip install -q -e . !pip install -q roboflow </code></pre> <p>Error:</p> <pre><code>/co...
<python><pip><setuptools><setup.py>
2025-09-23 19:05:20
1
3,446
Encipher
79,772,860
2,562,750
Calling into a member function of a foreign C++ DLL with mangled names from Python
<p>I have a C++ DLL I want to call into from Python. <strong>I have no control over the C++ DLL nor do I have its source code or headers.</strong></p> <p>The mangled functions are of the form:</p> <pre><code>2980 BA3 005A3060 ?getFoo@FooLib@@YAAEAVFoo@1@XZ 2638 A4D 005A3020 ?getApplicationData@Foo@FooLib@@QEAAAEAVApp...
<python><c++><windows><dll><interop>
2025-09-23 16:29:50
3
1,104
Nick Bauer
79,772,776
357,546
Django migration successfully applied, but the database is not modified
<p>I need to use a secondary SQLite database in a new Django project. This database is on the local filesystem but outside the Django folder. Its path is specified in a <code>.env</code> file at the root of the Django project.</p> <p>I want Django to be able to manage migrations on that database, but I already have dat...
<python><django><sqlite><database-migration>
2025-09-23 15:05:42
1
1,618
s427
79,772,771
279,711
Write tests that check the order in which actions are done
<p>I'm encountering a recurring challenge when using TDD to develop code that must perform actions in a specific order. Usually I'm able to write tests such that it is only possible to create a correct solution. However, when I need to test code that is required to perform actions in a specified sequence this becomes m...
<python><tdd>
2025-09-23 15:02:43
2
1,701
Bart
79,772,749
5,241,389
How to set background seaborn style in a multi-plot figure with subplot()
<p>I have a multi-plot bar plot figure produced with matplotlib/ seaborn and I'd like to control the tick lines and background style. When I try to use sns.set_style(&quot;whitegrid&quot;), the background is grey/ not whitegrid.</p> <p>Example data, similar structure to mine:</p> <pre><code>data = { &quot;Country&quo...
<python><pandas><matplotlib><seaborn>
2025-09-23 14:46:05
1
407
Will Hamilton
79,772,712
2,578,235
Problem with running rust compiler in subprocess with memory limits
<p>I want to execute rust code in the Python subprocesses. But when I try to limit process memory error I keep getting errors from rust. What might be the issue?</p> <pre class="lang-py prettyprint-override"><code> import os import resource import pytest import subprocess import platform import fcntl TIMEOUT = 15 ...
<python><rust>
2025-09-23 14:16:42
0
2,963
Johnny Cheesecutter
79,772,623
4,247,599
How to get the current UTC date in Python as a type of datetime.datetime
<p>I would like to use the Python standard library <code>datetime</code> to assign to a variable the current date, in UTC and having it of type <code>datetime.datetime</code>.</p> <p>i.e. <code>datetime.datetime(2025, 9, 23, 0, 0, tzinfo=datetime.timezone.utc)</code></p> <p>How can I do that?</p> <p>Note that the built...
<python><datetime>
2025-09-23 12:55:18
2
4,299
SeF
79,772,560
6,345,518
Extend existing Pydantic type
<p>I'd like to extend existing Pydantic types such as <code>FilePath</code> by f.i. adding a file type <code>pattern</code> for</p> <ul> <li>validation</li> <li>serialization to JSON schema.</li> </ul> <h2>Current approach</h2> <p>I'd f.i. like to define my custom type <code>FilePathPattern</code> extending <code>FileP...
<python><pydantic>
2025-09-23 11:54:22
1
5,832
JE_Muc
79,772,503
1,663,232
Azure monitor opentelemetry does not close span on chain end in Langchain
<p>I'm trying to setup Langchain tracing in Azure Monitor (via Application Insights) and I use the following test code</p> <pre><code>if __name__ == &quot;__main__&quot;: configure_azure_monitor(connection_string=application_insights_connection_string) OpenAIInstrumentor().instrument() tracer = AzureAIInfe...
<python><azure><langchain><open-telemetry>
2025-09-23 10:56:45
0
1,371
Sergey
79,772,437
2,272,386
xsdata dataclass generation from XSD with choice fields
<p>How is it possible using <strong>xsdata</strong> for the generation of the model (dataclass) from an XSD with choice elements, to perform validations on those choices, so that it only allows one of them to be set?</p> <p>XSD fragment</p> <pre><code>&lt;xs:complexType name=&quot;ThirdPartyType&quot;&gt; &lt;xs:choi...
<python><xsd><python-dataclasses>
2025-09-23 09:43:53
0
727
Luis Daniel
79,772,386
12,158,757
How to clear output from all cells?
<p>With iPython, is there any way to clear output from all cells? I am looking for a command that can do it in one shot.</p> <p>I see that <code>clear_out</code> like below can do the cleaning work, but it works for one single cell, not all:</p> <pre class="lang-python prettyprint-override"><code>from IPython.display i...
<python><jupyter-notebook><ipython>
2025-09-23 08:43:47
1
105,741
ThomasIsCoding
79,772,181
1,719,931
Show progress bar when reading files with globbing with polars
<p>I have a folder with multiple Excel files.</p> <p>I'm reading all of them in a single polars DataFrame concatenated vertically using globbing:</p> <pre><code>import polars as pl df = pl.read_excel(&quot;folder/*.xlsx&quot;) </code></pre> <p>How can I have a progress bar that tracks files that are read?</p>
<python><progress-bar><python-polars><polars>
2025-09-23 03:18:31
1
5,202
robertspierre
79,772,091
1,360,544
OSX does not display the names of free-threaded python threads
<p>I am running free-threaded python3.13t with PYTHON_GIL=0 on MacOS Sequoia 15.7.</p> <p>I create threads like this:</p> <pre><code>thread = threading.Thread(target=lambda: time.sleep(10), name=&quot;test-thread&quot;) thread.start() </code></pre> <p>But their names would not be displayed by OS (note the second line, ...
<python><multithreading><python-multithreading><gil><python-3.13>
2025-09-22 21:54:34
0
14,716
Boris Burkov
79,771,953
10,902,944
How to properly use joblib files in Dask?
<pre><code>from joblib import load ntrees_16_model = load(r&quot;ntrees_quantile_16_model_watermask.joblib&quot;) ntrees_50_model = load(r&quot;ntrees_quantile_50_model_watermask.joblib&quot;) ntrees_84_model = load(r&quot;ntrees_quantile_84_model_watermask.joblib&quot;) </code></pre> <p>I am using xarray's <code>xr.m...
<python><dask><python-xarray><joblib>
2025-09-22 18:40:10
0
397
Adriano Matos
79,771,920
1,747,834
Trouble building C++ extension for Python-3.12
<p>The <code>setup.py</code> works fine with Python-3.6 on RHEL7: <code>python3 setup.py build &amp;&amp; python3 setup.py install --user</code></p> <p>Trying to do the same on RHEL8 with Python 3.12 (and g++ 8.5.0), however, I get an error from <code>g++</code>:</p> <pre class="lang-none prettyprint-override"><code>In...
<python><g++><rhel8>
2025-09-22 17:54:14
0
4,246
Mikhail T.
79,771,903
1,620,696
Alembic migrations autogenerate with Docker Compose workflow
<p>I am developing a FastAPI project and using SQLAlchemy and Alembic. I'm running everything in Docker containers with Docker Compose. Now, I'm worried about something. I would like to take advantage of the <code>alembic revision --autogenerate</code> command, but it <em>requires</em> a connection to the database, obv...
<python><docker-compose><sqlalchemy><devops><alembic>
2025-09-22 17:32:55
1
11,487
user1620696
79,771,657
8,231,936
How can I rename a duplicated column to make it unique in pandas?
<p>I have a dataframe with two duplicated columns, that can be in variable position. In the example, COLUMN1 and COLUMN4 are optionals.</p> <pre><code>COLUMN1 CLASIFICATION CLASIFICATION COLUMN4 </code></pre> <p>or</p> <pre><code>CLASIFICATION CLASIFICATION COLUMN4 </code></pre> <p>so far this works</p> <pre><code>arch...
<python><pandas><dataframe>
2025-09-22 13:22:43
0
517
Cristian Avendaรฑo
79,771,481
14,236,974
How to extract enum from C-Header in Python
<p>I have an unprocessed C Header that contains a lot of comments and defines and a few enums. Now I want to have 2 of these enums as enums in Python and extract that enum from the header file during runtime.</p> <p>What's the best way to get that enum at runtime in Python? Regex? FFI?</p> <p>It should be pretty robust...
<python><c>
2025-09-22 10:06:32
0
325
maribox
79,771,178
6,793,603
Display game variation tree using compact vertical layout
<p>I want to create a multi-line string that can be printed out or displayed via curses. This string displays the moves and variations of a go/weiqi/baduk game from an sgf file using unicode characters. Each vertical line of stones is supposed to represent one line of moves while variations show off to the side. I c...
<python><unicode><tree><nodes><display>
2025-09-22 02:10:51
1
315
Ali Kakakhel
79,771,046
145,682
pymongo is not inserting document with base64 string
<p>I have data which pymongo fails to upload, and, I cannot understand why.</p> <p>Data available <a href="https://gist.github.com/deostroll/e53d61cb9f01496ca9f5315a78389275#file-1758480758-json" rel="nofollow noreferrer">here</a></p> <p><strong>main2.py</strong>:</p> <pre class="lang-py prettyprint-override"><code>fro...
<python><base64><pymongo>
2025-09-21 19:08:25
0
11,985
deostroll
79,770,865
4,408,232
Python: Converting string in NZ summer time to UTC gives wrong result
<p>I am creating a simple script where I need to convert strings with date and time given in NZ time to corresponding UTC time. The time series are done in NZ summer (Dec-Feb) and hence the NZ time is 13 hours before UTC time. Below is a simple test with just one NZ time string to be converted:</p> <pre class="lang-pyt...
<python><datetime><timezone><zoneinfo>
2025-09-21 12:32:39
1
301
IgorLopez
79,770,740
10,127,906
Follow selected track in Ableton using Python MIDI Remote script
<p>Doing my DIY midi controller. It works well. Only problem is that user needs to go left and right trough banks and track to be able to control some particular track. So I want to focus and control track which was selected by mouse.</p> <p>I wrote Python MIDI Remote script which send to my arduino track index, so I s...
<python><midi><ableton-live>
2025-09-21 08:07:52
1
427
Artem
79,770,466
5,058,384
Flux Kontext copy part of an image into another
<p>I'm trying to copy/merge/integrate items in one image into another image using Flux. I'm trying to do this with Kontext as I've been unable to understand how to do it with inpainting. I found one inpainting example (here: <a href="https://www.reddit.com/r/comfyui/comments/1ift1x2/best_way_to_inpaint_an_existing_obje...
<python><flux>
2025-09-20 17:41:43
0
966
garrettlynchirl
79,770,419
1,658,617
How do I implement a Python Protocol with one of two methods?
<p>For example, if I'd need to implement <code>Iterable</code> as a runtime checkable <code>typing.Protocol</code>, I'd implement one that either has <code>__iter__</code> or both <code>__len__</code> and <code>__getitem__</code>:</p> <pre class="lang-py prettyprint-override"><code>class Iterable[T](Protocol): def __...
<python><python-typing>
2025-09-20 16:26:02
1
27,490
Bharel
79,770,363
4,503,546
Tiingo Python Pandas Datetime
<p>I am grabbing OHLC stock price data from tiingo using the following code:</p> <p><code>df = get_tiingo_data(ticker, start_date=&quot;1990-01-01&quot;, end_date=&quot;2025-12-31&quot;)</code></p> <p>Which calls this function:</p> <pre><code>def get_tiingo_data(ticker, start_date, end_date): url = f&quot;https://a...
<python><pandas><tiingo>
2025-09-20 14:40:48
2
407
GC123
79,769,903
11,614,319
Python read matlab .mat file containing table
<p>I'm trying to read a matlab .mat file (v7.3) from python. The thing is one of the field in the .mat object is a table (7x6) with named columns, and every time I read the object I only get a 1x6 array with random numbers. I've tried with the h5py and pymatreader libraries but it didn't work.</p> <p>How to correctly r...
<python><matlab><matlab-table>
2025-09-19 19:48:14
1
362
gee3107
79,769,871
9,705,687
PySide6 subclassing QSqlDatabase
<p>I've run into an issue with PySide6 that I cannot subclass QSqlDatabase.</p> <p>My biggest complaint about the QtSql system is that it does not throw exceptions when things go wrong. You have to manually check if things are really open or if there are any errors. So I want to subclass parts of it to automatically th...
<python><pyside><pyside6><qsqldatabase>
2025-09-19 19:12:25
0
5,933
bfris
79,769,830
1,747,834
Question about Python's tp_repr implementation
<p>I created my own type in C++ (called &quot;scenario&quot;). In order to be able to send objects of this type over the network, I implemented converting it into dictionary -- using my own <code>scenarioToDict()</code> function. My <code>tp_repr</code>-method uses that same function to &quot;represent&quot; the data a...
<python><c++><refcounting>
2025-09-19 18:20:54
0
4,246
Mikhail T.
79,769,542
633,001
Python and multiple inheritance
<p>I tried to understand multiple inheritance behaviour with Python, so I tried something but I have no idea why the output of my code is what it is. (I know that diamond inheritance is bad, but was interested to see what happens.)</p> <pre><code>class Base: name = &quot;Base&quot; def test(self): print...
<python><multiple-inheritance>
2025-09-19 13:03:11
1
3,519
SinisterMJ
79,769,523
3,234,994
Pydantic model inserts None values in Databricks Delta table as string type instead of null type
<p>I have the below pydantic model with 6 columns out of which 2 columns are <code>null</code>able.</p> <pre><code>from pydantic import BaseModel from typing import Optional class Purchases(BaseModel): customer_id: int customer_name: str purchase_date: str city: str customer_nickname: Optional[str]...
<python><pyspark><databricks><pydantic>
2025-09-19 12:52:24
1
2,583
LearneR
79,769,501
1,924,194
pip not updating after pip.ini edit
<p>I edited my <code>pip.ini</code> file. The command <code>pip config debug</code> shows that the file is taken into account, but it looks like it is still stuck with the old content of the file.</p> <p>My old config uses <em>mycompanyrepo0</em> and <em>mycompanyrepo1</em>. I try to use <em>mycompanyrepo2</em> with pi...
<python><pip>
2025-09-19 12:29:45
0
903
Vulpo
79,769,419
18,362,468
OpenAI Agents SDK doesn't call tools or subagents when using Structured Outputs
<p>For the following example tool call doesn't work, however if I remove the <code>output_type</code> then the tool call does work.</p> <p>Why is this the issue, and how can I fix it?</p> <pre class="lang-py prettyprint-override"><code>@function_tool def get_weather(city: str) -&gt; str: &quot;&quot;&quot; Use ...
<python><agent><openai-agents><litellm>
2025-09-19 10:54:30
1
839
blest
79,769,393
15,560,990
How to pass a Python datetime to BigQuery through Avro?
<p>I have a Python pipeline where I try to:</p> <ol> <li>get some json data from an API response</li> <li>modify it via duckdb (just in memory)</li> <li>convert the resulting data to a list of python dicts (1 row: 1 dict)</li> <li>Add a python datetime to every dict in the list</li> <li>write an avro file from that dic...
<python><google-cloud-platform><google-bigquery><avro><fastavro>
2025-09-19 10:19:54
2
460
Dasph
79,769,347
1,216,183
Python type hint problem with mixin depending on another
<p>I'm struggling to have the right types in a code implying two related classes and two related mixins, which can be applied on these classes.</p> <p>Here is the minimal code I have to demonstrate my problem and expectations.</p> <p>Three things I need help on:</p> <ol> <li>The last statement <code>TestCImpl2().mixin_...
<python><python-typing><mypy>
2025-09-19 09:32:51
0
2,213
fabien-michel
79,769,295
14,282,714
AttributeError: 'DynamicCache' object has no attribute 'seen_tokens'
<p>I'm following the <a href="https://www.oreilly.com/library/view/hands-on-large-language/9781098150952/" rel="nofollow noreferrer"><code>Hands-On Large Language Models</code></a> book to learn more about LLMs. I'm trying to generate text using the <code>&quot;microsoft/Phi-3-mini-4k-instruct&quot;</code> model which ...
<python><large-language-model><transformer-model>
2025-09-19 08:39:58
1
42,724
Quinten
79,769,146
1,581,090
How to fix Jupyter Lab installation on Windows 11 (using powershell)?
<p>On Windows 11 I had <code>jupyter lab</code> running before (on PowerShell), but now it seems to be gone. I installed and reinstalled <code>jupyter lab</code>:</p> <pre><code>pip uninstall jupyterlab pip install jupyterlab </code></pre> <p>but this does not help. The system is windows 11, python 3.10.11, pip 25.2. R...
<python><windows><powershell><jupyter-notebook>
2025-09-19 05:23:46
1
45,023
Alex
79,768,990
667,355
Saving a figure with the name of passed dataframe
<p>I have a function that receives a pandas dataframe as an argument, plot it, and save the generated figure with the name of passed dataframe. .</p> <p>For instance this is the function:</p> <pre><code>def plot_function(df): plt.figure(figsize=(8, 5)) plt.bar(df[&quot;x&quot;], df[&quot;y&quot;]) plt.title...
<python><pandas><matplotlib>
2025-09-18 23:05:45
2
3,491
amiref
79,768,968
2,647,342
I need a Python implementation of my Longest Possible Common Subsequence (LPCS) algorithm
<p>Please be merciful - I've never asked a question here (I've answered a few) and am a total Python noob.</p> <p>I developed an algorithm in SQL Server to compute the <strong>Longest <em>Possible</em> Common Subsequence (LPCS)</strong> between two strings and am struggling to rewrite it in Python.</p> <p><strong>The A...
<python><algorithm><nlp>
2025-09-18 22:16:51
1
8,008
Alan Burstein
79,768,902
13,132,728
Sort each row of a pandas column consisting of delimited strings
<h1>CONTEXT</h1> <p>Let's say I have <code>df</code>, which consists of a column of delimited strings that I would like to sort.</p> <pre><code>import pandas as pd df = pd.DataFrame({'sort_me':['foo; bar','foo; bar','bar; foo']}) df sort_me 0 foo; bar 1 foo; bar 2 bar; foo </code></pre> <h1>DESIRED OUTPUT...
<python><pandas><dataframe><list><sorting>
2025-09-18 20:47:22
1
1,645
bismo
79,768,658
597,234
Matching on a type hint
<p>I have to interact with an API that returns every result in binary, so I am writing a converter that takes a list of field names and types and converts each returned result to the expected type:</p> <pre class="lang-py prettyprint-override"><code>@classmethod def _normalize_result(cls, item: dict, column_types: Opti...
<python><python-typing>
2025-09-18 15:38:11
1
2,036
yakatz
79,768,378
3,909,202
How can I plot a chemical structure with repeat units using Python?
<p>I would like to use Python to generate figures of the repeat units of a range of polymers, using the common notation of square brackets with a subscript &quot;n&quot;. Here is an example from <a href="https://de.wikipedia.org/wiki/Polymer#/media/Datei:Polypropylene.svg" rel="nofollow noreferrer">Wikipedia</a>:</p> <...
<python><chemistry><rdkit><openbabel>
2025-09-18 11:45:54
0
1,379
BernhardWebstudio
79,768,198
8,188,120
PayFast cancel subscription (sandbox mode) in Python
<p>I am trying to cancel a PayFast subscription (in the sandbox) using the API tools, in Python.</p> <p>Looking at the PayFast documentation for <a href="https://developers.payfast.co.za/api#cancel-a-subscription" rel="nofollow noreferrer">recurring billing cancellations</a> it appears to be a PUT request with minimal ...
<python><rest><authentication><request><payfast>
2025-09-18 08:56:41
0
925
user8188120
79,768,155
5,852,506
Python Flask app connected to Cassandra Astra DB RAM memory issue
<p>I'm running a minimal Python Flask app with one API endpoint which make a simple call to retrieve data from the a Cassandra Datastax DB inside a for loop.</p> <pre><code># Day-2-Day Power @app.route(&quot;/d2d_new_2/power&quot;) def d2d_power(): data = request.args result = get_data_op_power_d2d(data) re...
<python><flask><cassandra><memory-leaks><datastax-astra>
2025-09-18 08:20:09
0
886
R13mus
79,767,913
2,409,039
Modulenotfounderror When Installing Python Package from Github
<p>When installing the fantraxapi python package using pip normally (<code>pip install fantraxapi</code>), it yields no errors. However, when trying to install it from a git repo, it has a modulenotfounderror for requests.</p> <pre><code>pip install git+https://github.com/meisnate12/FantraxAPI.git@master Collecting gi...
<python><git><packaging>
2025-09-18 01:14:11
2
1,313
riders994
79,767,759
1,658,617
Loading SciPy offline using Pyodide
<p>I wish to load SciPy on Pyodide without using a CDN.</p> <p>For that, I installed the pyodide package using npm, and within a webworker I ran</p> <pre><code>pyodide.loadPackage('/wheels/scipy-1.14.1-cp313-cp313-pyodide_2025_0_wasm32.whl') </code></pre> <p>The pyodide version on the node project was pinned to 0.28.2 ...
<python><scipy><openblas><pyodide>
2025-09-17 19:46:31
2
27,490
Bharel
79,767,693
7,886,407
Explain a class that appears to extend itself
<p>I'm trying to understand some aspects of the Python TKinter package.</p> <p>The package root <a href="https://github.com/python/cpython/tree/a9b6b091411a4b54421b2f81edad9778d374e3f8/Lib/tkinter" rel="nofollow noreferrer"><code>cpython/Lib/tkinter</code></a> is found on GitHub. I'm looking at the file <a href="https...
<python><tkinter>
2025-09-17 18:35:15
2
531
Darien Marks
79,767,509
16,525,263
How to validate the latest subdirectories in HDFS using pyspark
<p>I need to check the subdirectory status in HDFS and based on that I need to flag a column. My desired output is:</p> <pre><code>Date SourceName SourceType IndName IndValue 2024.01.30 PPL app PPL_Repo OK 2024.01.30 INT app INT_Repo OK </code></pre> <p>The IndValue ...
<python><pyspark>
2025-09-17 15:10:22
0
434
user175025
79,767,497
11,598,948
`ipyleaflet` shows a grey map after modifying medium-sized data
<p>I have an app made with Shiny for Python which displays an <code>ipyleaflet</code> map with a couple thousands of markers.</p> <p>On startup, the map renders fine. However, if I press the &quot;Reload&quot; button to mimick some computations, then the entire map becomes gray and unusable. This only happens when the ...
<python><py-shiny>
2025-09-17 14:57:39
0
8,865
bretauv
79,767,425
7,321,700
Merging Pandas dataframes on column combinations
<p>Scenario: I am trying to merge 2 pandas dataframes. DF1 has the bulk data, and DF2 is a sort of mapping. Based on the combination of the values of 3 different columns, I want to put a column from DF2 into DF1.</p> <p>Data sample (just a snippet of both dfs): DF1:</p> <pre><code>+-------+-----------------------------...
<python><pandas><dataframe>
2025-09-17 13:56:09
2
1,711
DGMS89
79,767,306
8,411,980
DuckDB query that works with time intervals produces incorrect values
<p>Running through python - no tables needed. See below query and result:</p> <pre class="lang-py prettyprint-override"><code>import duckdb sampling_period_sec = 13 date_range = ('2023-01-01', '2023-01-02') db_conn = duckdb.connect() db_conn.query( f&quot;&quot;&quot; DROP TABLE IF EXISTS date_range_query; ...
<python><sql><duckdb>
2025-09-17 12:16:51
1
573
AOK
79,766,854
1,719,931
How to create a cross table with percentages in Polars?
<p>I would like to create a cross table that shows, in each cell, the percentages of rows over the total number of rows.</p> <p>Inspired by <a href="https://stackoverflow.com/a/77097672/1719931">this post</a> I started with:</p> <pre><code>df = pl.DataFrame({&quot;a&quot;: [2, 0, 1, 0, 0, 0], &quot;b&quot;: [1, 1, 1, 0...
<python><dataframe><pivot><python-polars>
2025-09-17 03:36:21
2
5,202
robertspierre
79,766,750
629,186
How can I get the accurate time spent in the pytest-html report when the tests are run in parallel (via pytest-xdist)?
<p>I've noticed an error in the report generated by <code>pytest-html</code> and I'm surprised I can't find it mentioned anywhere.</p> <p>I am running a series of tests (70 total) and using <code>pytest-html</code> to generate a report on the results. I am also using <code>pytest-xdist</code> so that the tests run in p...
<python><pytest><pytest-html><pytest-xdist>
2025-09-16 22:51:23
1
1,817
MivaScott
79,766,638
21,826,195
AttributeError: 'AsyncSniffer' object has no attribute 'stop_cb'
<p>When running the following code:</p> <pre class="lang-python prettyprint-override"><code>import time from scapy.all import AsyncSniffer sniffy = AsyncSniffer(iface=&quot;wlp0s20f3&quot;, filter=&quot;not arpand not port 22&quot;) sniffy.start() time.sleep(1) sniffy.stop() </code></pre> <p>I get:</p> <pre><code> ...
<python><scapy>
2025-09-16 20:07:24
1
2,028
Mo_
79,766,617
2,482,575
python request getting different result than postman
<p>I am attempting to improve my python by working on a side-project, just interacting with websites to look at avaialble golf tee times. Zero intention/plans to do anything commercial, this is just a semi-practical way to learn more about the requests library and web site/api interaction.</p> <p>If I use the same URL...
<python><python-requests>
2025-09-16 19:35:16
0
439
tman
79,766,610
3,357,935
How do I use multiple filters in the Google Analytics 4 API from Python?
<p>I am using the <a href="https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart" rel="nofollow noreferrer">Google Analytics 4 Data API</a> with the <a href="https://google.analytics.data_v1beta" rel="nofollow noreferrer">Python client library</a> to run reports. I'm able to run a report with a...
<python><google-analytics><google-analytics-4>
2025-09-16 19:29:24
1
27,724
Stevoisiak
79,766,577
1,719,931
Drop column by index in polars
<p>I need to drop the first column in a polars DataFrame.</p> <p>I tried:</p> <pre class="lang-py prettyprint-override"><code>result = df.select([col for idx, col in enumerate(df.columns) if idx != 0]) </code></pre> <p>But it looks long and clumsy for such a simple task?</p> <p>I also tried:</p> <pre class="lang-py pre...
<python><dataframe><python-polars>
2025-09-16 18:43:03
3
5,202
robertspierre
79,766,564
13,564
How do I pass through the click on a GtkEditableLabel to the GtkColumnView row containing it?
<p>I have a <code>Gtk.ColumnView</code> where cells are represented by <code>Gtk.EditableLabel</code>s. Keyboard navigation works fine, clicking in the cells to edit them works fine, tab navigation works fine.</p> <p>However, clicking within a row to select that row doesn't work.</p> <p>Some cells are editable (i.e. <c...
<python><user-interface><gtk><gtk4>
2025-09-16 18:23:08
1
32,066
Glyph
79,766,387
155,861
when streamlit_app.py file are under nested folders then ModuleNotFound Error comes for other import s in streamlit cloud
<p>we have streamlit based project and deployed on streamlit cloud and it was working fine when main file <em>streamlit_app.py</em> was under <em>src</em> and now move the main file under nested folder of <em>src/alpha/streamlit_app.py</em> and now it shows ModuleNotFoundError of import file.</p> <p>python v 3.12 and u...
<python><streamlit><python-poetry>
2025-09-16 15:10:32
1
54,183
xkeshav
79,766,282
1,801,359
How do I import package when running
<p>I have a directory structure that can be simplified like this:</p> <pre><code>test/ scripts/ a.py src/ b.py </code></pre> <p>In a.py, I have the line:</p> <p><code>import src.b</code></p> <p>If I'm in the test directory, I want this to work:</p> <p><code>python3 scripts/a.py</code></p> <p>If ...
<python><python-3.x><import><module><package>
2025-09-16 13:25:25
2
422
user1801359
79,766,211
1,612,369
VENV does not include pip in newly created environment
<p>I found a number of questions related to my problem but solutions did not really help me. I work on Windows 10 and PowerShell 7, and have currently installed a few Python versions, s.a. 3.11, 3.12 and 3.13. Then, I use launcher <code>py.exe</code> to create virtual environments for different version, since many apps...
<python><pip><venv>
2025-09-16 12:08:31
0
2,691
Celdor
79,766,097
2,473,382
Celery: How can I kill a task at a specific time?
<p>I want to be sure that a task is killed at a certain time if it is still running. The context is an overloaded worker, where tasks are not picked up straight away.</p> <p>Image this &quot;busy&quot; worker (concurrency=1 to simulate business):</p> <pre class="lang-bash prettyprint-override"><code>uv run celery --app...
<python><celery>
2025-09-16 10:12:25
1
3,081
Guillaume
79,766,024
2,123,706
group_by with polars concatenating values
<p>I have a polars dataframe that I want to group by and concatenate the unique values in as a single entry.</p> <p>in pandas, I go:</p> <pre><code>def unique_colun_values(x): return('|'.join(set(x))) dd=pd.DataFrame({'col1':[1,1,2,3,4],'col2':['a','a','a','b','b'],'col3':['qwe','rty','asd','fgh','zxc']}) dd.group...
<python><dataframe><group-by><python-polars>
2025-09-16 09:16:53
1
3,810
frank
79,765,921
4,948,719
Python Protocol write-only attributes
<p>The <a href="https://typing.python.org/en/latest/spec/protocol.html" rel="nofollow noreferrer">Python documentation on Protocols</a> (<code>typing.Protocol</code>) mentions the following:</p> <blockquote> <p>By default, protocol variables as defined above are considered readable and writable. To define a read-only p...
<python><python-typing>
2025-09-16 07:53:20
0
1,834
tbrugere
79,765,883
11,863,823
Static typing for an `Enum` that contains compiled regex patterns
<p>I am in a scenario (that could be compared to writing an AST) where I compile multiple regex patterns that I want to reuse later, and for the sake of simplicity and readability I want to store them in an <code>Enum</code>. It works properly:</p> <pre class="lang-py prettyprint-override"><code>import re import enum ...
<python><enums><python-typing>
2025-09-16 07:18:59
0
628
globglogabgalab
79,765,711
5,046,485
How can I type a dict to match a generic `Callable`โ€™s `ParamSpec.kwargs`?
<p>Iโ€™m trying to write a small utility that forwards a dict of keyword arguments to an arbitrary callable, and Iโ€™d like static type checking to verify that the dictโ€™s keys/values match the callableโ€™s keyword parameters.</p> <pre class="lang-py prettyprint-override"><code>def apply[R](fn: Callable[..., R], inputs: dict[...
<python><python-typing>
2025-09-16 01:45:00
0
619
grahamcracker1234
79,765,591
1,028,270
Is it possible to set the type of a field based on the value of another field?
<p>I want to set and instantiate the right type based on the value of another field and get typing and autocomplete on it.</p> <p>I want this to happen automatically when the class is instantiated:</p> <pre class="lang-py prettyprint-override"><code>TMyBackendConfig = TypeVar(&quot;TMyBackendConfig&quot;) class MyBack...
<python><python-typing><pydantic>
2025-09-15 20:34:16
1
32,280
red888
79,765,521
14,826,251
use existing env with new exe from pyinstaller
<p>I would like to reduce the volume of my pyinstaller generated exe that I have to deploy every time.</p> <p>I create my app using pyinstaller. when I use the onefile flag I get a ~750MB exe file. Without the onefile flag, the exe is ~50MB and the _internal folder ~1.6GB (650MB when as zipped). I cannot remove depende...
<python><pyinstaller>
2025-09-15 19:07:18
4
1,125
SiP
79,765,484
4,470,365
Why does Pandera print failing rows with pa.check() and a lambda function but not on a column check?
<p>New to using Pandera. I want it to print the record(s) that fail the check. This is the simple check I want, fail when the system capacity is over 500:</p> <pre class="lang-py prettyprint-override"><code>import pandera.pandas as pa import pandas as pd schema = pa.DataFrameSchema( { &quot;TotalSystemCapac...
<python><pandas><pandera>
2025-09-15 18:24:03
1
23,346
Sam Firke
79,765,445
21,405,520
Get rows with unique value in a specific column in pandas
<p>Following is my data frame.</p> <pre class="lang-none prettyprint-override"><code>id name class -------------------------- 0 Nick a 1 Jane b 2 Jacon a 3 Jack b 4 Cooze a -------------------------- 5 Nick b 6 Jane ...
<python><pandas>
2025-09-15 17:34:55
4
621
user6781
79,765,416
3,749,646
Matplotlib show time ticks every two hours with minute offset
<p>I want to make a graph with Matplotlib. I want the X-axis ticks to be every 2 hours and aligned with my data.</p> <p>Using ser_major_locator(mdates.MinuteLocator()) may accept interval=120 to make ticks every two hours, but this does not align with the data. MinuteLocator() will accept a range to byminute which sati...
<python><matplotlib>
2025-09-15 16:48:20
1
430
peteey
79,765,297
1,900,384
Does mypy not consider "bool(object) == True"?
<p>If Python classes do not define <code>__bool__</code> or <code>__len__</code>, <code>bool(&lt;class object&gt;)</code> <a href="https://docs.python.org/3/library/stdtypes.html" rel="nofollow noreferrer">defaults to <code>True</code></a>.</p> <p>However, mypy (tested with: <code>v1.15.0</code>) doesn't seem to consid...
<python><python-typing><mypy>
2025-09-15 14:50:08
2
2,201
matheburg
79,765,276
6,662,425
How can I efficiently get both a column and a scalar using Polars expressions?
<p>Polars suggests the usage of Expressions to avoid eager execution and then execute all expressions together at the very end. I am unsure how this is possible if I want a column and a scalar. For example let's say I start with a single column <code>'test'</code> and want to calculate its mean and produce a centered c...
<python><dataframe><python-polars>
2025-09-15 14:32:36
3
1,373
Felix Benning
79,765,206
5,349,916
Type hint empty dict
<p>I need to type-hint that a value is either some <code>TypedDict</code> or a completely empty <code>dict</code>. The <code>TypedDict</code> itself already exists and is non-trivial, and it's an all-or-nothing situation โ€“ so modifying the <code>TypedDict</code> to have optional keys is not sufficient.<br /> Both of th...
<python><python-typing>
2025-09-15 13:30:55
3
53,360
MisterMiyagi
79,765,153
5,118,421
python kafka doesn't see headers/metadata while kafka ui and kafka go lang does
<p>Kafka-python doesn't see kafka-headers, while kafka golang does. It doesn't see any headers in all the messages.</p> <p><strong>Example of code:</strong></p> <pre><code>for message in consumer: # message value and key are raw bytes -- decode if necessary! # e.g., for unicode: `message.value.decode('utf-8')` print( ...
<python><apache-kafka><kafka-python>
2025-09-15 12:46:33
2
1,407
Irina
79,764,974
10,982,755
Do I have to copy every workspace member in the Dockerfile to be able to use `uv sync --locked`
<p>I'm currently in the process of migrating an existing codebase in my org to use uv as a package manager. It's a monorepo and having the ability to setup workspaces within a single repo was amazing. I'm still running into an issue for building a Docker image with the uv.lock file.</p> <p>Below is my folder structure....
<python><docker><uv>
2025-09-15 09:43:14
1
617
Vaibhav
79,764,955
11,159,734
Pytest in FastAPI + Postgres results in: <sys>:0: RuntimeWarning: coroutine 'Connection._cancel' was never awaited
<p>I'm writing tests for my fastapi application that uses asynchronous posgtres connection:</p> <pre><code># backend/database/session.py from sqlmodel import SQLModel from sqlmodel.ext.asyncio.session import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import sessionmaker from...
<python><pytest><python-asyncio><fastapi><asyncpg>
2025-09-15 09:27:34
3
1,025
Daniel
79,764,845
10,953,274
TensorRT DLA Engine Build Fails for PWC-Net on Jetson NX - Missing Layer Support?
<p>I'm converting a PWC-Net optical flow model to run on Jetson NX DLA using the iSLAM framework, but the TensorRT engine build fails during DLA optimization.</p> <h2>Environment</h2> <ul> <li><strong>Hardware</strong>: NVIDIA Jetson NX</li> <li><strong>Framework</strong>: iSLAM (PyTorch-based SLAM system)</li> <li><st...
<python><machine-learning><nvidia><opticalflow><tensorrt>
2025-09-15 07:33:55
0
705
Unknown
79,764,832
9,021,547
How to access params string within a DAG run in Airflow?
<p>I have a dag, which runs several sql scripts on certain tables. There are two options to run this dag:</p> <ol> <li>On the production tables</li> <li>On frozen archived tables</li> </ol> <p>I want to be able to select which tables to use based on a dag_run param value. The general structure is something like this:</...
<python><airflow>
2025-09-15 07:09:16
2
421
Serge Kashlik
79,764,826
396,373
How to verify that obscure Python behavior is by design
<p>Iโ€™ve been experimenting in order to deepen my understanding of Python metaprogramming, and I have noticed a potentially useful behavior that I cannot find documentation to explain, so I donโ€™t know whether it is safe to use and assume it will work in other Python versions and implementations.</p> <p>Specifically, I h...
<python><language-lawyer><metaprogramming>
2025-09-15 07:04:29
1
12,777
Steve Jorgensen
79,764,680
1,844,397
Map a generic type to an instance of its type
<p>I have the following inheritance structure:</p> <pre class="lang-py prettyprint-override"><code>class S: ... class A(S): ... class B(S): ... </code></pre> <p>I'd like to conceptually do something like the following:</p> <pre class="lang-py prettyprint-override"><code>class Foo: T = TypeVar('T', bou...
<python><generics><python-typing>
2025-09-15 02:00:37
2
1,744
bossi
79,764,480
81,120
Recursively rename all column names and nested struct fields to lowercase in a Polars DataFrame?
<p>Is there a way for Polars to rename all columns, not just at the top level, but including multiple levels of nested structs?</p> <p>I need them to all be lowercase via <code>str.lower</code></p>
<python><dataframe><python-polars>
2025-09-14 18:15:42
4
598
dsully
79,764,028
16,462,878
Validate a globed-like path
<p>I am writing a API for a program. The program has a native support of &quot;globed&quot; paths such as <code>img-0*.png</code>. I would like to know how to be sure that there is <em>at least</em> a file satisfying that pattern, a kind of <code>is_globable(path)</code> method.</p> <pre><code>path = 'img-0*.png' if o...
<python><validation><path><glob>
2025-09-14 00:28:18
3
5,264
cards
79,764,012
2,989,089
Make subclass use custom `__str__` in an f-string
<p>I wrote a subclass of Decimal to represent an amount of money. I wrote a custom <code>__str__</code> to display the currency along with a sign format. My method works when calling <code>str()</code> but in a f-string somehow my custom <code>__str__</code> is not used. What is happening here?</p> <p>My goal is to hav...
<python><f-string>
2025-09-13 23:45:32
2
884
Antoine Gallix
79,763,862
428,542
How to use type hints in a dict with TypeVar and a function that depends on that TypeVar?
<p>I have a relative simple app in which I use a Message Bus to pass messages.</p> <p>I prefer a bit more stricter type checking: rather than passing arbitrary text strings as topic, I pass message objects, and to be exact: I pass instances of a subclass of the BaseMessage class, and I want to ensure that the handler i...
<python><python-typing><type-variables>
2025-09-13 17:35:45
1
3,568
MacFreek
79,763,516
259,543
Type invariance in generic class when callable is involved
<p>Why, in the following example, the type variable <code>T</code> in class <code>E</code> is invariant?</p> <pre class="lang-py prettyprint-override"><code>class C: pass class D(C): pass class E[T: C = C]: def g(self, f: Callable[[], T]) -&gt; T: return f() x: E = E[D]() # error </code></pre> <...
<python><python-typing>
2025-09-13 05:13:03
2
5,252
alecov
79,763,515
1,719,931
How to create a SQL View in SQLModel?
<p>How can I create a view in <a href="https://github.com/fastapi/sqlmodel" rel="nofollow noreferrer">SQLModel</a>?</p> <p>For instance, starting from this example taken from <a href="https://sqlmodel.tiangolo.com/tutorial/connect/create-connected-rows/#refresh-and-print-heroes" rel="nofollow noreferrer">the user guide...
<python><sqlmodel>
2025-09-13 05:12:43
2
5,202
robertspierre
79,763,416
16,037,994
setuptools: fetch a remote cross-compiled library
<p>My <a href="https://github.com/cvanaret/Uno/" rel="nofollow noreferrer">C++ library</a> uses external dependencies, most of which are open source, but at least one of them is only available as <a href="https://github.com/leyffer/BQPD_jll.jl/releases" rel="nofollow noreferrer">cross-compiled binaries</a>. In our <a h...
<python><github><cross-compiling><setuptools>
2025-09-12 22:54:44
0
401
Charlie Vanaret - the Uno guy
79,763,327
534,674
How to correct 3rd party sphinx ambiguous cross-reference warnings?
<p>I'm trying to document a variety of classes that use scikit-learn bases <code>BaseEstimator</code> and <code>TransformerMixin</code>. Sphinx builds with a warning that,</p> <pre class="lang-console prettyprint-override"><code>/home/jake/github/proj/pkg/__init__.py:docstring of sklearn.utils._set_output._SetOutputM...
<python><scikit-learn><python-sphinx>
2025-09-12 20:33:03
0
1,806
Jake Stevens-Haas
79,763,247
6,439,229
How to make QTableView's drag selection behave like a QTreeView
<p>There's a difference in behaviour between <code>QTableView</code> and <code>QTreeView</code> when it comes to selecting multiple items by dragging the mouse.</p> <p>In a <code>QTreeView</code> you can start outside the populated area and drag over the items, and they will be selected. In a <code>QTableView</code> th...
<python><pyqt><qtableview><pyqt6><qtreeview>
2025-09-12 18:17:42
0
1,016
mahkitah