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,346,838
16,854,651
Issues in updating Excel table range and conditional formatting programmatically using openpyxl, python
<p>I am using Python <strong>openpyxl</strong> to update an Excel sheet that contains a table and conditional formatting. The table has a predefined style, and the conditional formatting uses a 3-color scale applied to a specific range. I am trying to:</p> <ul> <li>Extend the table range to include a new column.</li> <...
<python><python-3.x><pandas><openpyxl>
2025-01-10 19:37:01
1
344
Josal
79,346,700
843,400
mlflow.pytorch.load_model failing due to failure "No module named 'src.<mymodelname>'" issue with unpickler.load
<p>I am working to support some model developers by prototyping some functionality with MLflow model registry.</p> <p>We successfully register versions of the model fine (it's a Pytorch Lightning model), and I recently also added code_paths to the log_model call so that theoretically all of the original model code ends...
<python><pytorch><mlflow><pytorch-lightning>
2025-01-10 18:31:56
0
3,906
CustardBun
79,346,575
5,344,240
Overriding __str__ and __repr__ magic methods for built-in float class in Python
<p>The class below works as expected:</p> <pre><code>class Storage(float): def __new__(cls, value, unit): instance = super().__new__(cls, value) instance.unit = unit return instance def __str__(self): return f&quot;{super().__repr__()} {self.unit}&quot; # 1. # retur...
<python>
2025-01-10 17:40:53
1
455
Andras Vanyolos
79,346,555
6,038,082
How to use Python logger in help messages without the __main__.INFO getting printed
<p>I am using 'logging' module to log my info,error and warning messages. However to print the help message, I am removing the logger handler by removeHandler otherwise <strong>main</strong>.INFO gets printed with the help messages. So I am using 'print' function instead for that.</p> <p>Is there a way to use logger fo...
<python>
2025-01-10 17:34:50
1
1,014
A.G.Progm.Enthusiast
79,346,395
7,425,379
Why do I get "AttributeError: 'str' object has no attribute 'value'" when trying to use darts ExponentialSmoothing with a "trend" argument?
<p>Here is the code I have:</p> <pre><code># Define models models = { 'ExponentialSmoothing': [ ExponentialSmoothing(trend='add', seasonal='add', seasonal_periods=52), ExponentialSmoothing(trend='add', seasonal='mul', seasonal_periods=12) ], 'SeasonalARIMA': [ ARIMA(p=1, d=1, q=1, seasona...
<python><time-series><forecasting><u8darts>
2025-01-10 16:42:13
1
1,134
GaB
79,346,210
3,858,619
Python cmislib3 PDF being white after createDocumentFromString
<p>I need to send PDF file over CMIS using Browser bindings. I have the following code, but on my CMIS application my PDF is blank. Furthermore, I try using createDocument() but it's not working.</p> <p>BTW, my PDF before open and read/decode/encode is good. So I think there is an issue while converting to b64 or other...
<python><cmis>
2025-01-10 15:35:47
0
1,093
Nathan30
79,345,994
10,037,034
How to run a task for specific time?
<p>I am creating a DAG in Airflow, and within this DAG, I need to trigger another DAG using a TimeSensor. The goal is to set the target time to between 2:00 AM 3:00 AM, and if the Timesensor is triggered after 2:00 AM, it should wait until the next day's 2:00 AM. However, I am encountering the following error:</p> <pre...
<python><airflow>
2025-01-10 14:19:07
0
1,311
Sevval Kahraman
79,345,986
7,959,614
Fast(est) exponentiation of numpy 3D matrix
<p><code>Q</code> is a 3D matrix and could for example have the following shape:</p> <blockquote> <p>(4000, 25, 25)</p> </blockquote> <p>I want raise <code>Q</code> to the power <code>n</code> for <code>{0, 1, ..., k}</code> and sum it all. Basically, I want to calculate</p> <blockquote> <p>\sum_{i=0}^{k-1}Q^n</p> </bl...
<python><numpy>
2025-01-10 14:16:00
3
406
HJA24
79,345,979
14,254,771
Show waiting input string when attaching to a container
<p>I'm trying to run a client-server application in Python using docker-compose:</p> <p>I wrote a client.py file that awaits input: <code>command=input(&quot;enter command&quot;)</code>. The client.py sends requests to the server based on the command it got.</p> <p>The project tree looks like this:</p> <pre><code>. β”œβ”€β”€...
<python><python-3.x><docker><docker-compose>
2025-01-10 14:13:53
1
499
Wahalez
79,345,801
273,593
Typing issue using a taskgroup in a taskflow-based dag
<p>I'm trying to improve the readability of my dags using taskgroups.</p> <p>I also rely on the taskflow syntax, and the ability to map function parameters / return values to xcom automatically.</p> <p>Also also :) I'm a mypy / pyright user, and I try to keep the source code of my project type-annotated.</p> <p>With th...
<python><airflow><python-typing>
2025-01-10 13:08:35
0
1,703
Vito De Tullio
79,345,778
1,627,106
Poetry not updating sub dependencies despite version constraint allowing it
<p>My code is using a package (<code>taskiq</code>), which in turn depends on another package (<code>pycron</code>). Why is <code>poetry update</code> not updating <code>pycron</code> despite version constraints allowing it?</p> <pre class="lang-shell prettyprint-override"><code>$ poetry update Updating dependencies Re...
<python><python-poetry>
2025-01-10 12:58:34
1
1,712
Daniel
79,345,695
9,467,944
Pair data located in the same string, AWK or other
<p>I have a file with strings like this</p> <pre><code>1A,1B,1C, 2A,2B,2C, </code></pre> <p>between the group &quot;1&quot; and the group &quot;2&quot; there is a tab (each string has a different number of elements inside the file); I would need to pair the &quot;A&quot;, &quot;B&quot;, and &quot;C&quot;, and move ea...
<python><bash><awk>
2025-01-10 12:21:03
3
549
Emma Athan
79,345,689
11,790,979
Trouble calling an activate script from within a powershell script
<p>I'm trying to write some powershell scripts to &quot;one-click&quot; some setup for project initialisation.</p> <p>I am unable to get it to call the activate script. Typically, in a terminal I would create the virtual environment, then call the activate script using <code>.\venv\Scripts\Activate</code>. However, bec...
<python><powershell>
2025-01-10 12:18:55
1
713
nos codemos
79,345,665
4,465,920
Pact file not being saved to configured directory
<p>For some reason the Json contract file Pact generates after running the test I created is being saved to the project's root folder instead of using the path I have defined on its configuration. This application is running in WSL, and it saves to the wrong place in the virtual environment and in my local folder, too....
<python><windows-subsystem-for-linux><pact>
2025-01-10 12:09:50
1
927
apires
79,345,483
1,166,789
Install package from private Github repository with dependency on another private Github repository
<p>I am having troubles installing a package from a private Github repository (I am using a personal access token for this), but this package has a dependency to another private Github repository from the same organization (so the PAT token is valid) which is not correctly resolved during the installation. Here is the ...
<python><github><pip><access-token>
2025-01-10 11:03:51
0
351
Javier
79,345,392
1,473,517
Running functions in parallel and seeing their progress
<p>I am using joblib to run four processes on four cores in parallel. I would like to see the progress of the four processes separately on different lines. However, what I see is the progress being written on top of each other to the same line until the first process finishes.</p> <pre><code>from math import factorial...
<python><joblib><tqdm>
2025-01-10 10:34:59
3
21,513
Simd
79,345,354
2,915,050
FileNotFoundError within Python package on a file in same directory as calling function
<p>I have created a Python package, and one of the functions I have written opens a <code>.txt</code> file in the same directory as that function. Locally, this works fine, but when the package is built and executed a <code>FileNotFoundError</code> is produced.</p> <p>My package directory looks like this:</p> <pre><cod...
<python><python-packaging>
2025-01-10 10:22:05
0
1,583
RoyalSwish
79,345,299
2,957,687
Best default location for shared object files
<p>I have compiled C code to be called by a Python script. Of course I can include it with <code>cdll.LoadLibrary(&quot;./whatever.so&quot;)</code>, but I would prefer it to be accessible to all Python scripts in different folders. The idea is that I use <strong>default paths</strong> for shared objects and do not cha...
<python><shared-libraries><dynamic-linking>
2025-01-10 10:01:22
1
921
Pygmalion
79,345,142
8,638,267
arabic(hijri) date picker for tkinter python
<p>I could only find georgian date picker, is there a way to show hijri/arabic dates on a date picker? I'm not looking for a converter from georgian to hijri.</p>
<python><tkinter><datepicker>
2025-01-10 09:08:38
1
1,173
John Sall
79,345,130
2,269,457
Create geoparquet file from large data set in chunks in python
<p>I am trying to achieve chunkwise writing of geoparquet files. While writing a parquet file chunkwise via <code>pyarrow.RecordBatch</code> is trivial for <code>pandas</code> chunks and also well documented, doing the same when creating a geoparquet file via <code>geopandas</code> (or any other approach) seems to be l...
<python><parquet><geopandas><pyarrow>
2025-01-10 09:02:53
1
403
Sacha Viquerat
79,344,960
687,331
Extracting vendor info from Probe Request using Scapy
<p>Trying to extract the vendor information (Apple, Samsung, etc) from Probe Request coming from mobile, So far no luck. Not sure where the corrections to be made to get this info.</p> <p>Adding my code:</p> <pre><code>import codecs from scapy.all import * from netaddr import * def handler(p): if not (p.haslayer(...
<python><scapy><probe>
2025-01-10 07:55:17
1
1,985
Anand
79,344,934
1,849,773
Mails sent with attachments, using the library exchangelib in Python, are NOT visible in the sent folder
<p>I have email addresses stored in AWS Workmail and I want to use them with an AWS Lambda in order to send mails to different destination email addresses. I managed to send mails however only the mails WITHOUT attachments are visibile in the sent folder (named Sent Items in AWS Workmail). This is a huge problem for us...
<python><amazon-web-services><exchangelib><amazon-workmail>
2025-01-10 07:45:42
0
1,042
Yassir S
79,344,879
2,944,736
How do I run torch.distributed between Docker containers on separate instances using the bridge network?
<p>I am trying to run a simple torch.distributed script between two Docker containers running on separate instances. Below is the code I am using:</p> <pre><code>import os import torch import torch.distributed as dist def init_distributed(): os.environ['MASTER_ADDR'] = &quot;10.12.27.241&quot; os.environ['MAST...
<python><docker><pytorch><docker-network><gloo>
2025-01-10 07:16:35
1
579
Jay Dharmendra Solanki
79,344,840
1,573,589
mariadb MEDIUMTEXT COMPRESSED updating takes forether
<p>I am using mariadb to store HTML files, and the column defined as MEDIUMTEXET CONPRESSED for HTML with some other columns storing INT and VARCHAR keys. Yet I encountered a rather bizarre behaviour:</p> <ol> <li>When I create a record with HTML, it flies, however</li> <li>When I create a record first, and add HTML la...
<python><mariadb><mariadb-10.5>
2025-01-10 06:58:49
1
337
Alex J.
79,344,258
1,227,012
PostgreSQL connection problem from a Python script that uses psycopg2. What am I missing?
<p>I have a pretty vanilla PostgreSQL installation. I'm trying to use a feature of <code>jsonschematoddl</code> to create a table(s) from a JSON schema file.</p> <p>I can load the schema file fine, but my connection to the local PostgreSQL database always fails with a 403 &quot;Forbidden,&quot; which I assume is an aut...
<python><postgresql>
2025-01-09 23:09:14
0
1,168
David Nedrow
79,344,159
1,926,221
Disable PySpark to print info when running
<p>I have started to use PySpark. Version of PySpark is <code>3.5.4</code> and it's installed via <code>pip</code>.</p> <p>This is my code:</p> <pre><code>from pyspark.sql import SparkSession pyspark = SparkSession.builder.master(&quot;local[8]&quot;).appName(&quot;test&quot;).getOrCreate() df = pyspark.read.csv(&quot;...
<python><apache-spark><pyspark><pipenv>
2025-01-09 22:07:59
2
3,726
IGRACH
79,344,148
1,504,016
FastAPI dynamic advanced dependencies /
<p>I started from the example shown on this page : <a href="https://fastapi.tiangolo.com/advanced/advanced-dependencies/#use-the-instance-as-a-dependency" rel="nofollow noreferrer">https://fastapi.tiangolo.com/advanced/advanced-dependencies/#use-the-instance-as-a-dependency</a></p> <pre><code>from typing import Annotat...
<python><dependencies><fastapi><decorator>
2025-01-09 22:03:30
1
2,649
ibi0tux
79,344,035
29,131,715
How to add requirements.txt to uv environment
<p>I am working with <a href="https://docs.astral.sh/uv/" rel="noreferrer">uv</a> for the first time and have created a venv to manage my dependencies. Now, I'd like to install some dependencies from a <em>requirements.txt</em> file.</p> <p>How can this be achieved with uv?</p> <p>I already tried manually installing ea...
<python><python-venv><uv>
2025-01-09 21:04:59
1
413
BitsAndBytes
79,343,989
1,718,989
Python Spyder IDE - How do view the docstring for a method in the REPL?
<p>Currently I am going through a course and am learning about Spyder and the interface. I downloaded Anaconda and am using Spyder 6.0.1 with Python 3.12.</p> <p>The text book was going through a section on how to &quot;figure things out in Python&quot;. One suggestion was to go to the REPL in Spyder and try typing <st...
<python><documentation><docstring>
2025-01-09 20:44:17
0
311
chilly8063
79,343,939
15,547,292
Get char limit for subprocess args
<p>In Python, is there a way to get the maximum number of characters that can be passed to a subprocess on the host in question?</p> <p>I'm asking for implementing xargs-like functionality, i.e. running a command on a (potentially huge) list of file paths collected previously by python functions, so I'd need to know ho...
<python><subprocess>
2025-01-09 20:19:20
1
2,520
mara004
79,343,888
13,100,489
Why does my SVG render correctly in web viewers but not in pydiffvg even when stroke attributes are missing?
<p>I’m trying to render an SVG using pydiffvg, but it fails or renders incorrectly (the structure is fine but the color is very off, missing elements) when certain stroke attributes like stroke-width are missing in the SVG. The same SVG renders perfectly in web browsers or tools like Inkscape, which seem to &quot;guess...
<python><svg><rendering>
2025-01-09 19:57:59
0
447
Ravish Jha
79,343,882
564,709
python, .env, and shell environment variables
<p>I could use some help understanding how python interacts with .env files and shell environment variables.</p> <p>I have a <code>.env</code> file that has general configurations for accessing our production server. I also have a number of separate customer-specific <code>.env.CUSTOMER</code> files that contain specif...
<python><bash><python-dotenv>
2025-01-09 19:55:10
0
3,336
dino
79,343,784
4,613,606
pyspark - Issue in converting hex to decimal
<p>I am facing an issue while converting hex to decimal (learned from <a href="https://stackoverflow.com/q/47930150/4613606">here</a>) in pyspark.</p> <pre><code>from pyspark.sql.functions import col, sha2, conv, substring # User data with ZIPs user_data = [ (&quot;100052441000101&quot;, &quot;21001&quot;), (&...
<python><pyspark><hash><hex>
2025-01-09 19:14:15
1
1,126
Gaurav Singhal
79,343,740
2,091,169
Torch model call works fine on Github Codespaces, but crashes on Render.com
<p>The following code:</p> <pre class="lang-py prettyprint-override"><code>from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC import torch audio_proc = Wav2Vec2Processor.from_pretrained( &quot;vitouphy/wav2vec2-xls-r-300m-timit-phoneme&quot; ) audio_model = Wav2Vec2ForCTC.from_pretrained( &quot;vitouph...
<python><pytorch><render.com>
2025-01-09 18:56:24
0
23,338
Jivan
79,343,728
5,561,472
ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object
<p>My code is as follows:</p> <pre class="lang-py prettyprint-override"><code>import pyomo.environ as pyo model = pyo.ConcreteModel() model.x = pyo.Var(range(2), domain=pyo.Reals) model.Constraint2 = pyo.Constraint(expr=sum([x for x in model.x]) &gt;= 0) </code></pre> <p>I am getting the error:</p> <pre><code>ValueErr...
<python><pyomo>
2025-01-09 18:51:06
1
6,639
Andrey
79,343,703
8,800,836
Generalized Kronecker product with different type of product in numpy or scipy
<p>Consider two boolean arrays</p> <pre class="lang-py prettyprint-override"><code>import numpy as np A = np.asarray([[True, False], [False, False]]) B = np.asarray([[False, True], [True, True]]) </code></pre> <p>I want to take the kronecker product of <code>A</code> and <code>B</cod...
<python><numpy><scipy><xor><kronecker-product>
2025-01-09 18:37:35
1
539
Ben
79,343,664
3,137,388
gunicorn is not maintaining persistent TLS connections
<p>We need to write a Python server which maintains persistent connections so when another request comes, it will use the old connection instead of creating new connection. We used <code>flask</code> and <code>gunicorn</code> for this.</p> <p>Python code:</p> <pre class="lang-py prettyprint-override"><code> from flask ...
<python><flask><gunicorn><keep-alive>
2025-01-09 18:21:48
1
5,396
kadina
79,343,557
311,864
Using %matplotlib widget in jupyer notebook and I get the interactive plot coming out nicely. But everything is duplicated
<p>Using %matplotlib widget in jupyer notebook and I get the interactive plot coming out nicely. But everything is duplicated.</p> <p>When I remove the display keyword. It renders but I need the HBox in order to align the widgets. If not nothing would be aligned.</p> <pre><code>%matplotlib widget import tomolyzer as t ...
<python><matplotlib><jupyter>
2025-01-09 17:43:16
1
413
n8CodeGuru
79,343,402
10,634,126
Pygooglenews import failure
<p>I have the following versions installed:</p> <pre><code>Name: pygooglenews Version: 0.1.3 </code></pre> <pre><code>Name: feedparser Version: 6.0.11 </code></pre> <p>Nevertheless, when I try to import pygooglenews, I get the following error:</p> <pre><code>-------------------------------------------------------------...
<python><feedparser><pygooglenews>
2025-01-09 16:37:45
1
909
OJT
79,343,187
14,824,108
Implementation for a recursive computation in python
<p>I'm trying to implement the recursion below for <code>tilde_alpha_t</code>: <a href="https://i.sstatic.net/YTfPlXx7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YTfPlXx7.png" alt="enter image description here" /></a></p> <p>I have <code>torch</code> tensors for <code>t</code> (time) which looks lik...
<python><pytorch>
2025-01-09 15:32:34
1
676
James Arten
79,342,997
13,441,462
Wagtail - add custom link option
<p>I would like to customize <code>External</code> link type in Wagtail links in admin <code>RichText</code> field - I need to change (or at least disable) the link validation (e.g., to my custom regex) in admin frontend, as my links have different format to <code>https://&lt;something&gt;</code>.</p> <p>Does anybody ...
<python><django><wagtail><wagtail-admin>
2025-01-09 14:34:41
0
409
Foreen
79,342,989
1,788,656
Xarray.open_dateset uses more than double the size of the file itself
<p>All, I am opening NetCDF files from <a href="https://cds.climate.copernicus.eu/datasets/derived-era5-land-daily-statistics?tab=download" rel="nofollow noreferrer">Copernicus data center</a> using xarray version 2024-11-0, using open_dataset function as the following:</p> <pre><code>import xarray as xr file1=xr.open_...
<python><python-3.x><python-2.7><multidimensional-array><python-xarray>
2025-01-09 14:33:26
1
725
Kernel
79,342,924
2,496,293
Can't enable PTP on basler cameras
<p>I am following <a href="https://docs.baslerweb.com/precision-time-protocol#enabling-ptp-clock-synchronization" rel="nofollow noreferrer">this</a> documentation in attempt to clock-sync multiple basler cameras. However, the code instructions I find there don't seem to work.</p> <p>Below is small self-contained piece ...
<python><basler>
2025-01-09 14:13:29
1
2,441
Sam De Meyer
79,342,896
5,118,420
How can I override settings for code ran in urls.py while unit testing django
<p>my django app has a env var <code>DEMO</code> which, among other thing, dictate what endpoints are declared in my <code>urls.py</code> file.</p> <p>I want to unit tests these endpoints, I've tried <code>django.test.override_settings</code> but I've found that <code>urls.py</code> is ran only once and not once per un...
<python><django><testing>
2025-01-09 14:01:02
4
385
Jean Bouvattier
79,342,804
10,567,859
pySpark Hadoop AWS s3 requester-pays.enabled config doesn't work
<p>I am trying to read AWS S3 bucket with pyspark. The bucket requires requester to pay to read.</p> <p>However, it doesn't seem to work although the similar credentials on aws-cli works and the reason that I believe <code>spark.hadoop.fs.s3a.requester-pays.enabled</code> config is the reason is because if I remove the...
<python><amazon-web-services><amazon-s3><hadoop><pyspark>
2025-01-09 13:33:12
1
523
Edward Chew
79,342,757
1,506,763
Add buttom from admin panel to ModelForm in Django
<p>In the admin panel of a django app when you are adding a database entry that links data from another table on a foreign key you get a dropdown to select the entry and 3 buttons to edit, add or view an entry like this:</p> <p><a href="https://i.sstatic.net/LhS7OaJd.png" rel="nofollow noreferrer"><img src="https://i....
<python><django>
2025-01-09 13:20:17
0
676
jpmorr
79,342,713
10,750,537
Deducing the behavior of non-blocking sys.stdin.read()
<p>Could you please explain me the logic of the return value of <code>sys.stdin.read.read(10)</code> in following code, according to the documentation? Honestly, I was not able to deduce it.</p> <pre><code>import sys, os os.set_blocking(sys.stdin.fileno(), False) c = sys.stdin.read(10) print(c) </code></pre> <p>This i...
<python><python-3.x><io>
2025-01-09 13:07:34
0
381
JtTest
79,342,389
13,259,162
Numpy grayscale image to black and white
<p>I use the MNIST dataset that contains 28x28 grayscale images represented as numpy arrays with 0-255 values. I'd like to convert images to black and white only (0 and 1) so that pixels with a value over 128 will get the value 1 and pixels with a value under 128 will get the value 0.</p> <p>Is there a simple method to...
<python><numpy><mnist>
2025-01-09 11:16:47
1
309
NoΓ© Mastrorillo
79,342,235
6,815,232
How to download image with selenium from etsy?
<p>I need dwonload image from etsy</p> <p>But after run this code, return this error:</p> <p><code>requests.exceptions.SSLError: HTTPSConnectionPool(host='i.etsystatic.com', port=443): Max retries exceeded with url: /40895858/r/il/764bf3/4699592436/il_340x270.4699592436_edpm.jpg (Caused by SSLError(SSLEOFError(8, 'EOF ...
<python><web-scraping><selenium-chromedriver>
2025-01-09 10:22:12
1
1,706
mySun
79,342,183
4,451,315
DuckDBPyRelation from Python dict?
<p>In Polars / pandas / PyArrow, I can instantiate an object from a dict, e.g.</p> <pre><code>In [12]: pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) Out[12]: shape: (3, 2) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ a ┆ b β”‚ β”‚ --- ┆ --- β”‚ β”‚ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ═════║ β”‚ 1 ┆ 4 β”‚ β”‚ 2 ┆ 5 β”‚ β”‚ 3 ┆ 6 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜ </code></pre> <p>Is there...
<python><duckdb>
2025-01-09 10:07:38
1
11,062
ignoring_gravity
79,342,159
1,090,562
Finding solutions to linear system of equations with integer constraint in scipy
<p>I have a system of equations where each equation is a linear equation with boolean constraints. For example:</p> <pre><code>x1 + x2 + x3 = 2 x1 + x4 = 1 x2 + x1 = 1 </code></pre> <p>And each <code>x_i</code> is either 0 or 1. Sometimes there might be a small positive (&lt;5) coefficient (for example <code>x1 + 2 * ...
<python><numpy><scipy><linear-programming><scipy-optimize>
2025-01-09 09:59:05
8
224,221
Salvador Dali
79,342,104
11,348,853
Dynamic type annotation for Django model managers custom method
<p>I need help with type hint for a custom model manager method.</p> <p>This is my custom manager and a base model. I inherit this base model to other models so that I don't have to write common fields again and again.</p> <pre class="lang-py prettyprint-override"><code>class BaseManager(models.Manager): def get_or...
<python><django><django-models>
2025-01-09 09:40:24
1
2,387
Nahidujjaman Hridoy
79,341,901
4,907,305
How to enter a multi-line command in %debug in a python Jupyter notebook?
<p>How to enter a multi-line command in %debug in a python Jupyter notebook?</p> <p>If you try enter, ctrl+enter, shift+enter, alt+enter the first line will be executed, instead of going to a second line.</p>
<python><debugging><jupyter-notebook><ipdb>
2025-01-09 08:33:31
1
384
Jens Wagemaker
79,341,886
1,045,755
Pandera validation on dynamic/unknown columns
<p>I am trying to use Pandera to validate at least some of my dataframe.</p> <p>As an example I have one that only contains a date column, and then some columns which I don't really know in advance. At least not the name. However, I know that every column should contain floats or NaN's.</p> <p>So how do I validate that...
<python><pandera>
2025-01-09 08:26:03
1
2,615
Denver Dang
79,341,787
14,739,428
threads not correctly running in Celery
<p>here is the testing code:</p> <pre><code>@app.task(base=AbortableServerSideContextTask) def test_watch_dog(): from common.utils.test_with_heartbeat import TestWithWatchDog with TestWithWatchDog(): times = 0 while times &lt; 10: from flask import current_app current_app...
<python><python-3.x><flask><celery>
2025-01-09 07:57:18
0
301
william
79,341,326
2,896,120
Semantic Kernel Plugin Function: Arguments must be in JSON format
<p>I'm using semantic kernel and azure open ai as my search. I have this plugin I created:</p> <pre><code>class QuerySQLTablesPlugin: @kernel_function( description=&quot;Get the schema of the table to create the query the user needs&quot;) async def fetch_schema_async(self, table_name: str): tab...
<python><openai-api><semantic-kernel>
2025-01-09 03:45:09
0
2,960
user2896120
79,341,136
3,137,388
Flask is closing https connections even after setting WSGIRequestHandler.protocol_version to http/1.1
<p>We need to write a flask application which should not close the connection after serving the client. Below is the python code</p> <pre><code>from flask import Flask, request, make_response, jsonify from werkzeug.serving import WSGIRequestHandler app = Flask(__name__) @app.route('/v1') def get_availability(): re...
<python><flask>
2025-01-09 01:19:58
0
5,396
kadina
79,341,135
11,505,680
Python initialization with multiple inheritance
<p>I have the following class hierarchy. The goal is for the calling code to choose either a base <code>Foo</code> object or a <code>Foobar</code> object that also provides the additional <code>Bar</code> functionality.</p> <pre class="lang-py prettyprint-override"><code>class Foo: def __init__(self): self....
<python><multiple-inheritance><super>
2025-01-09 01:18:36
3
645
Ilya
79,341,058
9,686,427
Counting the hashtags in a collection of tweets: two methods with inconsistent results
<p>I'm playing around with a numpy dataframe containing two columns: 'tweet_text' and 'cyberbullying_type'. It was created through <a href="https://www.kaggle.com/datasets/saurabhshahane/cyberbullying-dataset" rel="nofollow noreferrer">this dataset</a> as follows:</p> <p><code>df = pd.read_csv('data/cyberbullying_tweet...
<python><dataframe><numpy><numpy-ndarray><python-re>
2025-01-09 00:17:27
2
484
Sam
79,340,961
511,302
Google credentials not getting a refresh token?
<p>I have tried to access gmail through the google oauth2 client. However I cannot seem to make it work:</p> <pre><code>def readEmails(): &quot;&quot;&quot;Shows basic usage of the Gmail API. Lists the user's Gmail labels. &quot;&quot;&quot; creds = None # The file token.json stores the user's acces...
<python><google-oauth>
2025-01-08 23:07:42
0
9,627
paul23
79,340,945
20,295,949
Selenium Twitter Scraper Closes Immediately – Not Detecting New Tweets
<p>I'm trying to write a Selenium script that scrapes Twitter for new tweets from a specific user after the script starts running. The goal is to print and save tweets to a CSV if they are posted after the script begins execution.</p> <p>Here’s the code I’m working with:</p> <pre><code>from selenium import webdriver fr...
<python><selenium-webdriver><web-scraping><xpath><css-selectors>
2025-01-08 22:52:57
0
319
HamidBee
79,340,748
5,125,230
Regex for a particular character in an unpaired tag
<p>I'm trying to find a character within an unbalanced pair of tags. I can identify it within a matched set, and when the matching pairs are a single character each, but I can't seem to hit on the syntax to find it within an unmatched set when the pairs are multiple characters each. I've tried several combinations of l...
<python><python-3.x><regex>
2025-01-08 21:03:23
1
614
vr8ce
79,340,503
20,295,949
How to Adjust Nitter Scraper to Print New Tweets in Real-Time?
<p>I'm using the ntscraper library to fetch tweets from a specific user. Currently, the script fetches the most recent tweet, but it only pulls pre-existing tweets at the time the script runs. Here's the code I'm using:</p> <pre><code>from ntscraper import Nitter import pandas as pd # Initialize the scraper scraper = ...
<python><selenium-webdriver><web-scraping><scrapy>
2025-01-08 19:14:13
1
319
HamidBee
79,340,487
5,312,606
Properly re-expose submodule (or is this a bug in pylance)
<p>I am working on a python package <code>chemcoord</code> with several subpackages, some of whom should be exposed to the root namespace.</p> <p>The repository is <a href="https://github.com/mcocdawc/chemcoord" rel="nofollow noreferrer">here</a>, the relevant <code>__init__.py</code> file is <a href="https://github.co...
<python><packaging><pyright>
2025-01-08 19:09:33
1
1,897
mcocdawc
79,340,472
2,711,474
How to change drop-down object in Rally
<p>I have yet to figure out how to change any object represented by a drop-down selector on Rally to another value. I can copy an existing one from another User Story or the original Object into a new User Story, but I can't change any of the values in that object.</p> <p>I've tried way too many different methods to l...
<python><pyral>
2025-01-08 19:03:25
0
425
TesseractE
79,340,141
7,631,505
Issue solving differential equation with solve_ivp depending on t_span
<p>I'm using <code>solve_ivp</code> but I'm getting strange results depending on the settings of the problem, though i think it's more an issue with the implementation of the solver than a coding issue, but I'd love for someone to provide an input. So my code is as follows:</p> <pre><code>import numpy as np from scipy....
<python><scipy><ode>
2025-01-08 17:07:37
1
316
mmonti
79,339,965
4,431,798
Why does pyrtools imshow() print a value range that's different from np.min() and np.max()?
<p><strong>quick problem description:</strong></p> <p>pyrtools imshow function giving me different and negative ranges</p> <p><strong>details:</strong></p> <p>im following the tutorial at <a href="https://pyrtools.readthedocs.io/en/latest/tutorials/01_tools.html" rel="nofollow noreferrer">https://pyrtools.readthedocs.i...
<python><image-processing>
2025-01-08 16:09:10
1
441
SoajanII
79,339,759
4,536,981
Custom thumbnail upload succeeds but is not applied to YouTube Shorts
<p>I’m uploading a custom thumbnail for a YouTube Shorts video using the YouTube Data API v3. The API response indicates success, but the uploaded thumbnail is not applied to the video.</p> <pre><code>if thumbnail_path: try: # Verify thumbnail meets requirements img = Image.o...
<python><youtube-api><youtube-data-api>
2025-01-08 15:28:31
0
596
Wocugon
79,339,719
6,413,657
Extract Hijri date from excel file and plot it
<p>I have an excel sheet contain the following data:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Date</th> <th>counts</th> </tr> </thead> <tbody> <tr> <td>1446/05/25</td> <td>12</td> </tr> <tr> <td>1446/05/26</td> <td>2</td> </tr> <tr> <td>1446/05/26</td> <td>6</td> </tr> <tr> <td>1446/0...
<python><pandas><dataframe>
2025-01-08 15:18:53
1
363
Yousra Gad
79,339,649
9,396,198
Static type checker (mypy, pytype, pyright) complains with dynamically generated `Union`
<p>How does one go about creating a TypeAdapter from a dynamic <code>Union</code> without running into linting errors?</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel, TypeAdapter class Lion(BaseModel): roar: str class Tiger(BaseModel): roar: str ZOO = { &quot;lion&qu...
<python><python-typing><mypy><pydantic>
2025-01-08 14:58:20
1
1,558
fmagno
79,339,594
13,132,640
How to implement a custom equality comparison which can test pd.DataFrame attributes?
<p>I have a custom dataclass, which is rather lage (many attributes, methods). Some attributes are pandas dataframes. The default __eq__ comparison does not work for the attribtues which are pandas dataframes. Hence, I started trying to write a custom __eq__ function to handle this. I came up with this, which seems to ...
<python><class><equality>
2025-01-08 14:40:18
0
379
user13132640
79,339,539
10,200,255
Execution Reverted on Base Layer 2 Buy transaction using web3.py
<p>I'm trying to write a service using python and web3.py to execute a &quot;buy&quot; transaction on a <a href="https://basescan.org/address/0xf66dea7b3e897cd44a5a231c61b6b4423d613259" rel="nofollow noreferrer">Base smart contract</a>.</p> <p>I can't figure out why my buy transactions aren't working from my code but s...
<python><ethereum><web3py><evm>
2025-01-08 14:28:08
1
360
degenTy
79,339,486
1,089,161
Finding loops between numbers in a list of sets
<h5>I marked <a href="https://stackoverflow.com/a/79341725/1089161">my answer</a> as the answer because it is the one that is doing what I was wanting and anyone wanting to do the same thing should start there. But I would love to see a better answer (order of magnitude for the generation of all loops for example D sho...
<python><set><graph-theory><graph-traversal>
2025-01-08 14:11:40
5
19,565
smichr
79,339,377
7,441,757
Remove X.Y.dev0 packages from poetry package resolution
<p>We have several packages where feature branch releases are versioned with .devN (.dev0). Releasing packages from feature branches allows you to more quickly test integrations. This follows <a href="https://peps.python.org/pep-0440/" rel="nofollow noreferrer">Pep 420</a>.</p> <p>However, this creates some problems be...
<python><pip><python-poetry>
2025-01-08 13:36:41
0
5,199
Roelant
79,339,311
14,720,380
Is it possible to run a callable/function with a different virtual environment in Python?
<p>I have a WebAPI where it is wrapping an external library, the API needs to be able to handle multiple versions of a external library. Two ways I can think of handling this would be to:</p> <ol> <li>Have multiple instances of the API server, for each version of the library and use a reverse proxy to route traffic to ...
<python>
2025-01-08 13:21:22
1
6,623
Tom McLean
79,339,277
20,295,949
AttributeError: module 'requests' has no attribute 'models' when using Twikit in Python
<p>I'm trying to fetch tweets using the twikit Python library, but I keep encountering this error:</p> <pre><code>Traceback (most recent call last): File &quot;c:\users\gaming\anaconda3\lib\site-packages\requests\__init__.py&quot;, line 71, in main await get_tweets(QUERY, minimum_tweets=MINIMUM_TWEETS) File &qu...
<python>
2025-01-08 13:11:32
0
319
HamidBee
79,339,017
378,783
What is wrong with my python setup? Wrong lib loaded in some cases when multiple versions installed
<p>I think that it is the best to describe my problem with series of prompts. I am missing something, don't know what? How does python3.13 load python 3.11 libs???</p> <p>Solutions like delete other versions and similar are not good. I want to fix it as it is.</p> <pre><code>C:\Temp\2025\01\python_ver_check (master) &g...
<python><python-3.x><environment-variables>
2025-01-08 11:45:28
1
7,117
watbywbarif
79,338,848
4,451,315
"n_unique" aggregation using DuckDB relational API which counts nulls
<p>Similar to <a href="https://stackoverflow.com/questions/79314406/n-unique-aggregation-using-duckdb-relational-api/">&quot;n_unique&quot; aggregation using DuckDB relational API</a></p> <p>But, I need to count null values</p> <p>Say I have</p> <pre class="lang-py prettyprint-override"><code>import duckdb rel = duckd...
<python><duckdb>
2025-01-08 10:53:10
1
11,062
ignoring_gravity
79,338,790
7,959,614
Get adjacency matrices of networkx.MultiDiGraph
<p>I want to obtain the adjacency matrices of a <code>networkx.MultiDiGraph</code>. My code looks as follows:</p> <pre><code>import numpy as np import networkx as nx np.random.seed(123) n_samples = 10 uv = [ (1, 2), (2, 3), (3, 4), (4, 5), (5, 6) ] G = nx.MultiDiGraph() for u, v in uv: wei...
<python><networkx>
2025-01-08 10:34:59
1
406
HJA24
79,338,759
4,105,440
Explicit cast of a lazy frame not possible with type mismatch?
<p>I've only been using polars for a few months now (coming from pandas) so forgive me if I'm interpreting things wrong :) I want to read many parquet files, merge them into a single dataframe and then write this to disk. As some of the files have columns with the wrong type I'm trying to do an explicit cast</p> <pre c...
<python><dataframe><casting><python-polars><polars>
2025-01-08 10:26:21
1
673
Droid
79,338,728
1,021,819
Snowflake / Snowpark / Python connector - how to resolve unexpected '@"SNOWPARK_TEMP_STAGE_..."'?
<p>When trying to append to an existing snowflake table via a python stored procedure u using write_pandas, i.e.</p> <pre class="lang-py prettyprint-override"><code>session.write_pandas(my_df, table_name=my_table_name, overwrite=True,database='MY_DATABASE',schema='MY_SANDBOX') </code></pre> <p>I am getting:</p> <pre><c...
<python><stored-procedures><snowflake-cloud-data-platform>
2025-01-08 10:15:02
0
8,527
jtlz2
79,338,599
8,510,149
Why has the shap value array in a shap explanation object a different shape than expected from shap plots?
<p>I'm creating an Explanation object using SHAP. This object holds shap values, base values and the actual data. My problem is that the shap value array in the explanation object comes in a shape that is different from what shap plots expects. Does anybody now why this is occurring?</p> <p>Ref: <a href="https://shap.r...
<python><shap>
2025-01-08 09:40:20
0
1,255
Henri
79,338,219
13,396,497
Panda iterate rows and multiply nth row values to next(n+1) row value
<p>I am trying to iterate multiple column rows and multiply nth row to n+1 row after that add columns.</p> <p>I tried below code and it's working fine.</p> <p>Is there any other simply way to achieve the subtraction and multiplication part together?</p> <pre><code>import pandas as pd df = pd.DataFrame({'C': [&quot;Spa...
<python><pandas><dataframe>
2025-01-08 07:11:11
3
347
RKIDEV
79,337,879
1,783,652
Pyinstaller Windows executable cannot find some joysticks when Python script can
<p>This Python script will print out a list of attached joystick devices on a Windows PC:</p> <pre class="lang-none prettyprint-override"><code>from pyjoystick.sdl2 import Joystick print (&quot;--- Joysticks ---&quot;) print (&quot;\n&quot;.join([j.name for j in Joystick.get_joysticks()])) </code></pre> <p><a href="ht...
<python><pyinstaller><sdl-2>
2025-01-08 03:04:21
0
567
Brian K
79,337,859
1,190,077
In a numba function, replace cuda.popc() by CPU equivalent if not in CUDA
<p>I am writing common code that supports both numba-jitting on CPU and numba.cuda-jitting on GPU.</p> <p>It all works well, except that deep inside the common code, I would like to use an intrinsic instruction that counts the number of bits in an integer. It is <code>cuda.popc()</code> for the CUDA path, and a helper...
<python><cuda><numba>
2025-01-08 02:44:05
1
3,196
Hugues
79,337,751
4,316,166
"Right" way to define helper functions for Django models' Meta classes
<p>I'm trying to simplify a very verbose and repetitive <code>Check</code> constraint for a model, whose logic is currently very hard to parse, factoring out and aptly renaming the repetitive parts.</p> <p>Basically I want to turn this (simplified and abstracted snippet):</p> <pre class="lang-py prettyprint-override"><...
<python><django>
2025-01-08 01:14:01
0
858
kos
79,337,556
1,914,781
plotly - add vline with default grid color
<p>I would like to add a vline with default gride color. below code use <code>lightgray</code> as vline color, how to make it the same as the default grid color?</p> <pre><code>import plotly.graph_objects as go def main(): x = [1, 2, 3, 4, 5] y = [10, 11, 12, 11, 9] fig = go.Figure() fig.add_trace(go...
<python><plotly>
2025-01-07 22:52:47
1
9,011
lucky1928
79,337,434
4,240,413
What's the best way to use a sklearn feature selector in a grid search, to evaluate the usefulness of all features?
<p>I am training a sklearn classifier, and inserted in a pipeline a feature selection step. Via grid search, I would like to determine what's the number of features that allows me to maximize performance. Still, I'd like to explore in the grid search the possibility that <em>no feature selection</em>, just a &quot;pass...
<python><machine-learning><scikit-learn>
2025-01-07 21:39:17
1
6,039
Davide Fiocco
79,337,364
610,569
How to align two string's offset given a list of substrings offsets?
<p>Given <code>a</code> and <code>b</code> relating to a list of substrings in <code>c</code>:</p> <pre><code>a = &quot;how are you ?&quot; b = &quot;wie gehst's es dir?&quot; c = [ (&quot;how&quot;, &quot;wie&quot;), (&quot;are&quot;, &quot;gehst's&quot;), (&quot;you&quot;, &quot;es&quot;) ] </code></pre> <p>What...
<python><string><dynamic-programming><offset><text-alignment>
2025-01-07 21:16:17
4
123,325
alvas
79,337,347
6,357,916
Different values in group by columns before and after group by in pandas dataframe
<p>I havw following code:</p> <pre><code>sum_columns = ['p', 'q', 'r', 'Ax', 'Ay', 'Az'] avg_columns = ['Bx', 'By', 'Bz', 'G2 C03'] agg_map = {col: 'sum' for col in sum_columns} agg_map.update({col: 'mean' for col in avg_columns}) df = df.groupby(['MAC C01', 'MAC C02', 'MAC C03'], as_index=False).agg(agg_map) </code><...
<python><arrays><pandas>
2025-01-07 21:10:36
0
3,029
MsA
79,337,316
4,408,818
python-eve Cerberus keeps throwing "uknown rule" error for embedded dictionary?
<p>A production server is down due to some outdated drivers so I've been upgrading packages to get it working again. I think I'm quite close but eve is giving me some trouble. I have the following schema to validate. Removed some fields for clarity;</p> <p>survey.py</p> <pre><code>from . import question from . import b...
<python><validation><eve><cerberus>
2025-01-07 20:48:09
1
959
Ozymandias
79,337,242
2,913,725
Pyenv build failed when trying to install Python 3.10.15
<p>I have pyenv setup on my Macbook Pro M2 2022 Sonoma 14.6, which was migrated from an Intel-based chip a long while back. I was able to install and run python v3.10.13 via pyenv no problem but when I try to install python 3.10.15, the build fails, and I can't figure out why. I've tried both reinstalling Homebrew and ...
<python><macos><pyenv><macos-sonoma>
2025-01-07 20:16:01
1
1,599
JackKalish
79,337,201
839,733
mypy β€”explicit-package-based vs setuptools
<p>I’ve a project structured as follows:</p> <pre><code>. β”œβ”€β”€ hello β”‚ β”œβ”€β”€ __init__.py β”‚ └── animal.py β”œβ”€β”€ tests β”‚ β”œβ”€β”€ __init__.py β”‚ └── test_animal.py β”œβ”€β”€ README └── pyproject.toml </code></pre> <p>This is just a personal Python library, and doesn’t need to be published or distributed. The usage consists of run...
<python><setuptools><mypy>
2025-01-07 19:59:34
1
25,239
Abhijit Sarkar
79,337,116
1,106,952
Trying to understand how Flask sets the Location string in the response header
<p>I have a uwsgi application behind an nginx reverse proxy. In flask I was originally trying to see what location was getting set in the response headers so I added:</p> <pre><code>@app.after_request def add_header(response): print(response.headers) return response </code></pre> <p>And in my uwsgi logs I see:<...
<python><flask><uwsgi>
2025-01-07 19:22:27
0
1,761
TheDavidFactor
79,337,114
28,063,240
Detect if Tag is a block-level element?
<p>How can I check if a BeautifulSoup Tag is a block-level element (e.g. <code>&lt;p&gt;</code>, <code>&lt;div&gt;</code>, <code>&lt;h2&gt;</code>), or a &quot;phrase content&quot; element like <code>&lt;span&gt;</code>, <code>&lt;strong&gt;</code>?</p> <p>Basically I want to have a function that returns True for any T...
<python><html><beautifulsoup>
2025-01-07 19:20:52
3
404
Nils
79,337,064
210,867
How to run async code in IPython startup files?
<p>I have set <code>IPYTHONDIR=.ipython</code>, and created a startup file at <code>.ipython/profile_default/startup/01_hello.py</code>. Now, when I run <code>ipython</code>, it executes the contents of that file as if they had been entered into the IPython shell.</p> <p>I can run sync code this way:</p> <pre class="l...
<python><asynchronous><python-asyncio><ipython>
2025-01-07 18:52:25
3
8,548
odigity
79,336,883
6,160,119
How to add a prefix to layer names in AutoCAD using ezdxf
<p>I am trying to add a prefix to the layer names in a <code>.dxf</code> file. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import ezdxf doc = ezdxf.readfile('infile.dxf') layer_names = [layer.dxf.name for layer in doc.layers] for old_name in layer_names: try: layer = doc.layers.ge...
<python><autocad><dxf><ezdxf>
2025-01-07 17:41:28
1
13,793
Tonechas
79,336,866
25,625,672
Half-precision in ctypes
<p>I need to be able to seamlessly interact with <a href="https://en.wikipedia.org/wiki/Half-precision_floating-point_format" rel="noreferrer">half-precision</a> floating-point values in a ctypes structure. I have a working solution, but I'm dissatisfied with it:</p> <pre class="lang-py prettyprint-override"><code>impo...
<python><floating-point><ctypes>
2025-01-07 17:36:28
1
601
avigt
79,336,815
11,405,174
Merge two dataframes together dependent on one column containing the values of another column
<p>Let's say I have Dataframes A and B that look like this:</p> <pre class="lang-none prettyprint-override"><code>A: | B: Code Price | Name ID 1 ABC1210 128.14 | 1 TEXTABC1211987654 351 (contains A 2) 2 ABC1211 3620.10 | 2 SAMPLE12345 20 (doesn...
<python><python-3.x><pandas>
2025-01-07 17:15:57
0
464
Corsaka
79,336,754
2,243,490
pytest not maintaining the module structure
<p>pytest is not maintaining the module structure</p> <p><strong>Folder structure</strong></p> <pre><code>hello_world β”œβ”€β”€ config.py β”œβ”€β”€ main.py └── tests β”œβ”€β”€ config.py └── test_main.py </code></pre> <p><strong>./config.py</strong></p> <pre><code>name=&quot;app-config&quot; </code></pre> <p><...
<python><python-3.x><pytest>
2025-01-07 16:53:48
0
1,886
Dinesh