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,491,408
5,660,533
AsyncMock not working when mocked using SQLAlchemy in FastAPI
<p>I'm testing a FastAPI service that queries a database using SQLAlchemy's async execution. However, when I mock the database query, execute().scalars().all() returns an empty list instead of the expected [1, 2, 3].</p> <pre><code>async def retrieve_relevant_docs(session: AsyncSession, query: str, top_k: int): res...
<python><asynchronous><sqlalchemy><mocking><fastapi>
2025-03-07 06:07:36
0
740
Rohit Kumar
79,491,327
8,896,855
boto3 resource connection fail
<p>I haven't found any mention anywhere of a similar problem, but I am having difficulty connecting to an AWS SQS queue when using the boto3 library. When I connect to a boto3 resource in a program (polling application), it exits unexpectedly without any reported error. However, when I access the same queue in an int...
<python><boto3>
2025-03-07 05:16:20
1
608
AlecZ
79,491,308
1,629,527
Airbyte and langchain dependencies not compatible
<p>I am using <em>poetry</em> to manage the python project dependencies. When I try to install airbyte using command <code>poetry add airbyte</code> it throws below error:</p> <pre><code>Because no versions of airbyte-cdk match &gt;6.28.0,&lt;6.29.0 || &gt;6.29.0,&lt;6.29.1 || &gt;6.29.1,&lt;6.30.0 || &gt;6.30.0,&lt;6....
<python><langchain><python-poetry><airbyte>
2025-03-07 05:01:44
0
6,210
dd619
79,491,294
17,275,378
SqlAlchemy Table Object Doesn't Synchronise with BigQuery
<p>I'm reading data from <code>Google BigQuery</code> into a <code>polars</code> dataframe. Using a string query succeeds. I'd prefer to use an alchemy statement. Using <code>python-bigquery-sqlalchemy</code> provided by Google and following their <a href="https://github.com/googleapis/python-bigquery-sqlalchemy" rel="...
<python><google-bigquery><sqlalchemy><python-polars>
2025-03-07 04:50:41
1
326
eldrly
79,491,182
8,278,075
FastAPI using GET with alias params
<p>I want to serve a GET endpoint with a Pydantic BaseModel but a body is expected in the GET.</p> <pre class="lang-py prettyprint-override"><code>def convert_to_camel_case(string: str) -&gt; str: new_word = [] splitted = string.split(&quot;_&quot;) new_word.append(splitted[0]) for word in splitted[1:...
<python><fastapi><pydantic>
2025-03-07 03:16:18
0
3,365
engineer-x
79,491,063
9,232,275
LangChain AgentExecutor invoke() doesn't return multiline output
<p>I found that I'm only seeing the result as the last message output, instead of the full response. Here's an example that surprised me.</p> <p>I'm new to LangChain (though I've use LlamaIndex). Is it the case that this is just deprecated now in favor of LangGraph, or should I be always using streaming since one never...
<python><langchain><langchain-agents>
2025-03-07 01:42:50
0
402
Charles Thayer
79,491,031
6,227,035
Google Calendar - get an event by ID in python script
<p>I have created an event on Google calendar in python using these lines:</p> <pre><code>service = build('calendar', 'v3', credentials=credentials) now = datetime.datetime.utcnow().isoformat() + 'Z' events_result = service.events().list(calendarId='primary', timeMin=now, maxRe...
<python><get><calendar>
2025-03-07 01:13:04
1
1,974
Sim81
79,490,968
6,213,809
Access other columns in ibis across
<p>Is there any way to access other columns inside an ibis aggregate statement using across? I created a bunch of boolean columns using mutate across, but I want to sum another column (<code>df. net_spend_amount</code>) if the boolean column (<code>s.matches(&quot;is_pre|is_post&quot;)</code>) is True.</p> <pre class="...
<python><dataframe><ibis>
2025-03-07 00:06:07
1
896
Mark Druffel
79,490,852
3,078,473
Selenium Handshake Failed (new version of Selenium)
<pre><code>options1 = webdriver.ChromeOptions() options1.add_argument('--ignore-certificate-errors') options1.add_argument('--ignore-ssl-errors') driver = webdriver.Chrome(options=options1) </code></pre> <p>[14816:10204:0306/172921.348:ERROR:ssl_client_socket_impl.cc(877)] handshake failed; returned -1, SSL error code ...
<python><selenium-webdriver>
2025-03-06 22:37:28
0
419
JackOfAll
79,490,841
5,937,757
Snowflake ML Registry for Model Explainability: `ValueError: Model type <class 'NoneType'> is not supported` when logging a Pipeline
<p>I am training an <strong>XGBClassifier model using Snowflake ML</strong> and attempting to register it using <strong>Snowflake’s model registry</strong>. The training and evaluation steps complete successfully, but when I try to log the model using <code>log_model()</code>, I get the following error:</p> <pre><code>...
<python><machine-learning><snowflake-cloud-data-platform>
2025-03-06 22:28:30
1
423
mas
79,490,818
4,463,825
Function with two variables - Polynomial fit Python
<p>I have various pump performance data, and I am trying to fit curves as a combination of them.</p> <p>In below image, different curves are at different pump speeds (RPM), and the Y axis is Pressure head, and X axis is flow rate.</p> <p>I am trying to figure out the following functions:</p> <pre><code>pressure = func ...
<python><scipy><regression><curve-fitting>
2025-03-06 22:15:10
2
993
Jesh Kundem
79,490,815
4,710,409
ValueError: axes don't match array when trying to transpose
<p>I'm fetching a frame correctly from webcam:</p> <pre><code>success, image = self.video.read() </code></pre> <p>But when I try to change the mode of my frame to grayscale using the following code:</p> <pre><code>gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) </code></pre> <p>I get the following error:</p> <pre>...
<python><numpy><opencv><image-processing><valueerror>
2025-03-06 22:13:01
1
575
Mohammed Baashar
79,490,645
7,437,143
How to write an integration test on an urwid tui?
<p>While trying to test a urwid-based question with input validation and autocomplete suggestions, I am experiencing some difficulties. The code that I am trying to test using <code>pytest</code> is given in the two files below:</p> <h2>InputValidationQuestion.py</h2> <pre class="lang-py prettyprint-override"><code>fro...
<python><testing><integration-testing><tui><urwid>
2025-03-06 20:40:54
1
2,887
a.t.
79,490,610
2,700,041
How do I get google/gemma-2-2b to strictly follow my prompt in Hugging Face Transformers?
<p>I'm using the following code to send a prompt to the &quot;google/gemma-2-2b&quot; model via Hugging Face's Transformers pipeline:</p> <pre><code>from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline import torch HUGGINGFACE_TOKEN = &quot;&lt;my-token&gt;&quot; model_name = &quot;google/gemma-2-2b...
<python><prompt><large-language-model>
2025-03-06 20:24:34
1
1,427
hanugm
79,490,573
8,075,540
Field validator not called on SQLModel
<p>I have a FastAPI setup of the form:</p> <pre class="lang-py prettyprint-override"><code>class Foo(sqlmodel.SQLModel, table=True): id: typing.Optional[int] = sqlmodel.Field(primary_key=True) data: str @pydantic.field_validator(&quot;data&quot;, mode=&quot;before&quot;) def serialize_dict(cls, value):...
<python><pydantic><sqlmodel>
2025-03-06 20:06:58
1
6,906
Daniel Walker
79,490,493
5,660,533
AsyncMock Returns Empty List When Mocking SQLAlchemy Async Execution in FastAPI
<p>I have an app that basically ingests documents, stores their embeddings in vector form, then responds to queries that relate to the ingested docs.</p> <p>I have this retrieval.py function which searches through ingested and selected documents and returns which files have matching vectors.</p> <p>I'm testing a FastAP...
<python><sqlalchemy><mocking><pytest><fastapi>
2025-03-06 19:36:40
1
740
Rohit Kumar
79,490,103
72,437
Ensuring Successful File Uploads to S3 Using Presigned URLs
<p>Previously, I used the following approach to allow users to upload files to our cloud storage service:</p> <ol> <li>Server-side (Python): Generate a time-limited presigned upload URL.</li> <li>Client-side (Java): Upload the file using the presigned URL.</li> </ol> <h2>Java Code: Uploading a File</h2> <pre><code>priv...
<python><java><amazon-s3>
2025-03-06 16:49:40
0
42,256
Cheok Yan Cheng
79,490,056
366,628
compute named quantiles in pandas using groupby aggregate
<p>Among other descriptive statistics, I want to get some quantiles out of my pandas <code>DataFrame</code>. I can get the quantiles I want a couple of different ways, but I can't find the right way to do it with <code>aggregate</code>. I'd like to use aggregate because it'd be tidy and maybe computationally efficient ...
<python><pandas><group-by><aggregate>
2025-03-06 16:34:51
2
2,177
flies
79,490,048
52,791
Placing a Bull Put Spread order with IBKR's TWS API using ibapi
<p>I'm playing around with IBKR's ibapi library using the TWS API, and trying to make a simple script that will place a Bull Put Spread order.</p> <pre class="lang-none prettyprint-override"><code>from ibapi.wrapper import EWrapper from ibapi.contract import Contract from ibapi.order import Order import threading impor...
<python><interactive-brokers><tws>
2025-03-06 16:31:48
1
787
Rhys Causey
79,489,971
1,999,873
Assign numpy array to duckdb array column in where clause
<p>How do I update a duckdb array column with the value from a numpy array (returned from a python function) in a line where a where-clause matches?</p> <p>In the example I want to assign the value of <code>new_array</code> in the second line in the table example, that is the line in which <code>WHERE id = 2</code> mat...
<python><arrays><duckdb>
2025-03-06 16:07:56
1
2,662
snaut
79,489,931
2,532,408
Can you perform WebDriverWait in an ActionChain?
<p>I often build ActionChains to interact with MUI components. Here is one that enters the date <code>MM/DD/YYYY</code> but ensures we start typing in the MM portion of the input. I have to wait for the animation of the field label to move out of the way before the input will accept anything.</p> <pre class="lang-py ...
<python><selenium-webdriver><material-ui><mui-x-date-picker>
2025-03-06 15:52:34
2
4,628
Marcel Wilson
79,489,878
11,793,491
My modal doesn't appear after an action in Streamlit
<p>I have this Streamlit app:</p> <pre class="lang-python prettyprint-override"><code>import streamlit as st st.title(&quot;Simulator&quot;) tab_names = [&quot;tab1&quot;, &quot;tab2&quot;] tab1, tab2= st.tabs(tab_names) @st.dialog(&quot;Edit your relationships&quot;) def edit_relationships(result): edit_option...
<python><streamlit>
2025-03-06 15:36:41
2
2,304
Alexis
79,489,723
3,259,331
Why is this python code not running faster with parallelization?
<p>This is a MWE of some code I'm writing to do some monte carlo exercises. I need to estimate models across draws and I'm parallelizing across models. In the MWE a &quot;model&quot; is just parametrized by a number of draws and a seed.</p> <p>I define the functions below.</p> <pre><code>import time import pandas as pd...
<python><python-3.x><pandas><numpy><multiprocessing>
2025-03-06 14:45:25
2
1,601
jtorca
79,489,716
15,452,168
Download Confluence Pages as PDFs via API using Python
<p>I’m trying to download Confluence pages in a space as PDFs using the Confluence API and a Python script. However, I am unable to download the PDF despite manually being able to export pages via the browser.</p> <p>Goal: Download all pages in a Confluence space (in a hierarchy) as PDF files using Python and an API ke...
<python><confluence><confluence-rest-api>
2025-03-06 14:44:44
0
570
sdave
79,489,702
9,548,525
Is there a Numpy method or function to split an array of uint64 into two arrays of uint32
<p>Say I have an array as follows:</p> <pre><code>arr = np.asarray([1, 2, 3, 4294967296, 100], dtype=np.uint64) </code></pre> <p>I now want two arrays, one array with the lower 32 bits of every element, and one with the upper 32 bits of every element, preferably by using views and minimizing copies, to get something li...
<python><numpy><performance><optimization><numpy-ndarray>
2025-03-06 14:37:32
1
360
lrdewaal
79,489,599
5,931,672
ValueError: Expected x_min for bbox to be in the range [0.0, 1.0]
<p>I am using albumentations for my object detection data augmentation because it deals with bbox at the same time. My format is [xmin, ymin, xmax, ymax] with <a href="https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#pascal_voc" rel="nofollow noreferrer">pascal_voc format</a>.</p> <pre class=...
<python><albumentations>
2025-03-06 13:55:42
1
4,192
J Agustin Barrachina
79,489,528
16,389,095
How to show horizontal scroll bar into a python flet datatable
<p>I developed a simple code in Python Flet that consists of a <a href="https://flet.dev/docs/controls/datatable" rel="nofollow noreferrer"><code>DataTable</code></a> added to a Row, inserted into a Column. These nested controls are added into a container with dimensions that don't allow to display all the table conten...
<python><flutter><scroll><scrollbar><flet>
2025-03-06 13:29:48
1
421
eljamba
79,489,313
5,316,326
Join large partitioned parquet datasets in Polars and write to Postgres?
<p>I have two large datasets stored in partitioned Parquet format on S3, partitioned by <code>category_id</code>. I need to join them on <code>category_id</code> and <code>label_id</code> using Polars and write the results to Postgres.</p> <h2>The problem:</h2> <ul> <li>Data is too large for memory: Calling <code>.coll...
<python><postgresql><python-polars>
2025-03-06 12:13:46
2
4,147
Joost Döbken
79,489,177
8,264,511
Issues Running Code Chunks in Quarto on Positron
<p>Read more in <a href="https://github.com/quarto-dev/quarto-cli/discussions/12248" rel="nofollow noreferrer">GH discussion</a>.</p> <p>I’m encountering issues using <strong>Quarto</strong> within <strong>Positron</strong> when trying to include R or Python code chunks in my .qmd documents. When I run the quarto previ...
<python><r><quarto><positron>
2025-03-06 11:24:59
0
389
Erik De Luca
79,489,137
4,105,440
Nested parallelism with GridSearchCV causes infinite hang
<p>I'm running a <code>GridSearchCV</code> optimization into a parallelized function. The pseudocode looks like this</p> <pre class="lang-py prettyprint-override"><code>from tqdm.contrib.concurrent import process_map from sklearn.model_selection import GridSearchCV def main(): results = process_map(func, it, max_w...
<python><scikit-learn><multiprocessing><joblib><gridsearchcv>
2025-03-06 11:14:08
1
673
Droid
79,488,914
17,795,398
How to use typeguard for numpy structured arrays?
<p>I want to implement functions that act on specific numpy structured arrays, but typeguard doesn't seem to work properly:</p> <pre><code>import numpy as np from typeguard import typechecked mytype2 = np.dtype([(&quot;type&quot;, int), (&quot;pos&quot;, float, 2)]) mytype3 = np.dtype([(&quot;type&quot;, int), (&quot;...
<python><numpy><python-typing>
2025-03-06 09:50:29
2
472
Abel Gutiérrez
79,488,683
2,695,990
How to avoid "object has no attribute 'isAlive'" error while debugging in IntelliJ using Python plugin version 241.18034.62
<p>I am writing a simple project in python. My version of python is: 3.13.1 . I am using IntelliJ and Python plugin with version: 241.18034.62. I would like to debug my project but when I try to debug I am getting many errors:</p> <pre><code>AttributeError: '_MainThread' object has no attribute 'isAlive'. Did you mean:...
<python><debugging><intellij-idea><pycharm>
2025-03-06 08:28:35
3
3,174
fascynacja
79,488,423
5,937,757
Snowflake ML: `There is no method with name explain available in the model`
<h3>Issue:</h3> <p>I'm working with <code>snowflake-ml-python</code> and trying to use the <code>explain</code> function on an XGBoost model deployed in Snowflake. However, I get the following error when calling <code>run</code> with <code>function_name=&quot;explain&quot;</code>:</p> <pre class="lang-py prettyprint-ov...
<python><snowflake-cloud-data-platform>
2025-03-06 06:20:23
2
423
mas
79,488,214
3,161,801
Blender API Question - rotation about center of object
<p>I am running the following code. I would like to rotate the selected blocks about the x-axis in the center. However, it is rotating about the corner. Can I ask for assistance?</p> <pre><code>import bpy from mathutils import Matrix, Vector import math angle = math.radians(45) for obj in bpy.data.objects: if(o...
<python><blender>
2025-03-06 03:46:12
1
775
ffejrekaburb
79,487,911
145,504
Deriving path of Python Scripts folder on Windows
<p>I installed Python 3.13 on Windows 11 with</p> <pre><code>winget install python3 --scope machine` </code></pre> <p>Then I installed <code>pip</code> with</p> <pre><code>python -m ensurepip </code></pre> <p>This puts <code>pip</code> in <code>%APPDATA\Python\Python313\site-packages</code>. Since this directory is in ...
<python><windows><pip>
2025-03-05 23:30:37
1
4,458
rgov
79,487,849
1,788,656
Expanding numpy based code that detect the frequency of the consecutive number to work on multidimensional array instead of 1D array
<p>This <a href="https://stackoverflow.com/questions/79483656/vectoring-nested-while-statements-block-that-detects-the-frequency-of-consecutiv/79483704?noredirect=1">stackoverflow answer</a> provides a simple way (below) to find the frequency and indices of consecutive repeated numbers. This solution is much faster tha...
<python><numpy>
2025-03-05 22:43:40
1
725
Kernel
79,487,761
11,850,322
how to execute notebook in different namespace
<p>Let say I have two notebooks:</p> <ul> <li>nba.ipynb</li> <li>nbb.ipynb</li> </ul> <p>In notebook A, I try to run: <code>%run -n nbB.ipynb</code> so that the two notebooks are running in two different namespace. However, after execute <code>%run -n nbB.ipynb</code>, it still overwrite on my <code>x</code>, <code>y</...
<python><jupyter-notebook><jupyter-lab>
2025-03-05 21:42:49
0
1,093
PTQuoc
79,487,738
2,398,143
Not able to generate graphviz when runing on Mac
<p>I have followed the recommended steps:</p> <ul> <li>Installed graphviz on mac using <code>brew install graphviz</code>. Please see below.</li> </ul> <pre><code>ls /usr/local/Cellar/graphviz/12.2.1/bin/ acyclic diffimg dot_sandbox graphml2gv gvmap gxl2gv patchwork twopi bcomps dijkstra e...
<python><python-3.x><graphviz><dot>
2025-03-05 21:30:17
1
2,183
AnilJ
79,487,515
11,063,709
In Gymnasium, how can one run a vector environment's function in parallel similar to how step() can be run in parallel?
<p>I have a custom Gymnasium environment, <code>RLToy-v0</code> from the library <a href="https://github.com/automl/mdp-playground" rel="nofollow noreferrer">MDP Playground</a>. It separates out the transition function and reward function from the step function and calls them individually inside <code>step()</code>.</p...
<python><reinforcement-learning><gymnasium>
2025-03-05 19:40:07
0
1,442
Warm_Duscher
79,487,486
6,651,940
How can I extract absolute beta coefficients for all levels of multiple categorical variables in statsmodels?
<p>I’m performing linear regression in Python with statsmodels. I have two categorical predictors:</p> <ul> <li>sample: a factor with 8 levels</li> <li>distractor: a factor with 2 levels</li> </ul> <p>My goal is to determine the “absolute” beta (effect) for each level of each variable. When I fit the model with an inte...
<python><linear-regression><statsmodels>
2025-03-05 19:23:39
0
1,130
Blade
79,487,231
438,758
How to generate a PDF with a grid of images per page?
<p>Our work involves visually inspecting a number of plots together. All plots of same size. we want to print them in pages to study. Something like a 8.5&quot;x11&quot; paper with 1&quot; margin gives me a 7.5&quot;x10&quot; space with 3:4 aspect ratio. This space can be filled with 9 or 16 images each of the same asp...
<python><macos><image><pdf>
2025-03-05 17:20:41
4
7,215
BiGYaN
79,486,991
20,591,261
How to add a new level to JSON output using Polars in Python?
<p>I'm using Polars to process a DataFrame so I can save it as JSON. I know I can use the method <code>.write_json()</code>, however, I would like to add a new level to the JSON.</p> <p>My current approach:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;id&quot;:...
<python><python-polars>
2025-03-05 15:46:06
1
1,195
Simon
79,486,984
6,195,489
Get an array containing differences between two NumPy arrays with some members the same
<p>I have two very large NumPy arrays containing coordinates [[x1,y1,z1],[x2,y2,z2]...] (~10^9 elements)</p> <p>The arrays are of different sizes, and there will be overlap between the coordinates. So [x1,y1,z1] may be in array1, but not in array2.</p> <p>I would like to quickly get all of the coordinates that are in o...
<python><arrays><numpy>
2025-03-05 15:44:05
1
849
abinitio
79,486,908
7,124,155
How can I use a PySpark UDF in a for loop?
<p>I need a PySpark UDF with a for loop to create new columns but with conditions based on the iterator value.</p> <pre><code>def test_map(col): if x == 1: if col &lt; 0.55: return 1.2 else: return 0.99 elif x == 2: if col &lt; 0.87: return 1.5 ...
<python><pyspark><databricks>
2025-03-05 15:11:49
2
1,329
Chuck
79,486,685
4,451,315
Cumulative sum of one array in order defined by other array without doing 2 sort operations
<p>I have two numpy arrays:</p> <pre><code>import numpy as np arr1 = np.array([1,4,2,5,6,3,2]) arr2 = np.array([1,0,2,4,3,6,5]) </code></pre> <p>I would like to find the cumulative sum of <code>arr1</code> according to the order defined in <code>arr2</code>. Expected output:</p> <pre><code>array([ 5, 4, 7, 18, 13, 23...
<python><numpy>
2025-03-05 13:46:58
2
11,062
ignoring_gravity
79,486,249
16,389,095
How to stop updating a control during route change
<p>I developed a simple app using Python Flet 0.21.2. The app consists into two main views: the 'Welcome' and the 'Login', each of them defined into separate classes. Routing occurs into the main() function, in the route_change event, in which the 'views_manager()' is called. The 'Welcome' view implements a simple UI, ...
<python><flutter><user-interface><flet>
2025-03-05 10:55:12
1
421
eljamba
79,486,046
948,655
VSCode and Python virtualenv troubles
<p>I have 2 problems. Here <em>was</em> my set-up. I have all of my respositories in <code>~/dev/</code>, and I had all of my Python virtualenvs in <code>~/virtualenvs/</code>. This worked OK, but one annoying thing was that it was difficult to switch between virtualenvs, because for some reason VSCode doesn't automati...
<python><visual-studio-code><virtualenv><pylance>
2025-03-05 09:50:11
2
8,813
Ray
79,485,999
5,013,037
Gunicorn / Uvicorn extremely rare 502 Errors
<p>We observed an issue with our containerized Python FastAPI application, which we deploy using Gunicorn and Uvicorn on Kubernetes. In extremely rare cases (~1 in 100.000) a single request seem to be silently dropped / not correctly processed by the the gunicorn master process or the uvicorn workers. My nginx reverse ...
<python><nginx><fastapi><gunicorn><uvicorn>
2025-03-05 09:30:09
0
364
fragant
79,485,854
4,473,615
Not a valid OPENSSH private key file - Paramiko
<p>I'm trying to connect to a host using paramiko. I'm able to successfully connect to the host through winscp using the private key, but the script fails with below error</p> <p><strong>raise SSHException(&quot;not a valid {} private key file&quot;.format(tag)) paramiko.ssh_exception.SSHException: not a valid OPENSSH ...
<python><ssh><sftp><paramiko><scp>
2025-03-05 08:30:55
1
5,241
Jim Macaulay
79,485,776
1,942,868
How to kick the old session from websocket
<pre><code>async def connect(self): self.room_group_name = self.scope[&quot;url_route&quot;][&quot;kwargs&quot;][&quot;room_name&quot;] pool = redis.ConnectionPool(host='localhost', port=6379, db=0) self.redis = redis.Redis(connection_pool=pool) logger.info(&quot;channel_name:{} / group_name {}&quot;....
<javascript><python><websocket><redis>
2025-03-05 07:57:41
0
12,599
whitebear
79,485,612
2,981,639
Adding hours to a Polars time column
<p>I have a table representing a schedule, i.e. it contains day (monday-sunday), start_time and end_time fields</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ &quot;day&quot;: [&quot;monday&quot;, &quot;tuesday&quot;, &quot;wednesday&quot;, &quot;thursday&quot;, &quot;friday&quot;, &quot;sa...
<python><dataframe><python-polars>
2025-03-05 06:20:43
1
2,963
David Waterworth
79,485,504
1,563,347
Why unrecognized Argparse arg1 in bare "my_script .py arg1" vs "python my_script.py arg1"
<p>I can run a script on the command line with an argument either as the bare &quot;script.py arg1&quot; or I can run it as &quot;python script.py arg1&quot;. Both work until I use argparse for command line parameters.</p> <p>The bare script does not recognize arg1:</p> <pre><code>Directories.py usage: directories.py [...
<python><windows><command-line><argparse>
2025-03-05 05:07:35
0
601
wgw
79,485,464
5,003,606
string format a Decimal instance using an underscore as a thousands separator?
<p>I can easily do this for floats using an f-string like this:</p> <pre><code>x = float(123456789.123456) print(f&quot;{x:_f}&quot;) </code></pre> <p>prints <code>123_456_789.123456</code> exactly as expected.</p> <p>But if try the same technique for a Decimal</p> <pre><code>from decimal import Decimal x = Decimal(&qu...
<python><string><format><decimal><separator>
2025-03-05 04:42:59
0
951
HaroldFinch
79,485,298
4,352,047
Numpy Structured Array - Memory copy error
<p>I am using python <code>structured arrays</code> to arrange relevant data then passing it into C++ land. I noticed on occasion a memory copy error which leads to calculation issues. I first explored using hashing functions to make sure it was not corrupted but now use <code>np.where()</code> to see where the values ...
<python><arrays><python-3.x><numpy>
2025-03-05 02:16:18
1
379
Deftness
79,485,287
6,471,140
how to pass additional query filters to a SelfQueryRetriever?
<p>We are implementing a SelfQueryRetriever using OpenSearch as vectorstore, in general it works fine generating the metadata filters from the user query but we need some way to append other filters to the query, and I cannot find how to do that in the documentation, the use case is to make some things such as:</p> <ul...
<python><nlp><artificial-intelligence><langchain>
2025-03-05 02:03:39
0
3,554
Luis Leal
79,485,215
7,436,627
SIR parameter estimation with gradient descent and autograd
<p>I am trying to apply a very simple parameter estimation of a SIR model using a gradient descent algorithm. I am using the package <a href="https://github.com/HIPS/autograd" rel="nofollow noreferrer">autograd</a> since the audience (this is for a sort of workshop for undergraduate students) only knows numpy and I don...
<python><gradient><gradient-descent><autograd>
2025-03-05 01:02:57
1
323
Alonso Ogueda Oliva
79,485,175
6,041,629
Python frequency analysis - AIC of infinity for several distributions despite a good fit
<p>I am doing frequency analysis on many sets of snow data, which sometimes have (valid) zero values in the Annual Maxima Series.</p> <p>To help guide the selection of distribution, I am calculating some goodness of fit statistics including AIC and BIC. I am finding that even for apparently reasonable distribution fits...
<python><frequency-analysis><goodness-of-fit>
2025-03-05 00:18:21
0
526
Kingle
79,485,170
12,125,755
How to get field value from array of objects in python?
<p>I have a json file with a list of objects from which I need to get some objects with filtration.</p> <p>My json:</p> <pre><code>[ { &quot;_id&quot;: &quot;1&quot;, &quot;type&quot;: &quot;answer&quot;, &quot;segments&quot;: [ { &quot;slug&quot;: &quot;employees...
<python><arrays>
2025-03-05 00:12:06
2
2,010
NeverSleeps
79,485,018
159,072
A python translation of `XorShift128Plus`
<p>I need to translate <a href="https://github.com/m4rs-mt/ILGPU/blob/master/Src/ILGPU.Algorithms/Random/XorShift128Plus.cs" rel="nofollow noreferrer">ILGPU's <code>XorShift128Plus</code> class</a> into Python.</p> <p>First, I have written a unit test for the C# version:</p> <pre class="lang-cs prettyprint-override"><c...
<python><c#><random>
2025-03-04 22:27:58
0
17,446
user366312
79,484,907
2,279,501
How to Resolve Circular Import and Task Not Found Issues in Flask and Celery Integration?
<p>I'm working on a Flask application that uses Celery for background task processing. I'm encountering issues with circular imports and task not found errors. Here is the structure of my project:</p> <ul> <li>app.py: Main Flask application file</li> <li>tasks.py: Celery task definitions</li> <li>celery_config.py: Cele...
<python><flask><celery>
2025-03-04 21:31:52
0
567
cappy0704
79,484,899
20,895,654
Python inheritance vs. composition for InstanceManager
<p>I have created the following class, made to manage all instances created and to enable fast lookup and retrieval of specific values by the specified lookup keys:</p> <pre><code>class InstanceManager[InstanceT, LookupT: Hashable](): def __init__( self, get_lookups: Callable[[InstanceT], Iterable[...
<python><inheritance><instance><composition>
2025-03-04 21:26:40
1
346
JoniKauf
79,484,702
2,661,305
Python NiceGUI / FastAPI App Insights Integration
<p>I'm developing a NiceGUI application in python and wanted to add application insights to the app. I have been able to do this as I'm getting requests and telemetry sent no problem. The issue I'm having is that I cant seem to get my custom logging messages to send to app insights.</p> <p>I've previously added the con...
<python><fastapi><azure-application-insights><nicegui>
2025-03-04 19:38:41
0
381
user2661305
79,484,649
1,079,907
Substitution for comma match
<p>For the input string as shown below, I am trying to substitute <code>UK1/</code> after <code>Street</code> and every <code>,</code> and skip hyphen to create expected output shown below.</p> <p><code>Input = Street1-2,4,6,8-10</code></p> <p><code>Expected output = StreetUK/1-2,UK/4,UK/6,UK/8-10</code></p> <p>With th...
<python><regex>
2025-03-04 19:12:47
4
12,828
Sunil Bojanapally
79,484,615
7,456,317
Llama Index Vector Store: filter a list of documents with a NOT feature
<p>I have a vector store of documents, each document is a json document with features. I'd like to filter the documents according to some criteria. The problem is that some of the documents contain a NOT criteria, so they should be retrieved if the filter does <em>not</em> contain this feature. Here's a MOE:</p> <pre c...
<python><llama-index><vectorstore>
2025-03-04 18:52:53
0
913
Gino
79,484,575
1,653,413
Why does importlib.resources read_text raise UnicodeDecodeError on Windows but not mac and RPi?
<p>I am writing a small web app (<a href="https://github.com/r-owen/base_loom_server" rel="nofollow noreferrer">https://github.com/r-owen/base_loom_server</a>) and it runs on macOS and Raspberry Pi, but a Windows user reports an exception when Python reads a UTF-8-encoded resource file using <code>importlib.resources.f...
<python><unicode><python-importlib>
2025-03-04 18:32:05
1
449
Russell Owen
79,484,348
1,159,579
Python Azure Function nested code can't find modules even with init files
<p>I made a test.py, and it works fine.. So this has to be how Azure is starting the function.</p> <pre><code>import sys from pathlib import Path # Get the directory of the current file (test_function.py) current_dir = Path(__file__).parent # Add the 'code' directory to the PYTHONPATH sys.path.append(str(current_dir ...
<python><visual-studio-code><azure-functions>
2025-03-04 16:51:28
1
2,057
Steve Coleman
79,484,274
1,534,017
How to prevent the formatting of any linebreaks?
<p>Let's say I have a file like this:</p> <pre><code>import pandas as pd df = pd.DataFrame( { &quot;A&quot;: [&quot; a: yu&quot;, &quot;b: stuff &quot;, &quot;c: more_stuff&quot;], &quot;B&quot;: [4, 5, 6], &quot;C&quot;: [7, 8, 9], } ) df[&quot;A&quot;] = ( df[&quot;A&quot;] ...
<python><ruff>
2025-03-04 16:14:45
1
26,249
Cleb
79,483,931
357,313
Iterate xml using namespace prefix
<p>I have an xml file with a default namespace, like this:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;root xmlns=&quot;somelongnamespace&quot;&gt; &lt;child&gt;...&lt;/child&gt; &lt;/root&gt; </code></pre> <p>I starting using <code>lxml</code> to iterate and query this file, b...
<python><xml><lxml><xml-namespaces>
2025-03-04 14:07:17
1
8,135
Michel de Ruiter
79,483,874
1,980,208
calculate pearson correlation of each rows in 2D numpy array (n,m)
<pre><code>a = np.array([[1,2,4],[3,6,2],[3,4,7],[9,7,7],[6,3,1],[3,5,9]]) b = np.array([[4,5,2],[9,2,5],[1,5,6],[4,5,6],[1,2,6],[6,4,3]]) a = array([[1, 2, 4], [3, 6, 2], [3, 4, 7], [9, 7, 7], [6, 3, 1], [3, 5, 9]]) b = array([[4, 5, 2], [9, 2, 5], [1, 5, 6], ...
<python><numpy>
2025-03-04 13:41:57
2
439
prem
79,483,761
1,700,890
How do I fix TypeError from Llama api call
<p>I am running below code from: <a href="https://docs.llama-api.com/quickstart" rel="nofollow noreferrer">Llama quick start</a></p> <pre><code>import json from llamaapi import LlamaAPI # Initialize the SDK llama = LlamaAPI(&quot;&lt;your_api_token&gt;&quot;) # Build the API request api_request_json = { &quot;mod...
<python><llama>
2025-03-04 12:55:47
0
7,802
user1700890
79,483,748
1,940,534
Using xml.etree.ElementTree to extract values not working
<p>here is the XML:</p> <pre><code>&lt;multi-routing-engine-results&gt; &lt;multi-routing-engine-item&gt; &lt;re-name&gt;node0&lt;/re-name&gt; &lt;source-resource-usage-pool-information&gt; &lt;resource-usage-entry style=&quot;pat-pool&quot;&gt; &lt;resource-usage-pool-na...
<python><elementtree>
2025-03-04 12:48:19
1
1,217
robm
79,483,656
1,788,656
Vectoring nested while statements block that detects the frequency of consecutive numbers
<p>All, The following function <code>get_frequency_of_events</code> detects the frequency of consecutive numbers, for example,</p> <pre><code>import numpy as np aa=np.array([1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]) get_frequency_of_events(aa) </code></pre> <p>this yields the following:</p> <p>list of indices @ the beginning of...
<python><pandas><loops>
2025-03-04 12:08:14
1
725
Kernel
79,483,629
2,551,236
Failure while installing Python requirements in Windows System
<p>I am using <code>pip</code> for installing requirements of my project.</p> <p>Below is the error I get when I run the command <code>pip install -r requirements.txt</code></p> <pre><code>_frozenlist.c C:\Program Files\Python312\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file ...
<python><windows><visual-studio><visual-c++>
2025-03-04 11:59:20
0
3,829
Vihar
79,483,453
1,942,868
Ordering data after distinct
<p>I distinct data by <code>sku_id</code></p> <pre><code> queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('sku_id')) </code></pre> <p>However this result is not sorted by id,</p> <p>then I try to</p> <pre><code> queryset = self.filter_queryset(queryset.order_by('sku_id','id').distinct('s...
<python><sql><django><postgresql>
2025-03-04 10:56:46
2
12,599
whitebear
79,483,314
5,976,205
WhatsApp API Broadcast with Celery - Unable to Reach 1K Throughput Limit
<p>I am trying to send a WhatsApp broadcast using Meta's WhatsApp API, but I am not able to fully utilize the 1K messages per second throughput limit.</p> <blockquote> <p>Current Architecture:</p> </blockquote> <ol> <li>I process phone numbers and divide them into chunks of 1,000.</li> <li>These chunks are sent asynchr...
<python><asynchronous><celery><whatsapp-cloud-api><highperformance>
2025-03-04 10:11:27
1
2,599
Dev Jalla
79,483,117
10,232,932
Keep rows of dataframe based on column, where the column has a whole / round number
<p>I have a dataframe with a float column (number), e.g.:</p> <pre class="lang-none prettyprint-override"><code>value number 1 0.98 10 1.00 -1 1.23 -10 2.00 </code></pre> <p>I only want to keep the rows of the dataframe where the number column is a &quot;full&quot; number (1,2,3,...). How can I do t...
<python><pandas>
2025-03-04 08:50:40
0
6,338
PV8
79,482,899
1,964,692
Change images in a window via real time MIDI messages
<p>I am trying to create a program that will</p> <ul> <li>read in images from a dir and store in a list</li> <li>display first image in list in a window</li> <li>MIDI notes from USB MIDI Controller triggers a new image in the <em>same</em> window <ul> <li>the new image is retrieved using the note value and matching ind...
<python><matplotlib><midi>
2025-03-04 07:15:24
1
1,599
Korean_Of_the_Mountain
79,482,737
1,942,868
Redis data fetching error, redis.exceptions.ResponseError: WRONGTYPE Operation against a key holding the wrong kind of value
<p>I am trying to fetch the redis data, then</p> <p>at first try this script</p> <pre><code>pool = redis.ConnectionPool(host='localhost', port=6379, db=0) self.redis = redis.Redis(connection_pool=pool) for key in self.redis.keys(): print (&quot;key:&quot;,key) </code></pre> <p>It shows like this,</p> <pre><code>key...
<python><redis>
2025-03-04 05:29:26
1
12,599
whitebear
79,482,623
12,692,182
Why is Tkinter Button unpressable? (No errors raised, not disabled)
<p>I was working with Tkinter in OOP and I came across an odd bug: the button here goes completely unresponsive, despite being fully active and the mainloop running.</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk def main(): global root, button root = tk.Tk() pixel = ...
<python><tkinter><button>
2025-03-04 03:43:30
4
1,011
User 12692182
79,482,453
3,754,268
WxFormBuilder warning - First ID is less than 5999
<p>WxFormBuilder, version 4.2.1 and WxPython 4.2.2</p> <p>After upgrading from earlier versions of WxPython and WxFormBuilder, I loaded in a previously building and working project. When I click on 'Generate Code' (F8), the generator pops up an error message &quot;First ID is less than 5999.&quot; My code does not set ...
<python><wxpython><wxformbuilder>
2025-03-04 00:54:28
1
377
Traveler_3994
79,482,398
2,913,725
Google Speech returning all words ever spoken, instead of just the words from the transcript
<p>Using Google Speech in Python, I'm able to get a transcript for each phrase spoken using result.alternatives[0].transcript, but when I try to look at the words for the phrase, result.alternatives[0].words always returns an array of ALL of the words ever spoken, not just the words from the transcript... which seems w...
<python><speech><google-speech-api><google-speech-to-text-api>
2025-03-04 00:03:32
1
1,599
JackKalish
79,482,383
12,980,093
Lazy evaluations for DataFrames
<p>Let me provide quick demo which shows that second approach is 10x times slower than the first one.</p> <pre><code>import pandas as pd from timeit import default_timer as timer r = range(1,int(1e7)) df = pd.DataFrame({ 'col0': [i % 3 for i in r], 'col1': r }) df['pad'] = '*' * 100 start = time.time() prin...
<python><dataframe><lazy-evaluation>
2025-03-03 23:51:00
1
653
Slimboy Fat
79,482,376
3,782,963
Pandas dropping first group of values
<p>I want to drop the first group of rows based on a column's value. Here is an example of a table</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>stage</th> <th>h1</th> <th>h2</th> <th>h3</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>4</td> <td>55</td> <td>55</td> </tr> <tr> <td>0</td> <t...
<python><pandas>
2025-03-03 23:45:59
2
2,835
Akshay
79,482,290
2,144,360
How to handle German language specific characters like (ä, ö, ü, ß) while tokenizing using GPT2Tokenizer?
<p>I am working with German Texts, where I need to tokenize texts using GPT2Tokenizer.</p> <p>To tokenize the text, I wrote the implementation as follows:</p> <pre class="lang-py prettyprint-override"><code>from transformers import GPT2Tokenizer text = &quot;zügiger Transport des ABCD stabilen Kindes in die Notaufnahm...
<python><nlp><tokenize><large-language-model><gpt-2>
2025-03-03 22:32:36
1
1,372
RajibTheKing
79,482,197
8,167,752
python-pptx - Getting an unwanted slide at the start when using a custom template
<p>The company I work for has a standard PowerPoint template. I'm trying to use this template with python-pptx. However, I'm getting an unwanted slide at the start of my slide deck and I can't figure out what I'm doing wrong.</p> <p>My first attempt was a simple:</p> <pre><code>prs = Presentation('companyTemplate.pot...
<python><python-pptx>
2025-03-03 21:36:10
1
477
BobInBaltimore
79,482,145
6,041,629
Extreme value analysis and quantile estimation using log Pearson type 3 (Pearson III) distribution - R vs Python
<p>I am trying to estimate quantiles for some snow data using the log pearson type 3 distribution in Python and comparing with R. I do this by reading in the data, log transforming it, fitting Pearson type 3, estimating quantiles, then transforming back from log space.</p> <p>In python:</p> <pre><code>import numpy as n...
<python><r><statistics><frequency-analysis>
2025-03-03 21:04:42
1
526
Kingle
79,482,125
2,218,321
Agno (Phidata) reading PDF as knowledge base failed
<p>This is the code</p> <pre><code>from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.embedder.openai import OpenAIEmbedder from agno.knowledge.pdf_url import PDFUrlKnowledgeBase from agno.vectordb.lancedb import LanceDb, SearchType api_key = 'sk-XXX' knowledge_base = PDFUrlKnowledgeBase...
<python><phidata><agno>
2025-03-03 20:55:38
1
2,189
M a m a D
79,482,105
1,745,001
pyserial-asyncio client/server in Python 3.8 not communicating immediately
<p>I'm learning python and asyncio and after having success with asyncio for a TCP client/server I took my first stab at creating a serial client/server using pyserial-asyncio running in bash on a Raspberry Pi 5 using Python 3.8 (I cannot change version).</p> <p>Here is the server:</p> <pre><code>import asyncio import ...
<python><python-3.x><python-asyncio><pyserial>
2025-03-03 20:43:30
1
208,382
Ed Morton
79,482,028
140,903
Python Version Management with Pyenv on MacBook Pro
<p>I'm using <strong>pyenv</strong> to manage Python versions on my MacBook Pro. I have a question about how pyenv handles shim paths for each version.</p> <p>I've installed different Python versions using pyenv.</p> <pre><code> pyenv versions system 3.10.16 3.11.9 3.11.9/envs/extra 3.11.11 * 3.12.4 (set by /...
<python><pyenv><hatch>
2025-03-03 20:06:28
1
7,461
Am1rr3zA
79,481,878
2,537,486
Formatting pandas tables that contain lists of floats
<p>How can I format numbers in a <code>pandas</code> table, when a cell displays a list of floating point numbers instead of a single float value?</p> <p>Here's a code example:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'Values':[[0.1231245678,0,0],[1e-10,0,0]]}) df </code></pre> <p>I would like to form...
<python><pandas>
2025-03-03 18:44:26
4
1,749
germ
79,481,823
5,304,366
Get a Python plotly output with quarto reveal.js presentation
<p>Plotly graph are not outputed in quarto.</p> <p>Here is my code:</p> <pre><code>--- title: &quot;Title&quot; format: revealjs: auto-fit: false --- ## Slide ```{python} from IPython.display import HTML import plotly.express as px data = {&quot;x&quot;: [1, 2, 3, 4], &quot;y&quot;: [10, 20, 15, 25]} # Creat...
<python><plotly><quarto>
2025-03-03 18:20:33
0
2,179
Adrien Pacifico
79,481,758
1,942,868
How can I get the member list of log-in-ed
<p>I am using the <code>django</code> and <code>websocket</code>.</p> <p>I have the script like this, a user can login a websocket group</p> <p>Now I want to return the list of users log-in-ed and return the list to the client.</p> <p>How can I make this?</p> <pre><code>class ChatConsumer(AsyncWebsocketConsumer): ...
<python><django><websocket>
2025-03-03 17:58:39
1
12,599
whitebear
79,481,710
11,951,910
Pylint is ignoring disable flag
<p>I am running into an issue with pylint and lambda functions. To ignore the error I am using:</p> <pre><code>some_thing = lambda ... # pylint: disable=E731 </code></pre> <p>I have also tried:</p> <pre><code># pylint: disable=E731 some_thing = lambda .... # pylint: disable=E731 </code></pre> <p>Running my pipeline I h...
<python><pylint>
2025-03-03 17:32:59
0
718
newdeveloper
79,481,674
457,159
Namespace Package Import Issue in Linux but Not in Windows
<p>I have a namespace package called foo, which contains multiple distribution packages:</p> <ul> <li>foo.bar_one, foo.bar_two, and foo.bar_three are installed as distribution packages via pip from a private GitLab repository.</li> <li>These packages are installed under Python's site-packages, which is included in the ...
<python><python-3.x><namespaces>
2025-03-03 17:15:59
0
876
EKI
79,481,583
8,037,521
Poor responsiveness of a QScrollBar handle
<p>Not sure what is the issue: I am using list view and I struggle with the scrollbar. Somehow, the handle part is not always responsive. Sometimes I can click the handle and scroll fast to the place which I need, sometimes I cannot. I made a MRE from it and I could not identify if there are some specific conditions wh...
<python><qt><pyside2>
2025-03-03 16:37:55
0
1,277
Valeria
79,481,529
10,722,752
Getting Error Code: ScriptExecution.StreamAccess.NotFound error while trying to read in mltable in a pipeline
<p>I am trying to read in a MLTABLE in my pipeline, but getting:</p> <pre><code>Error Code: ScriptExecution.StreamAccess.NotFound Native Error: error in streaming from input data sources StreamError(NotFound) =&gt; stream not found NotFound Error Message: The requested stream was not found. Please make sure the...
<python><azure><azure-pipelines><azure-machine-learning-service>
2025-03-03 16:20:13
2
11,560
Karthik S
79,481,508
648,689
How does int() operate from memoryview -- does it create an intermediate bytes copy?
<p>I'm very interested in zero-copy operations (and disappointed that <code>memoryview</code> doesn't have all the member functions that <code>bytes</code> does). My application will be pretty intensive in this regard.</p> <p>Consider this python code, extracting integers from bytes/buffers:</p> <pre><code>&gt;&gt;&gt...
<python><in-place><memoryview><zero-copy>
2025-03-03 16:12:17
0
1,107
JimB
79,481,444
11,659,631
Fitting with Maximum likelihood estimation in python returns initial parameters
<p>I would like to use <code>minimize</code> from <code>scipy.optimize</code> to fit my data with a specific function: <a href="https://i.sstatic.net/oTV0WKIA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oTV0WKIA.png" alt="enter image description here" /></a></p> <p>I defined this log likelihood to th...
<python><scipy><scipy-optimize-minimize>
2025-03-03 15:49:33
0
338
Apinorr
79,481,290
1,750,498
Why did my mock test work with just a method instead of a full class?
<p>I always thought that you could mock a method on a class only when the class it is coming from is not instantiated in the code under test. And if it is you have to mock the class (just as you have to do for builtins).</p> <p>But today I made a &quot;mistake&quot; and saw that it just worked. So now I'm confused on w...
<python><mocking><python-unittest.mock>
2025-03-03 14:54:47
1
5,562
Nemelis
79,481,283
3,365,532
Polars lazy dataframe custom function over rows
<p>I am trying to run a custom function on a lazy dataframe on a row-by-row basis. Function itself does not matter, so I'm using softmax as a stand-in. All that matters about it is that it is not computable via pl expressions.</p> <p>I get about this far:</p> <pre class="lang-py prettyprint-override"><code>import polar...
<python><dataframe><python-polars><polars>
2025-03-03 14:52:24
2
443
velochy