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
78,205,470
536,262
setuptools pyproject.toml - managing paths of enclosed config files
<p>When using pyproject.toml setuptools how can I dynamically assure that my binary finds its config enclosed in the same directory as the python code?</p> <p>After pip install files are located:</p> <pre><code>: c:\dist\venvs\ranchercli\lib\site-packages\ranchercli\ranchercli-projects.json c:\dist\venvs\ranchercli\lib...
<python><setuptools><pyproject.toml>
2024-03-22 10:14:57
2
3,731
MortenB
78,205,398
8,764,412
RabbitMQ - consume messages from a classic queue to a MQTT connection
<p>I'm trying to consume messages from a queue in RabbitMQ which is already set up and has some messages. I am testing the MQTT subscriptor with a connection with the paho library:</p> <pre><code>import paho.mqtt.client as mqtt from paho.mqtt.enums import CallbackAPIVersion def on_connect(client, userdata, connect_fla...
<python><rabbitmq><mqtt>
2024-03-22 10:02:36
1
383
Arduino
78,205,293
7,162,827
FastAPI override Depends & Security
<p>I have a problem with testing endpoints that use both <code>Depends</code> AND <code>Security</code>. First of all, here is my root endpoint which i can test perfectly fine using <code>app.dependency_override</code>:</p> <pre><code># restapi/main.py from api_v1.api import router as api_router from authentication.ver...
<python><dependency-injection><pytest><fastapi>
2024-03-22 09:44:30
1
567
armara
78,205,206
7,176,676
Color edges distinctly in network based on attribute value
<p>Consider an undirected <code>multigraph</code> (without <code>self-loops</code>) in which the maximum vertex degree <code>d=8</code> (in other words, there are at most 4 edges between two neighboring nodes).</p> <p>I would like to assign to each of the parallel edges between two neighboring nodes a unique number fro...
<python><networkx><graph-theory><graph-coloring>
2024-03-22 09:27:20
0
395
flow_me_over
78,205,081
826,112
Why do Python list sizes in memory not match documentation?
<p>I've been trying to gain a better understanding of how Python allocates memory for lists when the list is being extended by appending. This <a href="https://stackoverflow.com/questions/63204377/memory-size-of-list-python">question</a> covers the basics well and explains the memory increments increase in size as the...
<python><memory>
2024-03-22 09:05:29
1
536
Andrew H
78,205,054
6,610,407
Type hint for a factory classmethod of an abstract base class in Python 3
<p>I have two abstract classes, <code>AbstractA</code> and <code>AbstractB</code>. <code>AbstractB</code> is generic and its type parameter is bound to <code>AbstractA</code>. <code>AbstractB</code> further has a factory classmethod that returns an instance of one of its subclasses--which one is determined from some in...
<python><generics><abstract-class><mypy><python-typing>
2024-03-22 08:59:17
1
475
MaartenB
78,205,031
2,202,989
Numpy image array to pyglet image
<p>I am trying to load image to a numpy array using imageio, and display it using pyglet. The end result is garbled, though I can see some structure. Code:</p> <pre><code>import pyglet as pg import imageio.v3 as im import numpy as np window = pg.window.Window() #Load image, and get_shape np_image = im.imread(&quot;...
<python><numpy><pyglet><python-imageio>
2024-03-22 08:53:54
1
383
Nyxeria
78,204,869
900,898
Python: urllib.parse.urljoin VS string concatenation
<p>Could you please explain to me the difference between two approaches of url formatting : concatenation and urllib.parse.urljoin and which is better to use?</p> <pre><code># base_url = &quot;http://example.com&quot; # url_path = &quot;/ssome/endpoint&quot; from urllib.parse import urljoin url = urljoin(base_url, url...
<python><url>
2024-03-22 08:20:45
0
548
ZigZag
78,204,798
7,905,329
urllib3 warning ReadTimeoutError while connecting to Nominatim's geolocator
<p>The code below code to extract pincodes, but raises the error below. How to work around this?</p> <pre><code>def get_zipcode(df, geolocator, lat_field, lon_field): location = geolocator.reverse(str(df[lat_field]) + &quot;,&quot; + str(df[lon_field])) # print(location) #-- uncomment this in case of checkin...
<python><urllib3><httpconnection><nominatim><geolocator>
2024-03-22 08:02:26
0
364
anagha s
78,204,656
1,274,613
How do I test whether two structural types are subtypes of each other?
<p>I have two Protocols in different modules.</p> <pre><code>class TooComplexProtocolInNeedOfRefactoring(Protocol): @property def useful(self) -&gt; int: ... @property def irrelevant1(self) -&gt; int: ... @property def irrelevant2(self) -&gt; int: ... @property de...
<python><python-typing><structural-typing>
2024-03-22 07:29:35
1
6,472
Anaphory
78,204,636
7,641,854
How to properly type hint usage of child classes in list?
<p>How do I properly type hint this:</p> <pre class="lang-py prettyprint-override"><code>from typing import Optional class A: ... class B(A): ... class C(A): ... my_dict: dict[str, list[Optional[A]]] = {&quot;b&quot;: [], &quot;c&quot;: []} b: list[Optional[B]] = [B()] c: list[Optional[C]] = [C()] my_dict[&quot;b&qu...
<python><mypy><python-typing>
2024-03-22 07:25:02
1
760
Ken Jiiii
78,204,517
13,392,257
How to get list of imported items in python file
<p>I want to get list of imported items in file</p> <p>Example I have a file</p> <pre><code># file1.py from mod1 import a from mod2 import b, c print(a) </code></pre> <p>I want a function that takes path of the file <code>foo(&quot;file1.py&quot;)</code> and returns the following</p> <pre><code>{ &quot;file1.py&q...
<python>
2024-03-22 06:58:05
1
1,708
mascai
78,204,333
143,397
How to run Rust library unit tests with Maturin?
<p>I'm building a custom Python module in Rust, with maturin.</p> <p>I am using PyEnv, with Python 3.12.2, installed with <code>env PYTHON_CONFIGURE_OPTS=&quot;--enable-shared&quot;</code> and <code>--keep</code> so the Python sources are available. I have a venv and I'm using <code>maturin develop</code> to build my l...
<python><unit-testing><rust><maturin>
2024-03-22 06:13:08
1
13,932
davidA
78,203,981
2,666,270
Downloading file from Google Drive
<p>I'm trying to download a file from Google Drive using <code>gdown</code> as follows:</p> <pre><code>file_id = url.split('=')[-1] gdrive_url = f'https://drive.google.com/uc?id={file_id}' output_path = os.path.join(extract_to, 'file.tgz') gdown.download(gdrive_url, output_path, quiet=False) ...
<python>
2024-03-22 04:07:12
2
9,924
pceccon
78,203,521
5,156,525
R `dnbinom` giving different results than Python `scipy.stats.nbinom.pmf` even after accounting for different parameterization
<p>I am trying to translate my colleague's R code into Python. It involves making a calculation with a negative binomial distribution's probability mass function, but the issue is that R's <code>dnbinom</code> uses a differing parameterization from Python's <code>scipy.stats.nbinom.pmf</code>. According to <a href="htt...
<python><r><statistics>
2024-03-22 00:56:11
1
318
Pacific Bird
78,203,369
9,582,542
Python Scrapy Function that does always work
<p>The script below work 90% of the time to collect weather data. However, there are few cases where for some reason it just fails and the html code is consistant with the other request. There times where code is the same with the same request but it fails.</p> <pre><code>class NflweatherdataSpider(scrapy.Spider): name...
<python><scrapy>
2024-03-21 23:55:47
1
690
Leo Torres
78,203,314
6,458,245
Avoid restarting jupyter notebook when encountering cuda out of memory exception?
<p>I am using pytorch and jupyter notebook. Frequently I'll encounter cuda out of memory and need to restart the notebook. How can I avoid needing to restart the whole notebook? I tried del a few variables but it didn't change anything.</p>
<python><jupyter-notebook><pytorch>
2024-03-21 23:32:00
1
2,356
JobHunter69
78,203,312
15,412,256
Polars map_batches UDF with Multi-processing
<p>I want to apply a <code>numba UDF</code>, which generates the same length vectors for each groups in <code>df</code>:</p> <pre class="lang-py prettyprint-override"><code>import numba df = pl.DataFrame( { &quot;group&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;], ...
<python><parallel-processing><python-polars>
2024-03-21 23:31:50
1
649
Kevin Li
78,203,204
6,458,245
urlopen inconsistent API return format for no content?
<p>I'm using an api http endpoint service where I retrieve some information from their url:</p> <pre><code>response = urlopen(url, cafile=certifi.where()) print(response.read().decode(&quot;utf-8&quot;)) </code></pre> <p>However, sometimes their service returns nothing and the code above prints either: '' or '[]'</p> <...
<python><url><urllib>
2024-03-21 22:53:12
0
2,356
JobHunter69
78,203,187
6,312,511
NBA_API: why is this Python code returning an empty dataframe?
<p>I am simply attempting to pull all of today's games; later I will merge team statistics onto it, but that's a different question.</p> <p>My question is, why does the code below return an empty dataframe? I can print the results using a for loop -- that's how I got the desired output below -- but I cannot put them in...
<python><pandas><nba-api>
2024-03-21 22:47:32
1
1,447
mmyoung77
78,203,150
525,865
BeautifulSoup: iteration over 24 char (from a to z) fails : reducing the complexity to get a first insight into the dataset:
<p>i have a list of insurers in spain - it is collected in 24 rubriques - on a website: See the following</p> <p>insurandes - espanol: the full list: <a href="https://www.unespa.es/en/directory" rel="nofollow noreferrer">https://www.unespa.es/en/directory</a></p> <p>it is divided into 24 pages: <a href="https://www.une...
<python><dataframe><web-scraping><beautifulsoup><request>
2024-03-21 22:35:36
1
1,223
zero
78,203,142
11,248,638
How to Populate Null Values in Columns After Outer Join in Python Pandas
<p>My goal is to join two dataframes from different sources in Python using Pandas and then fill null values in columns with corresponding values in the same column.</p> <p>The dataframes have similar columns, but some text/object columns may have different values due to variations in the data sources. For instance, th...
<python><pandas><join><outer-join>
2024-03-21 22:33:05
1
401
Yara1994
78,203,113
3,471,286
Shallow copy: is the Python.org documentation wrong?
<p>Is the official documentation on Python.org wrong, or did I interpret something wrongly?</p> <p>Near the end of the <a href="https://docs.python.org/3/tutorial/introduction.html#lists" rel="nofollow noreferrer">Lists Section</a> of the documentation in &quot;An Informal Introduction to Python&quot;, one can find the...
<python>
2024-03-21 22:23:42
2
731
Gui Imamura
78,203,093
11,796,910
The --memory-init-file is no longer supported
<p>I started using emscripten with Python to deploy my game to the web and it looks like the flag <code>--memory-init-file</code> is no longer valid and breaks the build.</p> <p>The github repo isn't sharing any older releases of the code so I cannot use older version of the code and carry on.</p> <pre><code>mark@eli:~...
<python><emscripten>
2024-03-21 22:17:41
1
1,559
Mark
78,202,830
9,518,890
Pydantic validation fails when importing module from a package when running pytest
<p>I am trying to understand why pydantic validation fails here. I was running into this in larger codebase and was able to condense it into small example.</p> <p>there is <code>misc_build.py</code> where pydantic model is defined</p> <p><code>metadata_manager/misc_build.py</code></p> <pre><code>from pydantic import Ba...
<python><pytest><pydantic>
2024-03-21 21:17:02
0
14,592
Matus Dubrava
78,202,811
726,730
PyQt5 - Using multiprocessing for matplotlib purposes
<p>With this code i am trying to plot a pydub.AudioSegment signal which has duration=125msec. The plot time window (x-axis) is 3 sec.</p> <p>code:</p> <pre class="lang-py prettyprint-override"><code>import time from PyQt5.QtCore import pyqtSignal, QThread from multiprocessing import Process, Queue, Pipe from datetime i...
<python><pyqt5><multiprocessing><qthread>
2024-03-21 21:10:58
0
2,427
Chris P
78,202,760
15,412,256
Polars Groupby Describe Extension
<p><code>df</code> is a demo Polars DataFrame:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;groups&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;], &quot;values&quot;: [1, 2, 3, 4, 5, 6], } ) </code></pre> <p...
<python><python-polars>
2024-03-21 20:58:49
1
649
Kevin Li
78,202,730
11,318,930
polars: efficient way to apply function to filter column of strings
<p>I have a column of long strings (like sentences) on which I want to do the following:</p> <ol> <li>replace certain characters</li> <li>create a list of the remaining strings</li> <li>if a string is all text see whether it is in a dictionary and if so keep it</li> <li>if a string is all numeric keep it</li> <li>if a ...
<python><regex><dataframe><python-polars>
2024-03-21 20:50:39
2
1,287
MikeB2019x
78,202,681
17,729,094
Explode a dataframe into a range of another dataframe
<p>I have some data in 2 dataframes that look like:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data = {&quot;channel&quot;: [0, 1, 2, 1, 2, 0, 1], &quot;time&quot;: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]} time_df = pl.DataFrame(data) data = { &quot;time&quot;: [10.0, 10.5], &quot;eve...
<python><python-polars>
2024-03-21 20:39:00
1
954
DJDuque
78,202,544
7,981,292
Python with Bleak - Pair with a device that requires a pin
<p>I'm attempting to read some characteristics from a Bluetooth device. The device requires a Pin to pair but I can't find any resources on how to enter a pin with python-bleak.</p> <p>My code is below. It will successfully connect and get the services. Any attempt to bond with the device gives me an error.</p> <blockq...
<python><bluetooth><python-bleak>
2024-03-21 20:09:06
1
363
Dave1551
78,202,512
2,675,349
Why do I get "Validators defined with incorrect fields" when trying to validate JSON data using pydantic?
<p>I am trying to parse a JSON object to pydantic validator and it's giving a compiler error.</p> <blockquote> <p>pydantic.errors.ConfigError: Validators defined with incorrect fields: validate_grade</p> </blockquote> <pre class="lang-json prettyprint-override"><code>{ &quot;grade&quot;: &quot;A&quot; &quot;subject...
<python><pydantic>
2024-03-21 19:59:33
1
1,027
Ullan
78,202,491
1,845,408
"Invalid constructor input for Tool" error when using function calling with gemini-pro
<p>I have the following code to enabling function calling with gemini-pro model (it is based on <a href="https://ai.google.dev/tutorials/function_calling_python_quickstart" rel="nofollow noreferrer">this example</a>).</p> <pre><code>def getWordCount(sentence:str): return len(sentence.split(' ')) model = genai.Gen...
<python><google-api><google-gemini>
2024-03-21 19:52:42
1
8,321
renakre
78,202,488
6,943,622
Combination of Non-overlapping interval PAIRS
<p>I recently did a coding challenge where I was tasked to return the number of unique interval pairs that do not overlap when given the starting points in one list and the ending points in one list. I was able to come up with an n^2 solution and eliminated duplicates by using a set to hash each entry tuple of (start, ...
<python><algorithm><combinations><intervals>
2024-03-21 19:52:05
2
339
Duck Dodgers
78,202,160
3,083,406
Python3 trying to get access to the object of my class that was instantiated in a thread call
<p>Working in Python3, I've created a class that is managing some tables. This class is instantiated in a call with threading.Thread() in which I have a &quot;run&quot; function that is called by the threads mechanism so it will instantiate the class. Now, that function will never exit as it runs some tk code and sits ...
<python><python-3.x><multithreading>
2024-03-21 18:34:16
1
911
Dowd
78,202,039
2,735,009
Show 2 histograms on the same plot with 1 calculated histogram in Python
<p>I have created the following sample dataset:</p> <pre><code>sample_df = pd.DataFrame({ 'user_id':np.arange(0,1000), 'sent_click_diff':np.random.randint(400, size=1000), 'clicked_or_not':np.random.choice( ['clicked','not clicked'], 1000), }) </code></pre> <p>And here's a sample code to display the % o...
<python><pandas><matplotlib><histogram>
2024-03-21 18:11:36
0
4,797
Patthebug
78,201,819
9,244,371
jupyterlab with pylsp .virtual_documents error
<p>I'm using <code>jupyterlab</code> 4.1.5 and am trying to follow these instructions: <a href="https://jupyterlab.readthedocs.io/en/latest/user/lsp.html" rel="nofollow noreferrer">https://jupyterlab.readthedocs.io/en/latest/user/lsp.html</a></p> <p>I <code>pip</code> installed <code>pylsp</code> using the provided com...
<python><jupyter-lab><language-server-protocol>
2024-03-21 17:28:58
0
428
Hutch3232
78,201,741
354,051
Generate MFCC with good noise for an audio signal of 0.01 seconds
<p>I'm using 16000Hz, mono WAV files for my CNN project. Here is the code for MFCC generation</p> <pre class="lang-py prettyprint-override"><code>import librosa import numpy as np signal, sr = librosa.load('test.wav', sr=None) mfccs = np.mean(librosa.feature.mfcc(y=signal[0:160], sr=16000, n_fft=160, ...
<python><mfcc>
2024-03-21 17:12:43
0
947
Prashant
78,201,636
4,475,588
How to Stop an Airflow DAG and Skip Future Processing if File is Empty?
<p>I am working on an Airflow DAG where I need to perform certain processing tasks on a file only if the file is not empty. The workflow should ideally check if the file has content, and if it's empty, the DAG should stop executing further and skip any future processing related to this file.</p> <p>Here is the simplifi...
<python><airflow><directed-acyclic-graphs>
2024-03-21 16:53:30
1
626
Igor Tiulkanov
78,201,631
4,976,543
How would you vectorize a fraction of sums of matrices (Expectation Maximization) in numpy?
<p>I am trying to vectorize the following Expectation-Maximization / clustering equation for a 2-dimensional Gaussian distribution using numpy. I have a naive approach that I will include at the end of my question:</p> <p><a href="https://i.sstatic.net/M8Wqw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.n...
<python><numpy><vectorization>
2024-03-21 16:53:09
2
712
Branden Keck
78,201,566
13,142,245
AWS Step Functions: Unable to apply ReferencePath
<p>I am attempting a step function but am not certain about the <code>&quot;$.&lt;variable&gt;&quot;</code> syntax. For brevity, resources like Lambda functions and S3 buckets are defined elsewhere in infraConstruct (details that I can provide upon request.)</p> <p>My goal is to construct two Lambda functions. The firs...
<python><amazon-web-services><aws-lambda><aws-step-functions>
2024-03-21 16:42:25
1
1,238
jbuddy_13
78,201,546
4,522,501
Global variable not being updated with a thread in python
<p>I have a Thread that is checking every hour of a time and keep updating a global variable, for some reason global statement is not working and it's keeping the same value in the global variable even if the thread update it, please reference to my code:</p> <pre><code>paymentDate = &quot;2024-03-22&quot; currentDate ...
<python><multithreading><variables><global>
2024-03-21 16:39:12
1
1,188
Javier Salas
78,201,299
13,314,132
Unable to send keys to text box using Selenium. Getting selenium.common.exceptions.TimeoutException: Message:
<p>I am trying to send keys to the search bar text box using Selenium but getting the error:</p> <pre><code>Traceback (most recent call last): File &quot;.\test.py&quot;, line 19, in &lt;module&gt; WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, &quot;input#typeahead-input-56352&quot;...
<python><selenium-webdriver>
2024-03-21 15:58:28
1
655
Daremitsu
78,201,240
10,462,461
Records not getting caught in if statement
<p>I've created a sample dataframe below.</p> <pre><code>import pandas as pd import numpy_financial as npf df = pd.DataFrame({ 'loannum': [111, 222], 'datadt': [dt.datetime(2024, 2, 29), dt.datetime(2024, 2, 29)], 'balloondt_i': [dt.datetime(2024, 8, 1), dt.datetime(2024, 8, 1)], 'balloondt': [dt.datet...
<python><pandas>
2024-03-21 15:48:59
1
340
gernworm
78,201,163
3,639,372
Python Mediapipe replace pose landmark line drawings with custom image drawings
<p>I'm using a webcam to stream a video and would like to use mediapipe to estimate and replace/blur a user's face with a custom yellow image and the user's eyes with a heart (❤) emoji and the user's lips with a smile drawing.</p> <p>The code I currently have below is only drawing landmark lines.</p> <p>Could someone p...
<python><graphics><drawing><mediapipe>
2024-03-21 15:39:01
1
867
Vakindu
78,201,124
11,251,938
Django query doesn't return the instance that I just saved in database
<p>I'm working on a project that requires to trace the events related to a process. In my case I have <code>Registration</code> and <code>RegistrationEvent</code> models with the latter connected throug a ForeignKey to <code>Registration</code>.</p> <p>I also have written a method of <code>RegistrationEvent</code> call...
<python><django><django-models>
2024-03-21 15:31:14
1
929
Zeno Dalla Valle
78,201,028
6,606,057
Cannot Convert Local CSV to dataframe in Pandas on Spyder
<p>Hello I am learning Python using Spyder (Python 3.8.10 64-bit | Qt 5.15.2 | PyQt5 5.15.10 | Windows 10 (AMD64). I am unable to convert a local copy of a csv into a dataframe using pandas</p> <pre><code># import pandas module import pandas as pd # making dataframe df = pd.read_csv(&quot;C:\Test\test.txt&quot;) # o...
<python><pandas><dataframe>
2024-03-21 15:17:31
1
485
Englishman Bob
78,200,996
4,999,991
Automatically Detecting and Installing Compatible Versions of `setuptools` and `pip` with PowerShell for Any Python Version
<p>I am trying to automate the setup of Python environments on Windows and encountered a challenge with legacy Python versions. Specifically, I need a PowerShell script that:</p> <ol> <li>Detects the last version of <code>setuptools</code> that is compatible with the currently active local Python version, downloads it,...
<python><windows><powershell><pip><setuptools>
2024-03-21 15:12:26
0
14,347
Foad S. Farimani
78,200,945
4,928,783
Firebase Python Function called from Firebase Hosted App
<p>I would like to call a firebase function written in Python from my firebase hosted app. I've followed the documentation here (<a href="https://firebase.google.com/docs/functions/callable?gen=2nd#call_the_function" rel="nofollow noreferrer">https://firebase.google.com/docs/functions/callable?gen=2nd#call_the_function...
<javascript><python><firebase><firebase-authentication><google-cloud-functions>
2024-03-21 15:05:52
0
390
John Robinson
78,200,863
7,631,505
Draw an image and a stem plot in 3d with matpltolib
<p>I'm trying to make a 3d plot with python that shows an image at a certain level and certain specific points as a stem plot (basically the image is a sort of 2d map and the stem plots represent the value of a certain parameter at the point in the map)</p> <p>Current code :</p> <pre><code>import numpy as np import mat...
<python><matplotlib><matplotlib-3d>
2024-03-21 14:56:30
1
316
mmonti
78,200,862
2,989,642
How may I combine multiple adapters in Python requests?
<p>I need to make multiple calls to a web endpoint that is somewhat unreliable, so I have put together a timeout/retry strategy that I issue to a <code>requests.Session()</code> object as an adapter.</p> <p>However, I <em>also</em> need to mount this same endpoint using a client PKCS12 certificate and a public certific...
<python><python-requests>
2024-03-21 14:56:22
2
549
auslander
78,200,819
6,665,586
ModuleNotFoundError: No module named 'msgraph.generated.users'
<p>I'm trying to run a Python application that uses msgraph-sdk. This error <code>ModuleNotFoundError: No module named 'msgraph.generated.users'</code> is happening in this method</p> <pre><code>async def get_user_groups(self, token: str) -&gt; List[str]: credentials = OnBehalfOfCredential(tenant_id=TENANT_ID, ...
<python><microsoft-graph-api>
2024-03-21 14:50:05
0
1,011
Henrique Andrade
78,200,730
4,009,645
Pandas: replace regex with string ending with tab not working
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame({'Depth':['7500', '7800', '8300', '8500'], 'Gas':['25-13 PASON', '9/8 PASON', '19/14', '56/26'], 'ID':[1, 2, 3, 4]}) </code></pre> <p><a href="https://i.sstatic.net/FXvXI.png" rel="nofollow noreferrer"><img src="https://...
<python><pandas><regex>
2024-03-21 14:35:08
3
1,009
Heather
78,200,693
4,999,991
pyenv-win not overriding system Python version with local setting
<p>I've installed <code>pyenv-win 3.1.1</code> on Windows using Chocolatey and successfully installed Python 2.6 using <code>pyenv install 2.6</code>. I then tried setting the local Python version for my project by navigating to the project directory and running <code>pyenv local 2.6</code>, which completed without err...
<python><windows><environment-variables><pyenv><pyenv-win>
2024-03-21 14:31:01
2
14,347
Foad S. Farimani
78,200,539
7,920,004
Existing column unrecognized by Delta merge
<p>Sample of my data I'm working on:</p> <p><strong>Source</strong></p> <pre><code>+---------+--------------------+-------------+--------------------+--------------------+--------------+------------------+ |store_id |type |store_status | name | owner |owner_code |store_asOfD...
<python><pyspark><delta-lake>
2024-03-21 14:06:38
1
1,509
marcin2x4
78,200,420
2,123,706
remove spaces from pandas column if there are 2 or 3
<p>I have:</p> <pre><code>pd.DataFrame({'id':[1,2],'col1':['a b c','a b c d']}) </code></pre> <p>I want:</p> <pre><code>pd.DataFrame({'id':[1,1,2],'col1':['ab c', 'a bc','ab cd']}) </code></pre> <ul> <li>there will always be 1,2 or 3 spaces in a column</li> <li>if there are 2 spaces (3 words), I want to duplicate the r...
<python><pandas>
2024-03-21 13:50:48
1
3,810
frank
78,200,263
3,590,067
Python: how to fill a ternary plot
<p>I want to make a legend in python as a ternary plot to compare the values of three matrices A,B,C. This what I am doing.</p> <pre><code>import numpy as np import matplotlib.patches as mpatches def create_color_map(A, B, C): &quot;&quot;&quot; Creates a color map based on the values in three matrices (A, B, C...
<python><matplotlib><ternary>
2024-03-21 13:25:58
0
7,315
emax
78,199,905
3,943,162
`expected string or buffer` error when running retriever within an LCEL chain, even working fine independently
<p>Working with LangChain, I created the following retriever based on the <a href="https://python.langchain.com/docs/modules/data_connection/retrievers/parent_document_retriever" rel="nofollow noreferrer">Parent Document Retriever docs</a>. I basically copy and paste the example, but I'm using just one .txt file instea...
<python><langchain><data-retrieval><py-langchain>
2024-03-21 12:21:06
0
1,789
James
78,199,880
458,742
why does TemporaryDirectory change type within a "with" block?
<p>In python3 console</p> <pre><code>&gt;&gt;&gt; x1=tempfile.TemporaryDirectory() &gt;&gt;&gt; print(type(x1)) &lt;class 'tempfile.TemporaryDirectory'&gt; &gt;&gt;&gt; with tempfile.TemporaryDirectory() as x2: ... print(type(x2)) ... &lt;class 'str'&gt; </code></pre> <p>Why is <code>x1</code> a <code>TemporaryDirec...
<python><python-3.x>
2024-03-21 12:17:09
1
33,709
spraff
78,199,832
12,297,666
Keras Hyperparameter Tuning with Functional API
<p>I am trying to user Keras Tuner to optimize some hyperparameters, and this is the code:</p> <pre><code>def criar_modelo(hp): lstm_input = Input(shape=(x_train_lstm.shape[1], 1), name='LSTM_Input_Layer') static_input = Input(shape=(x_train_static.shape[1], ), name='Static_Input_Layer') # LSTM 1 ...
<python><keras><keras-tuner>
2024-03-21 12:06:46
1
679
Murilo
78,199,615
10,722,752
How to filter group's max and min rows using `transform`
<p>I am working on a task wherein, I need to <strong>filter in</strong> rows that contain the group's max and min values and filter out other rows. This is to understand how the values change at each decile.</p> <pre><code>np.random.seed(0) df = pd.DataFrame({'id' : range(1,31), 'score' : np.random.un...
<python><pandas>
2024-03-21 11:33:54
1
11,560
Karthik S
78,199,605
10,211,480
libxml2 and libxslt development packages issue in Redhat Linux
<p>I am trying to install python module shareplum on python3.8 and My machine is RHEL 6.10 , but getting below error while using command:</p> <p><code>pip3.8 install shareplum</code></p> <pre><code> × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─&gt; [4 lines of output] &lt;...
<python><linux><redhat><libxml2><libxslt>
2024-03-21 11:32:16
0
343
Ashu
78,199,468
525,865
Beautifulsoup: iterate over a list from a to z and parse the data in order to store it in a df
<p>I am currently ironing out a very very easy parser that goes from a to z on a memberlist :: we have a memberlist here:</p> <p>see: <a href="https://vvonet.vvo.at/vvonet_mitgliederverzeichnisneu" rel="nofollow noreferrer">https://vvonet.vvo.at/vvonet_mitgliederverzeichnisneu</a></p> <p>note: we have to open the link ...
<python><pandas><dataframe><request>
2024-03-21 11:12:04
2
1,223
zero
78,198,984
14,739,428
immediately throw sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
<p>I encountered a very strange issue where I consistently receive the following exception at a fixed point in my test data when using the db.session.execute('insert into table_a select * from table_b where xxx') statement within a loop.</p> <pre><code>sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (20...
<python><mysql><flask><flask-sqlalchemy>
2024-03-21 09:58:37
1
301
william
78,198,787
10,211,480
SSL module not available in Python3.8
<p>I have RHEL6.10 machine where I used below steps to install python3.8</p> <pre><code>wget https://www.python.org/ftp/python/3.8.16/Python-3.8.16.tar.xz tar xcf Python-3.8.16.tar.xz cd Python-3.8.16.tar.xz ./configure make altinstall pip3.8 install shareplum </code></pre> <p>While using pip command to install any...
<python><python-3.x><ssl><pip><openssl>
2024-03-21 09:30:09
1
343
Ashu
78,198,539
2,801,669
How to distinguish between Base Class and Derived Class in generics using Typing and Mypy
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar import dataclasses @dataclasses.dataclass class A: pass @dataclasses.dataclass class B(A): pass T = TypeVar(&quot;T&quot;, A, B) def fun( x1: T, x2: T, ) -&gt; int: if type(x1) != t...
<python><generics><mypy><python-typing>
2024-03-21 08:47:02
1
1,080
newandlost
78,198,322
13,491,504
Plotting and solving three related ODEs in python
<p>I have a problem that might be a little more mathematical but the crux is that I want ot solve it in python and plot it. I have three ODEs which are related to one antoher in the following way:</p> <pre><code>x''(t)=b*x'(t)+c*y'(t)+d*z'(t)+e*z(t)+f*y(t)+g*x(t) y''(t)=q*x'(t)+h*y'(t)+i*z'(t)+p*z(t)+l*y(t)+m*x(t) z''(...
<python><scipy><sympy><ode>
2024-03-21 08:02:13
1
637
Mo711
78,198,291
3,336,423
How to correctly inherit from an abc interface and another class preserving restriction to create objects missing implementation?
<p>I'm trying to combine a class implementing an <code>abc</code> interface with another class.</p> <p>Let's start with <code>abc</code> simple example:</p> <pre><code>import abc class Interface(abc.ABC): @abc.abstractmethod def pure_virtual_func(self): raise NotImplementedError class Impl(Interface):...
<python><abc>
2024-03-21 07:55:34
1
21,904
jpo38
78,198,143
11,023,647
Python: Creating Zip file from Minio objects results in duplicate entries for each file
<p>In my application, I need to get files from Minio storage and create a Zip-file from them. Some files might be really large so I'm trying to write them in chunks to be able handle the process more efficiently. The result however is a zip file with multiple entries with the same file name. I assume these are the chun...
<python><stream><zip><minio>
2024-03-21 07:22:06
1
379
lr_optim
78,198,048
678,342
Start chat with context
<pre><code>model = GenerativeModel(&quot;gemini-1.0-pro&quot;, generation_config={&quot;temperature&quot;: 0}, tools=[retail_tool]) context = [ Content(role = &quot;user&quot;, parts = [ Part(text = &quot;System prompt: You are an assistent who can process json and answers off that.&quot;), Part(text = ...
<python><google-gemini><google-generativeai>
2024-03-21 06:59:17
2
2,230
Richeek
78,197,808
10,141,885
Python NetworkX graphviz layout - RuntimeWarning about gvplugin_pango.dll dependencies
<p>After installing pygraphviz via conda, and trying to create graph:</p> <pre><code># graph: nx.DiGraph pos = nx.nx_agraph.graphviz_layout(graph, prog='dot', ...) # pos[node] ... </code></pre> <p>positions are calculated normally, but the next warning is shown:</p> <blockquote> <p>agraph.py:1405: RuntimeWarning: Warni...
<python><networkx><graphviz>
2024-03-21 06:03:23
1
1,033
halt9k
78,197,752
22,860,226
Firebase , Active Directory - Will AD users get created in Firebase as well?
<p>I am reading about integrating Azure AD with Firebase so that our corporate customers can use our system using their accounts. My question is:</p> <p>When a user with an email a@x.com signs in using AD for the first time, will a User(User with uid, etc) get created in Firebase?</p>
<python><firebase><firebase-authentication><saml><firebase-admin>
2024-03-21 05:48:24
2
411
JTX
78,197,681
5,439,546
Pyppeteer closed unexpectedly for specific sites which has password alert box
<p>I am trying to open a web page which has alertbox when opening,</p> <p>When we set <code>await page.setRequestInterception(True)</code> it takes forever and not finishing it,</p> <p>I also tried dismissing the dialog box but nothing works, here is my code below.</p> <pre><code>from pyppeteer import launch from utils...
<python><pyppeteer>
2024-03-21 05:23:13
0
6,169
Pyd
78,197,665
13,347,225
Django models field not getting generated in database
<p>I am creating a basic Django project. I am using the default db sqlite3. I have created an app product inside my main folder. So, my folder structure is like this:</p> <pre><code>-project -djangoproject -products -models.py -manage.py </code></pre> <p>I am adding my new product model in models.py but when I ...
<python><django><database><sqlite>
2024-03-21 05:17:02
1
393
Piyush Mittal
78,197,479
673,018
python gRPC authentication issues with a self signed certificates
<p>Referred to the grpc docs: <a href="https://grpc.github.io/grpc/python/_modules/grpc.html#ssl_channel_credentials" rel="nofollow noreferrer">grpc docs</a> and attempting secure authentication, I have already the certificate (.cert file), server URL, and credentials. Moreover, I am able to consume the gRPC proto usin...
<python><python-3.x><grpc><grpc-python>
2024-03-21 04:04:19
0
13,094
Mandar Pande
78,197,195
10,853,071
Pandas categorical columns to factorize tables
<p>I am working on a huge denormalized table on a SQL server (10 columns x 130m rows). Take this as data example :</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame({ 'status' : ['pending', 'pending','pending', 'canceled','canceled','canceled', 'confirmed', 'confirmed','confirmed'], 'cl...
<python><sql><pandas><dask><categorical-data>
2024-03-21 02:20:45
2
457
FábioRB
78,197,178
11,276,356
3D RGB-D Panorama to 3D mesh
<p>I am projecting a Panorama image back to 3D, however I am struggling with the projection.</p> <p><a href="https://i.sstatic.net/z8Lrr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/z8Lrr.png" alt="enter image description here" /></a></p> <p><a href="https://i.sstatic.net/WTGqB.png" rel="nofollow nore...
<python><projection><360-panorama>
2024-03-21 02:14:26
0
4,122
Hannah Stark
78,197,152
14,109,040
How do I fill in days of the week between two days
<p>I have a list like <code>['Monday', 'Thursday']</code> with two days of the week. I want to be able to retrieve a list of days of the week between these two -&gt; <code>['Monday', 'Tuesday', 'Wednesday', 'Thursday']</code></p> <ol> <li><p>I am happy to write a custom function in Python to do this. But wondering if t...
<python>
2024-03-21 02:05:29
1
712
z star
78,197,003
4,549,682
How to use warmupTrigger in Python V1 azure function
<p>I'm confused by how to actually use a Python warmup trigger in Python V1 functions. My understanding is:</p> <ul> <li>follow the example <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-warmup?tabs=isolated-process%2Cnodejs-v4&amp;pivots=programming-language-python" rel="nofollow n...
<python><azure><azure-functions>
2024-03-21 01:01:07
1
16,136
wordsforthewise
78,196,999
4,443,784
How does psycopg2.pool.SimpleConnectionPool manage the connections in the pool
<p>As a connection pool, SimpleConnectionPool should take care of the connection management in the pool. For example,</p> <ol> <li>keep alive the connections in the pool</li> <li>evict the closed connections</li> <li>close the long idle connections and create new connections upon needed</li> </ol> <p>But, when I look a...
<python><psycopg2>
2024-03-21 01:00:37
0
6,382
Tom
78,196,921
2,289,030
Is there a way to "feature flag" python dependencies?
<p>In Rust, you can use <a href="https://doc.rust-lang.org/cargo/reference/features.html" rel="nofollow noreferrer">features</a> to gate entire sections of your application behind flags you set at build/dependency install time.</p> <p>This allows you to, for example, enable &quot;all&quot; features, which is great for ...
<python><pip><python-packaging><python-poetry><anaconda3>
2024-03-21 00:31:33
0
968
ijustlovemath
78,196,675
12,304,000
vercel: Error: Size of uploaded file exceeds 300MB
<p>I am trying to deploy a basic python app which uses the Deepface.analyze function. When trying to deploy the app on Vercel, I get this error:</p> <pre><code>Size of uploaded file exceeds 300MB </code></pre> <p>Is it because of large libraries like deepFace and tensorflow? Or could it because of my code structure?</p...
<python><tensorflow><machine-learning><vercel><deepface>
2024-03-20 23:05:34
1
3,522
x89
78,196,632
1,711,271
In a text file, count lines from string 'foo' to first empty line afterwards. Raise exception if 'foo' not found
<p><strong>Background</strong>: I want to read some data from a text file, into a <code>polars</code> dataframe. The data starts at the line containing the string <code>foo</code>, and stops at the first empty line afterwards. Example file <code>test.txt</code>:</p> <pre><code>stuff to skip more stuff to skip skip me...
<python><file-io><python-polars><text-parsing>
2024-03-20 22:53:15
6
5,726
DeltaIV
78,196,623
12,304,000
the layer sequential has never been called and thus has no defined input
<p>I am running a simple script within my Anaconda virtual env</p> <pre><code>from deepface import DeepFace face_analysis = DeepFace.analyze(img_path = &quot;face3.jpeg&quot;) print(face_analysis) </code></pre> <p>But I keep getting this error.</p> <pre><code>Action: age: 25%|██████████████████████████▊ ...
<python><tensorflow><machine-learning><deep-learning><deepface>
2024-03-20 22:50:10
1
3,522
x89
78,196,391
8,157,102
Persistently tracking user input asynchronously using Python
<p>I'm seeking a Python script that persistently awaits user input for some time at each interval. Should the user fail to provide input within this timeframe, the script should automatically execute a predefined operation and continue this process indefinitely. In other words, I require a routine that perpetually runs...
<python><python-3.x><multithreading><asynchronous>
2024-03-20 21:42:30
1
961
kamyarmg
78,196,339
5,495,134
How to solve "OperationFailure: PlanExecutor error ... embeddings is not indexed as knnVector"
<p>I'm trying to perform a vector search using pymongo, here is my index definition:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;fields&quot;: [ { &quot;numDimensions&quot;: 1536, &quot;path&quot;: &quot;embeddings&quot;, &quot;similarity&quot;: &quot;cosine&quot;, &quot;...
<python><mongodb><aggregation-framework><pymongo>
2024-03-20 21:30:47
1
787
Rodrigo A
78,196,316
6,392,523
PyTorch Segementation Fault (core dumped) when moving Pytorch tensor to GPU
<p>I have a machine with RTX 6000 ADA GPUs.</p> <p>We used to have CUDA version 11.x and I used the following image: <code>nvcr.io/nvidia/pytorch:21.04-py3</code> (I use PyTorch 1.x).</p> <p>However, it seems that drivers on our machine were updated to the following -</p> <p>Driver information from nvidia-smi command:<...
<python><pytorch><gpu>
2024-03-20 21:25:44
2
1,054
ChikChak
78,196,314
6,118,662
Make DBT choose the schema in dbt_project.yml instead of the name of the source
<p>Here is how I formatted my dbt_project.yml</p> <pre><code>name: 'project_name' version: '0.1.0' config-version: 2 profile: 'project_name' model-paths: [&quot;models&quot;] analysis-paths: [&quot;analyses&quot;] test-paths: [&quot;tests&quot;] seed-paths: [&quot;seeds&quot;] macro-paths: [&quot;macros&quot;] snapsh...
<python><dbt>
2024-03-20 21:24:57
1
458
linSESH
78,196,296
14,293,020
Scipy 2D interpolation not accomodating every point
<p><strong>Context:</strong> I have a sparse 2D array representing measures of ice thickness along flight traces. However, because of instrument errors, intersects between traces can have different values. I want to interpolate the 2D grid between the traces.</p> <p><strong>Problem:</strong> I am comparing 2 interpolat...
<python><scipy><interpolation><spline>
2024-03-20 21:20:33
0
721
Nihilum
78,196,235
9,208,758
"Update your browser error" when trying to access the SQL database using pyodbc in python
<p>I am trying to access the SSMS database using python. Please note, that the authentication required for the SSMS login uses MFA - &quot;Azure Active Directory - Universal with MFA&quot;. My dummy code is as follows:</p> <pre><code>import pandas as pd import numpy as np import sqlalchemy import pymssql import pyodbc...
<python><sql-server><azure>
2024-03-20 21:05:57
1
589
Isaac A
78,196,062
3,597,746
Python Import is failing with error message ImportError: attempted relative import with no known parent package
<p>I'm working with Python and have this directory structure:</p> <pre><code>/new/uiautomation/testscripts/dropdown_test.py /new/uiautomation/apis/runner.py /new/apis/restapi.py from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) </code></pre> <p>In my dropdown_test.py file, l...
<python>
2024-03-20 20:22:11
1
4,255
Ammad
78,195,754
1,436,763
Chrome driver exception: Message: session not created: Chrome failed to start: crashed
<p>I'm running python 3.12. Both chrome for testing and chrome driver are the same version i.e. 123.0.6312.58 - this has been checked and verified</p> <p>It's working perfectly fine on my Mac. However when I run the dockerized app I get the error</p> <pre><code>024-03-20 19:53:58 03/20/2024 06:53:58PM - ERROR - helper_...
<python><google-chrome><selenium-webdriver>
2024-03-20 19:08:09
2
427
Seroney
78,195,717
6,714,667
How can i authenticate using token instead of api key for azure searchClient?
<p>I am trying to use the searchClient library:</p> <pre><code>service_endpoint = os.environ[&quot;AZURE_SEARCH_SERVICE_ENDPOINT&quot;] index_name = os.environ[&quot;AZURE_SEARCH_INDEX_NAME&quot;] key = os.environ[&quot;AZURE_SEARCH_API_KEY&quot;] search_client = SearchClient(service_endpoint, index_name, AzureKeyCred...
<python><azure><azure-cognitive-search>
2024-03-20 18:58:16
1
999
Maths12
78,195,680
1,999,585
How can I draw the bottom spline if I use set_xlim and set_ylim in Matplotlib?
<p>I want to plot two sets of data, called <strong>real_values</strong> and <strong>predicted_values</strong>. The code I use is this:</p> <pre><code>def plot_experimental_vs_predicted_values(real_values, predicted_values, plot_title, show_plot=True): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_...
<python><matplotlib>
2024-03-20 18:48:21
0
2,424
Bogdan Doicin
78,195,645
10,517,777
How to add an unique id of each value in a new column of dask dataframe
<p>I have the following dask dataframe</p> <pre><code>column1 column2 a 1 a 2 b 3 c 4 c 5 </code></pre> <p>I need to add a new column with the unique consecutive number of the values in the column1. My output will be:</p> <pre><code>column1 column2 column 3 a 1 1 a ...
<python><dask>
2024-03-20 18:42:28
1
364
sergioMoreno
78,195,465
54,873
Best way to dump large pandas dataframe into an *existing* Excel file?
<p>I have a large <code>pandas</code> dataframe that I'd like to dump into an existing excel file (essentially, that file then takes the data and does Excel-y things with it, and I want to update a single <code>raw_data</code> tab).</p> <p>For now I use code from here: <a href="https://stackoverflow.com/questions/20219...
<python><pandas><excel>
2024-03-20 18:07:00
1
10,076
YGA
78,195,369
351,771
Applying matrix multiplication in chain to several sets of values
<p>Mathematically, I'm trying to calculate <strong>x</strong>^T <strong>A</strong> <strong>x</strong>, where <strong>x</strong> is an n-dimensional coordinate and <strong>A</strong> a n-dimensional square matrix. However, I'd like to efficiently calculate this for a set of coordinates. For example, in two dimensions:</...
<python><numpy><matrix>
2024-03-20 17:46:17
1
2,717
xioxox
78,195,336
2,343,309
Preserve coordinates in xarray.Dataset when subsetting a DataArray
<p>I want to have multiple coordinate systems for a given dimension, e.g., a single <code>&quot;time&quot;</code> dimension with coordinates for (the default) <code>datetime64[ns]</code> type but also for a numeric year, or a season. This seems to be possible using <code>Dataset.assign_coords()</code> but has some unex...
<python><python-xarray>
2024-03-20 17:41:43
1
376
Arthur
78,195,234
11,402,025
SPARQL query response to objects
<p>I have a SPARKQL query that send me a response in json.</p> <pre><code> &quot;results&quot;: { &quot;response&quot;: [ { &quot;nameinfo&quot;: { &quot;data&quot;: &quot;data1&quot; }, &quot;namedetails&quot;: { ...
<python><json><fastapi><sparql><pydantic>
2024-03-20 17:24:17
0
1,712
Tanu
78,195,193
16,717,009
Removing Pandas duplicates with more complicated preference than first or last
<p>Pandas .drop_duplicates lets us specify that we want to keep the first or last (or none) of the duplicates found. I have a more complicated condition. Let's say I have a set of preferred values for a column. If a duplicate pair is found and one is in the preferred set, I want to keep that one, regardless of whether ...
<python><pandas>
2024-03-20 17:17:20
3
343
MikeP
78,195,132
14,793,223
Aligning to "North west" in moviepy
<p>I am new to moviepy and have a question. I want to know whether it is possible to align TextClip both to north and west</p> <pre class="lang-py prettyprint-override"><code>title_clip = TextClip(title, font=&quot;Inter-SemiBold&quot;, size=(1002, 88), method=&quot;caption&quot;, align=&quot;west&quot;, fontsize=36, c...
<python><moviepy>
2024-03-20 17:04:42
1
690
Arya Anish