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,446,618
1,442,731
Update a prepackaged Protobuf message from **args
<p>I have a Python function that sends pre-canned Protobuf messages based on a command id that's passed in. I also need to be able to modify fields in that message based on <code>**args</code> that are passed into the function:</p> <pre><code>def sendCmd(self, id, **args): cmdType = mod_com.commandToMessage[id] # ...
<python><protocol-buffers>
2025-02-17 21:23:51
0
6,227
wdtj
79,446,466
3,936,496
pandas remap new two columns based other column
<p>I have pandas table where I want to create new column and fill data based on another columns values. I also want to know, if new columns value is updated So I have dictionary like this:</p> <pre><code>update_values = {&quot;Groub_A&quot;: {&quot;aadff2&quot;: &quot;Mark&quot;, &quot;aasd12&quot;: &quot;Otto&quot;, &...
<python><pandas>
2025-02-17 19:54:52
3
401
pinq-
79,446,445
7,519,434
Selection not working after changing Text widget focus
<p>I have an application with two Text widgets in two Frames. Clicking a link (formatted text with a tag bind) in one Text widget (<code>Results.text</code>) should select text in another (<code>Editor.text</code>).</p> <p>When I click once on the link, the <code>see</code> part works but <code>mark_set</code> and appl...
<python><tkinter><tkinter-text>
2025-02-17 19:44:44
1
3,989
Henry
79,446,437
825,227
Convert dictionary of lists with entries as dictionaries into dataframe with top level key as additional column value in resulting dataframe
<p>I have a dictionary of lists, each with a key string value (stock ticker) and value consisting of a list of dicts which looks like this:</p> <pre><code>data Out[88]: {'NVDA': [{'open': 144.75, 'high': 144.21, 'low': 174.33, 'close': 210.47}, {'open': 123.97, 'high': 128.5, 'low': 110.25, 'close': 154.09}, {'ope...
<python><pandas><dataframe><dictionary>
2025-02-17 19:35:35
5
1,702
Chris
79,446,423
3,637,646
"File Load Error for...Invalid response: 404 Not Found" when loading .ipynb on Spyder Notebook
<p>I am using Spyder v6 and I am trying to load a .ipynb file using the Notebook plugin. The Notebook plugin is successfully installed, since I can see the Notebook interface when I open Spyder.</p> <p>However, when I try to load the .ipynb file I do get the following error:</p> <pre><code>File Load Error for test_file...
<python><jupyter-notebook><spyder><ipynb>
2025-02-17 19:25:45
0
1,268
CafféSospeso
79,446,382
11,246,348
Negative lookahead regex in `re.subn()` context
<p>I am trying to use regular expressions to replace numeric ranges in text, such as <code>&quot;4-5&quot;</code>, with the phrase <code>&quot;4 to 5&quot;</code>.</p> <p>The text also contains dates such as <code>&quot;2024-12-26&quot;</code> that should <em>not</em> be replaced (should be left as is).</p> <p>The regu...
<python><regex>
2025-02-17 19:09:31
3
887
Max
79,446,162
405,017
Check if one array contains another in psql with psycopg3
<p>My PostgreSQL 14 database has a table with a field that is an array of strings, <code>tags TEXT[]</code>. I have a list of strings in Python <code>[&quot;foo&quot;, &quot;bar&quot;]</code>, and I want to select rows in the table that have all the tags in the list.</p> <p>Based on <a href="https://www.crunchydata.com...
<python><postgresql><psycopg2><psycopg3>
2025-02-17 17:23:21
1
304,256
Phrogz
79,446,161
2,440,505
Problem while retrieving entire word match from regex with findall()
<p>I'm trying to get the entire word that matches the expression. I can do it for one match, with <code>search()</code> but there are several in the string.</p> <p>With this code I get exactly what I want, but only the first one.</p> <pre><code>re_pattern = r&quot;(\d+(\.\d+){2,})-(20\d{2})(\d{2})(\d{2})-XPTO&quot; s =...
<python><regex>
2025-02-17 17:23:14
1
864
Christian Dechery
79,445,973
1,356,926
Copy Optuna study while slightly altering trial scores
<p>I am using Optuna to optimize the parameters of a non-ML task. Now, each trial consists in processing several files in sequence, each of which gets a score. The scores are summed cumulatively in order to allow Optuna to prune unfavorable trials, and the final sum of all scores is reported.</p> <p>In order to optimiz...
<python><optuna>
2025-02-17 16:06:05
0
5,637
Svalorzen
79,445,887
893,254
How to create a system-wide environment to install pip packages when using pip inside a Docker container?
<p>I am trying to build an existing <code>Dockerfile</code>, which needs to be migrated from an older ubuntu version base image to a more up-to-date base image.</p> <p>The existing <code>Dockerfile</code> contains commands such as</p> <pre><code>pip install pandas </code></pre> <p>There are many such <code>pip</code> c...
<python><python-3.x><docker><pip>
2025-02-17 15:33:53
1
18,579
user2138149
79,445,863
9,430,509
How can I prevent the "Telemetry client instance id changed from AAAAAAAAAAAAAAAAAAAAAA to" log in a confluent-kafka-python consumer?
<p>When the consumer (which is a very simple confluent-kafka-python consumer) starts, we see this log message after the assignment</p> <blockquote> <p>%6|1739802885.947|GETSUBSCRIPTIONS|&lt;consumer id&gt;#consumer-1| [thrd:main]: Telemetry client instance id changed from AAAAAAAAAAAAAAAAAAAAAA to &lt;some random strin...
<python><kubernetes><apache-kafka><confluent-kafka-python>
2025-02-17 15:26:09
1
935
Sergej Herbert
79,445,857
2,648,504
Pandas DataFrame returning only 1 column after creating from a list
<p>I'm using something similar to this as <code>input.txt</code></p> <pre><code> 040525 $$$$$ 9999 12345 040525 $$$$$ 8888 12345 040525 $$$$$ 7777 12345 040525 $$$$$ 6666 12345 </code></pre> <p>Due to the way this input is being pre-processed, I cannot correctly use pd.read_cs...
<python><pandas>
2025-02-17 15:23:46
1
881
yodish
79,445,822
6,128,612
Getting tweet replies with tweepy gives '429 Too Many Requests'
<p>I am trying to get tweet replies of a chosen tweet using tweepy (academic access, API 2.0)</p> <pre><code>import tweepy import time bearer_token = &quot;bearer_token&quot; twitter_client = tweepy.Client(bearer_token=bearer_token) tweet = &quot;numbers&quot; def check_replys(tweet_ID): time.sleep(1) #where to p...
<python><twitter><tweepy>
2025-02-17 15:11:22
1
343
Alexandros
79,445,265
12,760,550
Python script to run Jupyter Notebook in loop and save results to HTML
<p>Currently I have a jupyter notebook data analysis that I run for multiple countries and the only thing I need to do is replace the &quot;country&quot; variable on top with the country I desire to run the analysis. After analysis is complete, I have to save the jupyter and only then run this code:</p> <pre><code>!jup...
<python><html><jupyter-notebook><executable><nbconvert>
2025-02-17 11:33:43
0
619
Paulo Cortez
79,445,198
11,277,108
Does an errback method always get called regardless of retries?
<p>The <a href="https://docs.scrapy.org/en/latest/topics/request-response.html#using-errbacks-to-catch-exceptions-in-request-processing" rel="nofollow noreferrer">scrapy docs</a> state:</p> <blockquote> <p>The errback of a request is a function that will be called when an exception is raise while processing it.</p> </b...
<python><scrapy>
2025-02-17 11:04:33
1
1,121
Jossy
79,445,122
687,331
Sniffing bluetooth packet using Scapy on raspberry pi5
<p>I have been working on Scapy to sniff the wifi packets &amp; works like a champ. With self interest started to read other supporting feature like bluetooth that supported by Scapy <a href="https://scapy.readthedocs.io/en/latest/layers/bluetooth.html#what-is-bluetooth" rel="nofollow noreferrer">framework</a></p> <p>S...
<python><ubuntu><bluetooth><scapy><raspberry-pi5>
2025-02-17 10:35:30
0
1,985
Anand
79,445,120
3,059,001
llama3 responding only function call?
<p>I am trying to make Llama3 Instruct able to use function call from tools , it does work but now it is answering only function call! if I ask something like <code>who are you ?</code> or <code>what is apple device ?</code> it answer back function call , I believe it is something in chat template ? or still something ...
<python><artificial-intelligence><chatbot><llama><llama3>
2025-02-17 10:35:20
1
14,460
Kodr.F
79,444,966
4,194,483
Error in BLE communication between ESP32 and Python
<p>I am running a BLE server on an ESP32 which is sending the value of time periodically. This code is being run on Arduino IDE. On the other hand, I have a Python code running on my PC which needs to receive that value and display it on the GUI.</p> <p>When I run the Python code, it connects to the ESP32 successfully ...
<python><bluetooth-lowenergy><arduino-esp32>
2025-02-17 09:33:18
1
645
Mobi Zaman
79,444,566
4,451,521
Gradio dataframe dynamically changes its height
<p>This is something that I have began noticing lately. I have a dataframe in Gradio like</p> <pre><code>dataframe_output = gr.DataFrame( label=&quot;Results Dataframe&quot;, headers=[&quot;Image Path&quot;], # , &quot;Result&quot;, &quot;Check&quot;], wrap=True, ...
<python><gradio>
2025-02-17 06:27:04
0
10,576
KansaiRobot
79,444,501
11,156,131
Fpdf header and background
<p>I need to create a pdf with header, footer and background color. Tge following code is generating all 3, but it seems the footer is getting behind the pdf rect</p> <pre><code>from fpdf import FPDF class PDF(FPDF): def header(self): self.set_font(family='Helvetica', size=8) self.cell(0, 10, 'test...
<python><fpdf2>
2025-02-17 05:49:24
1
4,376
smpa01
79,444,425
9,448,637
Altair line chart with last values labeled - how to stop overlapping labels?
<p>How can I stop line labels from overlapping when the last values that the labels are pinned to are close together? I am using Altair 5.5.</p> <pre><code>import altair as alt from vega_datasets import data # Import example data source = data.stocks() # Create a common chart object chart = alt.Chart(source).transfor...
<python><altair>
2025-02-17 04:44:04
1
641
footfalcon
79,444,392
3,163,618
How does PyPy implement integers?
<p>CPython implements arbitrary-precision integers as <a href="https://docs.python.org/3/c-api/long.html#c.PyLongObject" rel="nofollow noreferrer">PyLongObject</a>, which extends PyObject. On 64-bit platforms they take at least 28 bytes, which is quite memory intensive. Also well-known is that it keeps a cache of small...
<python><integer><implementation><pypy>
2025-02-17 04:20:43
2
11,524
qwr
79,443,999
7,437,143
How to open an image, parse input from user, and close the image afterwards in Python?
<p><a href="https://stackoverflow.com/a/31751501/7437143">This</a> answer did not work for me, nor for some Mac users, and I did not find a working solution among the following similar questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/69576881/how-to-open-an-image-in-python-and-close-afterwards?nored...
<python><image>
2025-02-16 21:53:11
1
2,887
a.t.
79,443,888
1,951,507
How can python type var and type aliases be used to simplify function definitions with multiple generics
<p>Say I have a definition:</p> <pre><code>def foo[A: AMin, B: BMin, C: CMin](d: D[A, B, C], e: E[A, B]) -&gt; F[C]: ... </code></pre> <p>Is there a way (in python 3.13) to simplify (by type vars/aliases) to make this more condense, while keeping typing checkers like pyright happy?</p> <p>E.g. import the <code>A, B, C<...
<python><generics><python-typing>
2025-02-16 20:34:36
0
1,052
pfp.meijers
79,443,799
1,860,376
Is there an idiomatic way of raising an error in polars
<p>When doing some types of data processing, I want to receive an indicative error message in polars. For example, if I have the following transformation</p> <pre class="lang-py prettyprint-override"><code>import polars as pl lf = pl.LazyFrame( { &quot;first_and_middle_name&quot;: [&quot;mister banana&quot...
<python><dataframe><error-handling><python-polars>
2025-02-16 19:27:25
3
609
nadavge
79,443,495
7,366,596
Given A and B, find the number of all integer X values such that X*(X+1) falls between [A, B], both inclusive
<p>Given A and B, find the number of all integer X values such that X*(X+1) falls between [A, B], both inclusive.</p> <p>My approach:</p> <p>X^2 + X &gt;= A --&gt; X^2 + X - A &gt;= 0</p> <p>X^2 + X &lt;= B --&gt; X^2 + X - B &lt;= 0</p> <ol> <li><p>Find the roots of both equations using find_quadratic_roots() below.</...
<python><math>
2025-02-16 16:14:17
1
402
bbasaran
79,443,476
2,249,312
Constant Volume chart in python
<p>I want to create a constant volume chart in python. Here is an example with a constant volume of 50 and some sample data:</p> <pre><code>import pandas as pd import numpy as np date_rng = pd.date_range(start='2024-01-01', end='2024-12-31 23:00:00', freq='h') # Create a dataframe with the date range df = pd.DataFrame...
<python><pandas>
2025-02-16 16:02:31
1
1,816
nik
79,443,038
971,904
How to make viewport auto-scroll to the bottom in Renpy
<p>I am currently trying to make a phone text game. I have got most of functionality working except the part where I want to make the viewport of a screen to automatically scroll to the bottom when a new text comes in. I have already tried using <code>YScrollValue</code> but Renpy doesn't seem to recognize it, so I'm s...
<python><renpy>
2025-02-16 11:22:19
0
9,664
Danny
79,443,020
1,485,926
Python script to detect stale users in GitHub organizations fails getting members activity
<p>I have developed a Python script to detect stale users in GitHub organizations. In particular a script that gets all the users of a given GitHub organization and prints it's last activity date.</p> <p>The script is as follows (explained below):</p> <pre><code>import requests def get_github_organization_members(toke...
<python><github><github-api>
2025-02-16 11:11:47
0
12,442
fgalan
79,442,983
13,222,679
How to do web scraping using pyspark
<p>Hello I've a question how to do web scraping and read the response in pyspark Here's my code</p> <pre><code>import requests import pyspark from pyspark.sql.functions import * from pyspark.sql import SparkSession r = requests.get('https://www.skysports.com/football-scores-fixtures') spark=SparkSession.builder.getOrC...
<python><apache-spark><web-scraping><pyspark>
2025-02-16 10:47:29
2
311
Bahy Mohamed
79,442,953
545,537
Tracing the cause of drf_spectacular.plumbing.UnableToProceedError
<p>I have inherited a Django app in which DRF Spectacular was never fully installed. I want to get it working so I can easily see how the API has been set up.</p> <p>There are quite a few models and serializers, and I suspect a custom field may be the cause of this error I am getting: <code>drf_spectacular.plumbing.Una...
<python><django><drf-spectacular>
2025-02-16 10:21:20
0
3,040
koosa
79,442,836
7,290,715
Python asyncio not able to run the tasks
<p>I am trying to test python <code>asyncio</code> and <code>aiohttp</code>. Idea is to fetch the data from API <strong>parallely</strong> and store the .html file in a local drive. Below is my code.</p> <pre><code>import asyncio import aiohttp import time import os url_i = &quot;&lt;some_urls&gt;-&quot; file_path = &...
<python><python-asyncio>
2025-02-16 08:51:53
1
1,259
pythondumb
79,442,327
3,259,222
DataFrame values not computed during Dask Delayed.compute
<p>I want to make custom Dask task graphs, which consist of operations over Dask DataFrames.</p> <p><a href="https://docs.dask.org/en/stable/custom-graphs.html" rel="nofollow noreferrer">Here</a>, I see two interfaces with the one constructing a Delayed object from a dictionary being the preferred one, as I hope of bei...
<python><dask>
2025-02-15 22:27:12
0
431
Konstantin
79,442,105
16,869,946
Subtle mistake in pandas .apply(lambda g: g.shift(1, fill_value=0).cumsum())
<p>I have a dataframe that records the performance of F1-drivers and it looks like</p> <pre><code>Driver_ID Date Place 1 2025-02-13 1 1 2024-12-31 1 1 2024-11-03 2 1 2023-01-01 1 2 2025-01-13 5 2 2024-12-02 1 2 2024-11-12 2 2 ...
<python><pandas><dataframe><group-by>
2025-02-15 19:13:19
1
592
Ishigami
79,442,094
7,706,098
Does python reads all lines of a file when numpy.genfromtxt() is executed?
<p>I have really large ASCII file (63 million lines or more) that I would like to read using <code>numpy.genfromtxt()</code>. But, it is taking up so much memory. I want to know what python actually does when <code>numpy.genfromtxt()</code> is executed. Does it read all the lines at once?</p> <p>Look at the below code,...
<python><numpy>
2025-02-15 19:09:41
2
301
Redshoe
79,441,934
1,725,553
python venv install skips component file "pointer.png"
<p>This is a strange issue. I maintain the pi3d python module and it contains this file <code>github.com/tipam/pi3d/blob/master/src/pi3d/util/icons/pointer.png</code></p> <p>When I clone the repo locally it has the .png file but when the package is installed using pip it seems to be missing. This didn't used to be a pr...
<python><pip><venv>
2025-02-15 16:59:47
1
2,277
paddyg
79,441,739
12,415,855
Try to click on element in shadow root?
<p>i try to click on a button in a shadow root using the following code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by imp...
<python><selenium-webdriver>
2025-02-15 15:01:17
1
1,515
Rapid1898
79,441,548
418,507
Forwarding multiple ports through one channel
<p>I have a simple python channel ( socket on <code>Asyncio Streams</code> ) and client-server software that uses several TCP ports for connection. Is it possible to forward this connection through this socket channel so that the software does not notice it?</p>
<python>
2025-02-15 12:56:57
1
24,878
Bdfy
79,441,532
72,437
How to specific WhisperX Models stored location?
<p>I expected all model files to be downloaded into the <code>/app/.cache</code> folder using the following code, but they were not. Why is this happening? How can I specify the storage location for the models?</p> <pre><code>import os import whisperx os.environ[&quot;HF_HOME&quot;] = &quot;/app/.cache&quot; # Store ca...
<python><openai-whisper>
2025-02-15 12:41:48
0
42,256
Cheok Yan Cheng
79,441,474
7,215,135
pytest isn't catching exception found in Qt Event Loop?
<p>I am writing an integration test for saving data disk as JSON. The desired behavior: when a record already exists in the JSON file, the application should raise an exception before overwriting existing JSON records. Since the exception being raised is desired behavior, the integration test should catch this excepti...
<python><qt><pytest><pyside><pyside6>
2025-02-15 12:02:42
1
663
David
79,441,232
7,290,715
Parallel OData API calls using python asyncio to extract large data from SAP
<p>I am trying to develop a code that will call the SAP OData API endpoints multiple times in parallel and fetch data in json. Lets assume that at a time we want to send 5 concurrent requests. Now in each request, the OData API attribute values are to be changed dynamically.</p> <p>Below is the OData API url:</p> <pre>...
<python>
2025-02-15 09:03:27
0
1,259
pythondumb
79,441,142
10,416,012
async filter function with generic typing
<p>I'm trying to implement the python built in <code>filter</code> but async, seem like an easy task right?</p> <pre><code>async def simulated_data() -&gt; AsyncIterator[int|None]: for i in [1, None,3,5]: yield i async def afilter[T](predicate, iterable): async for item in iterable: if predicat...
<python><filter><python-asyncio><generator><python-typing>
2025-02-15 07:37:58
3
2,235
Ziur Olpa
79,441,048
7,290,715
Python: Values incremented by a user supplied number in each iteration using a loop
<p>Below is my problem statement: I want to generate the below things using <code>while</code> loop (or <code>for loop</code>)</p> <pre><code>c top skip 1 1000 0 2 1001 2000 --- added 999 3 2001 3000 --- added 999 4 3001 4000 --- added 999 --and so on. </code></pre> <p>lets assume that c...
<python>
2025-02-15 06:15:55
1
1,259
pythondumb
79,440,957
11,953,868
How to avoid AttributeError in multiple labels
<p>I have dicom files from different sources and sometimes i get error like this:</p> <blockquote> <p>AttributeError: 'FileDataset' object has no attribute 'PatientAge' because some files doesn't have this attribute.</p> </blockquote> <p>I've created function to check objects for errors:</p> <pre><code>def check_if_exi...
<python><attributeerror><dicom><pydicom>
2025-02-15 04:30:32
2
2,179
James Jacques
79,440,929
765,271
workaround for NotImplementedError: Initial conditions produced too many solutions for constants from dsolve?
<p>Is there a workaround for this? Using sympy 1.13.3 with python 3.13.1 when trying to solve <code> y'(x)=y(x)^(1/3)</code> with IC <code>y(0)=1</code> it gives</p> <blockquote> <p>NotImplementedError: Initial conditions produced too many solutions for constants</p> </blockquote> <p>Does sympy really not able to solv...
<python><sympy>
2025-02-15 03:43:26
1
13,235
Nasser
79,440,854
6,591,667
LLDB running a Python debugging script. I'm getting error: invalid thread
<p>I'm trying to run a Python debug script in LLDB, but I'm getting invalid thread errors. I'm not sure why.</p> <p>Here are my programs:</p> <p><em><strong>main.c:</strong></em></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int addNumbs(int a, int b) { return a+b; } int main() { ...
<python><debugging><lldb>
2025-02-15 01:42:00
1
8,891
tadm123
79,440,679
6,791,342
Is there a way to isolate redis-py pipelines so they are not prematurely flushed by async workers?
<p>Is there a way to isolate pipelines between jobs or threads?</p> <p>My Redis wrapper has 2 methods:</p> <pre><code>def queue_redis_message_on_pipeline(message, pipeline): pipe = pipeline or get_websocket_redis_client().pipeline() ... pipe.publish(message) def execute_redis_pipeline(pipeline): pip...
<python><redis><celery><redis-py>
2025-02-14 22:36:59
1
915
baumannalexj
79,440,210
1,442,731
Python: Shutting down child thread when parent dies
<p>I have a parent Python task that starts a child task to listen for a USB/BLE response. Problem is that if the parent task dies, the child listener task keeps running and the process has to be killed.</p> <p>Parent Process:</p> <pre><code> self.listenerTask = threading.Thread(target=self.listener, name=&quot;...
<python><multithreading>
2025-02-14 17:58:58
1
6,227
wdtj
79,440,163
1,473,517
tqdm, multiprocessing and how to print a line under the progress bar
<p>I am using multiprocessing and tqdm to show the progress of the workers. I want to add a line under the progress bar to show which tasks are currently being processed. Unfortunately, whatever I do seems to end up with this being printed on top of the progress bar making a mess. Here is a MWE that shows the problem:<...
<python><multiprocessing><tqdm>
2025-02-14 17:40:09
1
21,513
Simd
79,440,067
219,159
Retrieve server certificate in urllib3
<p>In python's urllib3, can one retrieve the server certificate after making a successful HTTPS request? If so, how?</p>
<python><https><urllib3>
2025-02-14 17:00:39
1
61,826
Seva Alekseyev
79,439,971
2,648,504
Pandas - only select rows containing a substring in a column
<p>I'm using something similar to this as <code>input.txt</code></p> <pre><code>header 040525 $$$$$ 9999 12345 random stuff 040525 $$$$$ 8888 12345 040525 $$$$$ 7777 12345 random stuff 040525 $$$$$ 6666 12345 footer </code></pre> <p>Due to the way this input is ...
<python><pandas>
2025-02-14 16:21:47
4
881
yodish
79,439,943
6,345,968
how to use/accept single line of suggested code in Google Collab
<p><strong>Problem Description</strong><br /> Google Collab gives suggestions on what your code might be, and you can hit <em>tab</em> to implement the suggested code. The thing is, often I don't need all of the suggested code, I just need a single line. Is there a command to just get the the suggested code for the r...
<python><autocomplete><google-colaboratory>
2025-02-14 16:08:11
0
347
Bob
79,439,706
254,343
Is it possible to add a custom element locator strategy to Selenium (Python)
<p>I am writing a test and would like to replicate the user's workflow -- users don't go by CSS selectors, element names, or XPath queries, all they can see is what the user agent renders. To that end, I would like to find an element on the page based on its [rendered] <em>content</em>, and being case-insensitive at th...
<python><selenium-webdriver>
2025-02-14 14:36:36
1
9,260
Armen Michaeli
79,439,634
6,077,239
How can matrix be stored efficiently in Polars dataframe and performance matrix operations
<p>I have a lot of <code>dates</code>. For each <code>date</code>, there is a vector <code>v</code> (with length <code>n</code>) and a square matrix <code>M</code> (with dimension <code>n</code> by <code>n</code>). <code>v</code>, <code>M</code> and <code>n</code> will vary by <code>date</code> in terms of both values ...
<python><python-polars><polars>
2025-02-14 14:09:52
2
1,153
lebesgue
79,439,301
16,383,578
How to get all Unicode ranges a font has glyphs for and the exceptions?
<p>I am trying to write a Python program to convert Markdown as used by Stack Exchange directly into images. The logic of Markdown is quite simple, I find MathJax to be challenging to render, but I have found <a href="https://www.bearnok.com/grva/it/knowledge/software/mathjax" rel="nofollow noreferrer">this</a>.</p> <p...
<python><algorithm><unicode><fonts>
2025-02-14 11:56:56
1
3,930
Ξένη Γήινος
79,439,244
2,125,540
Python Markdown extension for shifting headings
<p>I'm trying to inject markdown notes into templated pages. To do so, I need to shift the headings for the page to be consistent:</p> <ul> <li><code># bla</code> -&gt; <code>&lt;h3&gt;bla&lt;/h3&gt;</code>,</li> <li><code>## foo</code> -&gt; <code>&lt;h4&gt;foo&lt;/h4&gt;</code>.</li> </ul> <p>I think that the simples...
<python><markdown>
2025-02-14 11:35:49
0
363
FrViPofm
79,439,132
769,486
sqlalchemy: associationproxy with custom setter
<p>I’m trying to build a model with a relationship being represented as a string key, but changes to this key should create or load instances instead of modifying the property.</p> <p>Currently I attempt doing this using an associationproxy as it does <em>almost</em> exactly what I want.</p> <pre class="lang-py prettyp...
<python><sqlalchemy>
2025-02-14 10:53:45
0
956
zwirbeltier
79,438,961
6,727,914
Is there a way to use symlink in site-packages to reduce disk space usage?
<p>Every time I create a new project, it copies the entire package codebase into the project folder, which I find wasteful. For example, I don't want each of my projects to occupy 1 gigabyte worth of Tensorflow v2.8 disk space.</p> <p>In other languages, we can easily avoid this. For instance, in Node.js, we can use <c...
<python>
2025-02-14 09:50:16
3
21,427
TSR
79,438,809
9,686,427
Is is possible to define class methods in multiple cells in Jupyter notebooks?
<p>Say that I am creating a class with multiple methods on an <code>ipynb</code>:</p> <pre><code>class Example: def method1(self): print(&quot;Hello!&quot;) def method2(self): print(&quot;Bye!&quot;) </code></pre> <p>What should I do if I want to include a Markdown in between both methods? Simp...
<python><python-3.x><jupyter-notebook>
2025-02-14 08:49:50
1
484
Sam
79,438,588
843,400
Fixing Python import paths for a package in src used both from entry points outside of src and as a dependency in other packages?
<p>I have a model package that runs in Sagemaker. It's structure looks something like this (domain-specific stuff redacted):</p> <pre><code>&lt;My project root&gt; --&gt; src |--&gt; potato |----&gt; a bunch of nested modules |--&gt; utils |----&gt; some modules |--&gt; da...
<python><amazon-sagemaker>
2025-02-14 07:01:50
0
3,906
CustardBun
79,438,495
7,498,328
How to speed up Python for highlighting cells for an Excel spreadsheet conditionally?
<p>I have the following Python code which tries to color rows of an Excel spreadsheet conditionally upon the values of the columns. Due to the number of rows, the run time is very slow at more than <code>30 mins</code>. I am wondering if there are ways to make this much faster? Thanks.</p> <pre><code>import openpyxl fr...
<python><excel><openpyxl>
2025-02-14 06:02:08
2
2,618
user321627
79,438,489
86,072
What is the correct way to please the typechecker for a '(bytes | str) -> str' function?
<p>I have the following code:</p> <pre><code>def from_utf8(string: bytes | str) -&gt; str: if isinstance(string, bytes): return string.decode(&quot;utf-8&quot;) else: return string # &lt;- type warning on this line </code></pre> <p>pylance gives me a type warning on the <code>return string</cod...
<python><visual-studio-code><python-typing><python-3.11><pyright>
2025-02-14 05:59:13
1
53,340
LeGEC
79,438,335
10,034,073
How to make Pydantic's non-strict, coercive mode apply to integer literals?
<p>I'm validating inputs to a function using Pydantic's <code>@validate_call</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>from typing import Literal from pydantic import validate_call @validate_call def foo(a: Literal[0, 90, 180, 270]) -&gt; None: print(a, type(a)) </code></pre> <p>I want...
<python><type-conversion><pydantic><pydantic-v2>
2025-02-14 03:55:40
1
444
kviLL
79,438,268
139,150
How to run a macro before converting a file to PDF?
<p>I need to convert a .txt file (unicode) file to PDF using libreoffice using AWS lamabda function. It can be achieved using the code found here...</p> <p><a href="https://github.com/fritzpaz/lambda-libre-office/blob/main/main.py#L19" rel="nofollow noreferrer">https://github.com/fritzpaz/lambda-libre-office/blob/main/...
<python><amazon-web-services><aws-lambda><libreoffice><libreoffice-macros>
2025-02-14 03:12:04
0
32,554
shantanuo
79,438,265
785,494
How to remove the "4 files to analyze" messages from vscode?
<p>As explained in <a href="https://stackoverflow.com/questions/75604975/my-vs-code-status-bar-is-showing-42-files-to-analyze-numbers-that-keeps-increa">My VS code status bar is showing &quot;42 files to analyze&quot; numbers that keeps increasing</a> , VS code flashes a message when it analyzes files (in Python). Whi...
<python><visual-studio-code><user-interface><configuration><statusbar>
2025-02-14 03:10:38
1
9,357
SRobertJames
79,438,248
2,893,712
Mysql rowcount always returns 1 on INSERT IGNORE statement
<p>I am using <code>pymysql</code> connector to do some inserts into my database. I am trying to return whether or not a record was added or updated.</p> <p>My code is</p> <pre><code>import pymysql db = pymysql.connect(host='127.0.0.1',user='USERNAME',password='PASSWORD',database='DATABASE') cursor = db.cursor() sql =...
<python><mysql><sql-insert><pymysql><database-cursor>
2025-02-14 02:55:16
1
8,806
Bijan
79,438,224
9,538,252
Accessing output in Python HVPlot Panel for further operations (getting a variable from bind)
<p>I have a Jupyter Notebook with a Pandas Dataframe using Panel for interactive controls. My desired outcome is I want to manipulate a dataframe using the controls, then I would like to see the modified dataframe, then take additional action on this dataframe in subsequent cells. The way I currently have my script c...
<python><pandas><holoviz-panel>
2025-02-14 02:40:12
0
311
ByRequest
79,438,105
1,115,716
Running two functions in their own processes and terminating one
<p>I have a setup to run a render and measure the workload on the GPU in Python, using two functions that I run independently using the <code>multiprocessing</code> module to launch them. However, I need to terminate one from the other, so I store the object returned by <code>subprocess.popen()</code> globally to termi...
<python>
2025-02-14 00:58:19
4
1,842
easythrees
79,437,896
5,091,805
Chaining celery task results not working with signatures and kwargs
<p>This is what I was doing, and it was working up until today.</p> <pre class="lang-py prettyprint-override"><code>workflow = chain( signature( &quot;my.task&quot;, args=(1, 2, 3), options={&quot;queue&quot;: &quot;default&quot;}, ), signature( &quot;my.other.task&quot;, ...
<python><celery>
2025-02-13 22:36:54
0
6,289
Ari
79,437,815
1,532,974
How can I get mypy to handle subclassing EnumType/EnumMeta correctly?
<p><em>disclaimer: will refer to <code>EnumType</code> as opposed to the older <code>EnumMeta</code></em></p> <p>The following is valid at runtime (and is typically what is recommended to do):</p> <pre class="lang-py prettyprint-override"><code>import sys from enum import Enum, IntEnum from typing import Any, Type, Typ...
<python><enums><python-typing><mypy>
2025-02-13 21:55:33
0
621
kratsg
79,437,778
8,032,508
Run loop while writing to paramiko SFTP file is in progress
<p>I'm writing a script that will transfer large amounts of data to an SFTP server, and I'd like to have some sort of terminal print-out during the long loading time for troubleshooting/debugging. I'm using paramiko for the SFTP connection and file writing.</p> <p>What I currently have it this:</p> <pre><code>remote_zi...
<python><while-loop><paramiko>
2025-02-13 21:36:03
1
752
Jwok
79,437,667
20,591,261
How to count unique state combinations per ID in a Polars DataFrame
<p>I have a Polars DataFrame where each id can appear multiple times with different state values (either 1 or 2). I want to count how many unique ids have only state 1, only state 2, or both states 1 and 2.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;id&quot;: ...
<python><python-polars>
2025-02-13 20:40:19
3
1,195
Simon
79,437,593
12,403,550
Update item in nested dictionary containing list
<p>I am writing a method that can update any item in a nested dictionary. The method takes the path, json, and value:</p> <pre><code>from functools import reduce import operator json_test = {'request_version': 'v1.0', 'fields': [{'team': [{'name': 'Real Madrid', 'colour': 'white'}], 'location': {'type': 'Feature',...
<python><dictionary>
2025-02-13 20:02:24
1
433
prayner
79,437,460
14,614,150
How to filter a HAIL genetic table based on the a .txt file with the correct rows?
<p>If I have a hail genetic table like this on my juypter python notebook:</p> <pre><code>variant_qc gq_stats info locus alleles filters a_index was_spli...
<python><hail>
2025-02-13 18:54:27
0
507
HKJ3
79,437,319
1,564,659
Object is not subscriptable in Scrapy Fake User Agent
<p>I got this error:</p> <pre><code> from fake_useragent import UserAgent File &quot;D:\Kerja\HIT\Python Projects\Ongoing Projects\Andrew Mancilla\mancilla-env\lib\site-packages\fake_useragent\__init__.py&quot;, line 4, in &lt;module&gt; from fake_useragent.fake import FakeUserAgent, UserAgent File &quot;D:\...
<python><python-3.x><scrapy><user-agent><python-3.8>
2025-02-13 17:51:07
1
19,366
Aminah Nuraini
79,437,187
243,031
backward lookup is not working in django 5.x
<p>We are migrating our django app from <code>django==3.2.25</code> to <code>django==5.1.6</code>. <code>OneToOneField, ManyToManyField</code> are giving errors on revers lookup.</p> <p>Create fresh setup.</p> <pre><code>python -m venv app_corp_1.0.X ./app_corp_1.0.X/bin/pip install django mkdir djangotutorial ./app_c...
<python><django><django-orm>
2025-02-13 17:10:20
1
21,411
NPatel
79,437,175
616,514
Flask: Match folder hierarchy of `static` to `templates`
<p>In a blueprint folder hierarchy, the contents of <code>templates</code> shadows the hierarchy.</p> <p>Ultimately, I'd like to</p> <ul> <li>Mirror the hierarchy of blueprint <code>templates</code> in blueprint <code>static</code>?</li> <li>Add a <code>url_prefix</code> to the blueprint which applies to <code>template...
<javascript><python><html><flask>
2025-02-13 17:05:42
0
615
kando
79,437,137
7,195,666
assert_type with callable
<p><code>pyright</code> seems to expect a name of the parameter in a <code>Callable</code> when using <code>assert_type</code></p> <p>For such code:</p> <pre><code>from typing import assert_type from collections.abc import Callable def tuple_of_nums(n: int) -&gt; tuple[int,...]: return tuple(range(n)) assert_type(t...
<python><python-typing><pyright>
2025-02-13 16:55:27
1
2,271
Vulwsztyn
79,437,082
1,145,011
Unable to run Playwright test scripts in debug Mode
<p>I'm trying to learn Playwright, so I was checking Playwright Inspector concept and written below piece of code. In Pycharm terminal I run the below i.e. set PWDEBUG=1 and use pytest</p> <pre><code>PWDEBUG=1 pytest -s test_saucedemo.py </code></pre> <p>I get error message</p> <pre class="lang-none prettyprint-overrid...
<python><pytest><playwright><playwright-python>
2025-02-13 16:39:25
1
1,551
user166013
79,436,968
1,922,959
How to isolate problematic text in a large csv file with Python
<p>I'm pretty new with Python and text analysis in general...working on a project for a class. I'm reading in a bunch of free text from .csv files that came from excel. There are over 200,000 rows.</p> <p>I read them in with just <code>pd.read_csv()</code> and then</p> <pre><code>df['Text'].fillna('').apply(str) df['...
<python><pandas><text>
2025-02-13 16:04:23
0
1,299
jerH
79,436,915
3,420,542
Return error code and message to API caller
<p>I have a web application that put some data into a database using the SQLAlchemy: if the element does not exist into the table it is added else it doesn't. In both cases it shows a popup message to the user telling if the operation was successful or not using the flash command, so it works fine.</p> <p>The problem i...
<python><flask><sqlalchemy>
2025-02-13 15:44:23
1
748
xXJohnRamboXx
79,436,541
6,544,849
How to detect edges of the following image
<p>I am trying to detect the fringes/edges of the following image but it doesn't work</p> <p>Here is the python code:<a href="https://i.sstatic.net/eAZLGVtv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eAZLGVtv.png" alt="nevermind the title" /></a></p> <pre><code>import cv2 import numpy as np import m...
<python><opencv><image-processing>
2025-02-13 14:39:13
1
321
wosker4yan
79,436,530
4,473,615
Py4JError: An error occurred while calling None.org.apache.spark.api.python.PythonFunction
<p>While reading a JSON file and converting from pandas dataframe to spark. Process stops with this error.</p> <blockquote> <p>Py4JError: An error occurred while calling None.org.apache.spark.api.python.PythonFunction. Trace: py4j.Py4JException: Constructor org.apache.spark.api.python.PythonFunction([class [B, class ja...
<python><apache-spark><pyspark>
2025-02-13 14:35:46
0
5,241
Jim Macaulay
79,436,464
118,549
Satisfying Python type checking for values from a dictionary
<p>I have a Python script that pulls in some config variables using dotenv_values and sets some initial constants using these. The constants are then passed as arguments to a function. If I define the constants in the global context, I get a type-checking error due to the function expecting a string. If I define the co...
<python><python-typing>
2025-02-13 14:12:55
0
752
Gordon Mckeown
79,436,352
2,490,392
How to insert a column at a specific index with values for some rows in a single operation?
<p>I want to insert a column at a specific index in a Pandas DataFrame, but only assign values to certain rows. Currently, I am doing it in two steps:</p> <pre><code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50] }) df.insert(1, 'NewCol', None) df.loc[[1, 3], 'NewCol'] = ['X', 'Y']...
<python><pandas><dataframe>
2025-02-13 13:40:55
1
389
kirgol
79,436,332
8,329,213
Modeling Time series with ARIMA
<p>I am trying to model a <code>time series</code>. I am not certain if my approach is correct and that's why I am posting a question here. May be someone could point out the mistake I am doing. Can someone propose a better model here?</p> <p>Here is the data for <code>36 months</code>.</p> <pre><code>Revenue 5200, 498...
<python><time-series><arima><sarimax>
2025-02-13 13:32:17
0
7,707
cph_sto
79,436,279
10,666,216
KeyError when constructing a prompt with JSON text in LangChain
<p>I'm trying to create a few-shot prompt for a bot that summarizes the contents of a JSON file. No matter what input I give the FewShotPromptTemplate, it fails with a <code>KeyError: '\n &quot;name&quot;'</code>. Just doing <code>example_prompt.invoke(examples[0]).to_string()</code> works fine though.</p> <pre clas...
<python><langchain><large-language-model>
2025-02-13 13:09:49
0
1,073
Jan Berndt
79,436,180
14,743,705
How can I get the date from weeknr and year using strptime
<p>I'm trying to get the date of monday given some weeknr and year. But I feel like strptime is just returning the wrong date. This is what I try:</p> <pre><code>from datetime import date, datetime today = date.today() today_year = today.isocalendar()[0] today_weeknr = today.isocalendar()[1] print(today) print(today_y...
<python><strptime>
2025-02-13 12:33:09
2
305
Harm
79,436,039
13,860,719
How to plot polygons from categorical grid points in matplotlib? (phase-diagram generation)
<p>I have a dataframe that contains 1681 evenly distributed 2D grid points. Each data point has its x and y coordinates, a label representing its category (or phase), and a color for that category.</p> <pre><code> x y label color 0 -40.0 -30.0 Fe #660066 1 -40.0 -29.0 Fe #660...
<python><pandas><algorithm><matplotlib><plot>
2025-02-13 11:42:43
3
2,963
Shaun Han
79,435,652
1,487,336
How to avoid data copying in joblib parallel?
<p>I have a function <code>f(df, x)</code> where <code>df</code> is a large dataframe and <code>x</code> is a simple variable. The function <code>f</code> only read from <code>df</code> and doesn't modify it. Is it possible to share the memory of <code>df</code> and not copying it to sub-processes when using <code>jobl...
<python><python-3.x><memory-management><joblib>
2025-02-13 09:24:59
0
809
Lei Hao
79,435,641
1,553,368
Having problem to transform time attribute when transorming between stream and sql api
<p>I have a simple <code>Pyflink</code> application where I need a primary key for temporal table joining. Since my source uses avro confluent-format and it has problems with primary keys I use transformation: SQL API -&gt; Stream objects -&gt; SQL API. And here I get a problem explaining it table has time attribute.</...
<python><pyflink>
2025-02-13 09:21:06
1
329
Olga Gorun
79,435,496
2,700,041
Fastest way to map column from unique key dataframe to a duplicate-allowed dataframe
<p>I have two DataFrames:</p> <ul> <li><code>A</code>: Contains unique <code>(A1, A2)</code> pairs and a column <code>D</code> with numerical values.</li> <li><code>B</code>: Contains <code>(A1, A2)</code> pairs, but allows duplicates.</li> </ul> <p>I need to efficiently map column <code>D</code> from <code>A</code> to...
<python><pandas><performance><join><time>
2025-02-13 08:29:08
1
1,427
hanugm
79,435,219
3,076,866
Cannot Apply + Operator Between Series[float] and float
<p>I'm developing an indicator in <strong>Indie</strong>. I’m trying to calculate <strong>Bollinger Bands</strong> and <strong>Keltner Channels</strong>, but I’m running into an error when adding a <code>Series[float]</code> to a <code>float</code> value.</p> <p>Here’s the error message:</p> <blockquote> <p>Error: 20:2...
<python><indie><indie-v4>
2025-02-13 06:22:10
1
9,715
Hardik Satasiya
79,435,178
5,023,889
Python IO – show read speed interactively
<p>is it possible to show reading speed interactively when reading a file?</p> <p>The reason is that I would like to measure the speed when reading a file from network drive via Python and compare it against copying the file to local drive manually.</p> <p>Let's say I have a simple open read function:</p> <pre class="l...
<python><io>
2025-02-13 05:56:58
1
4,949
Darren Christopher
79,434,994
678,228
Consolidating data with multiple columns in Pandas
<p>I have an excel file, with 4 columns, namely &quot;Item&quot;, &quot;Size&quot;, &quot;Price&quot;, &quot;Quantity&quot;.</p> <p>I would like to combine all the items with same value in &quot;Item&quot;, &quot;Size&quot;, &quot;Price&quot;, and sum up their &quot;Quantity&quot; into a single entry, and keep the sort...
<python><excel><pandas>
2025-02-13 03:33:06
2
3,521
Feng-Chun Ting
79,434,990
704,265
In AWS CDK, how can we get the arn from the role that is created along with an aws_sso.CfnPermissionSet?
<p>To be explicit, the code uses the following class: <code>aws_cdk.aws_sso import CfnPermissionSet</code> with the <code>inline_policy</code> argument.</p> <p>After it's deployed, there is a role that matches that <code>inline_policy</code>. I'm looking for a way to use that role arn within the stack, to allow me to s...
<python><amazon-web-services><aws-cdk>
2025-02-13 03:25:08
0
3,166
Finch_Powers
79,434,771
1,115,716
launching multiple commands in parallel and parsing their outputs
<p>I have two functions, each launch a command, and I need to run both in parallel:</p> <pre><code>def time_render(filename: str) -&gt; str: # Run the render and time the operation # We expect the full path for the file command_to_run = '{} -b {} -f 10 -- --cycles-device CUDA'.format( render_executa...
<python>
2025-02-13 00:07:37
0
1,842
easythrees
79,434,678
2,626,865
explain the following attribute lookup
<pre><code>class Test(io.BufferedIOBase): def __init__(self, f): self.f = f def __getattr__(self, name): print(&quot;getattr: searching for: &quot;, name) #try: # v = getattr(self.f, name) #except Exception: # print(&quot; found nothing!&quot;) #...
<python>
2025-02-12 22:50:14
0
2,131
user19087
79,434,667
1,188,381
pymongo create a dict based on a group match
<p>I'm new to pymongo and can't quite wrap my head around the logic of creating a nested group and match.</p> <p>Im trying to find all the unique models types and then create a list of the logical names used for the models.</p> <p>The output that I want to create, or close to it.</p> <pre><code> { {&quot;Mod...
<python><mongodb><pymongo-3.x>
2025-02-12 22:40:11
1
1,445
onxx
79,434,556
3,282,758
Best place to initialize a variable from a postgres database table after django project startup
<p>I have a django project where I have some database tables.</p> <p>One of the database tables is designed to store messages and their titles. This helps me to create/alter these messages from my django-admin.</p> <p>Now I want to initialize a variable (as a dictionary) from this table as follows :</p> <pre><code>MY_M...
<python><django><django-models><django-views>
2025-02-12 21:52:58
1
1,493
user3282758