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,671,711
10,200,497
How can I filter groups by comparing the first value of each group and the last cummax that changes conditionally?
<p>My DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'group': ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e'], 'num': [1, 2, 3, 1, 12, 12, 13, 2, 4, 2, 5, 6, 10, 20, 30] } ) </code></pre> <p>Expected output is getting three groups from above <code>...
<python><pandas><dataframe>
2024-06-26 10:03:35
1
2,679
AmirX
78,671,562
1,037,407
Parsing a source code with just one digit
<p>Could some please walk me through, how CPython parses a file contain just one character <code>1</code>?</p> <p>In particular, why <code>ast.parse(&quot;3&quot;)</code> returns <code>...Expr(...)...</code> as (I believe) Python's source code is a list of statements?</p> <p>In other words, reading <a href="https://doc...
<python><parsing><cpython>
2024-06-26 09:35:06
1
11,598
Ecir Hana
78,671,534
3,070,007
How to Download a CSV File from a Blob URL Using Selenium in Python?
<p>I'm trying to automate the download of a CSV file from a Blob URL on a dynamic website using Selenium with Python. The CSV download is triggered by clicking a button, but the button click generates a Blob URL, which isn't directly accessible via traditional HTTP requests. I'm having trouble capturing and downloading...
<python><selenium-webdriver><selenium-chromedriver><blob>
2024-06-26 09:30:46
1
1,585
rischan
78,671,448
2,706,344
Insert lists into DataFrame cells
<p>Look at this code:</p> <pre><code>df=pd.DataFrame(data=[['a','b'],['c','d']],columns=['B','C']) df.insert(loc=0,column='A',value='Hello world!') </code></pre> <p>What it does: It inserts a new column named <code>'A'</code> and writes <code>'Hello world!'</code> into each cell of that new columns. But now watch this:...
<python><pandas><dataframe>
2024-06-26 09:15:19
0
4,346
principal-ideal-domain
78,671,295
14,833,503
ElasticNetCV in Python: Get full grid of hyperparameters with corresponding MSE?
<p>I have fitted a ElasticNetCV in Python with three splits:</p> <pre><code>import numpy as np from sklearn.linear_model import LinearRegression #Sample data: num_samples = 100 # Number of samples num_features = 1000 # Number of features X = np.random.rand(num_samples, num_features) Y = np.random.rand(num_samples) ...
<python><machine-learning><scikit-learn><sklearn-pandas>
2024-06-26 08:49:51
2
405
Joe94
78,670,658
1,371,666
Cannot find play button on a web page in selenium using python
<br> I am using Python 3.11.9 in windows with google chrome Version 126.0.6478.127 (Official Build) (64-bit).<br> Here is the simple code <pre><code>driver = webdriver.Chrome() url = &quot;https://onlineradiofm.in/stations/vividh-bharati&quot; driver.get(url) radio_is_paused=True while radio_is_paused: time.sleep(30) ...
<python><python-3.x><google-chrome><selenium-webdriver><selenium-chromedriver>
2024-06-26 06:35:50
1
481
user1371666
78,670,441
485,330
AWS Lambda Timeout to Amazon SES
<p>The code below to send an Amazon SES email works fine. However, I need the code to communicate with a local EC2 database, so I need to add this Lambda function to my VPC and Subnets - At this point, the code below stops working and timeouts.</p> <p><strong>How can I fix this?</strong></p> <pre><code>import json impo...
<python><amazon-web-services><aws-lambda><amazon-vpc><amazon-ses>
2024-06-26 05:19:40
2
704
Andre
78,670,098
2,989,330
Wrapped functions of a Python module raise TypeError
<p>I am currently trying to replace a module in a large code base in a certain condition and to figure out when any function of this module is called, I wrap each function/method in the module with a warning that prints a short message with the stack trace. The implementation of this method is as follows (printing the ...
<python><types><typeerror><metaprogramming>
2024-06-26 02:10:59
1
3,203
Green 绿色
78,670,018
9,872,200
python pandas loop through dataframe replicate many tables in excel
<p>I want to convert a large dataframe to a series of report tables that replicates the template for each unique id within the dataframe seperated/skipped excel row. I would like to do this with a series of loops. I think I can accomplish through mapping each item in the df to an excel file... but it would take sever...
<python><excel><pandas><report>
2024-06-26 01:23:23
1
513
John
78,669,908
3,486,684
Why is `re.Pattern` generic?
<pre class="lang-py prettyprint-override"><code>import re x = re.compile(r&quot;hello&quot;) </code></pre> <p>In the above code, <code>x</code> is determined to have type <code>re.Pattern[str]</code>. But why is <code>re.Pattern</code> generic, and then specialized to string? What does a <code>re.Pattern[int]</code> r...
<python><mypy><python-typing><python-re>
2024-06-26 00:11:00
1
4,654
bzm3r
78,669,790
17,835,120
Clicking on popup with selenium
<p>Trying to click on this button but cannot:</p> <p>last attempt:</p> <pre><code> # Attempt to locate and click the 'Start' button try: start_button = WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, &quot;//button[text()='Start']&quot;)) ) start_button.click() </code></pre> <...
<python><selenium-webdriver>
2024-06-25 22:59:18
0
457
MMsmithH
78,669,675
299,754
Python requests: how to get the client port used *before* sending a request?
<p>I'm trying to debug an apparently low level intermittent ConnectionError (likely happening at the TCP layer). For this I've built a multiprocessed program spamming a remote site and catching the relevant error, and am monitoring the traffic via wireshark with the goal of capturing a full faulty TCP conversation. It'...
<python><python-requests>
2024-06-25 22:09:41
0
6,928
Jules Olléon
78,669,632
10,203,572
One-liner split and map within list comprehension
<p>I have this bit for parsing some output from stdout:</p> <pre><code>out_lines = res.stdout.split(&quot;\n&quot;) out_lines = [e.split() for e in out_lines] out_vals = [{&quot;date&quot;:e[0], &quot;time&quot;:e[1], &quot;size&quot;:e[2], &quot;name&quot;:e[3]} for e in out_line...
<python>
2024-06-25 21:51:19
4
1,066
Layman
78,669,542
12,347,371
How to send a telegram message without blocking main thread
<pre class="lang-py prettyprint-override"><code>from telegram import Bot import asyncio TOKEN = &quot;blah&quot; CHAT_ID = 1 async def send_message_async(): message = &quot;This is a test update from the bot!&quot; bot = Bot(token=TOKEN) await bot.send_message(chat_id=CHAT_ID, text=message) print(&quo...
<python><python-asyncio><telegram><python-telegram-bot>
2024-06-25 21:14:13
1
675
Appaji Chintimi
78,669,465
11,829,999
Pandas:using list as cell value - different approach to modify values and NaN issues
<p>This is 50% a question and 50% an observation that baffles me a bit. Maybe someone can enlighten me.</p> <p>Also I would like to know opinions on using lists as cell values. Yes/No and why please.</p> <p>Here is a trivial example:</p> <pre><code>data = [[['apple', 'banana'],1], [['grape', 'orange'],2], [['banana', '...
<python><pandas><dataframe><nan>
2024-06-25 20:47:23
0
508
sebieire
78,669,299
4,421,575
rearrange columns in dataframe depending on sorting output
<p>I have the following data frame:</p> <pre><code>df = pd.DataFrame( { 'a':[1,2,3,4,5,6], 'b':[1,1,3,3,5,5], 'c':[1,2,3,4,5,6], 'd':[1,1,1,1,1,5], } ) In [1051]: df Out[1051]: a b c d 0 1 1 1 1 1 2 1 2 1 2 3 3 3 1 3 4 3 4 1 4 5 5 5 1 5...
<python><pandas><sorting>
2024-06-25 19:55:17
2
1,509
Lucas Aimaretto
78,669,277
2,952,838
Define a matrix in R in a similar fashon as with Numpy
<p>I love the fact that using numpy in Python it is very easy to define a matrix/array in a way that is very close to the mathematical definition. Does R have a similar way of achieving this result?</p> <pre class="lang-py prettyprint-override"><code>import numpy as np n = np.arange(4) m = np.arange(6) ## Now I w...
<python><r><numpy><matrix>
2024-06-25 19:48:50
1
1,543
larry77
78,669,161
9,116,959
How to Remove Wildcard Imports from a Large Python Repository?
<p>I am working on a large python project that contains many thousands of files, includes a mix of independent scripts (many with main functions) and common modules. Unfortunately, in my project there is extense usage of wildcard imports (e.g., from module import *). This causes me to not be able to do automatic optimi...
<python><import><refactoring>
2024-06-25 19:11:17
1
632
Kfir Ettinger
78,669,116
5,527,646
How to use gdal_translate in Python
<p>I am trying to convert a <code>netCDF</code> file to a <code>Cloud Optimized GeoTiff</code> (COG) format. I have been able to do so successfully in the OSGeo4W Shell using the following command:</p> <pre><code>gdal_translate -of GTiff NETCDF:my-precip-data.nc:monthly_prcp_norm my_precip-monthly-normal.tif -of COG -c...
<python><subprocess><netcdf><gdal><geotiff>
2024-06-25 18:57:26
0
1,933
gwydion93
78,669,086
2,153,235
np.ones(30011,30011) needs 7.2GB, but Task Manager shows 5.3GB
<p>A 30,011x30,011 of 64-bit floats takes 7.2GB. There are many explanations for why one might see <code>np.zeros([30011,30011])</code> take up (say) a miniscule 0.7MB. However, my Windows 2010 Task Manager also shows noticeably less memory than expected for <code>np.ones([30011,30011])</code>. Specifically, 5.3GB, ...
<python><memory><memory-management><numpy-ndarray>
2024-06-25 18:50:29
1
1,265
user2153235
78,669,082
11,999,957
Is there a way to speed up vectorized log operations in scipy optimize?
<p>I'm doing some optimization in which I am calculating the $ amount needed to get the change in conversion using elasticities. Originally, I used simple elasticities but am thinking of converting to compounding elasticities. However, just doing this simple switch has increased the time it takes for me to optimize d...
<python><numpy><optimization><scipy><mathematical-optimization>
2024-06-25 18:48:36
1
541
we_are_all_in_this_together
78,668,998
13,597,979
Withdrawn window not reappearing with deiconify after filedialog in Tkinter on MacOS
<p>The code below is meant to ask for a file name with <code>filedialog</code> with a hidden root window, after which the root reappears and shows a label that has the selected filename. However, on MacOS 14.5 and Python 3.9.6, the <code>deiconify</code> does not make the window reappear. I have to click on the Python ...
<python><tkinter>
2024-06-25 18:26:39
1
550
TimH
78,668,978
4,701,426
Condition in a function to stop it when called in a loop?
<p>Please consider this simple function:</p> <pre><code>def my_func(x): if x &gt; 5: print(x) else: quit() print('this should be printed only if x &gt; 5') </code></pre> <p>Then if we call this function in a loop:</p> <pre><code>for i in [2, 3, 4, 5, 6, 7]: my_func(i) </code></pre> <p><...
<python>
2024-06-25 18:17:29
3
2,151
Saeed
78,668,957
1,367,705
ImportError: cannot import name 'Ollama' from 'llama_index.llms' (unknown location) - installing dependencies does not solve the problem
<p>I want to learn LLMs. I run Ollama with the following Docker Compose file - it's running:</p> <pre><code>services: ollama: image: ollama/ollama:latest ports: - 11434:11434 volumes: - ollama_data:/root/.ollama healthcheck: test: ollama list || exit 1 interval: 10s timeo...
<python><large-language-model><llama-index><ollama>
2024-06-25 18:11:54
2
2,620
mazix
78,668,860
18,227,234
Is there a clean way to handle reuse of try...except blocks that force early function return?
<p>I'm writing an Azure Functions API, with many different endpoints with similar internal behavior. One major step in each endpoint is to take each naked POST and parse out any and all arguments (comes in as a dictionary) to a custom request object I define that can be further used for all function behavior. Each requ...
<python><azure-functions>
2024-06-25 17:46:43
1
318
walkrflocka
78,668,711
20,920,790
How to get pd.Dataframe from ClickHouseHook()?
<p>I got this code in my DAG for Airflow:</p> <pre><code>import pandas as pd import datetime import io import httpx from airflow.decorators import dag, task from airflow.models import Variable from clickhouse_driver import Client from airflow_clickhouse_plugin.hooks.clickhouse import ClickHouseHook from airflow.models ...
<python><pandas><airflow><clickhouse>
2024-06-25 17:06:39
2
402
John Doe
78,668,650
3,070,181
Problem when adding dependencies to pyinstaller using poetry to manage dependencies
<p>I am attempting to create an executable file in Windows 10 Pro from a python script that uses <em>import</em></p> <pre><code># main.py from termcolor import cprint def main() -&gt; None: cprint('Hello', 'red') if __name__ == '__main__': main() </code></pre> <p>I have installed <em>poetry</em> and created ...
<python><windows><pyinstaller><python-poetry>
2024-06-25 16:52:26
1
3,841
Psionman
78,668,507
435,317
python regex, split string with multiple delimeters
<p>I know this question has been answered but my use case is slightly different. I am trying to setup a regex pattern to split a few strings into a list.</p> <p>Input Strings:</p> <pre><code>1. &quot;ABC-QWERT01&quot; 2. &quot;ABC-QWERT01DV&quot; 3. &quot;ABCQWER01&quot; </code></pre> <p>Criteria of the string ABC - QW...
<python><regex>
2024-06-25 16:18:36
1
1,762
Drewdin
78,668,423
18,769,241
Is there an naoqi SDK for Python 3?
<p>I can't seem to find a Python NaoQi SDK for Python 3? All I find is for Python 2.7 from the reference installation page: <a href="http://doc.aldebaran.com/2-8/dev/python/install_guide.html" rel="nofollow noreferrer">http://doc.aldebaran.com/2-8/dev/python/install_guide.html</a></p> <p>The latest version of the SDK (...
<python><nao-robot>
2024-06-25 15:59:44
2
571
Sam
78,668,385
1,685,729
ModuleNotFoundError: No module named 'arichuvadi.valam'; 'arichuvadi' is not a package
<ul> <li><p>ModuleNotFoundError: No module named 'arichuvadi.valam'; 'arichuvadi' is not a package Installed the local package in editable form with the following command</p> <p>#+begin_src shell</p> <pre><code>pip install -e . </code></pre> <p>#+end_src</p> </li> </ul> <p>I get this error when running the code like th...
<python><import>
2024-06-25 15:52:26
2
727
vanangamudi
78,668,318
118,562
Python PyAudio always record in mono sound
<p>Here is my code:</p> <pre><code>import pyaudio import wave class AudioRecorder: def __init__(self, chunk=1024, sample_format=pyaudio.paInt16, channels=2, fs=44100, filename=&quot;output.wav&quot;): self.chunk = chunk self.sample_format = sample_format self.channels = channels sel...
<python><pyaudio>
2024-06-25 15:40:30
0
12,986
Bagusflyer
78,668,306
15,912,168
PyInstaller-built API Not Recognizing Routes After Building
<p>I'm building an API using PyInstaller 6.4.0, but it's not working.</p> <p>For some reason, the built file is not recognizing my routes.</p> <p>The project folder structure is:</p> <p>markdown Copiar código</p> <pre><code>API ├── logs └── v1 └── routes ├── router1.py └── router2.py </code></p...
<python><fastapi><pyinstaller>
2024-06-25 15:36:29
1
305
WesleyAlmont
78,668,255
3,768,977
Is there a better way to generate my dataframe?
<p>I have a set of data that I need to perform some transformations on. The raw form of the data is as follows (actual dataset will have many more columns, reduced set here for simplicity):</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>lVoterUniqueID</th> <th>sElectionAbbr1</th> <th>sElect...
<python><pandas><dataframe>
2024-06-25 15:23:31
1
553
MPJ567
78,668,248
15,370,142
Convert a complex string representation of a list (containing tuples, which look like function calls) into a list
<p>I am trying to create a fixture for unit testing. I retrieve data from an API and need data that looks like what I get from the API without making the call to the API. I need to create a number of list literals that capture different scenarios for the unit test. Here is the string representation of the list I'm tryi...
<python><list><type-conversion><tuples><function-call>
2024-06-25 15:22:09
3
412
Ted M.
78,668,028
3,533,800
python: "from library import module" works, but "import library.module" could not be resolved
<p>I've got this dts:</p> <pre><code>Pipfile module-common\ __init__.py setup.py common\ library-common.py module-a\ __init__.py setup.py functional-module\ library-a.py library-b.py </code></pre> <p>Pipfile is defined as</p> <pre><code>... [packages] module-common = {file = &quot;module-common...
<python><module><importerror><pipenv><pipfile>
2024-06-25 14:39:37
0
329
Ozeta
78,667,785
9,571,463
Communicating between Queues in Asyncio not Working as Expected
<p>I'm working on a pattern where I communicate amongst multiple queues to process items along a pipeline. I am using sentinels to communicate between the queues when to stop working, however in the following code, I am seeing results that confuse me.</p> <p>When reading from the <code>write_q</code> in <code>write_tas...
<python><async-await><queue><python-asyncio>
2024-06-25 13:52:15
1
1,767
Coldchain9
78,667,734
6,939,324
How to avoid a nan loss (from the first iteration) and gradients being None?
<p>I am trying to predict/ fit filter coefficients using an MLP, my target function is:</p> <p><img src="https://github.com/pytorch/pytorch/assets/15731839/7b15cf05-86fc-43e7-bdd3-6e5543a42b42" alt="biquad" /></p> <p>However, the system is stuck in the same loss (<code>nan</code>) and there is no learning or update hap...
<python><machine-learning><pytorch><signal-processing><torchaudio>
2024-06-25 13:40:11
0
2,966
SuperKogito
78,667,698
12,955,644
Terminal does not open on Ubuntu when using updated python version, only works with specific version
<p>I have these versions of python installed under python:</p> <p>1.</p> <pre><code>update-alternatives --list python /usr/bin/python3 /usr/bin/python3.11 /usr/bin/python3.12 /usr/bin/python3.8 /usr/bin/python3.9 </code></pre> <ol start="2"> <li></li> </ol> <pre><code>update-alternatives --list python3 /usr...
<python><python-3.x><ubuntu><terminal>
2024-06-25 13:33:44
0
333
Imtiaz Ahmed
78,667,638
6,622,697
How to query from a joined table in SQLAlchemy
<p>I have 2 tables with a many-to-many relationship, so I have a join table between them. They are defined like this</p> <pre><code>from sqlalchemy import String, Integer, Boolean from sqlalchemy.orm import mapped_column, relationship from root.db.ModelBase import ModelBase class Module(ModelBase): __tablename_...
<python><sqlalchemy>
2024-06-25 13:20:13
1
1,348
Peter Kronenberg
78,667,579
7,195,787
Return the list of all registered models in MLflow
<p>I'm using mlflow on databricks and I've trained some models, that I can see in the &quot;registered models&quot; page.</p> <p>Is there a way to extract the list of these models in code?</p> <p>Something like</p> <pre><code>import mlflow mlflow.set_tracking_uri(&quot;databricks&quot;) model_infos = mlflow.tracking.Ml...
<python><databricks><mlflow>
2024-06-25 13:06:26
1
443
Carlo
78,667,500
4,190,657
conditional split based on list of column
<p>I have a dataframe having 2 column - &quot;id&quot; (int) and &quot;values&quot; (list of struct). I need to split on name. I have a list of column names as delimiter. I need to check the occurence of column names from the list, if one of the column name is present , then split the dataframe.</p> <pre><code>from pys...
<python><regex><apache-spark><pyspark><split>
2024-06-25 12:51:01
1
305
steve
78,667,448
10,317,745
Python typing for nested iterator on list of objects with iterable property
<p>I have a somewhat tricky python typing question. I have a function (generator) that iterates over a list of objects, and then over a particular attribute of each of these objects like this:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar('T') S = TypeVar('S') def iter_attribute(outer: Iterable[T], a...
<python><mypy><python-typing>
2024-06-25 12:41:22
1
1,273
Ingo
78,667,096
11,779,593
Efficiently Resampling and Interpolating Pandas DataFrames with Millisecond Accuracy
<p>I have a Pandas DataFrame with timestamps that have millisecond accuracy and corresponding altitude values. I want to resample and interpolate this data efficiently. Here is a simple example:</p> <pre><code>import pandas as pd import numpy as np # Generate 5 random timestamps within the same minute with millisecond...
<python><pandas><time-series>
2024-06-25 11:35:38
1
317
bfgt
78,666,967
3,665,976
SPARK_GEN_SUBQ_0 WHERE 1=0, Error message from Server: Configuration schema is not available
<p>I'm trying to read the data from sample schema from table nation from data-bricks catalog from my local machine via spark but i'm getting this error.</p> <p><code>com.databricks.client.support.exceptions.GeneralException: [Databricks][JDBCDriver](500051) ERROR processing query/statement. Error Code: 0, SQL state: nu...
<python><pyspark><azure-databricks>
2024-06-25 11:06:31
1
606
Hassan Shahbaz
78,666,961
10,309,712
Meta-feature analysis: split data for computation on available memory
<p>I am working with the meta-feature extractor package: <a href="https://github.com/ealcobaca/pymfe" rel="nofollow noreferrer">pymfe</a> for complexity analysis. On a small dataset, this is not a problem, for example.</p> <pre><code>pip install -U pymfe from sklearn.datasets import make_classification from sklearn.da...
<python><machine-learning><meta-learning>
2024-06-25 11:05:09
2
4,093
arilwan
78,666,883
3,852,385
pip install quickfix failed in windows
<p>I'm trying to install the quikcfix library on my windows machine. The python version is 3.12.2. However I get the below error.</p> <pre><code>python setup.py bdist_wheel did not run successfully exit code: 1 [7 lines of output] Testing for std::tr1::shared_ptr... ...not found Testing for std::shared_ptr... ...not fo...
<python><quickfix>
2024-06-25 10:50:13
1
711
dGayand
78,666,868
9,709,594
Access SQL Server with Active Directory Domain\Username credentials from Linux using Python
<p>I have the following scenario.</p> <p>I received access to a Windows SQL server with <code>Domain/Username</code> authentication attached to my personal Windows <strong>Active Directory</strong> and also our team's Service Account's Active Directory. When I test with my Windows work station, I can confirm that, I am...
<python><sql-server><linux><active-directory><pyodbc>
2024-06-25 10:47:28
0
416
0xMinCha
78,666,683
5,552,153
How to update axis labels in Plotly Dashboard?
<p>I am using the following code to monitor an output file from another application named TOUGH.</p> <p>I define a graph component and update its figure using the update_graph_live() call back function. In order for my graphs to remain legible, I adjust the x-axis time units. But although the data appears to update cor...
<python><plotly><plotly-dash>
2024-06-25 10:08:20
1
935
Sorade
78,666,658
12,427,876
PyLance Auto-Completion with Docker
<p>I'm using PyLance in Visual Studio Code to work on a Dockerized Python project, and there are certain dependencies that is very complex to be built on MacOS, so I dockerized the project and now it works fine.</p> <p>The problem is, since I didn't build/install the library locally on my OS, PyLance is not able to det...
<python><docker><pylance>
2024-06-25 10:03:27
0
411
TaihouKai
78,666,604
3,825,948
Call openai.Audio.transcribe('model_name', bytes, prompt=language_prompt, response_format='verbose_json') with timeout
<p>Is it possible to call the OpenAI speech to text API in Python with a timeout so if it doesn't respond within the timeout the call is cancelled? The call has the following signature:</p> <p>openai.Audio.transcribe('model_name', bytes, prompt=language_prompt, response_format='verbose_json')</p> <p>I tried using the P...
<python><timeout><openai-api>
2024-06-25 09:51:38
0
937
Foobar
78,666,512
2,016,165
Modify QGIS layer every/after ~5 seconds (without blocking the main thread)
<p>I wrote a Python script for QGIS 3.36.2 (uses Python 3.12.3) that does the following:</p> <ol> <li>Create a layer</li> <li>Start an HTTP GET request to fetch new coordinates (runs asynchronously by default)</li> <li>Use these coordinates to draw a marker on the layer (the old marker is removed first, has to run on t...
<python><qgis>
2024-06-25 09:32:16
1
2,013
Neph
78,666,266
7,476,542
No module named 'src'
<p>I have a python project. The folder structure is like the following:</p> <pre><code>📦src ┣ 📂utils ┃ ┣ 📜custom_pow.py ┃ ┣ 📜equation.py ┃ ┗ 📜__init__.py ┣ 📜app.py ┗ 📜__init__.py </code></pre> <p><strong>custom_pow.py</strong></p> <pre><code>class Pow: def __init__(self,a,n): self.a = a ...
<python><path>
2024-06-25 08:44:04
1
303
Sayandip Ghatak
78,666,050
2,660,278
Understanding result of combining 3D transformations with `pytransform3d`
<p>I feel like I am missing something very basic here. Question is specific to <code>pytransform3d</code>. I am most likely missing a basic understanding of 3D transformations and/or the <code>pytransform3d</code> library.</p> <p>Here is the setup:</p> <p><a href="https://i.sstatic.net/7AMv4Ame.png" rel="nofollow noref...
<python><3d><rotation><coordinate-systems><coordinate-transformation>
2024-06-25 07:55:13
0
358
user2660278
78,665,714
4,097,712
How to create rv_histogram from known probability density function values
<p>Let's say there is a distribution, and all what is known about the distribution is the value of its probability density function in a small range(e.g. from 0.0 to 0.001).</p> <p>Then, I want to use statistical functions in <code>scipy</code> to describe the distribution, and I found there is a function called <code>...
<python><numpy><math><scipy><statistics>
2024-06-25 06:35:57
0
940
Tonny Tc
78,665,646
2,385,132
PyTorch model training with DataLoader is too slow
<p>I'm training a very small NN using the HAM10000 dataset. For loading the data I'm using the DataLoader that ships with PyTorch:</p> <pre><code>class CocoDetectionWithFilenames(CocoDetection): def __init__(self, root: str, ann_file: str, transform=None): super().__init__(root, ann_file, transform) de...
<python><pytorch><pytorch-dataloader>
2024-06-25 06:12:50
1
3,930
Marek M.
78,665,637
1,390,558
Using AWS Moto with Python mock to write unit tests
<p>I am working with a codebase that doesn't have any tests setup. I am trying to add some tests and currently have the below test class <code>test_main.py</code></p> <pre><code>from unittest import TestCase from moto import mock_aws import boto3 from main import collect_emr class Test(TestCase): def setUp(self...
<python><mocking><moto>
2024-06-25 06:09:44
0
1,469
Justin S
78,665,486
9,757,174
(4096, 'Microsoft Outlook', 'The operation failed.', None, 0, -2147287037) error when saving an email to my local machine
<p>I am trying to download some emails from my outlook folder to my local machine as <code>.msg</code> files using the following code.</p> <pre class="lang-py prettyprint-override"><code>messages = source_folder.Items for message in messages: # Estimate the size of the email size = message.Size if size &lt;...
<python><python-3.x><automation><outlook><win32com>
2024-06-25 05:09:43
1
1,086
Prakhar Rathi
78,665,239
1,228,276
install awscli on java 17 docker
<p>I am upgrading JAVA8 to JAVA17(<code>FROM amazoncorretto:17-alpine-jdk</code>) with one of my Spring boot service. I have <code>awscli</code> being installed as with below command in my <code>Dockerfile</code></p> <pre><code>RUN apk add --no-cache \ python3 \ py3-pip \ &amp;&amp; pip3 install --upgrade pip \...
<python><spring><docker><java-17>
2024-06-25 03:10:18
0
1,093
rakeeee
78,664,824
1,185,242
Find all consensus locations of 2D line segment intersections
<p>I have a set of line segments, subsets of which all intersect at some locations. The line segments are noisy though so the intersections points aren't exact and there are some erroneous line segments in the set too. What's a good robust algorithm for finding the most likely set of intersection points? My first thoug...
<python><computational-geometry>
2024-06-24 22:49:47
0
26,004
nickponline
78,664,718
1,897,688
Reshape Pandas Dataframe and group by 2 level columns
<p>I have a dataframe with flat structure of having unique Rows as follow. <a href="https://i.sstatic.net/JApDzl2C.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JApDzl2C.png" alt="Original Df" /></a></p> <p>I need to reshape it as shown below. <a href="https://i.sstatic.net/7rC1lbeK.png" rel="nofollow ...
<python><pandas><group-by><pivot-table><reshape>
2024-06-24 21:56:31
1
356
rush dee
78,664,503
7,089,108
3D scatterplot, matrix operations and calculation of the inverse
<p>I have a scatter-plot with the code shown below.</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') scatter = ax.scatter(x, y, z...
<python><multidimensional-array><alignment><noise><svd>
2024-06-24 20:33:21
0
433
cerv21
78,664,472
25,413,271
gitlab CI: powershell job doesnt fail on python exception
<p>I have a simple gitlab config:</p> <pre><code>variables: P7_TESTING_INSTALLATION_PATH: D:\Logos_block_gitlab_runner\pSeven-v2024.05 stages: - cleanup - installation cleanup_build: tags: - block_autotest variables: ErrorActionPreference: stop allow_failure: false stage: cleanup script: -...
<python><gitlab-ci>
2024-06-24 20:24:11
1
439
IzaeDA
78,664,449
651,174
Add a "log" for a single function
<p>I need to debug some legacy code and I only want to print some information to a file that will not disturb any other places in the codebase. The most crude way I have found so far is something like:</p> <pre><code>def my_func(): f = open('/tmp/log.txt', 'a') # help with logging stuff f.write('Here is my crud...
<python><logging>
2024-06-24 20:15:40
2
112,064
David542
78,664,393
3,486,684
What determines the order of type variables when narrowing a generic type?
<p><strong>Note:</strong> this question refers to Python 3.12+</p> <p>Suppose I have:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, TypeVar import numpy as np T = TypeVar(&quot;T&quot;) U = TypeVar(&quot;U&quot;) ListLike = T | list[T] | tuple[T, ...] | np.ndarray[Any, U] ListLikeStr = ...
<python><mypy><python-typing>
2024-06-24 19:54:49
1
4,654
bzm3r
78,664,347
16,707,518
Randomly adding rows from another datatable based on group and a probability
<p>Suppose I have a dataframe called <strong>Main</strong> of this format - which will have a large combination of Region and Type of thousands of rows, with the Region/Type combination duplicated multiple times but with difference numbers in the Value column. This is a shortened version of the <strong>Main</strong> da...
<python><pandas><dataframe>
2024-06-24 19:42:00
1
341
Richard Dixon
78,664,293
3,486,684
What is a union dtype in numpy, and how do I define it?
<p>Suppose I have an array like this:</p> <pre class="lang-py prettyprint-override"><code>x = np.array([[&quot;Hello&quot;, 0, 1], [&quot;World&quot;, 1, 2]], dtype=np.object_) </code></pre> <p>I'd like to do better in terms of how I define the <code>dtype</code> for this array. More specifically, I want the array to a...
<python><numpy>
2024-06-24 19:26:12
1
4,654
bzm3r
78,664,231
14,655,211
How to assign values from a list to variables from a list in python?
<p>I have some code that is asking users questions and storing the responses in a list. I then want to assign the response values to variables from a list. Its not working as expected though as it doesnt look like the variables exist when I try and use them later in my script. I've seen a few similar questions on here ...
<python>
2024-06-24 19:08:47
1
471
DeirdreRodgers
78,664,168
3,970,738
Subprocess initiated from Jupyter notebook does not use the same python virtual environment. Why and how to fix?
<p>I am exectuting a python script as a subprocess. Doing this from a regular module ineherits the virtual environment but when I do it inside a Jupyter notebook, the subprocess is using the system python. Why is this and how can I fix it in a platform independent way? (I do not know what virtual environments will be u...
<python><jupyter><virtualenv>
2024-06-24 18:49:45
1
501
Stalpotaten
78,664,154
1,245,262
What does num_entities in Milvus collection increase when one overwrites existing entities
<p>I had thought that <code>num_entities</code> would indicate the number of records (or whatever the correct term is) within a Milvus collection. However, I created 1 file - <code>test_milvus.py</code> to create a simple collection like so:</p> <pre><code>import numpy as np from pymilvus import connections, Collection...
<python><milvus>
2024-06-24 18:45:57
1
7,555
user1245262
78,664,094
9,571,463
Asyncio Task was destroyed but it was pending
<p>I am making requests to an external API, getting the response back and writing it to a file. Everything works/runs fine, however I receive the &quot;Task was destroyed but it is pending!&quot; warning that I'd like to clean up.</p> <p>I have emulated the process below. I receive items from a source (e.g. a list) of ...
<python><python-asyncio><producer-consumer><python-aiofiles>
2024-06-24 18:31:10
1
1,767
Coldchain9
78,664,009
2,142,338
Altair chart legend for subset of data
<p>As an exercise for learning more advanced altair, I'm trying to generate a simplified version of this chart: <a href="https://climatereanalyzer.org/clim/t2_daily/?dm_id=world" rel="nofollow noreferrer">https://climatereanalyzer.org/clim/t2_daily/?dm_id=world</a>.</p> <p>To simplify, I'm using gray for all years prio...
<python><legend><altair>
2024-06-24 18:08:20
2
888
Don
78,663,904
6,622,697
How to store database uri in Flask config for SQLAlchemy?
<p>I'm using Flask and SQLAlchemy (<em>not</em> flask-sqlalchemy).</p> <p>I'm trying to get access to the flask config from my database code, but it's telling me that I'm not in an application context, probably because the app is not yet fully initialized.</p> <p>I have <code>app.py</code>:</p> <pre><code>from flask im...
<python><flask><sqlalchemy>
2024-06-24 17:40:38
2
1,348
Peter Kronenberg
78,663,854
4,391,360
Not the same sys.path in a shell and in Spyder
<p>Why isn't the <code>sys.path</code> in Spyder the same as in a shell?</p> <p>In a shell, <code>python -c &quot;import sys ; print(sys.path)&quot;</code> doesn't give the same thing as if I stop the script at the first line with a breakpoint to do in the debugging console <code>import sys ; print(sys.path)</code>.</p...
<python><spyder><sys.path>
2024-06-24 17:25:47
1
727
servoz
78,663,819
3,279,603
couchbase.exceptions.UnAmbiguousTimeoutException using Python SDK
<p>I’m getting <code>couchbase.exceptions.UnAmbiguousTimeoutException</code> every time I try to connect to my Couchbase cluster using the python SDK. With the same naming and configuration, I have no issue connecting via <code>.NET</code> sdk.</p> <p>This is my Python code:</p> <pre class="lang-py prettyprint-override...
<python><sdk><timeout><couchbase>
2024-06-24 17:16:03
1
5,230
aminrd
78,663,805
7,486,038
mlflow doesn't autolog artifacts while logging images
<p>I am fairly new to mlflow. I stumbled across some strange behavior. When I am running a simple Keras model fit with MLFlow Autolog like this:</p> <pre><code>mlflow.set_tracking_uri(&quot;sqlite:///mlflow.db&quot;) mlflow.set_experiment(&quot;keras_log&quot;) mlflow.tensorflow.autolog() # Define the parameters. num_...
<python><machine-learning><mlflow>
2024-06-24 17:12:13
1
326
Arindam
78,663,622
1,215,889
How to pass feature value to custom loss in Keras
<p>I am using a custom loss to train my model and want to use feature value to have a differential loss, something like</p> <pre><code>def custom_loss(y_true, y_pred, feature_val): return (feature_val ** 2) * abs(y_true - y_pred) </code></pre> <p>How can I achieve this in Keras?</p>
<python><tensorflow><keras><deep-learning>
2024-06-24 16:27:41
0
9,159
neel
78,663,537
7,465,462
Using REST API in Python to run Workflows in Azure Purview
<p>We are trying to use Purview REST APIs to make a user request that should be able to trigger a Purview workflow run. The workflow should trigger whenever the user is trying to update an asset, for example its description.</p> <p>According to the <a href="https://learn.microsoft.com/en-us/rest/api/purview/workflowdat...
<python><rest><azure-purview>
2024-06-24 16:04:22
3
9,318
Ric S
78,663,524
5,443,120
How to specify colorway for plotly line graph theme?
<p>I'm plotting line graphs in Python with plotly. I can manually specify the colour of each line from the <code>fig.line()</code> call with the <code>color_discrete_map</code> argument. But what I want to do is specify the default colours using a <a href="https://plotly.com/python/templates/" rel="nofollow noreferrer"...
<python><plotly><themes>
2024-06-24 16:00:44
1
4,421
falsePockets
78,663,324
5,786,649
Is it possible to have an inline-definition of a dataclass in Python?
<p><em>Preliminary note:</em> The first three examples provided all work. My question is: If I declare dataclasses that are only used once inside another dataclass, can I avoid the &quot;proper&quot; declaration of the nested dataclass in favour of an &quot;inline&quot; declaration? I want to use nested dataclasses bec...
<python><python-typing><python-dataclasses><pyright>
2024-06-24 15:16:03
1
543
Lukas
78,663,210
6,622,697
Alembic creates foreign key constraints before other table is created
<p>I'm trying to setup Alembic for the first time. I dropped all my tables, so that Alembic would be starting from scratch. I entered</p> <pre><code>alembic revision --autogenerate -m &quot;Initial tables&quot; alembic upgrade head </code></pre> <p>I got an immediate error because it was creating a table which has a ...
<python><alembic><alchemy>
2024-06-24 14:56:53
2
1,348
Peter Kronenberg
78,662,921
447,426
pyspark How to read a folder with binary files continuously - on new files
<p>I created a pyspark pipeline that begins on reading binary files:</p> <pre><code>unzipped: DataFrame = spark.read.format(&quot;binaryFile&quot;)\ .option(&quot;pathGlobFilter&quot;, &quot;*.pcap.tgz&quot;)\ .option(&quot;compression&quot;, &quot;gzip&quot;)\ .load(folder) </code><...
<python><apache-spark><pyspark>
2024-06-24 13:56:55
0
13,125
dermoritz
78,662,706
16,527,170
Interchange Start Date, End Date and other Columns with Earlier Row if Dates greater than 8 in pandas dataframe
<p>Data:</p> <pre><code># Sample data data = { 'Start Date': ['2022-10-18', '2022-10-25', '2023-04-17'], 'End Date': ['2022-10-20', '2023-04-06', '2023-07-04'], 'Close1': [17486.95, 17656.35, 17706.85], 'Close2': [17563.95, 17599.15, 19389.00], 'NF_BEES1': [0.58, 0.19, 0.12], 'NF_BEES2': [0.63, ...
<python><pandas><dataframe>
2024-06-24 13:12:57
2
1,077
Divyank
78,662,483
3,170,559
Why is my PySpark row_number column messed up when applying a schema?
<p>I want to apply a schema to specific non-technical columns of a Spark DataFrame. Beforehand, I add an artificial ID using <code>Window</code> and <code>row_number</code> so that I can later join some other technical columns to the new DataFrame from the initial DataFrame. However, after applying the schema, the gene...
<python><apache-spark><pyspark><rdd><azure-synapse>
2024-06-24 12:35:42
1
717
stats_guy
78,662,482
1,083,855
Is it possible to improve orientation detection with tesseract by specifying language and script?
<p>I am using tesseract to detect orientation of scanned images. They mostly contains text. It works in general but sometimes fails, even for simple cases :</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: center;">Input</th> <th>Result</th> </tr> </thead> <tbody> <tr> <td ...
<python><ocr><tesseract>
2024-06-24 12:35:39
0
4,576
tigrou
78,662,478
5,823,008
Compute statistical values out of a precounted list in Python
<p>I have a dataframe of precounted data (shown below). Let's assume it's a &quot;Do you like?&quot; scale, where 4 people answered 1-Don't like at all, 10 people answer 2-Don't like and so on.</p> <p>How can I compute the different statistical values? I want to compute the mean (in this case, it can be done by hand <c...
<python><statistics>
2024-06-24 12:34:42
3
350
MatMorPau22
78,662,180
273,593
invoke a `@classmethod`-annotated method
<p>Dummy scenario:</p> <pre class="lang-py prettyprint-override"><code># where I want to collect my decorated callbacks cbs = [] # decorator to mark a callback to be collected def my_deco(cb): cbs.append(cb) return cb class C: @my_deco @classmethod def cm(cls): ... # execute the collected...
<python><python-3.x><python-decorators><class-method>
2024-06-24 11:37:05
3
1,703
Vito De Tullio
78,662,089
1,083,855
How to update exif data without losing JFIF header?
<p>I use the following code to rotate an JPG image by 180 degrees, by updating EXIF header. I want to avoid re-encoding the image :</p> <pre><code>import PIL import piexif filename = &quot;somefile.jpg&quot; img = PIL.Image.open(filename) exif_dict = piexif.load(img.info['exif']) exif_dict[&quot;0th&quot;][274] = 3 #1...
<python><jpeg><exif>
2024-06-24 11:18:23
1
4,576
tigrou
78,661,816
9,736,176
How to check for uncommited changes to git in a subset of files using python
<p>I'm doing data analysis, and for reproducibility I want to make sure my results are marked with the version of the code used to produce them. I do this with</p> <pre><code>import git repo = git.Repo(search_parent_directories=True) last_commit_hex = repo.head.object.hexsha </code></pre> <p>But that's not necessarily ...
<python><git>
2024-06-24 10:22:53
1
436
BurnNote
78,661,811
1,422,096
Convert to int if not None, else keep None
<p>I have a <code>request</code> dict and I need to parse some elements into either <code>int</code> or <code>None</code>. This works:</p> <pre><code>request = {&quot;a&quot;: &quot;123&quot;, &quot;c&quot;: &quot;456&quot;} a, b = request.get(&quot;a&quot;), request.get(&quot;b&quot;) # too many ...
<python><nonetype>
2024-06-24 10:21:31
3
47,388
Basj
78,661,800
6,809,075
How to Implement a Memory-Efficient Custom Iterator for Large Files in Python?
<p>I need to iterate over extremely large files (several gigabytes each) in Python without loading the entire file into memory. Specifically, I want to implement a custom iterator that reads and processes data from these large files efficiently. What are the best practices and techniques for achieving this?</p> <p><str...
<python><memory-management><iterator>
2024-06-24 10:18:16
0
680
safiqul islam
78,661,106
3,486,684
How do I type annotate a worksheet, or more specifically, a read-only worksheet?
<p>I have <code>types-openpyxl</code> installed.</p> <p>I load a workbook in read-only mode, and then access a worksheet from it:</p> <pre><code>from pathlib import Path import openpyxl as xl from openpyxl.worksheet._read_only import ReadOnlyWorksheet excel_file = Path(&quot;./xl.xlsx&quot;) wb: xl.Workbook = xl.load_...
<python><openpyxl><mypy><python-typing>
2024-06-24 07:42:33
2
4,654
bzm3r
78,661,005
10,200,497
How can I compare a value in one column to all values that are BEFORE it in another column to find the number of unique values that are less than?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [100, 100, 105, 106, 106, 107, 108, 109], 'b': [99, 100, 110, 107, 100, 110, 120, 106], } ) </code></pre> <p>Expected output is creating column <code>x</code>:</p> <pre><code> a b x 0 100 99 0 1...
<python><pandas><dataframe>
2024-06-24 07:16:53
4
2,679
AmirX
78,660,891
15,690,172
Can't control servo with Python using Raspberry Pi
<p>I am using a <strong>Raspberry Pi model 4B</strong> and a <strong>Tower Pro servo SG51R</strong> which only turns 180 degrees. I am writing code on the Raspberry Pi to control the servo <em>(which works as I have tested it with my Arduino Uno, it responds and works correctly)</em> with Python.</p> <p>I installed the...
<python><raspberry-pi><gpio><servo><gpiozero>
2024-06-24 06:44:54
0
309
realhuman
78,660,804
2,530,674
FastAPI via Docker is not running
<p>I have the following two files but I cannot get the FastAPI server to work via Docker.</p> <p>I am using the command <code>docker build -t my_project .</code> to build it and <code>docker run -it -p 8080:8080 my_project</code> to run the server. Finally, I use the following curl command to call the API, but I get th...
<python><docker><fastapi>
2024-06-24 06:18:32
2
10,037
sachinruk
78,660,560
4,801,767
PEP 668 Error (Externally managed environment) within Conda
<p>While trying to <code>pip install</code> packages, even though I am inside a Conda environment, I'm getting the familiar error:</p> <pre class="lang-none prettyprint-override"><code>error: externally-managed-environment </code></pre> <p>I would expect this if I'm using Python directly from the system prompt. But why...
<python><pip><conda>
2024-06-24 04:36:44
1
1,472
ahron
78,660,517
4,451,521
Is there a way to make the rows of a gradio dataframe clickable?
<p>I have the following script</p> <pre><code>import gradio as gr import pandas as pd import numpy as np def generate_random_dataframe(): # Generate a random DataFrame df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE')) return df with gr.Blocks() as demo: generate_button = gr.Button(&quot;...
<python><gradio>
2024-06-24 04:17:58
1
10,576
KansaiRobot
78,660,506
14,343,465
ImportError: cannot import name 'Credentials' from 'dbt.adapters.base'
<p>I'm trying to get an AWS Athena adapter setup with dbt-core</p> <h2>setup</h2> <pre><code>python -m pip install dbt-core dbt-athena </code></pre> <ul> <li>following this doc: <a href="https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup" rel="nofollow noreferrer">Athena setup | dbt Developer Hub</a><...
<python><amazon-web-services><amazon-athena><dbt>
2024-06-24 04:11:29
1
3,191
willwrighteng
78,660,487
13,642,249
Sniff Continuously and Save PCAP Files Simultaneously using PyShark's LiveCapture Method with display_filter
<p>I am attempting to continuously sniff packets while concurrently saving them to a PCAP file using PyShark's <code>LiveCapture</code> method with the <code>display_filter</code> param. I am attempting to replicate the feature from Wireshark where you can stop and save a capture at any given moment with any filter spe...
<python><pyshark>
2024-06-24 04:00:23
1
1,422
kyrlon
78,660,434
1,245,262
Why can't I connect to the default port on localhost when using Milvus?
<p>I'm just starting to use Milvus, but cannot connect to the port given in the example. I am running directly on my machine (i.e. not a Docker image), but cannot get initial exampe to work:</p> <pre><code>$ python Python 3.10.14 (main, May 6 2024, 19:42:50) [GCC 11.2.0] on linux Type &quot;help&quot;, &quot;copyright...
<python><database><port><milvus>
2024-06-24 03:25:05
0
7,555
user1245262
78,660,379
4,701,852
Straighten a Polygon into a line with Geopandas/Shapely
<p>I'm using Python. geopandas and shapelly to process the geometries of a road intersection.</p> <p>The geojson has a list of Polygons that I want to straighten into Lines, something like this:</p> <p><a href="https://i.sstatic.net/e83OFzZv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/e83OFzZv.png" a...
<python><line><polygon><geopandas><shapely>
2024-06-24 02:55:19
2
361
Paulo Henrique PH