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,413,507
1,230,724
Access `self` in classmethod when instance (self) calls classmethod
<p>Is it possible to access the object instance in a Python @classmethod annotated function when the call occurs via the instance itself rather than the class?</p> <pre><code>class Foo(object): def __init__(self, text): self.text = text @classmethod def bar(cls): return None print(Foo.bar()) foo = Foo(...
<python><inheritance><class-method>
2025-02-05 02:25:59
1
8,252
orange
79,413,347
16,706,763
Migrate from LLMChain to pipe operator
<p>I was following an <a href="https://www.analyticsvidhya.com/blog/2023/10/a-comprehensive-guide-to-using-chains-in-langchain/" rel="nofollow noreferrer">old tutorial</a> about chaining in Langchain. With it, I was writing some demo chains of my own, such as:</p> <pre class="lang-py prettyprint-override"><code>import ...
<python><langchain>
2025-02-05 00:13:25
1
879
David Espinosa
79,413,345
6,630,397
Jupyter interactive window in VSCode attached to dev container is priting a wrong path for __file__
<p>I have an official Python docker container (<code>python:3.11-slim-bookworm</code>) running with a vanilla bind mount on my host, defined as follow in a Compose file:</p> <pre><code>services: app: ... volumes: - ./src:/app </code></pre> <p>I'm using &quot;Dev Containers: Attach to Running Container.....
<python><visual-studio-code><docker-compose><dockerfile><jupyter>
2025-02-05 00:11:06
0
8,371
swiss_knight
79,413,251
23,192,403
PyTorch's seq2seq tutorial decoder
<p>I am learning through PyTorch's seq2seq tutorial: <a href="https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html" rel="nofollow noreferrer">https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html</a></p> <p>I have a question about the decoder</p> <pre><code>class DecoderRN...
<python><machine-learning><pytorch><recurrent-neural-network><seq2seq>
2025-02-04 23:01:44
1
313
RoomTemperature
79,413,114
1,721,431
why do i have this compile error installing numpy in venv on cygwin?
<p>I am running python 3.9 in cygwin on Windows 10. The python is cygwin's python. I tried &quot;pip install numpy&quot; from a newly created venv. However it was not able to find a compatible wheel and instead started to build numpy. Unfortunately, it died compiling several .c files on account of sys/select.h missing....
<python><numpy><cygwin>
2025-02-04 21:46:54
3
976
Motorhead
79,412,896
3,143,269
Using a pointer to fill a ctypes structure
<p>I have need create a ctypes struct using a pointer. Example code</p> <pre><code>class MessageDecoder: def __init__(self, raw_data : bytes): self.raw_data = raw_data self.writable_raw_data = None self.datagram = None self.tag = None def decode(self): c_array = cast...
<python><ctypes>
2025-02-04 20:02:54
1
1,124
AeroClassics
79,412,706
8,285,811
What's going on with the chaining in Python's string membership tests?
<p>I just realized I had a typo in my membership test and was worried this bug had been causing issues for a while. However, the code had behaved just as expected. Example:</p> <pre><code>&quot;test&quot; in &quot;testing&quot; in &quot;testing&quot; in &quot;testing&quot; </code></pre> <p><strong>This left me wonderin...
<python><string><expression><membership>
2025-02-04 18:34:28
2
6,922
Akaisteph7
79,412,652
3,125,823
Import Error: module does not define a "CustomJWTAuthentication" attribute/class
<p>I'm building a REST Auth API with Django/DRF.</p> <p>All of a sudden when I start working today, I'm getting this error message in my cli:</p> <pre><code>ImportError: Could not import 'users.authentication.CustomJWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: Module &quot;users.auth...
<python><django><django-rest-framework>
2025-02-04 18:12:55
0
1,958
user3125823
79,412,615
11,402,025
Understanding and Fixing the regex?
<p>I have a regex on my input parameter:</p> <pre><code>r&quot;^(ABC-\d{2,9})|(ABz?-\d{3})$&quot; </code></pre> <p>Ideally it should not allow parameters with <code>++</code> or <code>--</code> at the end, but it does. Why is the regex not working in this case but works in all other scenarios?</p> <pre><code>ABC-12 is ...
<python><regex>
2025-02-04 18:01:41
2
1,712
Tanu
79,412,592
7,531,433
Inheriting from SQLModel with table=True raises Value error if parent has a non-trivial field type
<p>On sqlmodel 0.0.22, the following code will crash with <code>ValueError: &lt;class 'list'&gt; has no matching SQLAlchemy type</code></p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import ARRAY from sqlmodel import Field, SQLModel, String class Foo(SQLModel, table=True): id: str = Field(pri...
<python><sqlmodel>
2025-02-04 17:53:39
0
709
tierriminator
79,412,501
13,971,251
Gmail Oauth2 - restrict the scope to only emails from a certain domain
<p>I have a Django site that uses Google Oauth2 to allow users to grant access to read and reply to their emails.</p> <pre class="lang-py prettyprint-override"><code>GOOGLE_OAUTH2_CREDENTIALS = { 'client_id': '********************', 'client_secret': '*******', 'scope': [ 'https://www.googleapis.com/...
<python><django><oauth-2.0><google-oauth><django-allauth>
2025-02-04 17:15:27
1
1,181
Kovy Jacob
79,412,451
268,581
plotly x-axis label is offset by one month
<h1>Code</h1> <pre class="lang-py prettyprint-override"><code>import pandas as pd import streamlit as st import plotly.express import plotly data = { '2024-01-31' : 1044, '2024-02-29' : 2310, '2024-03-31' : 518, '2024-04-30' : -1959, '2024-05-31' : 0, '2024-06-30' : -1010, '20...
<python><pandas><plotly><streamlit>
2025-02-04 16:54:16
2
9,709
dharmatech
79,412,371
1,473,517
How to do fft based convolution with long doubles/float128s quickly and accurately
<p>On my linux system I have:</p> <pre><code>np.finfo(np.float128) info(resolution=1e-18, min=-1.189731495357231765e+4932, max=1.189731495357231765e+4932, dtype=float128) </code></pre> <p>So that is an 80-bit long double. I want to perform a convolution between two reasonably long arrays of <code>np.float128</code>s. ...
<python><numpy><scipy><fft>
2025-02-04 16:22:09
1
21,513
Simd
79,412,357
8,445,557
python snowflake.connector & rsa private_key_file issue
<p>I meet an issue when trying to use <strong>snowflake.connector</strong> with an RSA <strong>pkcs8 key</strong> with <strong>passphrase</strong>.</p> <p>When I try this code, with this kind of RSA Key: <code>openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8</code></p> <pre class="lang-py prettypr...
<python><snowflake-cloud-data-platform><rsa>
2025-02-04 16:16:52
1
361
Stefano G.
79,412,334
11,940,250
Bevel in blender with bmesh after extrusion
<p>I've been trying to bevel with bmesh in Blender for a few hours. With bpy.ops this works without any problems but that's exactly what I want to avoid. Switching to edit mode makes the code very slow if you iterate through 100 objects or more.</p> <p>All my attempts so far have resulted in incorrect bevel results. I ...
<python><blender>
2025-02-04 16:09:48
0
419
Spiri
79,412,324
6,101,024
How to split a dataset in train, validation and test based on the value of another column
<p>Given a dataset of the form:</p> <pre><code> date user f1 f2 rank rank_group counts 0 09/09/2021 USER100 59.0 3599.9 1 1.0 3 1 10/09/2021 USER100 75.29 80790.0 2 1.0 3 2 11/09/2021 USER100 75.29 80790.0 3 1.0 3 1 10/0...
<python><dataframe><numpy><split>
2025-02-04 16:06:49
2
697
Carlo Allocca
79,412,281
9,182,743
Import Fitz with AWS Lambda : cannot import name '_extra' from partially initialized module 'pymupdf'
<p>I want to import fitz on AWS lambda</p> <p><a href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html" rel="nofollow noreferrer">Following these AWS instructions</a>, I have:</p> <ul> <li>pip installed PymuPdf <code>pip install --target ./package pymupdf</code></li> <li>added lambda_function.py to pac...
<python><aws-lambda><import><pymupdf>
2025-02-04 15:56:32
0
1,168
Leo
79,412,165
13,097,194
Trying to understand differences in weighted logistic regression outputs between Statsmodels and R's survey & srvyr packages
<p>I have <a href="https://raw.githubusercontent.com/ifstudies/carsurveydata/refs/heads/main/car_survey.csv" rel="nofollow noreferrer">a fictional weighted survey dataset</a> that contains information about respondents' car colors and their response to the question &quot;I enjoy driving fast.&quot; I would like to perf...
<python><r><logistic-regression><statsmodels><survey>
2025-02-04 15:11:52
1
974
KBurchfiel
79,412,108
5,676,198
How to specify conda env in Python Debugger in VScode
<h3>Problem</h3> <p>When I want to debug a Python file and hit the button <code>Python Debugger: Debug Python File</code> or <code>Debugin with JSON,</code> it selects the default conda environment.</p> <h3>Workaround</h3> <p>To fix that, I manually open the terminal (created by the debugger), <code>conda activate cond...
<python><visual-studio-code><anaconda><conda><vscode-debugger>
2025-02-04 14:54:29
1
1,061
Guilherme Parreira
79,412,014
1,866,038
Grouping function parameters with sphinx
<p>I want to group the parameters of a function so that, instead of</p> <pre><code>myfunc(from, until, col_color, col_taste) Parameters: · from First date of the period to be selected. · until Last date of the period to be selected. · col_color Whether to include the color colu...
<python><python-sphinx><documentation-generation>
2025-02-04 14:18:32
1
517
Antonio Serrano
79,411,840
2,989,642
Python pip - expressing trusted host in command line call
<p>I'm attempting to fetch a dependency and install in user scope, during script execution:</p> <pre><code># PYPI is a global settings dict try: resp = subprocess.check_call( [ sys.executable, &quot;-m&quot;, &quot;pip&quot;, &quot;install&quot;, &quot;--user&quot;, &quot;--trusted-...
<python><pip><command-line-interface>
2025-02-04 13:19:45
0
549
auslander
79,411,501
5,337,505
How to pass Input to a tensorflow backbone model without getting AttributeError: 'tuple' object has no attribute 'as_list'
<p>I am trying to use ResNet3D from <code>tensorflow-models</code> library but I am getting this weird error when trying to run the block</p> <pre><code>!pip install tf-models-official==2.17.0 </code></pre> <p>Tensorflow version is <code>2.18</code> on the Kaggle notebook.</p> <p>After installing <code>tf-models-offici...
<python><tensorflow><machine-learning><deep-learning><tf.keras>
2025-02-04 11:22:41
1
1,215
Siladittya
79,411,389
815,455
Snakemake - files as input/output with timestamp
<p>I try to setup a snakefile (snakemake 7.19.1). The final output should contain a timestamp. This is a minimal example:</p> <pre class="lang-py prettyprint-override"><code>#!/bin/python print('import packages') from datetime import datetime import time now = datetime.now().strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;) ta...
<python><snakemake>
2025-02-04 10:46:06
3
1,196
Antje Janosch
79,411,167
11,283,324
How to use the apply function to return a list to new column in Pandas
<p>I have a Pandas dataframe:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(150) df = pd.DataFrame(np.random.randint(0, 10, size=(10, 2)), columns=['A', 'B']) </code></pre> <p>I want to add a new column &quot;C&quot; whose values ​​are the combined-list of every three rows in column &quot;B&quot...
<python><pandas><sliding-window>
2025-02-04 09:28:01
4
351
Sun Jar
79,410,861
368,907
Locust Not Running
<p>I had coded some simple locust load testing code in python. Previously, it running without any errors but after some time i run the code, the http request is not get executed.</p> <pre><code>class WebsiteUser(HttpUser): wait_time = between(1, 5) #HTTPConnection.debuglevel = 1 #logging.basicConfig() #logging.getLogg...
<python><locust>
2025-02-04 07:22:51
1
2,802
Ivan
79,410,811
14,749,391
How to implement QueueHandler and QueueListener inside flask factory
<p>I have a flask application delivered by gunicorn that spawns multiple threads and processes from itself during the request. The problem is that when using the standard app.logger, some of the children get deadlocked because of the logging module not able to release the lock. This leads to these processes staying in ...
<python><python-3.x><flask><python-multiprocessing><flask-restful>
2025-02-04 07:02:00
0
772
Tony
79,410,679
6,711,954
Get changed columns and values from output of a do_orm_execute event
<p>I am trying to log the columns/values changed during an insert, update, delete statement using Session events.</p> <p>I am able to print the statement with their params, however I need the column/value pair (ex. {&quot;dept&quot;: &quot;HR&quot;} or {&quot;dept&quot;: {&quot;old&quot;: &quot;Finance&quot;, &quot;new...
<python><events><sqlalchemy><orm>
2025-02-04 05:49:13
0
828
Shine J
79,410,495
13,825,658
How to parse list of strings to pydantic settings?
<p>pydantic-settings can parse list of ints, but not list of strings</p> <p>This works:</p> <pre class="lang-py prettyprint-override"><code>class Settings(BaseSettings): my_list_of_ints: list[int] os.environ[&quot;my_list_of_ints&quot;] = &quot;[1, 2, 3]&quot; print(Settings().model_dump()) # {'my_list_of_ints': ...
<python><environment-variables><pydantic><pydantic-settings>
2025-02-04 03:09:32
0
1,368
Leonardus Chen
79,410,316
7,254,247
Transparent filesystem in pyfuse with encryption and compression
<p>I'm trying to make a simple transparent filesystem in fuse. I'm using <a href="https://www.stavros.io/posts/python-fuse-filesystem/" rel="nofollow noreferrer" title="example pass through filesystem in python">this guide</a> as a basis. This code works perfectly. I'm trying to modify it so that it compresses and then...
<python><encryption><compression><fuse>
2025-02-04 00:17:39
1
772
lee
79,410,268
1,273,751
After powershell update, conda elicits error as if command were empty
<p>After my system automatically updated Powershell to 7.5.0, my conda has not been working anymore.</p> <p>It doesn't correctly initialize when the terminal is started, nor when I run <code>conda init powershell</code>.</p> <p>I already checked the path: conda root folder, and Script and condabin folders are there.</p...
<python><windows><powershell><conda>
2025-02-03 23:38:55
0
2,645
Homero Esmeraldo
79,410,096
9,334,609
D-ID API: pending_url returned instead of video URL after successful POST and GET
<p>I'm encountering a <code>pending_url</code> issue when using the D-ID API. I'm making a POST request to create a talk, which returns a 201 status code and a talk ID.<br /> Immediately after, I'm making a GET request to retrieve the talk details using this ID. However, the GET request response includes a <code>pendi...
<python><flask>
2025-02-03 21:48:59
1
461
Ramiro
79,409,587
405,017
Performance impact of inheriting from many classes
<p>I am investigating the performance impact of a very broad inheritance setup.</p> <ol> <li>Start with 260 distinct attribute names, from <code>a0</code> through <code>z9</code>.</li> <li>Create 260 classes with 1 uniquely-named attribute each. Create one class that inherits from those 260 classes.</li> <li>Create 130...
<python><performance><python-internals>
2025-02-03 17:36:44
2
304,256
Phrogz
79,409,480
28,063,240
Expand a QuerySet with all related objects
<pre class="lang-py prettyprint-override"><code>class Hobby(models.Model): name = models.TextField() class Person(models.Model): name = models.TextField() created_at = models.DateTimeField(auto_now_add=True) hobbies = models.ManyToManyField(Hobby, related_name='persons') class TShirt(models.Model): ...
<python><django>
2025-02-03 16:55:59
2
404
Nils
79,409,259
6,662,425
How does Hydra `_partial_` interact with seeding
<p>In the configuration management library <a href="https://hydra.cc/" rel="nofollow noreferrer">Hydra</a>, it is possible to only partially instantiate classes defined in configuration using the <a href="https://hydra.cc/docs/1.1/advanced/instantiate_objects/overview/#partial-instantiation-for-hydra-version--112" rel=...
<python><machine-learning><pytorch><pytorch-lightning><fb-hydra>
2025-02-03 15:28:56
3
1,373
Felix Benning
79,409,091
10,595,871
Problem when using azure cognitive services (.dll file not found)
<p>I have an app made with flask that is working fine on my machine. I'm trying to move it to a server in order to make in accessible to some people. I've installed all the packages and check that everything has the same version as on my local machine.</p> <p>Everything seems fine but when I try to run the app, it thro...
<python><flask><azure-cognitive-services>
2025-02-03 14:19:54
0
691
Federicofkt
79,408,681
11,598,948
Perform a rolling operation on indices without using `with_row_index()`?
<p>I have a DataFrame like this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;x&quot;: [1.2, 1.3, 3.4, 3.5]}) df # shape: (3, 1) # ┌─────┐ # │ a │ # │ --- │ # │ f64 │ # ╞═════╡ # │ 1.2 │ # │ 1.3 │ # │ 3.4 │ # │ 3.5 │ # └─────┘ </code></pre> <p>I would like to make...
<python><dataframe><python-polars><rolling-computation>
2025-02-03 11:37:42
2
8,865
bretauv
79,408,524
2,883,209
Writing back to a panda groupby group
<p>Good morning all</p> <p>I am trying to process a lot of data, and I need to group data, look at the group, then set a value based on the other entries in the group, but I want to set the value in a column in the full dataset. What I can't figure out is how I can use the group to write back to the main dataframe.</p>...
<python><pandas>
2025-02-03 10:40:38
2
1,244
vrghost
79,408,042
11,405,787
CadQuery Stack Nagivation: how to unparent "XY" plane from `transformed`-made workplane
<p>Beginner at CadQuery,</p> <p>Trying to do basic modeling.</p> <p>I want to drill multiple holes from different direction in an object,</p> <p>so I:</p> <ul> <li>make the object, and then</li> <li>use <code>.faces(&quot;XY&quot;)</code> to get the top plane and then</li> <li>use <code>.transforms(...)</code> to rotat...
<python><cad><openscad><cadquery>
2025-02-03 07:02:43
0
1,211
啊鹿Dizzyi
79,407,989
2,537,745
Why am I getting a ‘required broadcastable shapes’ error after removing max_length in my TensorFlow seq2seq with Attention?
<p>I’m working through an example of an encoder–decoder seq2seq model in TensorFlow with Bahdanau-style Attention. I followed a tutorial/book example that uses a <code>TextVectorization</code> layer with <code>output_sequence_length=max_length</code>. When I keep <code>max_length</code>, everything works fine. However,...
<python><tensorflow>
2025-02-03 06:30:34
0
1,794
abkds
79,407,952
11,283,324
Find the index of the current df value in another series and add to a column
<p>I have a dataframe and a series, as follows:</p> <pre><code>import pandas as pd from itertools import permutations df = pd.DataFrame({'a': [['a', 'b', 'c'], ['a', 'c', 'b'], ['c', 'a', 'b']]}) prob = list(permutations(['a', 'b', 'c'])) prob = [list(ele) for ele in prob] ps = pd.Series(prob) &gt;&gt;&gt; df ...
<python><pandas>
2025-02-03 06:04:36
1
351
Sun Jar
79,407,620
470,801
What is the correct way to insert into the DuckDB JSON type via the Python API?
<p>The <a href="https://duckdb.org/docs/api/python/overview.html" rel="nofollow noreferrer">DuckDB Python API docs</a> have examples of how to read from a JSON file, but not doesn't explicitly state how to use the <a href="https://duckdb.org/docs/data/json/overview.html" rel="nofollow noreferrer">JSON type</a>.</p> <p>...
<python><json><duckdb>
2025-02-03 01:14:01
0
822
Chris Mungall
79,407,537
4,330,537
undetected_chromedriver and cloudflare issues if there are any undetected_chromedriver commands after the cloudflare challenge
<p>Hi I am trying to use import undetected_chromedriver as uc:</p> <p>this works clicking a button:</p> <pre><code>driver.execute_script(&quot;arguments[0].focus();&quot;, username_field) WebDriverWait(driver, 100).until(EC.element_to_be_clickable((&quot;id&quot;,&quot;ctl00_lower_panel_btnContinue&quot;))).click() </c...
<python><selenium-webdriver><undetected-chromedriver>
2025-02-02 23:33:46
0
835
RobM
79,407,429
2,525,593
Run .py file that is in a subdirectory
<p>I can run a file from the root of my project, but not from a subdirectory. How do I fix this?</p> <p>I have a directory tree that looks like this:</p> <pre><code>$ tree . ├── kalman │ ├── find_observibility.py │ ├── __init__.py │ ├── kalman.py │ └── model.py </code></pre> <p><code>find_observibility.py</cod...
<python>
2025-02-02 22:00:55
2
536
Tim Wescott
79,407,324
14,416,045
PIL vs OpenCV Affine Transform: why does the image turn upside down?
<p>I'm trying to get rid of OpenCV in my image pipeline. I'm replacing it with PIL. I understand that the affine transformation in OpenCV is source -&gt; destination, but the parameter for PIL is destination -&gt; source. The transformation matrix used in OpenCV can be inverted to be used in PIL.</p> <p>The problem I h...
<python><opencv><python-imaging-library>
2025-02-02 20:47:36
1
468
Tyler Norlund
79,407,317
7,295,599
How to create possible sets of n numbers from m-sized prime number list?
<p>Input: a list of <code>m</code> prime numbers (with possible repetition), and integers <code>n</code> and <code>t</code>.</p> <p>Output: all sets of <code>n</code> numbers, where each set is formed by partitioning the input into <code>n</code> parts, and taking the product of the primes in each part. We reject any s...
<python><algorithm><combinations><primes><python-itertools>
2025-02-02 20:46:02
1
27,030
theozh
79,407,242
274,460
How do I make FastAPI URLs include the proxied URL?
<p>I have a FastAPI application that is behind a NextJS reverse proxy. I'm using NextJS rewrites, which sets the <code>x-forwarded-for</code> header to the externally-visible hostname and port. The rewrite looks like this:</p> <pre><code>rewrites: async () =&gt; [ { source: &quot;/api/:slug*&quot;, ...
<python><next.js><fastapi><reverse-proxy><fastapi-middleware>
2025-02-02 19:54:58
1
8,161
Tom
79,407,071
16,891,669
Understanding descriptor protocol for 'wrapper-descriptor' itself
<p>I was trying to explore how would the descriptor protocol work if I were to access the object of the 'wrapper-descriptor' class itself.</p> <p>So, I explored the c code in <a href="https://github.com/python/cpython/blob/3.13/Objects/typeobject.c" rel="nofollow noreferrer">typeobject.c</a> and found two <code>__get__...
<python><cpython>
2025-02-02 18:12:40
1
597
Dhruv
79,406,955
281,965
Generate a token using Python requests vs mc binary?
<p>I am using Python MinIO SDK, but there are admin operations that it cannot do, and then we use the <code>mc</code> binary instead. But the binary has all these files on disk that we can't have in our ENV so we need to kick it out.</p> <p>I'm trying to simulate what the binary does, and while reviewing the <code>--de...
<python><python-3.x><minio>
2025-02-02 16:50:17
1
8,181
Ricky Levi
79,406,917
10,737,396
How can I accurately count tokens for Llama3/DeepSeek r1 prompts when Groq API reports “Request too large”?
<p>I'm integrating the Groq API in my Flask application to classify social media posts using a model based on DeepSeek r1 (e.g., <code>deepseek-r1-distill-llama-70b</code>). I build a prompt by combining multiple texts and send it to the API. However, I keep receiving an error like this:</p> <pre><code>Request too larg...
<python><tokenize><groq><llama3><deepseek>
2025-02-02 16:19:08
0
784
Towsif Ahamed Labib
79,406,912
8,621,823
How is the thread to be executed selected by the OS?
<p>Why this question is different from <a href="https://stackoverflow.com/questions/73336295/python-lock-always-re-acquired-by-the-same-thread">Python Lock always re-acquired by the same thread</a>.</p> <p>It may look similar because both questions use 2 threads. That question specifically requires each thread to execu...
<python><multithreading>
2025-02-02 16:13:16
0
517
Han Qi
79,406,608
8,849,755
Pandas datetime index empty dataframe
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>data = pandas.read_csv('data.csv') data['when'] = pandas.to_datetime(data['when']) data.set_index('when', inplace=True) print(data) print(data.index.dtype) </code></pre> <p>which prints:</p> <pre><code> price when ...
<python><pandas><datetime>
2025-02-02 12:49:12
3
3,245
user171780
79,406,511
3,333,449
Calculate cumulative sum of time series X for time points in series Y
<p>Imagine transactions, identified by <em>amount</em>, arriving throughout the day. You want to calculate the running total of <em>amount</em> at given points in time (9 am, 10 am, etc.).</p> <p>With pandas, I would use <code>apply</code> to perform such an operation. With Polars, I tried using <code>map_elements</cod...
<python><dataframe><time-series><python-polars>
2025-02-02 11:36:46
1
535
Dimitri Shvorob
79,406,498
2,869,544
TypeError raised when importing fbprophet
<p>Condition: any python command will have the same error. For example if run this simple command <code>python -V</code> , it will generate the same error.</p> <p>I am using:</p> <ul> <li>conda/miniconda3 version : 24.5.0</li> <li>spyder-kernels version : 3.0.2</li> <li>python version : 3.12.8</li> </ul> <p>My spyder-e...
<python><spyder><miniconda>
2025-02-02 11:28:21
1
1,004
noobsee
79,406,461
3,439,054
Navigate Firefox with Selenium
<p>I want to get to a particular session in firefox, so my login data is saved</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver profile_path = &quot;/home/XXXX/.mozilla/firefox/XXXX.selenium1&quot; # particular profile - I hid some part of the path for privacy reason options = webdr...
<python><selenium-webdriver><firefox>
2025-02-02 11:02:15
1
324
Sam
79,406,441
906,387
Iterable[str] vs [str]
<p>I'm trying to understand the difference between:</p> <pre><code>from typing import Iterable def func(self, stuff: Iterable[str]) -&gt; str: </code></pre> <p>and:</p> <pre><code>def func(self, stuff: [str]) -&gt; str: </code></pre> <p>Are both statements valid? Do they give the same information to Python (3.12+) inte...
<python><python-typing>
2025-02-02 10:49:54
1
1,379
suizokukan
79,406,394
347,484
How to save checkpoint in tensorflow format in ver 2.18?
<p>There was a feature - tensorflow format to save a checkpoint. I have checked and it is everywhere in the official docs and samples: <a href="https://www.tensorflow.org/tutorials/keras/save_and_load#savedmodel_format" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/keras/save_and_load#savedmodel_format...
<python><keras><tensorflow2.0>
2025-02-02 10:18:44
1
10,560
Boppity Bop
79,406,346
1,951,507
PyCharm type hinting for generic type concludes property instead of property's return type
<p>I have a problem with type hints recognition in Pycharm. Following simplified example constructed to show my issue:</p> <pre class="lang-py prettyprint-override"><code>class A: @property def a(self) -&gt; A: a_ = ... return a_ def f[T: A](b: T): c = b.a # `b.a` recognized as type `prope...
<python><pycharm><python-typing><pep-695>
2025-02-02 09:41:16
0
1,052
pfp.meijers
79,406,202
95,265
how to access copied content in python UIAutomator2
<p>I am trying to automate some flow in <code>UIAutomator</code> and a part of it has been to press the copy button on an app, after pressing this copy button I would need to access the copied content in code via python <code>UIAutomator</code>... how do I do so?</p> <pre class="lang-py prettyprint-override"><code>COPY...
<python><python-3.x><ui-automation><uiautomator2>
2025-02-02 07:24:02
1
14,438
aherlambang
79,406,027
28,063,240
Save all objects in QuerySet and related objects to a fixture
<p>I've written a function to save a QuerySet to a fixture JSON file:</p> <pre class="lang-py prettyprint-override"><code>def save_as_fixture(query_set: QuerySet, fixture_name: str, app_label: str='mainapp'): app_config = apps.get_app_config(app_label) fixture_dir = os.path.join(app_config.path, &quot;fixtures&...
<python><django>
2025-02-02 03:29:31
0
404
Nils
79,406,005
9,135,359
How to pass `self` into RunnableLambda?
<p>I am using LangChain and have a class with many methods. I intend to use parallel chains to process lots of data.</p> <p>Here is one of my steps, which happens to use other methods in the class in which it is contained:</p> <pre><code>def management_plan(self, input) -&gt; str: # uses management_plan_model print...
<python><langchain>
2025-02-02 02:58:00
1
844
Code Monkey
79,405,989
12,609,881
All possible decision paths / outcomes given multiple choices at each decision
<p>Given I am iterating through multiple lists of elements that are zipped together, I need to create all possible outcomes given I can only choose an element from a single list at each iteration.</p> <p>Example input 1:</p> <pre><code>a = [3,19,13] b = [20,18,7] </code></pre> <p>Example output 1:</p> <pre><code>[[3, 1...
<python><algorithm><math>
2025-02-02 02:38:24
1
911
Matthew Thomas
79,405,874
5,093,220
Android Chrome doesn't forget user even after Flask logout_user when using remember cookie
<p>I can't get Chrome on Android to let me logout a user.</p> <p>I'm using <code>Flask</code>, with <code>flask_login</code>'s user sessions. I use <code>login_user(remember=True)</code> in order to remember the logins even if the browser is closed and opened again afterwards. Then I use <code>logout_user</code> for lo...
<python><flask><flask-login><remember-me><google-chrome-android>
2025-02-01 23:57:21
0
631
Rusca8
79,405,832
4,098,506
mariadb.OperationalError: Access denied for user... but credentials are correct
<p>I use this simple connection script:</p> <pre><code>import configparser import mariadb config = configparser.ConfigParser() config.read('dbconfig.ini') config_default = config['DEFAULT'] print(f' mariadb -h {config_default[&quot;server&quot;]} -u {config_default[&quot;username&quot;]} -p{config_default[&quot;passw...
<python><mariadb>
2025-02-01 23:15:07
1
662
Mr. Clear
79,405,712
6,824,949
How to have a (FastAPI) GKE deployment handle multiple requests?
<p>I have a FastAPI deployment in GKE that has an end-point <code>/execute</code> that reads and parses a file, something like below:</p> <pre><code>from fastapi import FastAPI app = FastAPI() @app.post(&quot;/execute&quot;) def execute( filepath: str ): res = 0 with open(filepath, &quot;r&quot;) as fo: ...
<python><kubernetes><fastapi><google-kubernetes-engine>
2025-02-01 21:30:38
0
348
aaron02
79,405,672
4,710,409
'IterQueue' object has no attribute 'not_full'
<p>I have a class called &quot;IterQueue which is an iter queue:</p> <p><strong>IterQueue.py</strong></p> <pre><code>from multiprocessing import Process, Queue, Pool import queue class IterQueue(queue.Queue): def __init__(self): self.current = 0 self.end = 10000 def __iter__(self): self.current = 0 s...
<python><multiprocessing><queue>
2025-02-01 20:55:16
1
575
Mohammed Baashar
79,405,614
2,221,360
Slicing netCDF4 dataset based on specific time interval using xarray
<p>I have a netCDF4 dataset for the following datatime which is stored in <code>_date_times</code> variable:-</p> <pre><code>&lt;xarray.DataArray 'Time' (Time: 21)&gt; Size: 168B array(['2025-01-30T00:00:00.000000000', '2025-01-30T06:00:00.000000000', '2025-01-30T12:00:00.000000000', '2025-01-30T18:00:00.0000000...
<python><python-xarray><netcdf4>
2025-02-01 20:03:10
1
3,910
sundar_ima
79,405,222
9,049,108
pwntools [Errno 24] Too many open files [-] Starting local process
<p>I'm having an issue with some code I'm writing. I'm getting this pwntools error about too many files being open. My code looks like.</p> <pre><code> for a in range(0,2**3360): try: with open(&quot;output.txt&quot;, &quot;a&quot;) as f: p =process(os.getcwd()+ &quot;/flag&quot;,...
<python><file><process><pipe><pwntools>
2025-02-01 15:23:45
0
576
Michael Hearn
79,405,200
1,386,750
Using named columns and relative row numbers with Pandas 3
<p>I switched from NumPy arrays to Pandas DataFrames (dfs) many years ago because the latter has column names, which</p> <ol> <li>makes programming easier;</li> <li>is robust in order changes when reading data from a <code>.json</code> or <code>.csv</code> file.</li> </ol> <p>From time to time, I need the last row (<co...
<python><pandas><dataframe>
2025-02-01 15:06:33
1
468
AstroFloyd
79,404,917
1,892,584
Raise a window using tkinter on kde?
<p>With tkinter on Python you can use the following <a href="https://stackoverflow.com/questions/1892339/how-to-make-a-tkinter-window-jump-to-the-front">trick to raise a window</a></p> <pre><code>root.lift() root.attributes('-topmost',True) root.after_idle(root.attributes,'-topmost',False) </code></pre> <p>However, on ...
<python><tkinter><window><kde-plasma>
2025-02-01 11:46:33
1
1,947
Att Righ
79,404,581
1,371,949
Python SqlManagementClient Azure MSAL Login: Add Firewall Rules Programmatically Not Working
<p>In Python notebook, I want to connect to my Azure SQL DB using MSAL. In the second step, after logging in successfully, I need to configure the firewall by adding the public IP to the Firewall settings:</p> <pre><code>from msal import PublicClientApplication from azure.identity import DefaultAzureCredential from azu...
<python><sql-server><azure><firewall><rules>
2025-02-01 07:22:54
1
2,117
felixwcf
79,404,534
10,255,994
How to set up Crawl4AI with managed browser
<p>Hello I am trying to setup a crawl4ai script with a managed browser from this guide:</p> <p><code>https://docs.crawl4ai.com/advanced/identity-based-crawling/</code></p> <p>I am running with WSL2 on Windows11. When I run my script, it can't seem to execute the script with a managed browser. I see the below error:</p>...
<python><web-scraping><playwright><large-language-model>
2025-02-01 06:32:18
0
483
Bud Linville
79,404,513
647,987
Fast loading of a Solr streaming response (JSON) into Polars
<p>I want to load large responses of the Solr streaming API into polars (python), efficiently. The Solr streaming API returns JSON of the following form:</p> <pre><code>{ &quot;result-set&quot;:{ &quot;docs&quot;:[{ &quot;col1&quot;:&quot;value&quot;, &quot;col2&quot;:&quot;value&quot;} ,{ ...
<python><solr><python-polars>
2025-02-01 06:13:32
1
3,687
Lars Noschinski
79,404,210
2,084,503
How to cancel trigonometric expressions in SymPy
<p>I have a bunch of expressions <code>deque([-6*cos(th)**3 - 9*cos(th), (11*cos(th)**2 + 4)*sin(th), -6*sin(th)**2*cos(th), sin(th)**3])</code>.</p> <p>Then I run them through some code that iteratively takes a derivative, adds, and then divides by <code>sin(th)</code>:</p> <pre class="lang-py prettyprint-override"><c...
<python><sympy>
2025-02-01 00:00:52
1
1,266
Pavel Komarov
79,404,186
1,119,340
How to display an image in retina resolution from Python
<p>I'd like to open a window and display an image, in full resolution on a retina display, on MacOS.</p> <p>I can't find a way to do this, so I'm looking for a solution. I don't mind if it's via matplotlib or Tk or anything else. I don't need the script to do anything apart from generate the image and display it until ...
<python><macos><retina-display>
2025-01-31 23:40:30
1
8,479
N. Virgo
79,404,090
3,324,751
Python 3.13.1 interpreter accepts y = set[x] as correct syntax
<p>Just noticed my Python 3.13 interpreter accepts the following syntax:</p> <pre><code>&gt;&gt;&gt; x (1, 2, 3) &gt;&gt;&gt; y = set[x] &gt;&gt;&gt; y set[1, 2, 3] &gt;&gt;&gt; y = set[1,2,3] &gt;&gt;&gt; y set[1, 2, 3] &gt;&gt;&gt; d = dict[1,2,3] &gt;&gt;&gt; d dict[1, 2, 3] &gt;&gt;&gt; type(d) &lt;class 'types.Gen...
<python><python-3.x>
2025-01-31 22:07:36
2
577
hagh
79,404,077
20,554,684
How to fix alignment of projection from (x,y,z) coordinates onto xy-plane in matplotlib 3d plot?
<p>I was trying to make a 3D visualization of the joint probability mass function with the following code:</p> <pre><code>import math import numpy as np import matplotlib.pyplot as plt def f(x, y): if(1 &lt;= x + y and x + y &lt;= 4): return (math.comb(3, x) * math.comb(2, y) * math.comb(3, 4 - x - y)) / m...
<python><matplotlib><visualization>
2025-01-31 21:53:23
1
399
a_floating_point
79,404,070
10,951,092
Is there a way to tell where a user has clicked a 3D surface plot in matplotlib?
<p>I am creating a 3D plot using Matplotlib. The plot contains points, lines and surfaces displayed in 3D space. Using the “picker=true” option for the lines and points I can make them clickable. And when the user clicks on them I can return the location of their pointer in 3D space using “get_data_3d”. I can’t get thi...
<python><matplotlib><mplot3d>
2025-01-31 21:45:28
1
382
PetSven
79,403,767
1,678,371
How to create or copy folders to Windows AppData folders Using Python
<p>Using standard library Python functions like <code>os.makedirs</code> or <code>shutil.copy2</code>, I can put folders inside the <code>%HOME%/AppData/Roaming/MyApp</code> folder but they are invisible to Explorer, Powershell and any other app.</p> <p>I know they exist because I can see them via Python using <code>os...
<python><windows><appdata>
2025-01-31 18:54:04
1
2,285
Lucian Thorr
79,403,655
459,745
Click: How to propagate the exit code back to the group
<p>I have a script which use <code>click.group</code> to provide sub commands. Each of the sub command might pass or fail. How do I propagate the exit code from the sub commands back to main?</p> <pre class="lang-py prettyprint-override"><code>import click import sys @click.group() def main(): # How do I get the e...
<python><python-click>
2025-01-31 18:05:22
1
41,381
Hai Vu
79,403,612
10,145,953
Calculate the count of distinct values appearing in multiple tables
<p>I have three pyspark dataframes in Databricks: <code>raw_old</code>, <code>raw_new</code>, and <code>master_df</code>. These are placeholders to work out the logic on a smaller scale (actual tables contain billions of rows of data). There is a column in all three called <code>label</code>. I want to calculate the nu...
<python><pyspark><databricks>
2025-01-31 17:48:58
2
883
carousallie
79,403,409
14,802,285
How to prevent certain input from impacting certain output of neural networks in pytorch?
<p>I have an LSTM model that receives 5 inputs to predict 3 outputs:</p> <pre><code>import torch import torch.nn as nn class LstmModel(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(CustomLSTMModel, self).__init__() self.lstm = nn.LSTM(input_size, hidden_size, batch_fir...
<python><deep-learning><pytorch><neural-network><lstm>
2025-01-31 16:39:37
1
3,364
bird
79,403,323
1,559,388
Beam/Dataflow pipeline writing to BigQuery fails to convert timestamps (sometimes)
<p>I have a beam/dataflow pipeline that reads from Pub/Sub and writes to BiqQuery with <code>WriteToBigQuery</code>. I convert all timestamps to <code>apache_beam.utils.timestamp.Timestamp</code>. I am sure all timestamps are converted but I do get this error for some rows:</p> <pre><code>Error message from worker: gen...
<python><google-bigquery><runtime-error><google-cloud-dataflow><apache-beam>
2025-01-31 16:05:56
2
802
Jonathan
79,403,118
13,219,123
Pandas rolling rank issue
<p>I am trying to create a rolling rank column for a float column. However the output is not as expected. Below I have an example:</p> <pre><code>data = { 'time': pd.date_range(start='2025-01-01', periods=5, freq='H'), 'zone': ['A'] * 5, 'price': [1.0, 1.5, 1.7, 1.9, 2.0], } dummy_df = pd.DataFrame(data) c...
<python><pandas>
2025-01-31 14:53:46
1
353
andKaae
79,403,003
1,194,864
Conda installation in an ssh server
<p>I want to install <code>Miniconda</code> and create an environment where I can install specific packages. For installing Miniconda I am following these <a href="https://bash%20/miniconda3/miniconda.sh%20-b%20-u%20-p%20/miniconda3" rel="nofollow noreferrer">instructions</a>. In the server, there is <code>home</code> ...
<python><server><anaconda><conda>
2025-01-31 14:14:21
1
5,452
Jose Ramon
79,402,996
17,160,160
Paginated API requests
<p><strong>Description</strong><br /> I am trying to make a paginated request to a public api.<br /> The request limit is 100 and so looped paginated requests are required to pull all records.<br /> The api contains some number of erroneous records that, if contained within the paginated request, will cause to the requ...
<python><python-requests>
2025-01-31 14:12:45
0
609
r0bt
79,402,927
4,289,400
A puzzle with Robot framework, scroll into view. I can't get a slider of a web element to start scrolling down
<p>A profile <a href="https://stackoverflow.com/users/16991720/ltl">LTL</a> on stackoverflow did a great attempt to do the <a href="https://obstaclecourse.tricentis.com/Obstacles/List" rel="nofollow noreferrer">obstacle course</a> of Tosca but then done with Robot framework (real clever to train test automation and you...
<python><slider><robotframework><tosca>
2025-01-31 13:48:34
1
418
tijnn
79,402,794
3,906,713
Python vectorized minimization of a multivariate loss function without jacobian
<p>I have a loss function that needs to be minimized</p> <pre><code>def loss(x: np.ndarray[float]) -&gt; float </code></pre> <p>My problem has <code>nDim=10</code> dimensions. Loss function works for 1D arrays of shape <code>(nDim,)</code>, and with 2D arrays of shape <code>(nSample, nDim)</code> for an arbitrary numbe...
<python><scipy><minimization>
2025-01-31 12:55:49
2
908
Aleksejs Fomins
79,402,617
6,618,051
Top or Bottom navigation bar
<p>For some reasons only bottom bar is shown (independently of <code>is_mobile</code> state). How can it be fixed?</p> <pre class="lang-none prettyprint-override"><code>BoxLayout: orientation: 'vertical' ActionBar: hidden: app.is_mobile size_hint_y: 0 if app.is_mobile else None ActionVie...
<python><kivy>
2025-01-31 11:39:46
1
1,939
FieryCat
79,402,584
2,629,034
Obtaining diff for multiple columns in pandas
<p>i have a pandas dataframe with multiple columns (on which I am computing the cumulative value).</p> <p>I would like to get the incremental value for the same now.</p> <p>This is my current dataset:</p> <pre><code>Gender Cubic_Cap Branch UWYear yhat_all M 1000 A 2015 19 M 1000 ...
<python><pandas>
2025-01-31 11:26:48
1
571
galeej
79,402,505
923,095
Exclude BOM(byte order mark) character when combining files in Python
<p>I've created a Python script to combine multiple SQL files into one.Sometimes the script inserts a BOM(byte order mark) character and that obviously breaks the SQL script and needs to be manually corrected.I can't do a simple string replace because BOM is interpreted as binary and I tried various decoding methods on...
<python>
2025-01-31 10:49:02
2
17,067
Denys Wessels
79,402,318
9,525,238
In an array of counters that reset, find the start-end index for counter
<p>Given an array that looks like this:</p> <pre><code>values [0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 0, 1, 2, 3] index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 </code></pre> <p>If I search for index 3, I want to get the indexes of the start and end indexes f...
<python><numpy>
2025-01-31 09:40:48
4
413
Andrei M.
79,402,275
2,790,838
How to fix inconsistent method resolution order when deriving from ctypes.Structure and Mapping
<p>Given the following Python code:</p> <pre><code>import ctypes from collections.abc import Mapping class StructureMeta(type(ctypes.Structure), type(Mapping)): pass class Structure(ctypes.Structure, Mapping, metaclass=StructureMeta): pass struct = Structure() assert isinstance(struct, ctypes.Structure) asse...
<python><multiple-inheritance><pylint><metaclass>
2025-01-31 09:25:44
1
3,397
Markus
79,402,253
782,392
Can you specify a buffer size when opening a file in text I/O mode
<p>I'm confused by the documentation regarding the buffering when reading a file opened with the <code>open</code> function.</p> <p>Does the <code>buffering</code> parameter do anything when <code>mode</code> is <code>r</code> so that the file is opened in text I/O mode?</p> <p>The <a href="https://docs.python.org/3/li...
<python><python-3.x>
2025-01-31 09:17:05
1
2,674
T3rm1
79,402,169
6,751,456
Django customize validation error message
<p>I have a following serializer definitions that validate request payload:</p> <pre><code># diagnosis serializer class ICD10Serializer(serializers.Serializer): icd_10 = serializers.IntegerField(required=True, allow_null=False) class DetailsSerializer(serializers.Serializer): diagnosis_details = ICD10Serialize...
<python><django><django-rest-framework>
2025-01-31 08:39:59
1
4,161
Azima
79,402,087
7,798,669
Issue in detecting the bubble of OMR sheet
<p>I am working on an OMR sheet processing system where users bubble answers in four columns (A, B, C, D). My goal is to detect each individual bubble inside each column.</p> <p>I am successfully detecting all four columns, but there is an issue:</p> <ul> <li>For columns 1 &amp; 4, I can correctly detect the bubbles in...
<python><opencv><image-processing><computer-vision><omr>
2025-01-31 07:55:15
0
675
NoobCoder
79,401,951
8,668,595
How to correctly change layers in onnx model and restore them in onnxruntime
<p>I want to change onnx model and then restore the weights when using it with onnxruntime. However, the model doesn't seem to be changed.</p> <p>First, I load the existing model and change the weights based on <a href="https://github.com/onnx/onnx/issues/2978" rel="nofollow noreferrer">this</a> output. Then I save the...
<python><pytorch><onnx><onnxruntime>
2025-01-31 06:41:44
1
307
Eugene
79,401,801
1,570,408
ciphering services not available error on pysnmp v3 get using pysnmp7 - pycryptodome and cryptography not installed
<p>I am unable to get snmp usng pysnmp7 - cryptography and pycryptodome installed.</p> <p>Getting Error Indication: Ciphering services</p> <p>Referring <a href="https://stackoverflow.com/questions/79030219/ciphering-services-not-available-error-on-pysnmp-v3-walk">Ciphering services not available error on pysnmp v3 walk...
<python><cryptography><snmp><pysnmp><pycryptodome>
2025-01-31 04:59:44
1
6,107
Ulysses
79,401,768
6,141,238
In Python, what is the fastest way to append numerical tabular data to a data file?
<p>I am trying to write a script that appends new rows of a table to an existing file of tabular data, so that not all progress is lost if an error is encountered. Here are several ways to do this in Python:</p> <ul> <li>Write the data to a text file (a module-free method).</li> <li>Write the data to a CSV file using ...
<python><pandas><csv><append><tabular>
2025-01-31 04:24:39
0
427
SapereAude
79,401,703
3,296,786
Pytest not executing mock statement
<p>Iam writing pytest for method -</p> <pre><code>def upload(type=&quot;&quot;, local_file=None, remote_file=None, target_config=None, verify_existence=True,throw_on_error=False): if not local_file or not target_config: return None logger = default_logger target_path = remote_file if remote_file el...
<python><pytest>
2025-01-31 03:22:14
0
1,156
aΨVaN
79,401,690
958,266
Coverage Discrepancies in pytest: Code Executed but Not Tracked
<p>I discovered that when I run <code>pytest</code> with coverage, the coverage report shows that the tests do not fully cover the code, even though the tests execute the relevant code.</p> <h2>Full Coverage Command (100% Coverage)</h2> <p><code>coverage run --source=/root/MyProject/lib_python -m pytest /root/MyProject...
<python><pytest><code-coverage><coverage.py><pytest-cov>
2025-01-31 03:09:27
0
1,227
jinhwan