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,392,103
5,151,909
NumPy 2D indexing using different slice per column
<pre class="lang-py prettyprint-override"><code>import numpy as np x = np.arange(12).reshape(3, 4) print(x) idx = np.array([0, 1]) y = x[:2, idx : idx + 2] # should be # [[0 1] # [5 6]] </code></pre> <p>So I want to get different slice for each row. In this example, it's the <code>0, 1</code> indexes from the first...
<python><numpy>
2025-01-27 20:31:44
0
4,011
galah92
79,392,038
2,893,712
Pandas Batch Update Account String
<p>My organization has account numbers that are comprised of combining multiple fields. The last field is always 4 characters (typically 0000)</p> <pre><code>Org Account 01 01-123-0000 01 01-456-0000 02 02-789-0000 02 02-456-0000 03 03-987-0000 03 03-123-1234 </code><...
<python><pandas>
2025-01-27 20:00:00
1
8,806
Bijan
79,391,995
685,022
Post multipart/form-data using pythons httpx library only form data
<p>How do I send a POST with python HTTPX that will minic a CURL POST that works? This is to an opengear rest API. I believe it has to do something with the data field of the post.</p> <p>This is the working curl hitting the rest API properly.</p> <pre class="lang-bash prettyprint-override"><code>curl -s -k \ -X POST \...
<python><post><multipartform-data><httpx>
2025-01-27 19:44:17
1
1,903
krizzo
79,391,914
16,725,431
Notification after shut down on windows using python
<p>I want to create a function that displays a message for the user when windows start again after a shutdown.</p> <p>It is used together with the shutdown command <code>shutdown \s \hybrid</code></p> <p>Heres my attempt with the help of AI</p> <pre><code>import os def leave_message_on_startup(message): script_co...
<python><windows><startup><shutdown><windows-task-scheduler>
2025-01-27 19:11:10
2
444
Electron X
79,391,748
1,552,080
Communicating with REST service using Python/Flask, javascript and ajax
<p>I have a web application fetching data from database behind a REST service creating output in form of a table:</p> <p><a href="https://i.sstatic.net/JfBK6Ad2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JfBK6Ad2.png" alt="Output of Flask/javascript code generating table with data." /></a></p> <p>As...
<javascript><python><ajax><flask>
2025-01-27 18:04:30
1
1,193
WolfiG
79,391,696
5,110,870
How do you manage (create/delete/update) a custom classification?
<p>I am new to Purview, and have been playing with the <code>azure-purview</code> Python package.</p> <p>I noticed that Purview relies a lot on AtlasEntity, but I was wondering if anyone knew how to create, delete, or update a custom classification programmatically.</p> <p>Would a classification be an entity?</p> <p>If...
<python><azure-purview>
2025-01-27 17:43:01
1
7,979
FaCoffee
79,391,609
3,200,163
Python 3 how to zip the contents and folder that are in another folder
<p>I want to have a folder called 'product_a1' in a folder called 'product_a1' with a text file and process flag files such as 'completed' file. I want to zip the entire thing so it can be put onto a ftp server. The server is currently PHP using 7zip, and expects this structure, but I need to do this using Python cod...
<python><zip><7zip><shutil>
2025-01-27 17:13:16
1
629
Andrew Day
79,391,602
15,484,393
How to mock for subprocesses spawned by ProcessPoolExecutor in Python (here: elasticsearch.Elasticsearch)?
<p>I am trying to mock the <code>elasticsearch.Elasticsearch</code> class using <code>unittest.mock.patch</code> in a test, but the mock is not being applied to subprocesses created by <code>ProcessPoolExecutor</code>. Here's the code I'm working with:</p> <p>main.py</p> <pre><code>import concurrent.futures import elas...
<python><multiprocessing><pytest><concurrent.futures><monkeypatching>
2025-01-27 17:08:26
0
478
TSnake
79,391,560
1,700,890
Annotated python list with function as meta data
<p>I am trying to find out the purpose of the following code. What does it exactly do? Why there is operator in place of meta data? How is <code>operator.add</code> used? Does it append the list and if yes then when and how? I took from the following tutorial: <a href="https://python.langchain.com/docs/tutorials/summar...
<python><python-typing>
2025-01-27 16:52:50
0
7,802
user1700890
79,391,480
20,302,906
Can't assert folder creation path with unittest patch
<p>I'm trying to assert all paths that passed through <code>os.makedirs</code> to test that a folder structured has been created. The code isn't complicated and I'm sure it works find but my test reports that the method wasn't called with the paths I'm passing by checking calls in <code>assert_any_call(my_path, 511)</c...
<python><python-3.x><unit-testing><mocking><python-unittest>
2025-01-27 16:27:10
1
367
wavesinaroom
79,391,408
451,878
How to test (pytest), or mock, an app.state object of fastapi
<p>After some research, I can't find help to mock an app.state.* object(s) : Here my code :</p> <pre><code>def get_app(): settings = get_settings() application = FastAPI() config = {...} application = create_app(**config) return application app = get_app() @pytest.fixture(scope=&quot;module&quot;...
<python><google-bigquery><mocking><pytest>
2025-01-27 16:03:59
0
1,481
James
79,391,242
668,455
How to customise the LlamaIndex starter tuto to use the latest Llama model hosted on "akash.network"
<p>The akash chat API is supposed to be compatible with openai : <a href="https://chatapi.akash.network/documentation" rel="nofollow noreferrer">https://chatapi.akash.network/documentation</a>, it's compatible with the basic OpenAI SDK :</p> <pre><code>import openai import textwrap client = openai.OpenAI( api_key=&...
<python><large-language-model><llama-index>
2025-01-27 15:01:45
1
9,191
Tristan
79,390,866
4,877,683
anndata.concat resulting in 4x the size of the individual files causing memory issues
<p>I am new to anndata and would like to know if an issue that i am running into expected or not.</p> <p>I have 28 h5ad files (Tabula Sapiens)(<a href="https://figshare.com/articles/dataset/Tabula_Sapiens_v2/27921984" rel="nofollow noreferrer">https://figshare.com/articles/dataset/Tabula_Sapiens_v2/27921984</a>), that ...
<python><bioinformatics><scanpy><anndata>
2025-01-27 12:56:02
1
703
Danish Zahid Malik
79,390,711
1,472,474
Correct annotation for "apply" function
<p>In Python-3.10 (it must be this version) I want to add better annotation for my <code>apply</code> function:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Callable, Sequence, Any T = TypeVar('T') def apply(fn: Callable[..., T], vals: Sequence[Any]) -&gt; T: return fn(*vals) d...
<python><python-typing><mypy><python-3.10>
2025-01-27 12:21:46
1
5,587
Jan Spurny
79,390,708
1,277,624
Understanding Type Variance in Python Protocols with Generic Types
<p>I'm trying to understand how type variance works with Python protocols and generics. My test cases seem to contradict what I expect regarding invariant, covariant, and contravariant behavior.</p> <p>Here's a minimal example demonstrating the issue:</p> <pre><code>from typing import TypeVar, Protocol # Type variable...
<python><python-typing>
2025-01-27 12:20:12
1
408
rednammoc
79,390,586
6,708,322
Can I define an Alias to a foreign field in Django?
<p>I'm looking to define an alias to a foreign key related set so that it can then be used in a generic filtering function. To explain with a little more detail here is a simplified example of my use case demonstrating what I'm trying to achieve:</p> <p><strong>models.py</strong></p> <pre class="lang-py prettyprint-ove...
<python><django>
2025-01-27 11:34:58
1
1,111
Jake Conkerton-Darby
79,390,516
14,649,310
How to start ollama with docker compose with specific LLM model
<p>I have a docker compose where a dummy python app is using ollama LMs on the background for some tasks. I want to be able to tell ollama somehow which model to download and use on the app deployment. Now my docker compose is like this:</p> <pre><code>version: '3.8' services: elasticsearch: image: docker.elasti...
<python><linux><docker><docker-compose><ollama>
2025-01-27 11:08:05
1
4,999
KZiovas
79,390,166
5,618,856
Run python script with uv with path
<p>I'm using <a href="https://docs.astral.sh/uv/" rel="nofollow noreferrer">uv</a> as my python project manager. Within the project dir I can run my scripts with <code>uv run my_script.py</code> and all dependencies are resolved.</p> <p>But how can I call this script if my terminal in on another path? <code>uv run /pat...
<python><virtual-environment><uv>
2025-01-27 08:55:42
2
603
Fred
79,390,103
4,442,753
Numpy: vectorizing the comparison of 2 boolean arrays to derive start and end indices of regions of interest
<p>Assuming I have 2 boolean arrays of same size, <code>is_overlap</code> and <code>is_incomplete</code>. I would like to retrieve the start and end indices (end indices excluded) of regions of interest in these arrays (these regions are of interest for an analysis achieved in subsequent steps of the algo - start and e...
<python><numpy>
2025-01-27 08:28:01
1
1,003
pierre_j
79,389,885
3,508,956
How do I print out the tensor values in between layers in Keras 3?
<p>I'm using Keras 3 with the PyTorch backend.</p> <p>I'm trying to port a model written by someone else to another runtime, and I want to dump summary statistics about the tensor after each layer so I can figure out which operation I implemented incorrectly in my port (probably attention, lol).</p> <p>How do I insert ...
<python><machine-learning><keras>
2025-01-27 06:20:25
0
7,107
laptou
79,389,718
5,729,613
Python Queue not updated outside of Thread
<p>I've created a Flask app that retrieves data from a queue that is updated in a separate thread. I'm not sure why the Queue is empty when I retrieve it from the Flask GET endpoint, and am a bit ignorant of what Queues being thread-safe is supposed to mean, since my example doesn't appear to reflect that.</p> <p>In th...
<python><multithreading><flask>
2025-01-27 04:01:46
1
1,867
I Like
79,389,695
17,275,378
UnpicklingError from Azure Blob
<p>I'm developing an <code>Azure Function</code> to serve inferences from a machine learning model. The model is saved as a <code>.pkl</code> file on <code>Azure Blob Storage</code>. All attempts to read the file into Python fail.</p> <p>For simplicity, this example uses an arbitrary .pkl instead of a model file.</p> ...
<python><azure-functions><azure-blob-storage><pickle>
2025-01-27 03:20:57
1
326
eldrly
79,389,482
3,120,501
Matplotlib FuncAnimation blitting for 3D contourf?
<p>I'm trying to make a 3D Matplotlib animation with a contour 'slice' which moves through space. A minimum working example of the kind of thing I'm trying to accomplish is given by the following code:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np from matplotlib...
<python><matplotlib><animation>
2025-01-26 23:32:40
0
528
LordCat
79,389,452
1,429,450
2D NumPy array + 1D array →?
<p>For two NumPy arrays,</p> <pre><code>A = [[1,3,6], [2, 2, 5], …], B = [1,6,7,8,…], </code></pre> <p>what is the fastest way to make</p> <pre><code>C = [[[1,3,6], 2], [[2, 2, 5], 6], …] </code></pre> <p>?</p>
<python><arrays><numpy>
2025-01-26 23:01:14
1
5,826
Geremia
79,389,398
3,159,059
PyInstaller Build from MacOS Ventura Failing on High Sierra due to Missing Symbol '_OBJC_CLASS_$_MLModelConfiguration'
<p>I have developed a cross-platform app which runs on MacOS and Windows. I have packaged the app on MacOS Ventura (i7 Intel-based) with PyInstaller. When I try to run the packaged app on MacOS High Sierra, I get the below error. Can anyone provide insight how I can fix or work around this issue? I'm assuming it's re...
<python><macos><pyinstaller><symbols>
2025-01-26 22:21:36
0
5,749
GaryMBloom
79,389,160
8,160,995
Bluepy scan for devices and connect to them
<p>My task is to search for some devices with Bluetooth with a Raspberry PI 4B and to connect to send some commands and disconnect. For this, I started using bluepy package and I was able to do the two things separately. I can connect to a device with:</p> <pre class="lang-py prettyprint-override"><code>from bluepy.btl...
<python><bluetooth><raspberry-pi4>
2025-01-26 19:26:31
0
762
Ripper346
79,389,155
1,704,628
Map Logic with TypeVarTuple
<p>I have a rather simple function that accepts a sequence of classes and returns a tuple of their respective instances:</p> <pre class="lang-py prettyprint-override"><code>def f(*classes): return tuple(cls() for cls in classes) </code></pre> <p>Is there any way to annotate it so that mypy (and more importantly, In...
<python><python-typing><mypy>
2025-01-26 19:24:00
0
3,910
Dan Gittik
79,389,136
1,473,517
How to create a python module in C++ that multiprocessing does not support
<p>I am trying and failing to reproduce and understand a problem I saw where multiprocessing failed when using a python module written in C++. My understanding was that the problem is that multiprocessing needs to pickle the function it is using. So I made <code>my_module.cpp</code> as follows:</p> <pre><code>#includ...
<python><c++><multiprocessing><pybind11>
2025-01-26 19:06:53
1
21,513
Simd
79,389,053
18,775
Using Python how do I validate JSON against a JSON schema in a streaming fashion, e.g., not loading the whole object in memory?
<p>I have a large JSON that I do not want to load into memory. I would like to validate it against a JSON schema in a <em>streaming</em> fashion. All libraries I could find so far, only validate completely loaded JSON objects (like Pydantic or <a href="https://github.com/python-jsonschema/jsonschema" rel="nofollow nore...
<python><json><stream><jsonschema><python-jsonschema>
2025-01-26 18:17:29
7
6,532
Anton Daneyko
79,389,038
11,092,636
Why does plt.axis('off') change the colour of the plot?
<p>I'm a bit confused as to why <code>plt.axis('off')</code> would do anything else than removing the ticks in <code>matplotlib</code> (<code>Python 3.12.8</code>, <code>matplotlib==3.10.0</code>).</p> <p>Minimal Reproducible Example:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt i...
<python><matplotlib>
2025-01-26 18:04:29
2
720
FluidMechanics Potential Flows
79,388,926
3,380,902
pyenv BUILD FAILED on macOS 15.1
<p>I am running into BUILD FAILED Error (OS X 15.1 using python-build 2.5.1) when attempting to install python via <code>pyenv install 3.12.8</code></p> <pre><code>bash-3.2$ pyenv install 3.12.8 python-build: use openssl@3 from homebrew python-build: use readline from homebrew Downloading Python-3.12.8.tar.xz... -&gt; ...
<python><pyenv>
2025-01-26 16:56:55
2
2,022
kms
79,388,819
6,502,077
How can I change the sequence of the pages in a PDF file?
<p>I want to make a simple Python program that changes the order of the pages in a PDF file, which would allow me later to place two pages (A5) on one sheet (A4) and print the document as a booklet on a printer.</p> <p>As an example, this is how the pages will be placed on one sheet:</p> <p><a href="https://i.sstatic.n...
<python><pypdf>
2025-01-26 15:58:22
1
702
Lavonen
79,388,585
1,235,227
How can I call a @staticmethod on a generic type argument (defined with TypeVar)?
<p>I have a generic class in which I would like to call a static method on the type argument, but if I naively try it like in the following example, I get an error because the identifier representing the type is actually an instance of TypeVar which does not have this attribute:</p> <pre class="lang-py prettyprint-over...
<python><python-typing>
2025-01-26 13:20:04
0
1,941
hans_meine
79,388,538
6,105,259
How to set multiple variables in DBT/SQL by running `run_query()` iteratively over a list of strings
<p>In dbt, I want to utilize jinja syntax to reduce code repetition when assigning variables (with <code>set</code>). I have one preemptive query that I wish to run <em>repeatedly</em>, changing the value matched in its <code>WHERE</code> clause each time. For each iteration, I want to save the result into a separate v...
<python><sql><jinja2><dbt>
2025-01-26 12:44:07
1
4,303
Emman
79,388,126
2,106,815
Which elif usage is prefered in python?
<p>Which of the following is preferred for using chained elif.</p> <pre><code>elif 12 &lt;= person_age &lt; 16: print(&quot;In range&quot;) </code></pre> <p>OR</p> <pre><code>elif person_age &gt;= 12 and person_age &lt; 16: print(&quot;In range&quot;) </code></pre> <p><strong>Please note Pycharm advised to use ...
<python>
2025-01-26 07:12:11
1
2,896
Jabir
79,388,046
17,419,414
Distinction between Python environment and Jupyter kernel in VS Code
<p>In Python I can create a virtual environment in VS Code with the following commands, I'll also install a kernel to the same virtual environment:</p> <pre class="lang-bash prettyprint-override"><code>python3 -m venv .venv source .venv/bin/activate pip install ipykernel python3 -m ipykernel install --user --name=.venv...
<python><visual-studio-code><jupyter-notebook><virtualenv>
2025-01-26 06:10:56
2
361
jophuh
79,387,911
2,882,380
How to make values into rows instead of columns when using pivot table in pandas
<p>Say I have this data frame:</p> <pre><code>import pandas as pd x = pd.DataFrame([[1, 'step', 'id', 22, 33], [2, 'step', 'id', 55, 66]], columns=['time', 'head_1', 'head_2', 'value_1', 'value_2']) print(x) time head_1 head_2 value_1 value_2 0 1 step id 22 ...
<python><pandas>
2025-01-26 03:05:04
2
1,231
LaTeXFan
79,387,857
8,772,888
Django 5.1 - UserCreationForm won't allow empty passwords
<p>I'm upgrading a Django 3.0 app to 5.1 and have been moving slowly through each minor release. So far so good.</p> <p>However, once I went from Django 5.0 to 5.1, I saw changed behavior with my &quot;Create New User&quot; page which uses a <code>UserCreationForm</code> form that allows empty passwords. If no passwo...
<python><django><validation><django-forms><passwords>
2025-01-26 01:55:37
1
3,821
ravioli
79,387,481
9,329,400
Python imports from inside the package
<p>I'm trying to use a github repository that I cloned locally.</p> <p>The repo is structured like this:</p> <pre><code>project-name | __init__.py |____project-name | __init__.py | http_service.py | data.py </code></pre> <p>Now I'm trying to import stuff from <code>http_service.py</code>, lik...
<python><import><package>
2025-01-25 20:34:32
0
610
JTB
79,387,290
76,701
Get Click to not expand variables in argument
<p>I have a simple Click app like this:</p> <pre><code>import click @click.command() @click.argument('message') def main(message: str): click.echo(message) if __name__ == '__main__': main() </code></pre> <p>When you pass an environment variable in the argument, it expands it:</p> <pre><code>➜ Desktop python ...
<python><environment-variables><python-click>
2025-01-25 18:35:42
1
89,497
Ram Rachum
79,387,289
7,236,133
Python, filter vectors from Pinecone vector store based on a field saved in the metadata of these vectors
<p>I have vectors stored in a Pinecone vector store, each vector represents a content of a pdf file:</p> <blockquote> <p>Metadata:: hash_code: &quot;d53d7ec8b0e66e9a83a97acda09edd3fe9867cadb42833f9bf5525cc3b89fe2d&quot; id: &quot;cc54ffbe-9cba-4de9-9f30-a114e4c3c3fb&quot;</p> </blockquote> <p>I saved a new field in the...
<python><pinecone>
2025-01-25 18:35:01
2
679
zbeedatm
79,387,277
843,367
How to use single axis title with layer and facet?
<p>I would like to use one single title that goes across facets for the x-axis in this plot. How to do that in python using altair?</p> <p>Apparently, Altair does not provide that functionality.</p> <pre><code>import altair as alt import pandas as pd import textwrap df = pd.DataFrame({ 'y': [10, 20, 30 , 40] , ...
<python><axis><altair>
2025-01-25 18:30:30
1
871
Diogo
79,387,209
6,168,154
Selenium - AttributeError: 'Service' object has no attribute 'get'
<p>With this code below:</p> <pre><code>import requests, os from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager url = &quot;www.google.com&quot; service = ChromeDriverManager().install() folder = os.path.dirnam...
<python><selenium-webdriver><python-3.7>
2025-01-25 17:49:01
2
1,548
Peter.k
79,387,136
4,589,867
sudo + fork + Python subprocess = [Errno 38] Function not implemented
<p>Here's a simplified Python script (henceforth <code>app.py</code>) that forks a child which then runs a subprocess:</p> <pre><code>import os import subprocess if os.fork() &gt; 0: os._exit(0) subprocess.run([&quot;/bin/true&quot;]) </code></pre> <p>When run as a normal user, it works:</p> <pre><code>$ python3 ...
<python><subprocess><sudo>
2025-01-25 17:00:43
1
355
ab.
79,387,009
3,070,181
How to resolve incompatible imports in python and pytest
<p>I have created a project exactly as described by the <a href="https://docs.pytest.org/en/7.1.x/explanation/goodpractices.html#good-integration-practices" rel="nofollow noreferrer">pytest Good Integration Practices documentation</a>, specifically the <a href="https://docs.pytest.org/en/7.1.x/explanation/goodpractices...
<python><pytest>
2025-01-25 15:37:09
1
3,841
Psionman
79,386,829
10,985,257
How to provide tomllib
<p>Since python3.11 we are able to use builtin library <code>tomllib</code> before we had access to third party library <code>tomli</code> and a few others.</p> <p>I did not have analyzed both packages deeply but came to the conclusion, that I am able to replace <code>tomli</code> with <code>tomllib</code> for my purpo...
<python><dependency-management><pyproject.toml>
2025-01-25 13:44:57
1
1,066
MaKaNu
79,386,763
6,936,489
handle invalid encoding sequences in csv with polars
<p>Consider the following snippet:</p> <pre class="lang-py prettyprint-override"><code>from io import TextIOWrapper, BytesIO import polars as pl import pandas as pd csv_str = ( b&quot;spam,egg\n&quot; + &quot;spam,œuf\n&quot;.encode(&quot;cp1252&quot;) + &quot;spam,αυγό\n&quot;.encode(&quot;utf8&quot;) ) c...
<python><character-encoding><python-polars>
2025-01-25 13:04:11
1
2,562
tgrandje
79,386,521
1,744,834
Polars top_k_by with over, k = 1. Bug?
<p>Given the following dataFrame:</p> <pre><code>pl.DataFrame({ 'A': ['a0', 'a0', 'a1', 'a1'], 'B': ['b1', 'b2', 'b1', 'b2'], 'x': [0, 10, 5, 1] }) </code></pre> <p>I want to take value of column <code>B</code> with max value of column <code>x</code> within same value of <code>A</code> (taken from <a href="...
<python><python-polars>
2025-01-25 10:18:03
1
118,326
roman
79,386,183
6,335,363
How can I test that Python package entrypoints are correctly discovered and loaded?
<p>I am currently writing a package that seeks to load <a href="https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#using-package-metadata" rel="nofollow noreferrer">entrypoint contributions</a> from other installed packages using <a href="https://docs.python.org/3/library/importlib.metadata...
<python><pytest><python-packaging>
2025-01-25 04:44:43
1
2,081
Maddy Guthridge
79,386,093
67,153
How to read a file into memory in FastAPI and pass it to MarkItDown library?
<p>The need is to upload a file to a FastAPI endpoint, convert it to Markdown and save the text to Redis (Files are up to 4MB in size).</p> <p>The only logic I have found so far is to upload the file as <code>UploadFile</code>, read the contents, save them to disk with the right extension, pass that path to <a href="ht...
<python><file><fastapi><markitdown>
2025-01-25 02:33:06
2
53,813
Itay Moav -Malimovka
79,386,068
147,530
ImportError: libxxx: cannot open shared object file: No such file or directory
<p>I am trying to build a Python package that interops with C++ code. I created a PyBind11 wrapper to do the interop. I created a setup.py file following the instructions <a href="https://pybind11.readthedocs.io/en/stable/compiling.html#modules-with-setuptools" rel="nofollow noreferrer">here</a>:</p> <pre><code>from py...
<python><setup.py><pybind11>
2025-01-25 02:05:24
0
20,700
morpheus
79,385,866
2,834,978
Numpy array boolean indexing to get containing element
<p>Given a (3,2,2) array how do I get second dimension elements given a single value on the third dimension</p> <pre class="lang-py prettyprint-override"><code>import numpy as np arr = np.array([ [[31., 1.], [41., 1.]], [[63., 1.],[73., 3.]], [[ 95., 1.], [100., 1]] ] ) ref = arr[(arr[:,:,0] &gt; 41.) &am...
<python><numpy>
2025-01-24 23:16:17
3
14,328
LMC
79,385,857
23,570,806
Windows ModuleNotFoundError: No module named 'Crypto' even though pycryptodome is installed
<p>I'm trying to use the pycryptodome library in my Python project, but I keep getting the following error:</p> <pre><code>ModuleNotFoundError: No module named 'Crypto' </code></pre> <p>Here's what I have done so far:</p> <p>I installed pycryptodome using pip:</p> <pre><code>PS C:\Users\Nathan&gt; pip install pycryptod...
<python><python-3.x><windows><pip>
2025-01-24 23:09:15
1
485
Asile34
79,385,719
516,433
Conditionally use an context specific ansible_python_interpreter based on host
<p>I recently ran into a bug where my ansible plays stopped working because RedHat backported <a href="https://access.redhat.com/errata/RHSA-2025:0012" rel="nofollow noreferrer">a CVE patch</a> which was incompatible with the <a href="https://github.com/psf/requests/issues/6707" rel="nofollow noreferrer">python <code>d...
<python><docker><ansible>
2025-01-24 21:48:22
0
15,059
Lucas
79,385,676
13,968,392
Filter with expression expansion
<p>Is it possible to convert the following <code>filter</code>, which uses two conditions, to something that uses expression expansion or a custom function in order to apply the DRY priciple (avoid the repetition)?<br /> Here is the example:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;a&q...
<python><filter><user-defined-functions><python-polars>
2025-01-24 21:29:39
1
2,117
mouwsy
79,385,579
4,296,426
Azure Bot Skill in Copilot doesn't receive event activities in omnichannel live chat widget or SMS channel
<p>I have a fairly simple copilot bot with a python-fastapi azure bot service in azure added as a skill doing passthrough of messages. When I use the <code>send_activities</code> method on the <code>turn_context</code> object, messages come through fine on Omnichannel's live chat widget that they provide for a chat str...
<python><botframework><microsoft-copilot>
2025-01-24 20:38:19
2
1,682
Optimus
79,385,534
7,995,293
Python adaptor for working around relative imports in my QGIS plugin?
<p>I am writing a QGIS plugin. During early development, I wrote and tested the Qt GUI application independently of QGIS. I made use of absolute imports, and everything worked fine.</p> <p>Then, I had to adapt everything to the quirks of QGIS. I can't explain why and haven't been able to find any supporting documentati...
<python><plugins><python-import><pyqgis><relative-import>
2025-01-24 20:16:05
2
399
skytwosea
79,385,532
8,543,025
np.isin fails on pd.Index with multiple dtypes
<p>I noticed this strange behavior, wondering what's happening here:<br /> Say I want to find instances of a numpy array / pandas Index that are included in some predefined list, which has <strong>multiple dtypes</strong>:</p> <pre><code>lst = [&quot;A&quot;, &quot;B&quot;, 1, 2, &quot;C&quot;, 3] test = [&quot;B&quot;...
<python><pandas><numpy>
2025-01-24 20:15:41
0
593
Jon Nir
79,385,374
3,125,823
500 server error with Django Rest Framework
<p>I am using Django/DRF with Djoser and djangorestframework-simplejwt to create an API for full authentication including signup, login, activation, forgot password and reset password.</p> <p>I followed along with this <a href="https://www.youtube.com/watch?v=2pZmxh8Tf78" rel="nofollow noreferrer">YT tutorial</a></p> <...
<python><django><django-rest-framework>
2025-01-24 19:03:36
1
1,958
user3125823
79,385,231
668,624
XRPL-py API - call speed and larger batch retrieval
<p>I am working on an app to retrieve account &amp; balance data from the XRPL mainnet using the XRPL-py API without knowing the account (wallet) information beforehand.</p> <p>Here is link to the XRPL-py API documentation: <a href="https://xrpl-py.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">XRPL-py ...
<python><pagination><xrp><rippled>
2025-01-24 17:53:36
0
11,800
codingknob
79,385,122
673,600
async posting just hangs
<p>I'm using aiohttp to post multiple times, but I find an issue that means that I never get beyond the first post. Code then hangs for a while and produces the below error.</p> <pre><code>async def posted(URL, payload): #'Content-Type': 'application/json'} headers = {'User-Agent': get_random_user_agent(),...
<python><asynchronous><aiohttp>
2025-01-24 17:14:23
0
6,026
disruptive
79,385,026
93,910
Pandas groupby with tag-style list
<p>I have a dataset with 'tag-like' groupings:</p> <pre><code> Id tags 0 item1 ['friends','family'] 1 item2 ['friends'] 2 item3 [] 3 item4 ['family','holiday'] </code></pre> <p>So a row can belong to several groups. I want to create an object similar to groupby, so that I can use agg e...
<python><pandas><dataframe><group-by>
2025-01-24 16:39:08
3
7,056
Sanjay Manohar
79,384,929
4,673,585
Executing stored procedure via python doesn't modify data but via ssms or data studio works
<p>I have a stored procedure in azure sql database which moves data from staging table to target table. When I run the procedure manually, data moves:</p> <pre><code>exec [Construction].[uspProcess] 'Equipment',26 </code></pre> <p>So this procedure moves data for Equipment table from ConstructionStaging.Equipment to Co...
<python><sql-server><sqlalchemy><pyodbc><python-sql>
2025-01-24 16:06:59
0
337
Rahul Sharma
79,384,924
626,804
Python re.sub: backreference in replacement pattern followed by digit
<p>I would like to match a regular expression in a string and add the character <code>0</code> after all occurrences. That is, each match will be replaced with itself followed by <code>0</code>. But because <code>0</code> is a digit, I don't know how to write it in the replacement pattern given as the second argument...
<python><function><python-re><backreference>
2025-01-24 16:05:44
1
1,602
Ed Avis
79,384,811
10,461,632
Issues with Axes (matplotlib) inheritance
<p>I'm trying to mimic the <code>plt.subplots()</code> behavior, but with custom classes. Rather than return <code>Axes</code> from <code>subplots()</code>, I would like to return <code>CustomAxes</code>. I've looked at the source code and don't understand why I am getting the traceback error below.</p> <p>I'm able to ...
<python><python-3.x><matplotlib>
2025-01-24 15:22:22
1
788
Simon1
79,384,474
4,436,517
Polars - Get column value at another column's min / max value
<p>Given the following polars dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl pl.DataFrame({'A': ['a0', 'a0', 'a1', 'a1'], 'B': ['b1', 'b2', 'b1', 'b2'], 'x': [0, 10, 5, 1]}) </code></pre> <pre><code>shape: (4, 3) ┌─────┬─────┬─────┐ │ A ┆ B ┆ x │ │ ...
<python><dataframe><python-polars>
2025-01-24 13:15:46
3
1,159
rindis
79,384,472
2,355,176
Puppeteer not working with Django Viewset
<p>I am trying to write a Django REST endpoint which will convert the HTML content to PDF and then return the Streaming file response to download the report. For this purpose, I am using Puppeteer, which works fine out of Django scope (e.g. for testing purpose). The download view minimal example is following</p> <pre><...
<python><django><puppeteer><python-asyncio>
2025-01-24 13:13:49
0
2,760
Zain Ul Abidin
79,384,448
3,702,377
Issue with downloading file via Browser-use
<p>I am writing web automation to download a file by <code>browser-use</code> web automation tool that uses LLM as an AI Agent. The download files feature isn't supported by the Browser-use as a built-in functionality. That's why I have a complex code to do that. However, sometimes it works well and downloads the file ...
<python><python-asyncio><playwright><playwright-python><browser-use>
2025-01-24 13:05:18
1
35,654
Benyamin Jafari
79,384,404
451,878
Prepared query with Jinja and BigQuery
<p>For now, I use python, with sql templating (jinja2) for BigQuery API (not sdk) + fastapi.</p> <p>The queries are generated from api parameters to sql code. Those queries are sent to BQ.</p> <p>To prevent sql injection, I try the JinjaSQL module, but I can't send the prepared query directly to BQ, I must convert to &...
<python><google-bigquery><jinja2><sql-injection>
2025-01-24 12:51:17
0
1,481
James
79,384,228
8,663,643
Batch insert data using psycopg2 vs psycopg3
<p>Currently i am inserting to postgres database using psycopg2. Data is large and also the write frequency is high, so my database has WAL disabled and few other optimizations for faster writes.</p> <p>When i use <code>psycopg2</code> with execute_values, i am able to write batch of 1000 rows in 0.1-0.15 seconds.</p> ...
<python><postgresql><psycopg2>
2025-01-24 11:45:35
1
2,016
Nitesh Tosniwal
79,383,889
16,869,946
Summing columns of Pandas dataframe in a systematic way
<p>I have a pandas dataframe which looks like this:</p> <pre><code>1_2 1_3 1_4 2_3 2_4 3_4 1 5 2 8 2 2 4 3 4 5 8 5 8 8 8 9 3 3 4 3 4 4 8 3 8 0 7 4 2 2 </code></pre> <p>where the columns are the 4C2 combinations of 1,2,3,4. And I would like to generate 4 new columns <cod...
<python><pandas><dataframe><combinations>
2025-01-24 09:49:07
3
592
Ishigami
79,383,833
865,169
How do I use Pandas' infer_objects correctly (v. 2.2.3)
<p>I try the following example in Pandas 2.2.3:</p> <pre class="lang-py prettyprint-override"><code>outage_mask = pd.Series(([True]*5 + [False]*5)*5, index=pd.date_range(&quot;2025-01-01&quot;, freq=&quot;1h&quot;, periods=50)) [ts for ts in outage_mask.loc[outage_mask.diff().fillna(False)].index] </code></pre> <p>This...
<python><pandas>
2025-01-24 09:27:40
2
1,372
Thomas Arildsen
79,383,692
4,442,753
How to get start indices of regions of empty intervals?
<p>I have sorted start indices (included) and end indices (excluded) of intervals (obtained by using <code>seachsorted</code>), for instance:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # Both arrays are of same size, and sorted. # Size of arrays is number of intervals. # Intervals do not ov...
<python><numpy>
2025-01-24 08:34:24
1
1,003
pierre_j
79,383,586
4,382,391
langchain / Chroma Process finished with exit code -1073741819 (0xC0000005) with
<p>I am stumped with this problem</p> <pre class="lang-py prettyprint-override"><code>chunks = [] for path in file_paths: # path is a string filepath to a csv chunks.extend(self.chunk_data(path)) chunks = filter_complex_metadata(chunks) # add all relevant documents to chunks # creates a unique cache for this datase...
<python><langchain><access-violation><chromadb>
2025-01-24 07:43:15
0
1,070
Null Salad
79,383,492
48,956
How to handle infinity timestamptz?
<p>Executing:</p> <pre><code>await pg_acursor.execute(&quot;SELECT * FROM pg_roles;&quot;) await pg_acursor.fetchall() </code></pre> <p>...</p> <pre><code>  File &quot;/usr/local/lib/python3.10/site-packages/psycopg/cursor_async.py&quot;, line 235, in fetchall     records = self._tx.load_rows(self._pos, self.pgresult.n...
<python><postgresql><psycopg2><psycopg3>
2025-01-24 07:03:24
1
15,918
user48956
79,383,447
12,466,687
How to convert a plotnine chart to matplotlib in python?
<p>I have created a chart using <code>plotnine</code> and want to put this into <code>matplotlib</code> to combine it with other plots but I am unable to convert it into matplotlib form.</p> <p>Here is the Reference <a href="https://nrennie.rbind.io/2024-plotnine-contest/" rel="nofollow noreferrer">article</a> where th...
<python><matplotlib><plotnine>
2025-01-24 06:39:03
1
2,357
ViSa
79,383,240
1,232,087
Pandas works in terminal of VSCode but fails in code window of VSCode
<pre><code>Windows 10 Pro VSCode latest version Python 3.12 [selected as python interpreter] Pandas latest version 2.2.3 Virtual Environment created and pandas installed inside it </code></pre> <p><strong>Question</strong>: As shown below, following code works in <code>VSCode Terminal</code> but not inside the code win...
<python><pandas><visual-studio-code>
2025-01-24 04:39:56
0
24,239
nam
79,383,195
3,719,167
Django: How to Represent and Query Symmetrical Relationships for a Family Tree?
<p>I am building a family tree application in Django where I need to represent and query marriages symmetrically. Each marriage should have only one record, and the relationship should include both partners without duplicating data. Here's the relevant model structure:</p> <pre class="lang-py prettyprint-override"><cod...
<python><django><many-to-many><django-orm>
2025-01-24 03:59:22
1
9,922
Anuj TBE
79,383,056
11,062,613
How to optimize Delta Lake datasets in Polars (sorting, compaction, cleanup)?
<p>I'm planning to use Polars with Delta Lake to manage large, mutable datasets on my laptop. I've encountered two issues:</p> <ol> <li><p>Dataset is not sorted after merge: When I use write_delta() in &quot;merge&quot; mode, the resulting dataset is not sorted. My current workaround is to manually sort and overwrite t...
<python><parquet><python-polars><delta-lake>
2025-01-24 01:53:03
1
423
Olibarer
79,382,814
15,412,256
How to manually set certain dependecies in local dev enviorment for UV Python dependency manager to ignore?
<p>Currently I have the following pyproject.toml:</p> <pre class="lang-ini prettyprint-override"><code>[project] name = &quot;sample_project&quot; version = &quot;0.1.0&quot; description = &quot;Add your description here&quot; readme = &quot;README.md&quot; requires-python = &quot;&gt;=3.12&quot; dependencies = [ ...
<python><pyproject.toml><uv>
2025-01-23 22:57:26
1
649
Kevin Li
79,382,803
13,982,768
I am trying to cause race condition for demonstration purposes but fail to fail
<p>I am actively trying to get race condition and cause problem in calculation for demonstration purposes but i can't achieve such problem simply.</p> <p>My tought process was to create a counter variable, reach it from diffrent threads and async functions (i did not tried mp since it pauses process) and increase it by...
<python><python-3.x><multithreading><asynchronous><race-condition>
2025-01-23 22:51:57
1
367
Onuralp Arslan
79,382,718
567,493
How can I solve the "unexpected namespace: local" xray issue?
<p>I'm running an xray daemon on an ec2-backed ecs cluster, and I'm getting this in the xray daemon's cloudwatch logs:</p> <blockquote> <p>warn awsxrayreceiver@v0.78.0/receiver.go:116 X-Ray segment to OT traces conversion failed {&quot;kind&quot;: &quot;receiver&quot;, &quot;name&quot;: &quot;awsxray&quot;, &quot;d...
<python><aws-xray>
2025-01-23 22:09:46
0
2,267
davidpricedev
79,382,572
9,191,460
Condensing a Python method that does a different comparison depending on the operator passed
<p>I am trying to write a method that evaluates a statement, but the operator (&gt;, &lt;, =) is sent by the user. I am wondering if there is a easy way to write a more concise method.</p> <p>The simplified version of the code is:</p> <pre><code>def comparsion(val1: int, val2: int, operator: str): if operator == ...
<python>
2025-01-23 21:09:04
4
3,035
Rui Nian
79,382,453
1,850,165
subprocess.Popen: how to proper communicate in an interactive way?
<p>I'm working on an app that requires a conversational interaction with an external process, simulated here by the terminal calculator <code>bc</code>: I send something to stdin, and I get the response via stdout, or stderr if an error occurs. However, the proc quits when a non-fatal error occurs.</p> <p>Below is a sn...
<python><subprocess><popen>
2025-01-23 20:13:57
2
374
fabiog1901
79,382,350
10,319,707
How can I make a task dependent on another, but also only run at a certain time?
<p>I have two tasks.</p> <ol> <li>T05:30 - I wish for this to run at 05:30 every day.</li> <li>T08:30 - I wish for this to run at 08:30 every day, but only if T05:30 has succeeded today.</li> </ol> <p>Can this be achieved in Airflow? It appears that dependencies (i.e. run T8:30 only if only if T05:30 has succeeded toda...
<python><airflow><task><scheduled-tasks><directed-acyclic-graphs>
2025-01-23 19:30:05
1
1,746
J. Mini
79,382,089
12,466,687
How to get rid of extra row spaces from a facet plot with multiple Categories and sub categories in plotnine?
<p>I have created a <code>facet</code> plot as I am not sure how to do this without facet but I am open to alternate ways of doing this.</p> <p>I have a column with <code>parent category</code> and another column with <code>sub categories</code>.</p> <p><strong>Dummy Data:</strong></p> <pre><code>import pandas as pd n...
<python><plotnine>
2025-01-23 17:47:05
1
2,357
ViSa
79,381,979
11,895,146
How to avoid closed wait sessions that come from huge numbers of HTTP requests?
<p>We run thousands of Python scripts on our RHEL machines that open and close socket connections on port 8088. As a result, we are facing a high volume of HTTP requests.</p> <p>Here is very simple example of one of the scripts:</p> <pre><code>import socket import requests def get_yarn_details(state='RUNNING'): st...
<python><http><sockets><tcp><hadoop-yarn>
2025-01-23 17:08:28
0
2,640
jessica
79,381,751
243,031
enable socket level logging in uwsgi server
<p>Applicaiton is running on <code>uwsgi+DJango rest framework</code> and there is <code>httpd</code> server in front of the <code>uwsgi</code> service.</p> <p><code>httpd</code> server forward the request to <code>127.0.0.1:9000</code> <code>ProxyPass /myapi uwsgi://127.0.0.1:9000</code></p> <p>There is <code>uwsgi</c...
<python><apache><sockets><uwsgi>
2025-01-23 15:56:32
0
21,411
NPatel
79,381,694
14,463,396
sqlalchemy - This result object does not return rows despite using SET NOCOUNT ON
<p>I have a query that returns data in Miscrosoft SQL server management studio, but I'm getting the following error when trying to read in a query using pandas:</p> <pre><code>sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. </code></pre> <p>I from similar q...
<python><pandas><sqlalchemy>
2025-01-23 15:41:47
1
3,395
Emi OB
79,381,686
1,406,168
ImportError: Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage even after adlsf is installed
<p>I have an azure function with code below:</p> <pre><code>storage_account_url = f&quot;{self.datalake_settings.xx}/{parquet_folder_path}/{file_name}.parquet&quot; storage_options = { &quot;account_name&quot;: self.datalake_settings.xx, &quot;client_id&quot;: self.datalake_settings.xx, &quot;client_secret&...
<python><pandas><dataframe><azure-functions><azure-data-lake>
2025-01-23 15:38:42
1
5,363
Thomas Segato
79,381,630
3,941,671
Efficient way to cyclically update data of a class instance already saved on disk
<p>There is a class <code>Class</code> containing an initial empty list <code>list</code> and a method to add an element to the list. Each time an element was added to the list the whole instance should be saved to disk. So in most cases the already saved data only needs to be extended by the data of the last added ele...
<python><python-3.x><pickle>
2025-01-23 15:20:42
1
471
paul_schaefer
79,381,460
12,974,570
WebSocket recv() Call Not Timing Out Despite Setting Timeout in Python
<p>I'm working on a project where I need to receive messages from a WebSocket server using Python. I'm using the websocket library and have set a timeout for the recv() call, but it seems to be ignored, as the call hangs indefinitely without throwing a timeout exception.</p> <p>Here is the minimum working example of my...
<python><network-programming><websocket><timeout>
2025-01-23 14:24:27
0
1,229
Johannes Walter
79,381,326
3,825,996
Conceptual issues about responsibility with classmethod factories for inheritance in Python
<p>As far as I understand, the difference between <code>@classmethod</code> and <code>@staticmethod</code> is the <code>cls</code> parameter which is used so a class can construct instances of subclasses. I have encountered some issues with that concept while trying to develop a library. An example:</p> <pre class="lan...
<python><inheritance><class-method>
2025-01-23 13:47:56
1
766
mqnc
79,381,256
1,593,077
How to "fold" python files used as modules into the main script file?
<p>Suppose I have two Python script files: <code>foo</code> and <code>utils/bar.py</code> in some directory. In <code>foo</code>, I have:</p> <pre><code>import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) from utils.bar import func1, func2 # ... code using func1 or func2 # ... perhaps som...
<python><python-module><single-file>
2025-01-23 13:29:41
3
137,004
einpoklum
79,381,037
4,891,717
How to interpolate a multidimensional xarray DataArray?
<p>I am using the <code>xarray</code> library and I have some doubts/questions.</p> <p>I have this dataset::</p> <pre class="lang-none prettyprint-override"><code>ds &lt;xarray.Dataset&gt; Size: 2GB Dimensions: (Latitude: 364, Longitude: 246, Lon_u: 247, Lat_v: 364, Time: 1087) Coordinate...
<python><multidimensional-array><dataset><interpolation><python-xarray>
2025-01-23 12:29:37
0
9,732
ChesuCR
79,381,028
2,066,083
Why can't subfigures be nested in gridspecs to keep their suptitles separate in matplotlib?
<p>I would expect this code:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 6)) fig_gridspec = fig.add_gridspec(1, 1) top_subfig = fig.add_subfigure(fig_gridspec[(0, 0)]) top_subfig.suptitle(&quot;I am the top subfig&quot;) top_subfig_gridspec = top_subfig.add_gridspec(1, 1, top=.7) n...
<python><matplotlib>
2025-01-23 12:27:50
3
937
Katie
79,380,860
1,480,018
Python parse id attribute instead of element from xml
<p>This python code processed some XML data as shown in the comment</p> <pre><code># &lt;members&gt;&lt;id&gt;26&lt;/id&gt;&lt;name&gt;Alexi Delano&lt;/name&gt;&lt;id&gt;27&lt;/id&gt;&lt;name&gt;Cari Lekebusch&lt;/name&gt;&lt;/members&gt; def element_members(self, element): for id, name in grouper([child.te...
<python><xml>
2025-01-23 11:31:45
1
13,362
Paul Taylor
79,380,831
4,247,599
Python redirect logger to print (without repeating output when executing in a jupyter notebook)
<p>I found already how to <a href="https://stackoverflow.com/questions/11124093/redirect-python-print-output-to-logger">re-direct print to logger</a>, though I would like to do the other way around, so that the logger output will be also printed to console, and will be shown when running the code from jupyter notebooks...
<python><python-3.x><logging>
2025-01-23 11:23:03
0
4,299
SeF
79,380,723
6,623,277
Relationships are both of the same direction when declaring two-way foreign keys
<p>For my ORM classes <code>Trade</code>, <code>Order</code> and <code>Account</code> (of stock markets) I want <code>Order</code> and <code>Trade</code> linked to each other by a foreign key, while setting the column in order to be nullable (an order may not have a trade). But SQL Alchemy complains about relationships...
<python><python-3.x><sqlite><sqlalchemy><orm>
2025-01-23 10:50:24
0
2,077
KCK
79,380,706
7,887,965
ValueError: text input must be of type `str` (single example), `List[str]` (batch or single pretokenized example)
<p>I am trying to fine tune <code>vision llm model</code> like <code>Qwen/Qwen2-VL-7B-Instruct</code>. I have the following dataset in <code>.jsonl</code> file</p> <pre><code>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot...
<python><large-language-model>
2025-01-23 10:43:48
0
407
Filbadeha