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,658,805
587,587
Why does my pythonnet not load the correct dependency when loading DLL:s via reflection
<p>I'm writing a Python application that uses clr 3.0.3.</p> <p>I'm trying to load a DLL using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.loadfrom?view=net-9.0" rel="nofollow noreferrer">System.Reflection.Assembly.LoadFrom</a>. My code is basically doing the following:</p> <pre><co...
<python><.net><dll><reflection><python.net>
2025-06-09 11:32:16
1
492
Anton Lahti
79,658,376
2,624,876
How do I install a python-based CLI from a venv globally?
<p>I'm developing a CLI application with Python and I can install it with <code>pip install -e .</code> for an editable install, however this installs it only in the virtual environment. I can't access the CLI from things like Ubuntu's custom keyboard shortcuts, or Thunar's custom keyboard shortcuts.</p> <p>I can insta...
<python><pip><python-venv>
2025-06-09 05:05:34
1
4,298
1j01
79,658,364
311,567
asyncio run coroutine from a synchronous function
<p>How can I call <code>task2</code> from <code>func</code> without declaring <code>func</code> async and awaiting it? My first thought was to create a thread and use <code>run_coroutine_threadsafe</code> but it deadlocks. Same as not using a thread. Do I have to start a new loop?</p> <pre class="lang-py prettyprint-ov...
<python><python-asyncio>
2025-06-09 04:52:22
2
2,703
dashesy
79,658,347
11,793,491
How to form a projection while filtering some nodes in Neo4j
<p>I have the following query in Neo4j using the Python library graphdatascience:</p> <pre class="lang-py prettyprint-override"><code>G, result = gds.graph.project( &quot;communities&quot;, # Graph name &quot;__Entity__&quot;, # Node projection { &quot;_ALL_&quot;: { &quot;type&quot;...
<python><neo4j><cypher>
2025-06-09 04:18:34
0
2,304
Alexis
79,658,301
270,043
PySpark with aggregations failing
<p>I have a 106M dataframe with nested columns, that is, I have a few columns where the values are <code>{[1,2,3,4,5], &lt;timestamp&gt;, 1, 2 ,3}</code>. I'm trying to add a few more columns using <code>when</code>, then do an aggregation on the dataframe.</p> <pre><code>df_1 = df.withColumn(&quot;newCol&quot;, when((...
<python><dataframe><apache-spark><pyspark><aggregate-functions>
2025-06-09 02:30:44
0
15,187
Rayne
79,658,282
3,286,489
VSCode and Terminal result differently in identifying MCP Tools
<p>I have this code</p> <pre><code>import os import sys from dotenv import load_dotenv load_dotenv() from praisonaiagents import Agent, MCP agent = Agent( instructions=&quot;You are a Precise Assistant.&quot;, llm=&quot;ollama/llama3.2&quot;, tools=MCP(&quot;python server.py&quot;), ) agent.start(&quot;Wha...
<python><visual-studio-code>
2025-06-09 01:55:37
1
61,245
Elye
79,658,157
1,826,893
Efficient Algorithems to find position of vector in 2D array
<p>I have an interesting problem but cannot find the relevant literature, so need algorithem suggestions or just the correct way to phrase the problem so I can find the literature.</p> <p>I'm given a vector of floats of varying length coming from a 2D array. I know the orientation (i.e. which axis I'm looking in). I ne...
<python><algorithm><search><graph-traversal>
2025-06-08 20:41:01
1
1,559
Edgar H
79,658,104
17,086,233
How to type hint `flax.linen.Module.apply`'s output correctly?
<p>As of writing, this code does not pass the PyRight type checker:</p> <pre class="lang-py prettyprint-override"><code>import jax import jax.numpy as jnp import jax.typing as jt import flax.linen as nn class MLP(nn.Module): @nn.compact def __call__(self, inputs: jt.ArrayLike): inputs = jnp.array(input...
<python><python-typing><jax><pyright><flax>
2025-06-08 18:48:59
1
431
Arno
79,658,062
2,437,508
How to add conflicts into an index using pygit2
<p>I want to create a <code>pygit2.Index</code> instance out of thin air and populate it with conflicts. I see that in <code>libgit2</code> there is a <a href="https://libgit2.org/docs/reference/main/index/git_index_conflict_add.html" rel="nofollow noreferrer"><code>git_index_conflict_add</code></a> function available...
<python><libgit2><pygit2>
2025-06-08 17:55:36
0
31,374
eftshift0
79,658,047
3,333,319
Pandas API behaviour when CopyOnWrite is enabled
<p>I am new to <code>pandas</code> and I am trying to catch up on its API design. What I am most interested in is to get a good rule of thumb to predict wheter calling a method on a dataframe will return a new copy of it (that I must assign to a variable) or will modify it inplace.</p> <p>The documentation mentions eve...
<python><pandas><dataframe>
2025-06-08 17:29:29
1
973
Sirion
79,657,990
799,813
Why is my Shiny Express app having trouble controlling the barchart plot?
<p>Im having trouble setting the y axis to start at zero for the following shiny express python script. Instead it starts at 4.1 . the set_ylim is having no affect.</p> <pre><code>from shiny.express import input, render, ui import matplotlib.pyplot as plt import numpy as np data = { &quot;Maturity&quot;: ['1Y', ...
<python><matplotlib><py-shiny>
2025-06-08 16:23:29
1
1,053
Tommie Jones
79,657,735
1,379,184
Kafka Producing and Consuming in Python does not work. Kafka in Docker, and CreatingTopics does work
<p>Trying to get Kafka running in Docker on a Macbook.</p> <ul> <li>Starting Kafka works.</li> <li>Creating a Topic from inside the Docker Container works (with the provided Bash script)</li> <li>Creating a Topic from a Python script on the Host works. (See Python Script below)</li> </ul> <p><strong>But what does not w...
<python><docker><apache-kafka>
2025-06-08 10:09:30
1
2,748
BertC
79,657,561
16,399,497
Python authlib: How to handle multiple web-servers
<p>I'm developing a web-server based on FastAPI, to be integrated into a container to be deployed on Kubernetes with replicas. Authentification is performed by authlib and Keycloak.</p> <p>The server which redirects (via the <code>/login</code>) the user to the identity provider may not be the same as the one which run...
<python><oauth-2.0><keycloak><authlib>
2025-06-08 06:01:57
0
723
emonier
79,657,532
2,840,697
Importance of putting self in a function definition in Python?
<p>Let's assume that you have the following:</p> <pre><code>class Solution1(object): def some_function(self, a, b): self.ans = 0 def some_other_function(x, y): manipulates self.ans return self.ans class Solution2(object): def some_function(self, a, b): ans = 0 de...
<python>
2025-06-08 05:34:26
2
942
user98235
79,657,393
9,452,512
How to get the code of the hugging face models?
<p>There is a simple way to download a model from hugging face,</p> <pre class="lang-py prettyprint-override"><code># Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained(&quot;sentence-transformers/all-MiniLM-L6-v2&quot;) model = AutoModel.from_pretrained(&qu...
<python><huggingface-transformers><huggingface>
2025-06-07 23:03:04
1
1,473
Uwe.Schneider
79,657,387
4,018,331
Function in Digital Ocean Returning Errors Cannot Import Module and Cannot Connect to Database
<p>I have a simple Python function I've deployed as a Digital Ocean Function. However, the Function errors out on importing <code>psycopg2</code>.</p> <p>The function:</p> <pre class="lang-py prettyprint-override"><code>import os import psycopg2 def get_db_connection(): connection = psycopg2.connect( host=...
<python><digital-ocean>
2025-06-07 22:47:29
1
1,297
j3py
79,657,240
264,822
How can I run multiple commands on SSH in one go with Paramiko in Python?
<p>I've got some code that runs through a list of devices, connects to them via SSH and queries some parameters. The basic code looks like this:</p> <pre><code>ssh = paramiko.SSHClient() ssh.connect(ip_address, username='root', password=password) try: ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('uname -r'...
<python><ssh><paramiko>
2025-06-07 18:48:16
1
9,317
parsley72
79,657,059
1,150,923
How to create individual rich progress bars for each worker in Python multiprocessing's imap_unordered()?
<p>I have a simple code that you can run (the <code>logging</code> is to differentiate 4 workers):</p> <pre class="lang-py prettyprint-override"><code>import time import random import logging import logging.handlers from multiprocessing.dummy import Pool def do_something(number): logger.info(number) time.sleep...
<python><multithreading><progress-bar><tqdm><rich>
2025-06-07 14:38:55
2
30,704
hobbes3
79,656,740
1,150,923
How to create a simple status/count/progress output when searching for files using rglob() in Python?
<p>I have a simple line that searches for all <code>.json</code> files, except there are about 28k of them, so this one line takes about a minute to complete:</p> <pre><code>from pathlib import Path files = list(Path(&quot;~/foo/bar/).rglob(&quot;*.json&quot;)) </code></pre> <p>Is there a way to create a simple counte...
<python><progress-bar><glob><status>
2025-06-07 07:10:10
2
30,704
hobbes3
79,656,626
7,556,091
How to install pytorch and opencv using a fixed conda channel order?
<p>Conda creates a pristine environment, configures a fixed channel order, and then starts installing pytorch torchvisioni pytorch-cuda and opencv, and it prompts for dependency conflicts. Do I have to install opencv via pip?</p> <p>The same thing happens with python 3.10</p> <pre><code>$ conda create -n my_env3.9 pyth...
<python><opencv><ffmpeg><pytorch><conda>
2025-06-07 01:56:19
1
1,896
progquester
79,656,623
3,366,355
removing double // comments from json
<p>It turns out there's a format jsonc that allows comments like <code>//this</code> in the JSON along other things. Is it possible to produce a json example with <code>//this type</code> of comments that can make the resulting json invalid after applying this regex.</p> <pre class="lang-py prettyprint-override"><code...
<python><json><regex>
2025-06-07 01:44:09
1
1,032
martin
79,656,511
2,153,235
Pandas: What is wrong with this use of DataFrame.apply for finding maximum of other columns
<p>I have a DataFrame with a handful of date columns, I want to create a new column &quot;MaxDate&quot; that contains the maximum date. I tried using <code>apply</code>, but my various code patterns for the lambda function yield errors.</p> <pre><code>import pandas as pd import datetime as dt df=pd.DataFrame( [ [ ...
<python><pandas>
2025-06-06 21:37:29
1
1,265
user2153235
79,656,429
1,601,903
Feet and Hip Do Not Rotate During Circular Walking Motion - OpenSim RajaGopal2016
<p>I am currently working with motion capture data from the <a href="https://mocap.cs.cmu.edu/" rel="nofollow noreferrer">CMU MoCap dataset</a> and analyzing it using the <a href="https://simtk.org/projects/opensim" rel="nofollow noreferrer">RajaGopal2016 OpenSim model</a> in the GUI.</p> <p>To prepare the data, I did ...
<python><inverse-kinematics><opensimulator>
2025-06-06 20:11:46
0
418
sana
79,656,394
7,344,164
How to configure VS Code launch.json to debug a Streamlit app with a conda environment?
<p>To debug a python project with a specific conda env in VS code, I normally use this launch.json</p> <pre><code>{ &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python Debugger: Current File&quot;, &quot;type&quot;: &quot;debugp...
<python><visual-studio-code><streamlit><vscode-debugger>
2025-06-06 19:32:45
1
14,299
DevLoverUmar
79,656,194
9,884,998
Moving the Scientific Notation Offset of a Pyplot Graph below the top Spine
<p>I'm stacking multiple graphs using matplotlib-pyplot. This is my minimal reproducable example:</p> <pre><code>from matplotlib import pyplot as plt from numpy import linspace, sqrt, pi fig, ax = plt.subplots(3, 1, sharex=True) plt.subplots_adjust(hspace=0) def zr(w0, l): return pi*w0**2/l def w0(l, L, R): ...
<python><matplotlib>
2025-06-06 16:22:57
1
529
David K.
79,656,139
5,964,034
tf.keras: Why my UNet with final layer Conv3D with sigmoid activation gives probabilities less than 0 and more than 1
<p>I am really confused because this should never happen according to common sense and to all things that I found on the internet.</p> <p>In short. My UNet with sigmoid activation as last layer gives probabilities of less than 0 and more than 1.</p> <p>I have a UNet for semantic segmentation of 3-dimensional brain MRIs...
<python><tensorflow><keras><deep-learning>
2025-06-06 15:27:23
0
771
Ivan
79,656,085
2,620,122
Call LiteLLM proxy with LiteLLM SDK and client side credentials (Bedrock IAM + OpenAI)
<p>Is it possible to call a LiteLLM proxy that does not have configured model credentials with the LiteLLM Python SDK using client side credentials? Interested in doing this for bedrock with client side IAM instance role as well as OpenAI with explicit API key passed in client side. The examples in the docs <a href="ht...
<python><litellm>
2025-06-06 14:43:44
0
1,664
KlugscheiรŸer
79,656,077
2,082,681
Intellij IDEA: After upgrading to 2025.1 cannot run Python configurations: packaging_tool.py': [Errno 2] No such file or directory
<p>I had an installation of some 2024 version of Intellij IDEA and had no issues running Python configurations, like just running .py file in it.</p> <p>Today I got a notification to upgrate Intellij IDEA and it was version 2025.1 something. After I have upgraded, when I click the green arrow button to run a Python con...
<python><intellij-idea>
2025-06-06 14:37:37
1
329
havryliuk
79,655,640
4,972,737
How to prevent imported code from making unknown network connections
<p>Importing public Github repositories is often necessary in coding. However, very often Github repositories contain malicious codes that can send sensitive data to hacker IP.</p> <p>There are CodeQL and Semgrep that check malicious codes, but they don't support all languages. Also, they can't distinguish benign uploa...
<python><security><network-programming><windows-firewall><network-security>
2025-06-06 08:44:23
1
387
new
79,655,544
2,172,547
Not able to send stream from Asterisk audio socket to python audio socket server
<p>I added this in asterisk conf</p> <pre><code> same =&gt; n(newIvr),Log(NOTICE, Start New IVR POC flow) same =&gt; n,AudioSocket(${UUID()},172.25.25.150:1579) same =&gt; n,Playback(goodbye) same =&gt; n,Hangup() </code></pre> <p>and my python audio socket server</p> <pre><code>import sys import threading impor...
<python><asterisk><audiosocket>
2025-06-06 07:33:35
0
15,772
Code Guru
79,655,305
13,132,728
How to generate a given number of size N pairings from a list with minimum overlap between pairings?
<p>I have a list, <code>lst</code></p> <pre><code>lst = ['A','B','C','D','E','F','G'] </code></pre> <p>From this list, I want to generate a given number of lists, each of length <code>N</code> <strong>with the minimum possible amount of overlap between each item in <code>lst</code></strong>.</p> <p>For example, let's s...
<python><list><algorithm>
2025-06-06 00:21:11
4
1,645
bismo
79,655,299
15,848,470
Extremely slow DB insert using Turbodbc
<p>I have built Turbodbc 5.1.2 from source with simdutf 7.3.0, Python 3.11. When trying to insert 150,000 rows of 46 columns to a MySQL 8.0 InnoDB table, Turbodb takes about 190s, compared to 15s with my existing method. I have modeled my attempt after the advice in here the advanced usage section <a href="https://turb...
<python><insert><sql-insert><bulkinsert><turbodbc>
2025-06-06 00:00:44
0
684
GBPU
79,655,240
19,527,503
Accessing modules from other folders within a Python project
<p>I am getting the following error <code>No module named 'backend'</code> when trying to import from within <code>python1.py</code> file.</p> <p>I am trying to import as such:</p> <pre><code>import sys from backend.utils import * </code></pre> <p>Project folder is structured as follows:</p> <pre><code>Project Folder ...
<python>
2025-06-05 22:05:15
1
323
marsprogrammer
79,655,193
27,596,369
I cannot create table using SQLAlchemy
<p>I have a table with a few columns in an empty database and then <code>db.create_all()</code> with <code>with app.app_context()</code>but when I run the code, the database is still empty and there are no tables. CODE EDITOR: Visual Studio Code, DATABASE EDITOR: DB Browser for SQLite</p> <p>Here is my code:</p> <pre><...
<python><flask><sqlalchemy><flask-sqlalchemy>
2025-06-05 20:59:16
1
1,512
Aadvik
79,655,174
7,959,614
Use Scipy multivariate_normal with multiple covariance matrices
<p>I have a an array of covariance matrces with shape <code>(n_samples, n, n)</code>. I'd like to compute <code>logpdf</code> values for multiple coordinate values and covariance matrices in a vectorized way. For now I've tried to use the following code</p> <pre><code>import numpy as np import matplotlib.pyplot as plt ...
<python><scipy>
2025-06-05 20:30:46
2
406
HJA24
79,655,153
1,488,601
How to make a custom error message for Service Unavailable in FastAPI?
<p>I'm running my app like so:</p> <pre class="lang-bash prettyprint-override"><code>uvicorn main:app --host 0.0.0.0 --port 8080 --workers 2 --limit-concurrency 10 </code></pre> <p>Versions are:</p> <pre><code>fastapi==0.103.2 uvicorn==0.34.3 </code></pre> <p>When I start slamming it, I get the expected <code>503 Servi...
<python><exception><fastapi>
2025-06-05 19:56:19
1
2,507
grayaii
79,654,994
11,608,962
How to customize Pydantic validation error messages to exclude "Value error" prefix?
<p>The below code consists of a company model and I have put up a validation for a blank company name. I am considering raising a custom validation error message but the error message has the prefix <code>Value error, </code> which I do not want. How can I get rid of it?</p> <p>Python Code:</p> <pre class="lang-py pret...
<python><pydantic-v2>
2025-06-05 18:02:18
2
1,427
Amit Pathak
79,654,956
4,245,867
Python-Selenium: Loading the third page from bvc.com.co shows blank screen
<p>I'm trying to scrape some data from bvc.com.co (the Colombian Stock Exchange webpage). But always, when loading the third stock, the screen comes blank and the <code>target</code> <code>expected_condition</code> can not be executed (maybe because the page is not shown). Here is my code:</p> <pre><code>stocks = ['htt...
<python><css><selenium-webdriver><web-scraping>
2025-06-05 17:30:11
1
615
Ivan Castro
79,654,724
1,076,009
Scapy Raw layer in data frame is missing initial 3 characters of load and shortened load is repeated when printed
<p>I am using Scapy to learn about Wi-Fi. I am new to both Scapy and Wi-Fi.</p> <p>I have a Raspberry Pi 5 and a laptop, running Debian GNU/Linux 12 (Bookworm) and Ubuntu 22.04.1 LTS, respectively, and an ALFA AWUS036AXML Wi-Fi adapter set in monitor mode connected to each. I am using IPython and Scapy to interact with...
<python><wifi><scapy>
2025-06-05 15:03:39
0
398
Aldo
79,654,659
4,247,599
AttributeError: module 'geoarrow.c._lib' has no attribute 'GEOARROW_GEOMETRY_TYPE_GEOMETRY'
<p>I am using <code>KeplerGL</code> maps library on a streamlit application.</p> <p>All worked fine until it did not. Here are the pinned libraries of a working code that suddenly stopped working:</p> <pre class="lang-bash prettyprint-override"><code> [tool.poetry.dependencies] python = &quot;~3.12.0&quot; streamlit = ...
<python><kepler.gl>
2025-06-05 14:20:23
0
4,299
SeF
79,654,658
29,295,031
How to switch to a streamlit page from html
<p>I have made a footer with html :</p> <pre><code>ft=&quot;&quot;&quot; &lt;div style='font-size: 0streamlit .875em;color: #000;cursor: pointer;font-family: Inter;font-size: 14px;font-style: normal;font-weight: 500;line-height: 140%; /* 14px */'&gt; Footer &lt;/div&gt; &quot;&quot;&quot; st.write(ft, unsafe_allow_htm...
<python><streamlit>
2025-06-05 14:20:10
0
401
user29295031
79,654,624
1,472,474
How to make mypy ignore pytest.approx in a code outside of test functions
<p>I want to use <code>pytest.approx(...)</code> inside immutable dataclasses (<code>frozen=True</code>) in my unittest, so I can use a single <code>assert</code> to check possibly quite complex structures.</p> <p>This works fine when I use these structures inside test functions, but when I declare a global variable/co...
<python><pytest><python-typing><mypy>
2025-06-05 13:58:15
2
5,587
Jan Spurny
79,654,442
18,108,367
The redis command 'save' doesn't store immediately the snapshot on permanent memory
<p>I'm trying to force the storing of a Redis snapshot on permanent memory by the command <code>save</code>. The instance of Redis is configured to use <a href="https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/" rel="nofollow noreferrer">RDB persistence</a> with the configuration:</p> <pre><cod...
<python><redis><filesystems><persistence>
2025-06-05 12:27:26
1
2,658
User051209
79,654,182
704,329
Make Hydra to load configs from zip-archive
<p>I am trying to adopt <a href="https://github.com/ashleve/lightning-hydra-template" rel="nofollow noreferrer">this wonderful repository</a> with Lightning-Hydra template to my workflow.</p> <p>My workflow looks like following.</p> <ol> <li><p>Create a new git branch for a new experiment.</p> </li> <li><p>Write a code...
<python><git><fb-hydra><omegaconf>
2025-06-05 09:36:56
1
4,369
wl2776
79,654,091
15,001,463
Parent class initializes data that child class must use: better approach and enforcing contracts?
<p>I have a parent class that initializes a <code>matplotlib.axes._axes.Axes</code> object with some configuration that is necessary so that the resulting plots are saved correctly. A child class can extend the parent classes <code>_plot_initial_frame</code> and <code>_update_frame</code> methods in order to specialize...
<python><oop>
2025-06-05 08:43:04
1
714
Jared
79,654,033
364,595
debugging a PDF that will not open in Adobe
<p>disclaimer: I'm the author of <code>borb</code></p> <p>I'm currently working on the next (major) release. And for some reason I can not seem to get Adobe Reader to open the PDF.</p> <p>It throws 'There was a problem reading this document (14)'.</p> <p>You can get more information by ctrl+clicking the 'ok'. I did so....
<python><pdf><borb>
2025-06-05 08:01:19
1
9,217
Joris Schellekens
79,654,025
2,840,697
Does the way you define nested lists in Python matter?
<p>Let's assume that I defined a list <code>list1</code> as:</p> <pre><code> list1 = [[0]*10]*10 </code></pre> <p>and defined <code>list2</code> as:</p> <pre><code> list2 = [[0]*10 for i in range(10)] </code></pre> <p>Aren't these pretty much two equivalent ways of defining a nested list? Is there any reason these two ...
<python>
2025-06-05 07:57:23
1
942
user98235
79,653,909
29,295,031
How I can color a st.data_editor cell based on a condition
<p>I'm using streamlit's <code>st.data_editor</code>, and I have this <code>DataFrame</code>:</p> <pre><code>import streamlit as st import pandas as pd df = pd.DataFrame( [ {&quot;command&quot;: &quot;test 1&quot;, &quot;rating&quot;: 4, &quot;is_widget&quot;: True}, {&quot;command&quot;: &quot;test ...
<python><pandas><streamlit>
2025-06-05 06:41:37
1
401
user29295031
79,653,787
12,314,521
How to manipulate a model (Pydantic) which just is defined at runtime
<p>I have a situation like this: I know there will be a <code>Person</code> object model. But I haven't know it's attribute yet, until run time. a Person object will be defined and write into a Python file in project directory. Another option is at runtime a yml or json file will be created to describe that Person obje...
<python><pydantic>
2025-06-05 04:27:06
1
351
jupyter
79,653,549
981,351
df.to_json output appears to skip a date that is in the dataframe
<p>I have very limited knowledge of pandas.</p> <p>The data I'm using covers 2 dst (daylight saving) transitions for the UK (from 1 Sep 24 to 30 Apr 25), and consist of timestamps in milliseconds with values. The transition dates are 27 Oct 24 and 30 Mar 25.</p> <p>Using df.resample and a rule of 86400000ms I resample ...
<python><pandas><dataframe><time-series><dst>
2025-06-04 21:52:33
1
2,866
iss42
79,653,530
23,482,750
How to Test Password Reset Endpoint Using a Token That Doesnโ€™t Exist in the Database in FastAPI?
<p>I'm building a backend system using FastAPI, and I'm currently working on implementing unit tests for the password reset functionality that involves using tokens.</p> <p>Hereโ€™s the snippet of the code I'm testing:</p> <pre><code>def test_web_reset_password(): payload = { &quot;token&quot;: &quot;cozy_tok...
<python><jwt><fastapi><python-unittest><reset-password>
2025-06-04 21:30:36
0
343
Hiroshi Ashikaga
79,653,483
6,067,528
Should I use threading for a CPU-intense operation that is choking my service
<p>I am a maintainer of an ML service based on FastAPI and we I have CPU intense code that runs on main thread and with high CPU utilisation when a request heads down this path (I've seen occasional throttling too of cycles too).</p> <pre><code>def _svd_with_fallback(self, matrix: np.ndarray) -&gt; tuple[np.ndarray, np...
<python>
2025-06-04 20:54:32
0
1,313
Sam Comber
79,653,436
14,909,621
Which is a better way to move an iterator one step forward: `for x in iterator: break` or `x = next(iterator, None)`?
<p>While working on a learning task involving overlapping n-wise windows from an input iterable - similar to what <a href="https://docs.python.org/3/library/itertools.html#itertools.pairwise" rel="nofollow noreferrer">itertools.pairwise</a> does - I came across code like this:</p> <pre class="lang-py prettyprint-overri...
<python><iterator>
2025-06-04 20:15:39
1
7,606
Vitalizzare
79,653,395
1,310,814
Generate table rows in Word document
<p>I have a Word document template with a table. I want to generate the table rows from my python structure like below.</p> <pre><code>from docxtpl import DocxTemplate doc = DocxTemplate(&quot;template2.docx&quot;) context = { &quot;topic&quot;: &quot;Volcanoes&quot;, &quot;lessons&quot;: [ {&quot;ti...
<python><ms-word><docxtpl>
2025-06-04 19:36:05
1
894
ServerBloke
79,653,348
5,431,734
Efficiently group IDs by two keys into a 2D array of lists
<p>I have three NumPy arrays: class_label, student_name, student_id and grade. I am aggregating the grade per class and name as follows:</p> <pre><code>import numpy as np import numpy_groupies as npg class_label = [0, 2, 1, 1, 2, 3, 0, 1] student_name = [0, 0, 1, 2, 1, 1, 0, 1] student_id = [0, 1, 2, 3, 4, 5, 6,...
<python><numpy>
2025-06-04 19:05:51
1
3,725
Aenaon
79,653,257
13,682,559
How do I specify "related" types in a container class?
<p>I have various model classes, each working on its own data class. Like so:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass from typing import Any, Protocol, final @dataclass class Data(Protocol): val_generic: int @dataclass class DataA(Data): val_generic: int = 1 v...
<python><python-typing>
2025-06-04 17:39:05
1
1,108
Durtal
79,653,214
938,363
buildozer build error : configure: error: C compiler cannot create executables
<p>My kivy 2.3.1, buildozer 1.5.0, python-for-android 2024.01.21 in python virtualenv 3.11, on MacOS app throws error when <code>buildozer android debug</code>:</p> <pre><code>[DEBUG]: configure: error: in `/Users/macbook/Documents/code/py/vmonfront/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/build/other...
<python><kivy><buildozer>
2025-06-04 17:07:37
0
10,250
user938363
79,653,147
5,228,890
pip does not find new version of torch
<p>I have a Mac M1 laptop, where I have conda env with python=3.9.21, and pip=25.1.1.</p> <p>Currently I have torch=2.2.0 and I wanted to update it to the latest version, but when I tried <code>pip install -U torch</code> it shows that I have the latest version, and trying <code>pip install -U torch==2.7.0</code> ends ...
<python><macos><pytorch><pip>
2025-06-04 16:15:51
1
1,464
Afshin Oroojlooy
79,653,120
7,326,981
Supabase connection error "server didn't return client encoding"
<p>I am trying to connect and write a Pandas Dataframe to a Postgres custom schema on Supabase. Below is the code.</p> <pre><code>from sqlalchemy import create_engine def server_access(): # Create SQLAlchemy connection string conn_str = ( f&quot;postgresql+psycopg2://{&quot;[USER]&quot;}:{&quot;[PASSWO...
<python><pandas><postgresql><supabase>
2025-06-04 15:58:09
2
1,298
Furqan Hashim
79,653,054
11,578,996
Pandas multi-column multi-assignment merge / update
<p>I want to update the <code>base</code> pandas DataFrame with data from the <code>update</code> DataFrame. This applies to multiple rows of the base DataFrame (ie the merge features are not unique so can't be used as an index) and I cannot use the index matching techniques of <code>pd.join()</code> or <code>pd.merge(...
<python><pandas><dataframe><join>
2025-06-04 15:11:42
2
389
ciaran haines
79,652,961
12,403,550
Calculate overlap in cluster area between multiple clusters
<p>I have a raster image. Using scipy, I am clustering pixels that belong to each peak in the histogram that corresponds to the values in the image. I am able to detect two clear peaks that are clearly segregated in the image. What I want to know is how much these points overlap.</p> <p><a href="https://i.sstatic.net/o...
<python><scipy><shapely>
2025-06-04 14:19:44
1
433
prayner
79,652,902
401,516
Can the Django development server be restarted with a signal?
<p>I would like to be able to restart the <code>manage.py runserver</code> Django command using a signal (like in <code>kill -HUP PID</code>). Does Django even support this? <code>SIGHUP</code>, <code>SIGINT</code>, <code>SIGTERM</code> just exit the process.</p> <p>Tried <code>pkill -HUP</code>, didn't work.</p>
<python><django>
2025-06-04 13:45:18
1
1,034
dotz
79,652,650
10,305,444
Gedit plugin not showing custom context menu items with Python
<p>I'm developing a Gedit plugin in Python using Gtk. The plugin is supposed to add &quot;๐Ÿ”ฎ Generate&quot; and &quot;๐Ÿ“ Summarize&quot; items to the right-click context menu in the editor. However, the items are not showing up.</p> <p>Here are related code:</p> <pre><code>... def on_populate_popup(self, view, menu...
<python><gtk><gnome><gedit><gedit-plugin>
2025-06-04 11:22:46
1
4,689
Maifee Ul Asad
79,652,536
72,791
Matplotlib Hover Coordinates with Labelled XTicks
<p>I've got a matplotlib graph with labelled X-ticks:</p> <p><a href="https://i.sstatic.net/02h7A0CY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/02h7A0CY.png" alt="Graph of random data, with labelled X-ticks" /></a></p> <p>The labels repeat (in case that's relevant). In the real graph, there is a mu...
<python><matplotlib><mplcursors>
2025-06-04 10:01:28
2
73,231
DrAl
79,652,471
536,262
Type hint warning `"keys" is not a known attribute of "None"` for `Optional` in Pylance
<p>Recently Pylance has started to add red underlines in my code. I've managed to fix most of it, but I have problems with <code>Optional</code> typing:</p> <pre><code>def realms(testenv:str, active:bool=True) -&gt; Optional[Dict]: &quot;&quot;&quot; return a dict of active/inactive realms with info from keycloak, ...
<python><python-typing><pylance>
2025-06-04 09:20:18
1
3,731
MortenB
79,652,378
93,684
How can I implement multiple oauth providers parameters for multi tenant setup
<p>I am using Superset with SSO enabled using Cognito in a multi tenant environment. Each tenant is using a separate user pool. Is it possible to plug the connection parameters based on the tenant so that when connecting each tenant is directed to their correct user pool. I have the connection parameters for each tenan...
<python><flask><oauth-2.0><apache-superset><authlib>
2025-06-04 08:22:06
0
390
tamla83
79,652,218
2,947,469
Tensorflow - validation metric does not show up, it gets the same name as the train metric
<p>I am using the model.compile(metrics=[MyMetric])</p> <p>I was wondering why I only see loss and val_loss, but only se my_metric and not val_my_metric after the evaluation at end of each epoch completes.</p> <p>I have debugged therefore tensorflow code. I see in trainer.py:fit() it is ok:</p> <p><a href="https://i.ss...
<python><tensorflow><keras>
2025-06-04 06:32:36
0
1,827
Adam
79,652,036
10,531,186
Problems with streamlit using MCP client
<p>Having issues with Streamlit, it does not seem compatible with an MCP client. Getting <code>NotImplemented</code> error.</p> <p>This is the relevant streamlit code:</p> <pre class="lang-py prettyprint-override"><code>available_scripts = [&quot;mcp_server1.py&quot;, &quot;mcp_server2.py&quot;] selected_script = st.se...
<python><python-asyncio><streamlit><nest-asyncio><model-context-protocol>
2025-06-04 01:10:22
0
324
someguy
79,652,003
16,635,269
How do I upload unstructured documents with meta data to Google Cloud Platform data store with Python SDK?
<p>I am trying to upload unstructured data to a Google Cloud Platform (GCP) data store from a GCP Storage Bucket using the Python SDK. I want to use unstructured data with meta data which is mentioned <a href="https://cloud.google.com/generative-ai-app-builder/docs/prepare-data?_gl=1*cpveo*_ga*NTQ5OTkwMTE4LjE3NDY1NTM1M...
<python><google-cloud-platform><google-cloud-storage><google-cloud-datastore><google-cloud-vertex-ai>
2025-06-03 23:47:25
2
301
Fruity Fritz
79,652,001
1,084,875
GitLab CI pipeline for a uv Python project does not cache environment and dependencies
<p>I have a GitLab runner on a Linux machine that uses the shell executor. This runner is for testing a Python project that uses <a href="https://docs.astral.sh/uv/" rel="nofollow noreferrer">uv</a> for virtual environment and dependency management. I have the Python project setup to use the runner with the <code>.gitl...
<python><gitlab-ci><gitlab-ci-runner><uv>
2025-06-03 23:43:32
1
9,246
wigging
79,651,927
1,747,834
Installing my own single-file Python project
<p>I have a rather small package, with only the single <code>__init__.py</code> at the top-level, which I attempt to install with <code>pip-3.11 install --user .</code>.</p> <p>Pip duly processes my <code>pyproject.toml</code>, checking all of the dependencies, and ends with these reassuring messages:</p> <pre class="l...
<python><pip><python-packaging>
2025-06-03 21:46:04
0
4,246
Mikhail T.
79,651,863
14,122
Cleanup after waiting for first asyncio task to complete: Is it safe to swallow CancelledError when raised by task.get_exception()?
<p>I have an asyncio function that spawns multiple tasks, any of which can return a result, in which case we want to shut down all the others.</p> <p>Right now, it does so in a matter something like the following:</p> <pre class="lang-py prettyprint-override"><code>all_tasks = [asyncio.create_task(ds.get() for ds in da...
<python><python-asyncio><cancellation>
2025-06-03 20:33:47
0
299,045
Charles Duffy
79,651,861
1,581,090
How to extract intraday stock data from onvista with python and playwright/selenium?
<p>Using 3.9.6 and playwright on MacOS 14.7.5 I am trying to extract the public available intraday stock data from a webpage like</p> <pre><code>https://www.onvista.de/aktien/Airbus-Group-EADS-Aktie-NL0000235190 </code></pre> <p>To make the Intraday data load you have to click the &quot;Intraday&quot; button. Here is a...
<python><macos><selenium-webdriver><playwright><playwright-python>
2025-06-03 20:32:12
1
45,023
Alex
79,651,859
5,036,928
mpi4py: only rank 0 participating in scipy minimize after first iteration
<p>Given the code below, I am unable to remedy the fact that only rank 0 participates in evaluations of <code>Objective</code> after the first iteration of the (SciPy) minimizer. Obviously the rank!=0 workers finish their initial tasking and the minimizer does not reengage these workers. My question is <em>how</em> can...
<python><parallel-processing><scipy><scipy-optimize><mpi4py>
2025-06-03 20:28:21
1
1,195
Sterling Butters
79,651,358
7,036,941
Python type-hinting: a Tkinter Event
<p>I'm learning how to create GUIs with TKinter in Python. I'm using VSCode as my editor and I have this piece of code:</p> <pre class="lang-py prettyprint-override"><code>[...] # create a button and bind an action to the button press event button:tk.Button = tk.Button(master=gridFrame, text=&quot;Button&quot;)...
<python><python-typing><pyright>
2025-06-03 13:49:19
1
408
Joel Santos Rico
79,651,328
15,307,950
How do I render images sharp in Jupyter notebook with VScode when Windows scaling is enabled?
<p>I want to display an image from an array in a Jupyter notebook (inline) in Visual Studio Code. I'm running Windows 11 on a high DPI monitor with scaling set to 150%. Pixels don't render sharp in the notebook. 1 pixel in the source image should be 1 pixel on the screen. If I want to scale the image using integer scal...
<python><visual-studio-code><jupyter-notebook><highdpi>
2025-06-03 13:21:24
2
726
elechris
79,651,249
4,247,599
logger from Jupyter notebook: does not work unless calling the root logger at least once
<p>I would like to see the logging produced by some Python code from within a Jupyter notebook (logging version '0.5.1.2', python 3.12).</p> <p>If I run the following code:</p> <pre class="lang-py prettyprint-override"><code>import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logger.info(&quot;l...
<python><logging><python-logging>
2025-06-03 12:40:21
2
4,299
SeF
79,651,120
17,580,381
Formatting integers in pandas dataframe
<p>I've read <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.format.html" rel="nofollow noreferrer">the documentation</a> and simply cannot understand why I can't seem to achieve my objective.</p> <p>All I want to do is output integers with a thousands separator where appropriate.</...
<python><pandas>
2025-06-03 11:12:10
1
28,997
Ramrab
79,651,081
5,157,277
Multivalued column cannot be transformed
<p>Im working with Stackoverflow 2024 survey. In the csv file there are several multivalued variables (separated by ;). I want to apply One-hot encoding to the variables <strong>Employment</strong> and <strong>LanguageAdmire</strong> by use <code>MultiLabelBinarizer</code>. However, my code works only for the first one...
<python><data-preprocessing><multivalue>
2025-06-03 10:42:09
1
843
Lev
79,650,791
8,602,940
Custom embedder and Custom knowledge source in CrewAI - getting KeyError: 'OPENAI_API_KEY'
<p>I have setup a Custom Embedder to use with knowledge and tools, but keep getting the error:</p> <blockquote> <p>litellm.AuthenticationError: AuthenticationError: OpenAIException - The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable</p> <...
<python><postgresql><vector><large-language-model><crewai>
2025-06-03 07:25:29
0
1,392
lazzy_ms
79,650,652
1,015,761
Python Django Admin Form: show inline without rendering a form
<p>I have a Django admin page which allows me to edit a model in my domain. The ModelAdmin looks like this:</p> <pre><code>@admin.register(models.VehicleTemplate) class VehicleTemplateAdmin(ModelAdminBase): list_reverse_relation_inline = False search_fields = [&quot;name&quot;, &quot;description&quot;] list...
<python><django><django-forms><django-admin>
2025-06-03 05:15:07
0
3,876
Goulash
79,650,615
1,230,724
Using array indices to address another array
<p>I'm trying to &quot;overlay&quot; a numpy 1-d array over another 1-d array of larger size, so that the overlaying array sets multiple values in the overlayed array.</p> <p>I'm struggling with an efficient way to convert the indices from the overlaying array (<code>overlay</code>) to the overlayed array (<code>arr</c...
<python><arrays><numpy>
2025-06-03 04:22:57
2
8,252
orange
79,650,567
203,454
Django-allauth - Make phone number optional for SocialLogin
<p>I am using django-allauth in my project and I have configured Google as a SocialAuth provider. I have a custom signal receiver that updates the phone number on the SocialAuthAccount after the user signs up. But currently the system throws an error when the user logins via SocialAuth if they do not have a public phon...
<python><django><django-allauth>
2025-06-03 03:09:12
1
34,403
arunkumar
79,650,437
4,996,797
How to pretty print an array with small number in numpy
<p>I have an array that I would like to display</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # build a matrix with a few large values and noise matrix = np.diag([5.9, 0.0, 13.11]) rng = np.random.default_rng(seed=20250602) matrix += rng.random(size=(3, 3)) * 10e-10 with np.printoptions(preci...
<python><numpy>
2025-06-02 23:16:49
0
408
Paweล‚ Wรณjcik
79,650,396
219,153
How to limit matplotlib button_press_event to a single axis?
<p>This script:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.widgets import Button def fAccept(_): print(f'accepted') def onclick(event): print(f'click {event.xdata, event.ydata}') fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) fig.canvas.mpl_connect('button_press_event', onclick) ax...
<python><matplotlib><callback><onclick>
2025-06-02 22:10:43
1
8,585
Paul Jurczak
79,650,393
5,744,712
Is there a way to pre-define validators that can be used multiple times?
<p>I'm working on an API based flask app with flask-smorest and marshmallow validations. The issue I'm running into, is that many api endpoints require the same type of data, and I don't want to continually copy/paste the same validations over and over. Something like below would happen....</p> <pre><code>from marshm...
<python><marshmallow><flask-smorest>
2025-06-02 22:06:03
1
611
Stephan
79,650,348
2,153,235
Tuple comprehension creates generator; List comprehension evaluates all elements right away
<p>I am using a long ad hoc script for exploratory data analysis -- not for tool development. The script has gotten quite long, so I've taken to <code>del</code>ing ephemeral variables to keep the Spyder Variable Explorer clean. I've done this all over the script.</p> <p>I tried to be streamline the script by coding ...
<python><list><tuples><list-comprehension>
2025-06-02 21:20:05
1
1,265
user2153235
79,650,316
5,036,928
mpi4py deadlock with scipy.minimize
<p>I am trying to do something similar as described in <a href="https://stackoverflow.com/questions/37159923/parallelize-a-function-call-with-mpi4py">Parallelize a function call with mpi4py</a></p> <p>But there are some things there that make me skeptical of the provided answer. Additionally, I have a class implementat...
<python><scipy><mpi><scipy-optimize><mpi4py>
2025-06-02 20:50:45
2
1,195
Sterling Butters
79,650,165
13,344,315
Getting Azure Credentials from Hybrid Worker in Azure Automation with Python
<p>I have an automation account with a bunch of stored credentials. In the past I typically use Powershell and using Get-AutomationPSCredential has worked great in the past. However I need to get some credentials into a Python script that is running from a hybrid worker. All of my research says to use the automationass...
<python><azure-automation>
2025-06-02 18:33:25
1
301
Andrew Draper
79,650,102
1,715,495
PyPI publishing GitHub Action works with token but not trusted provider
<p>This <a href="https://github.com/batfish/docker/pull/137/files" rel="nofollow noreferrer">pull request</a> modifies our open source package <code>batfish/docker</code> GitHub actions to use PyPI trusted publishing on Test PyPI instead of a password. I'm talking about the <code>dev_whl</code> step that pushes a devel...
<python><openid-connect><pypi>
2025-06-02 17:43:19
1
2,257
Dan Halperin
79,649,970
9,703,451
contextlib.contextmanager does not raise exceptions if return is in finally clause
<p>I just encountered a really strange behaviour of python's <code>contextlib.contextmanager</code>. Can anyone explain to me if this is intended (and why):</p> <blockquote> <p>If you put a <code>return</code> into the <code>finally</code> of the <code>contextmanager</code>, any exception raised within the <code>contex...
<python>
2025-06-02 15:58:48
2
3,179
raphael
79,649,941
5,353,177
Get order of nodes in DiGraph networkx
<p>I have the next example of graph:</p> <pre class="lang-py prettyprint-override"><code>import networkx as nx G=nx.DiGraph() G.add_edges_from([('b','a'), ('b','c'), ('a','c'),('c','d')]) </code></pre> <p>In visual way it should look like this: <a href="https://i.sstatic.net/LhUJAEad.png" rel="nofollow noreferrer"><im...
<python><networkx>
2025-06-02 15:37:07
2
736
Sanek Zhitnik
79,648,605
12,372,992
How to define nullable fields for SqlTransform
<p>I'm using Beam SqlTransform in python, trying to define/pass nullable fields.</p> <p>This code works just fine:</p> <pre class="lang-py prettyprint-override"><code>with beam.Pipeline(options=options) as p: # ... # Use beam.Row to create a schema-aware PCollection | &quot;Create beam Row&quot; &gt;&gt; beam.Map(lamb...
<python><apache-beam><beam-sql>
2025-06-02 11:04:30
1
1,980
Yair Maron
79,648,524
6,681,932
ValueError: zero-size array to reduction operation maximum which has no identity in SVAR Mode
<p>I'm trying to fit a Structural Vector Autoregression (SVAR) model using statsmodels in Python, but I'm encountering the following error <code>ValueError: zero-size array to reduction operation maximum which has no identity</code>.</p> <p>There is my code:</p> <pre><code>import pandas as pd import numpy as np from st...
<python><valueerror><vector-auto-regression>
2025-06-02 10:02:42
1
478
PeCaDe
79,648,388
12,415,855
Problem with umlauts when writing with Python and opening with Excel?
<p>I am writing some content with umlauts in it using the following code:</p> <pre><code>import csv import os import sys data = [[&quot;รคwien&quot;, &quot;รถbgld&quot;, &quot;รผktn&quot;, &quot;noe&quot;, &quot;ooe&quot;, &quot;sbg&quot;, &quot;stmk&quot;, &quot;tirol&quot;, &quot;vbg&quot;]] path = os.path.abspath(os.pa...
<python><excel><csv>
2025-06-02 08:12:48
1
1,515
Rapid1898
79,648,275
3,366,355
Convert JSONC to JSON via regex
<p>I have JSONC as input (it is a superset of JSON that supports comments like <code>//this one</code> and <code>/* this one */</code>), and want to transform it into normal JSON (standard) using Python regex, but I'm not sure this can be solved with regex only. I know it can be done via semantic processing, maybe some...
<python><json><regex><bash><json-c>
2025-06-02 06:37:32
2
1,032
martin
79,648,080
11,421,839
How to use browser-use to make screenshots for each step and video recording for the whole session?
<p>I am trying to build a python project that uses <code>browser_use</code> to perform tasks, and create video recording for the whole session and screenshots for each step.</p> <p>But I can't find a way to do it. The official doc did provide some suggestions but those configurations didn't allow me to create those rec...
<python><playwright><playwright-python><playwright-test><browser-use>
2025-06-02 01:11:00
1
1,963
Terry Windwalker
79,647,899
948,866
How to order functions to avoid NameError "x is not defined"?
<p>15 years ago the <a href="https://stackoverflow.com/questions/1590608/how-do-i-forward-declare-a-function-to-avoid-nameerrors-for-functions-defined">answer</a> to this question was:</p> <blockquote> <p>The general rule in Python is that a function should be defined before its usage, which does not necessarily mean i...
<python><class><forward-reference>
2025-06-01 20:18:39
1
3,967
Dave
79,647,808
5,416,142
Cannot use local user data for Chrome while running Selenium
<p>I am running python program with Selenium to automate browser page processing. In order to open the pages correctly, I need to use my login and password saved in the Chrome user profile for my website. I created a new Chrome profile for that purpose. However, the program cannot read my user profile data for some rea...
<python><google-chrome><selenium-webdriver><selenium-chromedriver>
2025-06-01 18:14:54
2
757
BohdanZPM
79,647,650
1,088,979
Cannot import Python modules from sibling directory in Jupyter Notebook running in VS Code (os.chdir and sys.path.append do not work)
<p>I am running Jupyter Notebooks inside Visual Studio Code using the official Jupyter extension.</p> <p>My project structure is as follows:</p> <pre><code>my_project/ โ”œโ”€โ”€ notebooks/ โ”‚ โ””โ”€โ”€ analysis.ipynb โ”œโ”€โ”€ libs/ โ”‚ โ”œโ”€โ”€ __init__.py โ”‚ โ””โ”€โ”€ my_module.py </code></pre> <p>In <code>analysis.ipynb</code>, I would like t...
<python><visual-studio-code><jupyter-notebook><vscode-extensions>
2025-06-01 14:50:48
0
9,584
Allan Xu