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,336,731
15,804,190
Mock date.today() but leave other date methods alone
<p>I am trying to test some python code that involves setting/comparing dates, and so I am trying to leverage <code>unittest.mock</code> in my testing (using <code>pytest</code>). The current problem I'm hitting is that using <code>patch</code> appears to override all the other methods for the patched class (<code>date...
<python><date><mocking><pytest><python-unittest>
2025-01-07 16:41:32
3
3,163
scotscotmcc
79,336,604
20,302,906
Failed creating mock folders with pyfakefs
<p>I'm working on a project that uses <a href="https://pytest-pyfakefs.readthedocs.io/en/stable/usage.html#test-scenarios" rel="nofollow noreferrer">pyfakefs</a> to mock my filesystem to test folder creation and missing folders in a previously defined tree structure. I'm using <strong>Python 3.13</strong> on <strong>Wi...
<python><mocking><python-unittest><pyfakefs>
2025-01-07 16:01:21
1
367
wavesinaroom
79,336,594
2,236,794
uwsgi with https getting socket option missing
<p>I am running a Flask application on Docker with uwsgi. I have been running it for years now, but we need to add https to it. I know I can use an HAProxy and do ssl offloading, but in our current setup we cant do it this way, at least not right now. We need to do the SSL directly on the application. I have tried ...
<python><flask><uwsgi><dockerpy>
2025-01-07 15:57:52
1
561
user2236794
79,336,492
6,808,709
Is it possible to use XOAUTH2 through imaplib to access Google Workspace Gmail without IMAP being enabled on the domain?
<p>I have a task to build an integration with Gmail that will collect emails from a users inbox and store them within a Django system. The client I'm working with does not allow IMAP to be enabled on their Google Workspace account.</p> <p>The following code runs but generates a <code>An error occurred: [ALERT] IMAP acc...
<python><imap><google-workspace><imaplib>
2025-01-07 15:21:14
0
723
Pete Dermott
79,336,443
10,190,983
Python: BeautifulSoup scraping yield data
<p>I am trying to scrape Yield tables for several countries and several maturities from a website. So far I only get empty tables:</p> <p><a href="https://i.sstatic.net/md6bhS2D.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/md6bhS2D.png" alt="enter image description here" /></a></p> <p>while it should ...
<python><pandas><web-scraping><beautifulsoup>
2025-01-07 15:05:55
1
609
Luca91
79,336,434
5,118,757
Python polars: pass named row to pl.DataFrame.map_rows
<p>I'm looking for a way to apply a user defined function taking a dictionary, and not a tuple, of arguments as input when using <a href="https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.map_rows.html" rel="nofollow noreferrer"><code>pl.DataFrame.map_rows</code></a>.</p> <p>Trying somethi...
<python><dataframe><user-defined-functions><python-polars>
2025-01-07 15:02:37
1
320
paulduf
79,336,420
8,150,186
Unable to construct a DueDate String for the Invoice API call
<p>I am trying to make an API call using python and <code>httpx</code> to the Xero Invoice Api. I use the following api method:</p> <pre class="lang-py prettyprint-override"><code>async def create_invoice( invoice_detail: InvoiceCreateRequest, token_manager=Depends(oauth_manager) ) -&gt; InvoiceCreateRe...
<python><xero-api>
2025-01-07 14:57:43
1
1,032
Paul
79,336,338
4,581,311
Lifetime of local variable in Python if its reference was copied
<p>I did some experiment to access and use a local variable of a function at the caller level by saving the reference of the local variable into a variable that was defined at the caller level rather than using the return statement. I checked this case in a member function of a class also. And I experienced that the m...
<python>
2025-01-07 14:30:22
1
749
László Szilágyi
79,336,266
5,213,451
Can I make an asynchronous function indifferentiable from a synchronous one?
<p>If I can write a function in either synchronous or asynchronous fashion (e.g. for retrieving some data from an API), I would like to ideally only implement it once as asynchronous, and run it as synchronous whenever I implement a non-<code>async</code> function.</p> <p>I'm therefore looking for a <code>run</code> fu...
<python><python-asyncio>
2025-01-07 14:00:05
4
1,000
Thrastylon
79,336,182
12,642,588
Sample Size for A/B Test
<p>I want to test if a feature increases conversion.</p> <p>I want to detect a 5% increase, and my baseline is 80%. However, my code says that I need a sample size of 903 per group. Is there another method of sample calculation, perhaps for non-parametric tests, that can handle a smaller sample size?</p> <pre><code>imp...
<python><statistics><hypothesis-test>
2025-01-07 13:30:39
0
485
bakun
79,336,132
357,313
What does IPython expect after an underscore in a numeric literal?
<p>I know that <code>_</code>s can be used as digit separator within numeric literals, between (groups of) digits, for instance <code>1_000</code> means <code>1000</code> and <code>0_0</code> means <code>00</code> or just <code>0</code>. Today I accidentally typed a <em>letter</em> after the underscore, say <code>0_z</...
<python><ipython>
2025-01-07 13:14:55
0
8,135
Michel de Ruiter
79,336,036
10,944,175
How to remove Holoviews BoxWhisker duplicate legend?
<p>I'm using holoviews and panel in python with a bokeh backend to create a boxplot. Unfortunately, the legend in the boxplot shows all the entries twice. I don't know if I am doing something wrong or if it is a bug, but I would like to get rid of the duplicate entries.</p> <p>Here is a minimal working example:</p> <pr...
<python><bokeh><panel><holoviews>
2025-01-07 12:41:13
1
549
Freya W
79,336,023
7,959,614
Forward fill Numpy matrix / mask with values based on condition
<p>I have the following matrix</p> <pre><code>import numpy as np A = np.array([ [0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0] ]).astype(bool) </code></pre> <p>How do I fill all the rows column-wise after a column is <code>True</code>?</p> <p>My desired outp...
<python><numpy>
2025-01-07 12:36:21
3
406
HJA24
79,335,929
13,840,270
Difference between bool(prod( ... )) and all( ... )
<p>Since I am not &quot;native&quot; in Python, I used <code>bool(prod( ... )</code> to check if all elements in a list of boolean are <code>True</code>. I made use of the property, that boolean are mapped to <code>0</code> and <code>1</code> and since any <code>0</code> in a product makes the whole product <code>0</co...
<python>
2025-01-07 12:02:44
2
3,215
DuesserBaest
79,335,633
8,031,956
"OSError: [Errno 9] Bad file descriptor" with pandas.to_excel() function
<p>I am using the function <code>.to_excel()</code> in pandas,</p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [3, 4]]) with pd.ExcelWriter('output.xlsx') as writer: df.to_excel(writer, sheet_name=&quot;MySheet&quot;) </code></pre> <p>This results in the error <code>OSError: [Errno 9] Bad file descri...
<python><pandas><openpyxl>
2025-01-07 10:26:51
1
559
Rémi Baudoux
79,335,629
4,247,881
Transpose dataframe with List elements
<p>I have a dataframe like</p> <pre class="lang-none prettyprint-override"><code>┌─────┬────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┐ │ rul ┆ 647833 ┆ 64783 ┆ 64783 ┆ 64783 ┆ 64720 ┆ 64783 ┆ 64783 ┆ 64783 ┆ 6...
<python><dataframe><python-polars><polars>
2025-01-07 10:25:39
1
972
Glenn Pierce
79,335,580
10,722,752
Getting strange output when using group by apply with np.select function
<p>I am working with a Timeseries data wherein I am trying to perform outlier detection using IQR method.</p> <p>Sample Data:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'datecol' : pd.date_range('2024-1-1', '2024-12-31'), 'val' : np.random.random.randin(low = 100, high ...
<python><pandas><numpy>
2025-01-07 10:07:29
1
11,560
Karthik S
79,335,533
11,863,823
How to type Polars' Series in Python?
<p>I'm trying to type my functions in Python for <code>polars.Series</code> objects of a specific <code>dtype</code>.</p> <p>For instance, in a MWE, a function could look like:</p> <pre class="lang-py prettyprint-override"><code>import typing as tp import polars as pl u = pl.Series(range(5)) def f(L: tp.Sequence[int]...
<python><python-typing><mypy><python-polars>
2025-01-07 09:53:10
0
628
globglogabgalab
79,335,164
19,546,216
How can I set a cookie using Selenium on a site BEFORE accessing it?
<p>When I try to access our test environment LOCALLY (<a href="https://www.test.net" rel="nofollow noreferrer">https://www.test.net</a>), we are immediately redirected to Google SSO.</p> <p>How can we set a cookie for a site <strong>BEFORE</strong> accessing it?</p> <p><a href="https://i.sstatic.net/7wLAfzeK.png" rel="...
<python><selenium-webdriver><cookies><google-sso>
2025-01-07 07:24:28
0
321
Faith Berroya
79,335,053
8,206,716
Replace substring if key is found in another file
<p>I have files associated with people scattered around different directories. I can find them with a master file. Some of them need to be pulled into my working directory. Once I've pulled them, I need to update the master file to reflect the change. To keep track of which files were moved, I record the person's n...
<python><string><sed>
2025-01-07 06:24:45
3
535
David Robie
79,334,708
12,961,237
Is there any way to limit the operations TVMs autoscheduler can use when creating a schedule?
<p>I'm building my own auto tuner for TVM schedules. I would like to test it against TVMs built-in <code>auto_scheduler</code>. However the <code>auto_scheduler</code> uses a lot of advanced scheduling operations that my tuner does not yet support. Is there anyway to restrict <code>auto_scheduler</code> to only use the...
<python><gpu><apache-tvm>
2025-01-07 01:13:34
0
1,192
Sven
79,334,568
1,324,833
How to use subprocess.run when the subprocess requires an <ENTER> to complete
<p>I have an windows console executable provided by a third party. It's a file converter and requires an input and output file. On completion it has a &quot;Press any key to exit&quot; prompt. I'm trying to run it from within my program using subprocess.run. It works but it shows the prompt and an unhandled exception e...
<python>
2025-01-06 23:23:54
1
1,237
marcp
79,334,475
4,755,229
Writing Cython class with template?
<p><strong>Background</strong>: I am fairly new to the Cython, and I am not experienced with C++. I am aware of C++ template feature, and I am not really sure how to write a proper class in C++.</p> <p><strong>Objective</strong>: I am trying to write a class in Cython that mimics behaviors of a dictionary. But, instead...
<python><c++><cython>
2025-01-06 22:12:08
0
498
Hojin Cho
79,334,435
425,893
How do I post directly to a specific URL with Python Mechanize?
<p>With perl's mechanize module, nearly anything seems possible. But I'm not using perl, unfortunately, I still expected to be able to do what was needed with python. The login page that I have to automate can't be reached directly. The visible URL in the browser does not contain the web form (nor does anything, in web...
<python><python-3.x><mechanize-python>
2025-01-06 21:52:30
1
5,645
John O
79,334,421
9,415,280
Tensorflow dataset splitted sizing parameter problem: Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence
<p>Pretty new with data generator and dataset from tensorflow. I struggle with sizing batch, epochs and step... I can't figure the good set up to remove error &quot;Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence&quot;</p> <p>I try using size of a chunck of my data called by data generator and t...
<python><tensorflow><tensorflow-datasets>
2025-01-06 21:44:06
1
451
Jonathan Roy
79,334,351
3,614,460
How to convert UNIX time to Datetime when using Pandas.DataFrame.from_dict?
<p>I am reading from a json data file and loading it into a dictionary. It as key:value like below.</p> <pre><code>&quot;1707195600000&quot;:1,&quot;1707282000000&quot;:18,&quot;1707368400000&quot;:1,&quot;1707454800000&quot;:13,&quot;1707714000000&quot;:18,&quot;1707800400000&quot;:12,&quot;1707886800000&quot;:155,&qu...
<python><pandas>
2025-01-06 21:11:43
2
442
binary_assemble
79,334,315
6,151,828
Python: minimize function in respect to i-th variable
<p>I have a function <code>func(x)</code> where the argument is a vector of length <code>n</code>. I would like to minimize it in respect to <code>i</code>-th component of <code>x</code> while keeping the other components fixed. So to express it as a function of a single component I would do something like</p> <pre><co...
<python><optimization><vectorization>
2025-01-06 20:56:07
1
803
Roger V.
79,334,065
1,788,656
geopandas.read_file of a shapefile gives error if crs parameter is specified
<p>All, I use ESRI World Countries Generalized shape file, that is available <a href="https://hub.arcgis.com/datasets/esri::world-countries-generalized/explore?location=18.531425%2C34.576759%2C5.67" rel="nofollow noreferrer">here</a> using GeoPandas</p> <pre><code>shp_file =gpd.read_file('World_Countries/World_Countrie...
<python><python-3.x><geopandas><shapefile>
2025-01-06 19:05:41
1
725
Kernel
79,333,808
1,802,693
Data model duplication issue in bokeh (the library is possibly not prepared for this use case)
<p>I want to implement a stepping logic for a multi-timeframe charting solution with bokeh library. I need to export a static HTML file with all the data, therefore the size of the HTML export matters.</p> <p>In this solution multiple timeframes can be visualized at the same time, the charts of different timeframes are...
<javascript><python><bokeh>
2025-01-06 17:13:44
0
1,729
elaspog
79,333,765
1,547,004
Type Hinting and Type Checking for IntEnum custom types
<p>Qt has several <code>IntEnum</code>'s that support custom , user-specified types or roles. A few examples are:</p> <ul> <li><a href="https://doc.qt.io/qt-6/qt.html#ItemDataRole-enum" rel="nofollow noreferrer"><code>QtCore.Qt.ItemDataRole.UserRole</code></a></li> <li><a href="https://doc.qt.io/qt-6/qevent.html#Type-e...
<python><qt><pyside><mypy><pyside6>
2025-01-06 16:56:32
2
37,968
Brendan Abel
79,333,553
2,085,376
Trying to install an older version of Jax
<p>Trying to add a specific version of jax and jaxlib</p> <pre><code>pip install -U jaxlib==0.4.10 ERROR: Ignored the following yanked versions: 0.4.32 ERROR: Could not find a version that satisfies the requirement jaxlib==0.4.10 (from versions: 0.4.17, 0.4.18, 0.4.19, 0.4.20, 0.4.21, 0.4.22, 0.4.23, 0.4.24, ...
<python><jax>
2025-01-06 15:38:54
1
4,586
NoIdeaHowToFixThis
79,333,402
494,739
How to resize dimensions of video through ffmpeg-python?
<p>I'm trying to resize a video file which a user has uploaded to Django, by using <a href="https://github.com/kkroening/ffmpeg-python" rel="nofollow noreferrer"><code>ffmpeg-python</code></a>. The documentation isn't very easy to understand, so I've tried to cobble this together from various sources.</p> <p>This metho...
<python><django><ffmpeg><ffmpeg-python>
2025-01-06 14:42:57
2
772
kunambi
79,333,342
11,460,896
Can't Connect to MongoDB Replica Set Running on Docker with Python: "Temporary failure in name resolution" Error
<p>I'm trying to set up a MongoDB replica set on Docker and connect to it using Python. However, I'm encountering the following error:</p> <h4>Error Message</h4> <pre><code>ServerSelectionTimeoutError: mongo3:27017: [Errno -3] Temporary failure in name resolution (configured timeouts: socketTimeoutMS: 20000.0ms, connec...
<python><mongodb><docker>
2025-01-06 14:23:37
0
307
birdalugur
79,333,087
1,021,819
How do I resolve SnowparkSQLException: ... User is empty in function for Snowpark python SPROC invocation?
<p>When invoking a Snowpark-registered SPROC, I get the following error:</p> <pre><code>SnowparkSQLException: (1304): &lt;uuid&gt;: 100357 (P0000): &lt;uuid&gt;: Python Interpreter Error: snowflake.connector.errors.ProgrammingError: 251005: User is empty in function MY_FUNCTION with handler compute </code></pre> <p>for...
<python><stored-procedures><snowflake-cloud-data-platform>
2025-01-06 12:50:23
1
8,527
jtlz2
79,332,999
1,712,287
Point halving in elliptic curve cryptography
<p>In elliptic curve cryptography there is scalar multiplication using point addition and point doubling.</p> <p>Is there anyway of point halving. To make it simple, if a point is P, then is there any way of getting point P/2</p> <p>I have used following python code. Could you help me to modify the code so that I can m...
<python><cryptography><elliptic-curve>
2025-01-06 12:20:22
0
1,238
Asif Iqbal
79,332,996
2,523,860
Wait-Until strategy in PyTest
<p>I'm testing asynchronous code using PyTest.</p> <p>Can't find any existing libraries that provide simple function like &quot;Await until&quot; or &quot;Polling&quot;:</p> <pre class="lang-py prettyprint-override"><code>operation.run_in_background() await_until(lambda: operation.is_ready(), interval=1, timeout=10) <...
<python><asynchronous><pytest><assert>
2025-01-06 12:19:03
1
909
Aleks Ya
79,332,886
3,241,486
Query IMF data via smdx using pandasdmx
<p>I would like to send this exact query <a href="http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/PCPS/M.W00.PZINC.?startPeriod=2021&amp;endPeriod=2022" rel="nofollow noreferrer">http://dataservices.imf.org/REST/SDMX_JSON.svc/CompactData/PCPS/M.W00.PZINC.?startPeriod=2021&amp;endPeriod=2022</a> using the <a ...
<python><sdmx>
2025-01-06 11:32:03
1
2,533
chamaoskurumi
79,332,523
1,802,693
Initialize global variable in bokeh and use it in handler code
<p>What I want to achieve here:</p> <ul> <li>I want to generate static HTML and do the data initialization exactly once</li> <li>I want to pass a complex data structure to the document and use it by multiple buttons / UI elements</li> <li>I don't want to pass the same complex data structure to each button / UI element ...
<javascript><python><bokeh>
2025-01-06 08:40:58
1
1,729
elaspog
79,332,328
11,770,390
pydantic model: How to exclude field from being hashed / eq-compared?
<p>I have the following hashable pydantic model:</p> <pre><code>class TafReport(BaseModel, frozen=True): download_date: dt icao: str issue_time: dt validity_time_start: dt validity_time_stop: dt raw_report: str </code></pre> <p>Now I don't want these reports to be considered different just becau...
<python><pydantic>
2025-01-06 07:06:19
1
5,344
glades
79,331,937
3,511,656
Why Are plot_gate_map and plot_error_map Showing Empty Plots in Jupyter Notebook with Qiskit?
<p>so I've ben playing around with Qiskit recently and have had success not only logging into the IBM machines but also executing circuits on their backends. I recently tried to plot the gate_map and error_map of each backend, but when I try to do so the plots are just empty in my juypter notebook e.g.</p> <p><a href="...
<python><qiskit>
2025-01-06 02:23:24
0
1,133
Eigenvalue
79,331,481
3,614,460
How to line plot Pandas Dataframe as sub graphs?
<p>I have a DataFrame that looks like this: <code>{&quot;1578286800000&quot;:71,&quot;1578373200000&quot;:72,&quot;1578459600000&quot;:72,&quot;1578546000000&quot;:74,&quot;1578632400000&quot;:7,&quot;1578891600000&quot;:7,&quot;1578978000000&quot;:6,&quot;1579064400000&quot;:7,&quot;1579150800000&quot;:6}</code></p> <...
<python><pandas><matplotlib>
2025-01-05 20:20:49
2
442
binary_assemble
79,331,430
7,468,566
pd.testing.assert_frame_equal has AssertionError with same dtypes
<pre><code>import pandas as pd import pyarrow as pa import numpy as np from datetime import datetime, timedelta df = pd.DataFrame({ &quot;product_id&quot;: pd.Series( [&quot;PROD_&quot; + str(np.random.randint(1000, 9999)) for _ in range(100)], dtype=pd.StringDtype(storage=&quot;pyarrow&quot;) ), ...
<python><pandas><pyarrow>
2025-01-05 19:43:02
2
2,583
itstoocold
79,331,372
11,439,134
Find location of tcl/tk header files
<p>I'm trying to find a cross-platform way to find tcl.h and tk.h without having to search the entire system. I'm just wondering if there's a way to find this from Tcl or tkinter? <code>root.tk.exprstring('$tcl_pkgPath')</code> doesn't seem to include the right directories. Thanks!</p>
<python><tkinter><gcc><tcl>
2025-01-05 19:09:10
1
1,058
Andereoo
79,331,102
4,098,506
QStyledItemDelegate in QTableView is misaligned
<p>I want to show a list of files with star rating in a QTableView. For this I use the following delegate:</p> <pre><code>class StarRatingDelegate(QStyledItemDelegate): def __init__(self, parent=None): super().__init__(parent) def paint(self, painter, option, index): file: File = index....
<python><pyside6><qstyleditemdelegate>
2025-01-05 16:32:59
1
662
Mr. Clear
79,331,045
5,480,536
How to prevent users from installing my Python package on Windows?
<p>I have a Python package that I publish to PyPI.</p> <p>However, it does not support Windows, and I want to prevent that users install it on Windows.</p> <p>Can this be done using just <code>pyproject.toml</code>?</p> <hr /> <p>Note:</p> <p>I am using <code>pyproject.toml</code> and <code>setup.py</code>, but I under...
<python><windows><python-packaging>
2025-01-05 16:02:46
0
1,476
icpp-pro
79,330,953
3,621,464
Lemma of puncutation in spacy
<p>I'm using spacy for some downstream tasks, mainly noun phrase extraction. My texts contain a lot of parentheses, and while applying the lemma, I noticed all the punctuation that doesn't end sentences becomes <code>--</code>:</p> <pre><code>import spacy nlp = spacy.load(&quot;de_core_news_sm&quot;) doc = nlp(&quot;(...
<python><spacy><lemmatization>
2025-01-05 15:02:04
1
4,481
MERose
79,330,931
16,869,946
GridSearchCV with data indexed by time
<p>I am trying to use the <code>GridSearchCV</code> from <code>sklearn.model_selection</code>. My data is a set of classification that is indexed by time. As a result, when doing cross validation, I want the training set to be exclusively the data with time all before the data in the test set.</p> <p>So my training set...
<python><gridsearchcv>
2025-01-05 14:49:27
1
592
Ishigami
79,330,907
16,383,578
How to flatten a bunch of asynchronous generators asynchronously?
<p>I have a bunch of webpages to scrape, these webpages have addresses that differ only in page number thus can be processed in parallel using <code>aiohttp</code>.</p> <p>Now I am using an asynchronous function to process these webpages, each call takes one address as argument and returns a flat list of strings. I am ...
<python><python-3.x><python-asyncio>
2025-01-05 14:36:20
2
3,930
Ξένη Γήινος
79,330,857
1,447,207
Find straight lines in image
<p>I would like to find the locations of some lines in a series of images. The images are exported from GoPro videos, with the camera looking down onto a sloping floor (a beach, so to speak) in a wave tank. My goal (but not the topic of this question) is to analyse the images for the position of particles before and af...
<python><image-processing><computer-vision><scikit-image>
2025-01-05 14:02:56
0
803
Tor
79,330,788
1,060,344
Disable specific mypy checks for some files matching a naming pattern
<p>We have a python project wherein we are using mypy. In our project, the test files live next to the source as opposed to a separate package for tests. Their names follow the following pattern: <code>test_&lt;module&gt;.py</code>. Something like this:</p> <pre><code>src/ package_1/ __init__.py package_1.py ...
<python><mypy>
2025-01-05 13:18:33
1
2,213
vaidik
79,330,764
1,142,881
How can I silence `UndefinedMetricWarning`?
<p>How can I silence the following warning while running <code>GridSearchCV(model, params, cv=10, scoring='precision', verbose=1, n_jobs=20, refit=True)</code>?</p> <pre><code>/opt/dev/myenv/lib/python3.9/site-packages/sklearn/metrics/_classification.py:1531: UndefinedMetricWarning: Precision is ill-defined and being s...
<python><scikit-learn>
2025-01-05 13:03:49
1
14,469
SkyWalker
79,330,637
11,516,350
Inconsistent behavior between Flask real session storage and test_request_context during tests
<p>I’m using Flask’s session storage to temporarily save a list of dataclass objects. Here’s an example of the Transaction class and my TransactionMemoryRepository:</p> <pre><code>@dataclass class Transaction: transaction_date: datetime.date amount: decimal.Decimal concept: str </code></pre> <p>The reposit...
<python><flask><testing><pytest><flask-session>
2025-01-05 11:37:19
0
1,347
UrbanoJVR
79,330,620
1,142,881
How to specify the levels to iterate in a grid search with an ensemble classifier?
<p>I have the following setup but I can't find a way to pass levels to explore in the Grid search for svm* and mlp*:</p> <pre><code>steps = [('preprocessing', StandardScaler()), ('feature_selection', SelectKBest(mutual_info_classif, k=15)), ('clf', VotingClassifier(estimators=[(&quot;mlp1&quot;, mlp1)...
<python><machine-learning><scikit-learn>
2025-01-05 11:22:57
0
14,469
SkyWalker
79,330,475
12,016,688
Why ctypes.c_long.from_address.value yields reference count of an object?
<p>In this <a href="https://youtu.be/ydf2sg2C6qQ?t=280" rel="nofollow noreferrer">pycon conference</a> the presenter says that <code>ctypes.c_long.from_address(id(SOME_OBJECT)).value</code> would yields the reference count of an object. I tried to find this in the documentation but found nothing that helps me. The <a h...
<python><memory><ctypes><reference-counting>
2025-01-05 09:25:08
1
2,470
Amir reza Riahi
79,330,420
9,970,706
How to get maximum average of subarray?
<p>I have been working this leet code questions</p> <p><a href="https://leetcode.com/problems/maximum-average-subarray-i/description/" rel="nofollow noreferrer">https://leetcode.com/problems/maximum-average-subarray-i/description/</a></p> <p>I have been able to create a solution after understanding the sliding window a...
<python><python-3.x><logic><average><sub-array>
2025-01-05 08:34:18
2
781
Zubair Amjad
79,330,304
10,000,669
Optimizing sieving code in the Self Initializing Quadratic Sieve for PyPy
<p>I've coded up the Self Initializing Quadratic Sieve (<a href="https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve" rel="nofollow noreferrer">SIQS</a>) in Python, but it has been coded with respect to being as fast as possible in PyPy(not native Python).</p> <p>Here is the complete code:</p> <pre><code>...
<python><performance><optimization><pypy><sieve-algorithm>
2025-01-05 06:30:44
1
1,429
J. Doe
79,330,288
4,586,008
Pandas: Get moving average by weekday and hour
<p>I have a Series which is hourly sampled:</p> <pre><code>Datetime 2023-01-01 11:00:00 6 2023-01-01 12:00:00 60 2023-01-01 13:00:00 53 2023-01-01 14:00:00 14 2023-01-01 17:00:00 4 2023-01-01 18:00:00 66 2023-01-01 19:00:00 38 2023-01-01 20:00:00 28 2023-01-01 21:00:00 0 2023-01-...
<python><pandas><datetime>
2025-01-05 06:14:52
2
640
lpounng
79,330,224
2,893,496
Mismatch in shapes of Input and Prediction in Tensorflow
<p>I am compiling the Tensorflow model thusly:</p> <pre><code>model = tf.keras.Sequential() model.add( tf.keras.layers.InputLayer(shape=(2,)) ) model.add( tf.keras.layers.Dense(1024) ) model.add( tf.keras.layers.Dense(1024) ) model.add( tf.keras.layers.Dense(units=1) ) model.compile(loss=&quot;mean_squared_error&quot;...
<python><tensorflow>
2025-01-05 05:06:57
1
5,886
v010dya
79,330,156
506,824
Why has VS Code stopped discovering my python tests?
<p>I'm using</p> <ul> <li>VS Code Version: 1.96.2</li> <li>Python 3.11.8</li> <li>MacOS Sonoma 14.5</li> </ul> <p>I have a project that's been working for a long time, but now VS Code is failing to discover/run my tests. When I go into the TESTING tab, I have a progress indicator that keep running forever and the test...
<python><visual-studio-code><pytest>
2025-01-05 04:04:21
1
2,177
Roy Smith
79,330,093
18,125,194
Applying SMOTE-Tomek to nested cross validation with timeseries data
<p>I want to perform a nested cross-validation for a classification problem while ensuring that the model is not exposed to future data. Since the data is time-series, I plan to use a time-aware splitting strategy. In the inner loop of the nested cross-validation, I aim to apply SMOTE-Tomek, But I'm not sure of how to ...
<python><cross-validation><imblearn>
2025-01-05 03:06:44
0
395
Rebecca James
79,330,009
343,215
Pipenv not working after Debian system upgrade--maybe partial uninstall?
<p>Seems <code>pipenv</code> was uninstalled (not intentionally) during a system update and some config directories were left behind causing it to not run properly? If I try to run pipenv, I get:</p> <pre><code>&gt; $ pipenv Traceback (most recent call last): File &quot;/home/hostname/username/.local/bin/pipenv&quot;, ...
<python><pipenv-install>
2025-01-05 01:52:24
0
2,967
xtian
79,329,985
9,388,056
DeltaTable map type
<p>Using Spark, I can create a delta table with a map column type: <code>MAP&lt;STRING, TIMESTAMP&gt;</code><br /> How do I create a delta table with a map type without Spark?<br /> I have tried multiple approaches and none of them are working.</p> <pre><code>import pyarrow as pa from deltalake import write_deltalake ...
<python><python-polars><delta-lake><delta>
2025-01-05 01:28:03
1
620
Frank
79,329,672
12,357,696
Sympy: Define custom derivative on symbol
<p>I'm trying to create a custom symbol in sympy that behaves like r = √(x<sup>2</sup> + y<sup>2</sup> + z<sup>2</sup>) -- specifically, ∂r/∂x = x/r:</p> <pre class="lang-py prettyprint-override"><code>from sympy import Symbol, symbols x, y, z = symbols(&quot;x y z&quot;) class _r(Symbol): def __new__(self): ...
<python><sympy>
2025-01-04 21:52:55
1
752
Antimon
79,329,653
6,395,618
How to sub-class LangGraph's MessageState or use Pydantic for channel separation
<p>I am trying to create a Hierarchical LLM Agent workflow using <code>LangGraph</code>. The workflow is intended to be setup where the <code>research_team</code> conducts the research and the <code>writing_team</code> writes the report. The entire workflow should be executed for each sub-section of the main report req...
<python><openai-api><langchain><large-language-model><langgraph>
2025-01-04 21:37:58
0
2,606
Krishnang K Dalal
79,329,522
2,929,914
Find nearest following row with values greater than or equal to current row
<p>Starting with this DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df_1 = pl.DataFrame({ 'name': ['Alpha', 'Alpha', 'Alpha', 'Alpha', 'Alpha'], 'index': [0, 3, 4, 7, 9], 'limit': [12, 18, 11, 5, 9], 'price': [10, 15, 12, 8, 11] }) </code></pre> <p>I need to add a n...
<python><dataframe><python-polars>
2025-01-04 19:58:52
1
705
Danilo Setton
79,329,444
7,709,727
How to explicitly define a function's domain in sympy
<p>In sympy, I want to define a piecewise function within [1, 3], and I want to explicitly disallow values out of this range.</p> <p>My current code is as below. I am using <code>nan</code> to denote values out of the range.</p> <pre><code>from sympy import * x = symbols('x') f = Piecewise( (x * 2 - 3, (x &lt;= 2...
<python><math><sympy>
2025-01-04 19:11:20
1
1,570
Eric Stdlib
79,329,385
123,070
Converting Document Docx with Comments to markit using markitdown
<p>There is a new open source python library from Microsoft markitdown <a href="https://github.com/microsoft/markitdown" rel="nofollow noreferrer">https://github.com/microsoft/markitdown</a> It basically works fine on my Docx documents (if anyone uses it, make sure you use it on Python 3.10 or higher, on 3.9 it won't w...
<python><markdown><docx><document-conversion><markitdown>
2025-01-04 18:24:23
1
3,356
Bogdan_Ch
79,329,171
1,142,881
Can't run pytest with a `FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-build-env-3fagdb36/normal/bin/ninja' `
<p>I have tried many things like upgrading pip, pytest etc etc but nothing works. I have a fork of <code>scikit-learn</code> and working on some new functionality and would like to run all the unit tests but I can't:</p> <pre><code>(myenv) xxx@Thor:~/code/scikit-learn$ pytest ImportError while loading conftest '/home/x...
<python><scikit-learn><pytest><runtime-error>
2025-01-04 16:19:50
0
14,469
SkyWalker
79,329,141
524,587
Time different methods to recurse through directories in Linux
<p>I wanted to find out the most efficient method to recursively count subdirectories and files, and came up with the below tests. Some seem to work, but the results are inconsistent.</p> <ul> <li>How can I fix the inconsistency that every method results in different numbers of directories and different numbers of file...
<python><bash><recursion>
2025-01-04 15:59:31
2
4,228
YorSubs
79,329,131
14,896,203
Assist LSP with dynamically imported methods
<p>I have a directory structure with multiple subdirectories, each containing Python files (.py) that define classes. These classes need to be dynamically imported and attached as methods to a parent class. The parent class should have subclasses corresponding to each subdirectory, and the subclasses should contain the...
<python><pyright>
2025-01-04 15:52:47
0
772
Akmal Soliev
79,329,029
7,462,275
Ipywidgets : How to get the list of comm opened in a jupyter notebook?
<p>I created, in a Jupyter Notebook, a GUI where many ipywidgets are created, displayed or not, closed depending of user choices, file opened, ... But I am not sure that I do not let some <code>comms</code> (<a href="https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Low%20Level.html#comms" rel="nofollow nor...
<python><jupyter-notebook><ipython><ipywidgets>
2025-01-04 14:48:57
0
2,515
Stef1611
79,328,944
561,243
testing the output of seaborn figure level plots
<p>I'm writing a piece of code involving data displaying with seaborn. I would like to develop some testing units to test that the output of figure level plots are properly generated.</p> <p>I can test that the figure file is created, but how can I check that the output is the correct one? My idea would be to use a sta...
<python><pytest><seaborn>
2025-01-04 13:49:31
1
367
toto
79,328,792
1,788,656
Wrap_lon of the regionmask does not work with data span from -180 to 180
<p>All,</p> <p>I use regionmask package 0.13.0 to mask climate NetCDF data. I found that if my data extends from -180 to 180, the mask function returns all NAN even after I set <code>wrap_lon=180</code> and I did not set <code>wrap_lon</code> I got the following error</p> <p><code>ValueError: lon has data that is large...
<python><python-3.x><geopandas>
2025-01-04 12:02:32
1
725
Kernel
79,328,696
11,913,986
Azure Cognitive Vector search query and index creation
<p>I wanted to create a Azure Cognitive Search to query course catalogue using vectors. I have pandas dataframe called courses_pd and it has two columns, 'content' and 'embeddings' which is the embedding I have created using model = SentenceTransformer('all-MiniLM-L6-v2') and then model.encode(x).</p> <p>Below is the p...
<python><azure><vector><azure-cognitive-search><azure-ai-search>
2025-01-04 10:43:14
3
739
Strayhorn
79,328,291
16,783,860
mecab-python3 AWS lambda "circular import" error
<p>GOAL - to create a custom AWS lambda layer for <a href="https://pypi.org/project/mecab-python3/" rel="nofollow noreferrer">mecab-python3</a>.</p> <p>TRIED:</p> <ul> <li>local pip to zip and upload via S3 (using python3.11/3.12/3.13)</li> <li>docker container approach outlined below</li> </ul> <pre><code>FROM amazonl...
<python><aws-lambda><circular-dependency><mecab>
2025-01-04 05:16:38
0
383
kenta_desu
79,328,186
1,769,197
Python boto3: download files from s3 to local only if there are differences between s3 files and local ones
<p>i have the following code that download files from s3 to local. However, i cannot figure out how to download only if s3 files are different from and more updated than the local ones. What is the best way to do this ? Is it based on modified time or ETags or MD5 or all of these?</p> <pre><code>import boto3 import pat...
<python><amazon-web-services><amazon-s3><boto3>
2025-01-04 03:22:13
2
2,253
user1769197
79,327,929
1,760,791
Using OpenCV to achieve a top-down view of an image with ArUco Markers
<p>I have several images taken of a table setup with ArUco Markers. As end result, I would like to have a top-down coordinate system which defines the configuration of the markers on the tables.</p> <p>I managed to detect all the markers using the code:</p> <p><code>corners, ids = self.detect_aruco_markers(image)</code...
<python><opencv><computer-vision><augmented-reality><aruco>
2025-01-03 23:32:36
0
412
user1760791
79,327,903
12,590,154
Call function from macos framework (e.g. IntelPowerGadget)
<p>I'll say right away - this is my second day working with Python. So the question is probably simple. But for 2 days now I have not been able to find an answer to it. I want to use functions from the MacOS framework (IntelPowerGadget). At the moment I have written the following</p> <pre><code>if sys.platform == 'darw...
<python><macos>
2025-01-03 23:12:53
1
381
tremp
79,327,727
16,188,746
Conflicting dependencies while installing torch==1.10.0, torchaudio==0.10.0, and torchvision==0.11.0 in my Python environment
<p>I'm having trouble installing the following dependencies in my Python environment:</p> <pre><code>torch==1.10.0+cpu torchaudio==0.10.0 torchvision==0.11.0 pyannote-audio==0.0.1 lightning==2.3.3 numpy scipy pandas soundfile matplotlib </code></pre> <p>When running <code>pip install -r requirements.txt</code>, I encou...
<python><torch><torchvision><lightning><torchaudio>
2025-01-03 21:31:33
0
466
oran ben david
79,327,723
9,215,780
How Can I Use GPU to Accelerate Image Augmentation?
<p>When setting up image augmentation pipelines using <a href="https://keras.io/api/layers/preprocessing_layers/image_augmentation/" rel="nofollow noreferrer"><code>keras.layers.Random*</code></a> or other augmentation or <a href="https://keras.io/api/layers/preprocessing_layers/" rel="nofollow noreferrer">processing</...
<python><tensorflow><keras><pytorch><jax>
2025-01-03 21:28:17
1
17,272
Innat
79,327,540
9,632,639
How to reference an inner class or attribute before it is fully defined?
<p>I have a scenario where a class contains an inner class, and I want to reference that inner class (or its attributes) within the outer class. Here’s a concrete example using Django:</p> <pre><code>from django.db import models from django.utils.translation import gettext_lazy as _ class DummyModel(models.Model): ...
<python><python-3.x><django>
2025-01-03 19:55:38
2
881
Julio
79,327,508
6,312,511
Polars is killing the kernel on import
<p>I am running the following code on JupyterLab, with no other notebooks open:</p> <pre><code>!pip3 install polars --upgrade import polars as pl </code></pre> <p>The first line upgrades me to polars 1.18.0 with no issues, but then the program hangs for 3-5 seconds before I get an error message saying that the kernel h...
<python><python-polars><polars>
2025-01-03 19:41:01
1
1,447
mmyoung77
79,327,463
1,451,632
pytorch failing to load
<p>Until recently (before Christmas certainly, but not sure precisely when I last imported), <code>torch</code> was working fine on my Mac (w M1 Max chip), but it is failing to import today. The error message is</p> <pre><code>In [1]: import torch ------------------------------------------------------------------------...
<python><pytorch>
2025-01-03 19:20:11
0
311
user1451632
79,327,275
1,137,713
Gekko using APOPT isn't optimizing a single linear equation represented as a PWL
<p>I've run into an issue where I can't get APOPT to optimize an unconstrained single piecewise linear, and it's really throwing me for a loop. I feel like there's something I'm not understanding about <code>model.pwl</code>, but it's hard (for me) to find documentation outside of the <a href="https://gekko.readthedocs...
<python><nonlinear-optimization><gekko><mixed-integer-programming>
2025-01-03 17:53:28
1
2,465
iHowell
79,327,238
7,306,999
Replace table in HDF5 file with a modified table
<p>I have an existing HDF5 file with multiple tables. I want to modify this HDF5 file: in one of the tables I want to drop some rows entirely, and modify values in the remaining rows.</p> <p>I tried the following code:</p> <pre><code>import h5py import numpy as np with h5py.File(&quot;my_file.h5&quot;, &quot;r+&quot;)...
<python><numpy><hdf5><h5py><nastran>
2025-01-03 17:35:58
2
8,674
Xukrao
79,326,904
762,295
xxhash function gives different values between spark and python
<p>xxhash &quot;a&quot; provides different values</p> <p>spark</p> <pre><code>select xxhash64('b') -- -6391946315847899181 </code></pre> <p>python</p> <pre><code>import xxhash xxhash.xxh64('b', seed=42).intdigest() # 12054797757861652435 </code></pre> <p>While most of the bits are different, the first and last 2 bits a...
<python><apache-spark>
2025-01-03 15:17:54
0
1,463
Icarus
79,326,870
12,990,915
How to fix the size of only the “drawing” region (ignoring titles, labels) in Matplotlib?
<p>I’m creating plots for a research paper using Python’s Matplotlib and would like all plots to have the <em>exact same size</em> for the “inner” data region (where the plot or image is actually drawn). By default, <code>figsize</code> sets the overall figure dimensions, including margins for titles, axis labels, tick...
<python><matplotlib>
2025-01-03 15:00:49
2
383
user572780
79,326,812
3,557,405
FastAPI app: dynamically create an Enum and use it in SQLAlchemy models without circular dependencies?
<p>My app is structured as shown below.</p> <pre><code>app/ ├── backend/ │ └── main.py ├── models/ │ └── my_model.py └── utils/ └── enums.py </code></pre> <p><code>main.py</code> instantiates a config dict, containing key <code>prefix</code>, from a yaml file which is needed in <code>enums.py</code> to generate...
<python><oop><sqlalchemy><enums><fastapi>
2025-01-03 14:44:54
1
636
user3557405
79,326,712
4,653,423
Testing of cdk eks KubernetesManifest in python
<p>I am trying to write unit tests for my python CDK code. From the AWS doc I understand that templates are generated easily for the level-2 &amp; level-1 constructs so that the template can be tested. I am struggling to create tests for the code that use <code>aws_cdk.aws_eks.KubernetesManifest</code> because it uses ...
<python><aws-cdk><python-unittest>
2025-01-03 14:24:06
0
1,369
Mukund Jalan
79,326,576
1,406,168
Writing to application insights from FastAPI with managed identity
<p>I am trying to log from a FastAPI application to Azure application insights. It is working with a connection string, but I would like it to be working with managed identity. The code below does not fail - no errors or anything. But it does not log anything. Any suggestions to sove the problem, or how to troubleshoot...
<python><azure><fastapi><azure-application-insights><azure-managed-identity>
2025-01-03 13:19:36
1
5,363
Thomas Segato
79,326,501
775,066
How do I initialize empty variable for boto3 client
<p>I'd like to do a simple check if a variable for boto3 client is empty. I tried following approach:</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Example of boto3 client lazy initialization&quot;&quot;&quot; from typing import Optional import boto3 from botocore.client import BaseClient from m...
<python><boto3><python-typing><mypy><pyright>
2025-01-03 12:43:51
1
2,103
sumid
79,326,433
19,155,645
MarkItDown: missing documentation - how to use conversion features
<p>Microsoft released lately <a href="https://github.com/microsoft/markitdown/tree/main" rel="nofollow noreferrer">MarkItDown</a>, but the documentation for the Python API is quite short (or I did not manage to find it).</p> <p>Any help with how to figure out the different features it offers? At the moment the only doc...
<python><markdown><large-language-model>
2025-01-03 12:15:02
0
512
ArieAI
79,326,248
25,362,602
Cannot select venv created on WSL (when VS Code is NOT connected to WSL)
<p>I am working on Windows 11 with WSL2 (Ubuntu 22.04), with VS Code NOT connected to WSL (via command <code>Connect to WSL</code>).</p> <p>I used to work with a venv created on WSL, which I could select from the python interpreter list (command : <code>Python: Select Interpreter</code>), and it worked well.</p> <p>Now...
<python><visual-studio-code><windows-subsystem-for-linux><python-venv>
2025-01-03 10:58:35
0
451
vimchun
79,326,157
16,405,935
How to reorder columns if the columns have the same part name
<p>I want to reorder columns name if the columns have the same part name. Sample as below:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Branch': ['Hanoi'], '20241201_Candy': [3], '20241202_Candy': [4], '20241203_Candy': [5], '20241201_Candle': [3], '20241202_Candle': [4], '20241203_Candle': [5],...
<python><pandas>
2025-01-03 10:26:07
2
1,793
hoa tran
79,326,135
10,000,669
Very similar functions have noticeably different running times
<p>I have these 2 functions to find the left null space of a matrix over GF(2) for the Quadratic Sieve Factoring Algorithm, given a list of integers(each of which represent a bitarray):</p> <pre><code>import random import time def print_mat(m, n): for v in m: print(f&quot;{v:0{n}b}&quot;) def solve_bits_m...
<python><performance><optimization><bit-manipulation><sparse-matrix>
2025-01-03 10:16:46
1
1,429
J. Doe
79,326,029
2,092,445
Optimize the process of handling larger than memory feather files using python (pandas)
<p>I am storing stock prices for different entities as separate feather files in S3 bucket. On high level, the content of any feather file looks like below.</p> <pre><code>month | value | observation | ----------------------------- 2024-01 | 12 | High 2024-01 | 5 | Low </code></pre> <p>A lambda function written in py...
<python><pandas><feather>
2025-01-03 09:35:14
1
2,264
Naxi
79,325,674
687,331
blackboxprotobuf showing positive values instead of negative values for protobuf response
<p>I have an issue where blackboxprotobuf takes response of protobuf &amp; returning the dictionary where i see few values where suppose to be negative instead coming as positive value.</p> <p>Calling an APi with lat (40.741895) &amp; long(-73.989308). Using these lat &amp; long, a key is genereated '<strong>81859706</...
<python><protocol-buffers>
2025-01-03 06:37:36
1
1,985
Anand
79,325,663
2,012,814
Error during summarization: '>=' not supported between instances of 'int' and 'str' using transformers
<p>When sending queries to</p> <pre><code>outputs = model.generate(inputs, max_length=hf_max_length, num_return_sequences=1) </code></pre> <p>I have been getting this error</p> <pre><code>Error during summarization: '&gt;=' not supported between instances of 'int' and 'str' </code></pre>
<python><huggingface-transformers>
2025-01-03 06:31:35
1
363
kurtfoster
79,325,612
4,953,146
Should Python's module directory match the Python version?
<h3>Error message</h3> <p>Context: MacOS Ventura (Intel Imac)</p> <p>Python code:</p> <pre><code>import paho.mqtt.client as mqtt </code></pre> <p>Failure returns:</p> <blockquote> <p>ModuleNotFoundError: No module named 'paho'</p> </blockquote> <h3>Attempts to <a href="https://pypi.org/project/paho-mqtt/" rel="nofollow...
<python>
2025-01-03 05:59:37
0
1,577
gatorback
79,325,463
11,850,322
Pandas Groupby Rolling Apply Custom Function (Pass Dataframe not Series)
<p>I need to do a <code>groupby</code> then <code>rolling</code> and <code>apply</code> a custom function</p> <p>This is my custom function:</p> <pre><code>def reg_DOL(group): g = group.copy() if pd.isna(group['lnebit'].iloc[0]) or pd.isna(group['lnsale'].iloc[0]): return np.NaN else: g['l...
<python><pandas><group-by>
2025-01-03 04:00:30
0
1,093
PTQuoc