QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
79,325,394
5,004,159
Trouble identifying the "Connect" art deco button element in Linkedin for Scraping via Selenium
<pre><code>def send_linkedin_requests(speakers): &quot;&quot;&quot;Send LinkedIn connection requests to scraped speakers.&quot;&quot;&quot; driver = None try: print(&quot;\nStarting LinkedIn connection process...&quot;) driver = create_chrome_driver() driver.get(&quot;https://www.lin...
<python><selenium-webdriver><web-scraping>
2025-01-03 02:49:41
2
319
grehce
79,325,378
943,222
how to combine alive-progress with paramiko in multi-threaded setup
<p>I have a multi-threaded sftp python script and uses paramiko which works, now I want to add alive-progress to it so it can print the progress its making for each file it transfers.</p> <p>Currently it is making one sftp upload thread per file given and I want to be able to print out all the thread's progress kind of...
<python><multithreading><paramiko>
2025-01-03 02:35:15
0
816
D.Zou
79,325,277
22,146,392
Custom jinja filter using python pandas is returning only sometimes returning correct information?
<p>I'm building a site with the Material theme for MkDocs. I've added the following custom filter:</p> <pre class="lang-py prettyprint-override"><code>import pandas def csv_to_html(csv_path): return pandas.read_csv(csv_path).to_html() </code></pre> <p>I'm trying to find a CSV file based on the metadata of my MD doc...
<python><pandas><mkdocs><mkdocs-material>
2025-01-03 01:06:40
0
1,116
jeremywat
79,325,079
2,648,504
Pandas displaying the first row but not indexing it
<p>I have a large text file, with a header of 18 lines.</p> <p>If I try to display the entire dataframe:</p> <pre><code>df = pd.read_csv('my_log') print(df) </code></pre> <p>I get: <code>pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 19, saw 3</code></p> <p>If I try to use exclude ...
<python><pandas>
2025-01-02 22:15:43
1
881
yodish
79,324,850
5,602,104
Python: is there a straightforward way to determine if it is safe to move a line of code outside of a try-except?
<p>Suppose you have some code like this:</p> <pre><code>def some_func(): try: func_a() func_b() func_c() except SomeException as e: print(&quot;An exception occurred.&quot;) </code></pre> <p>Is there a straightforward way to determine whether it is safe to move any of the <code>f...
<python><exception><error-handling><try-except>
2025-01-02 20:07:06
0
729
jcgrowley
79,324,706
9,112,151
What happens with ContextVar if don't reset it?
<p>With code below what will happen to SqlAlchemy session that is set in ContextVar if not to reset it?</p> <pre><code>from contextvars import ContextVar from fastapi import FastAPI, BackgroundTasks from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession engine = create_async_...
<python><sqlalchemy><fastapi><python-contextvars>
2025-01-02 18:58:29
1
1,019
ΠΠ»ΡŒΠ±Π΅Ρ€Ρ‚ АлСксандров
79,324,668
10,886,283
How to get only the first occurrence of each increasing value in numpy array?
<p>While working on first-passage probabilities, I encountered this problem. I want to find a NumPythonic way (without explicit loops) to leave only the first occurrence of strictly increasing values in each row of a <code>numpy</code> array, while replacing repeated or non-increasing values with zeros. For instance, i...
<python><arrays><numpy>
2025-01-02 18:37:05
2
509
alpelito7
79,324,608
8,990,329
IPv6 Hop-by-Hop Scapy: ValueError: Missing 'dst' attribute
<p>I'm experimenting with <code>IPv6</code> Scapy and trying to set <code>Router Alert</code> Hop By Hop option. Here is the code sample:</p> <pre><code>hdr = IPv6ExtHdrHopByHop(options=[(&quot;Router Alert&quot;, b'\x01\x00')]) ip6 = IPv6(src=&quot;xxxx::xxxx&quot;, dst=&quot;yyyy::yyyy&quot;) send(ip6 / hdr) </code><...
<python><ipv6><scapy>
2025-01-02 18:09:36
1
9,740
Some Name
79,324,524
13,971,251
AttributeError with instance of model with Generic Foreign Field in, created by post_save signal
<p>I have 3 models that I am dealing with here: <code>SurveyQuestion</code>, <code>Update</code>, and <code>Notification</code>. I use a <code>post_save</code> signal to create an instance of the <code>Notification</code> model whenever an instance of <code>SurveyQuestion</code> or <code>Update</code> was created.</p> ...
<python><django><django-models><generic-foreign-key><django-model-field>
2025-01-02 17:33:43
1
1,181
Kovy Jacob
79,324,475
10,140,821
capture file name as variable based on substring in python
<p>I have a below scenario in <code>python</code>. I want to check the current working directory and the files present in that directory and create a variable.</p> <p>I have done like below</p> <pre><code>import os # current working directory print(os.getcwd()) # files present in that directory dir_contents = os.list...
<python>
2025-01-02 17:12:03
2
763
nmr
79,324,398
3,837,788
Custom implementation of Python http.server doesn't work properly when HTTPS is enabled
<p>I am aware that Python <code>http.server</code> module has been conceived mainly for testing purposes, since there are some well known security issues in its implementation.</p> <p>That said, for a very humble personal project, I implemented my own class, derived from <code>http.server.BaseHTTPRequestHandler</code>,...
<python><http><ssl><timeout>
2025-01-02 16:38:28
0
566
rudicangiotti
79,324,137
357,024
Why is Python's IsolatedAsyncioTestCase so slow?
<p>I'm working on writing test cases for some Python code that uses asyncio. I'm noticing a significant performance degradation when my test classes inherit from <code>unittest.IsolatedAsyncioTestCase</code> vs. using the non-async UnitTest and manually calling a coroutine using <code>asyncio.run</code></p> <p>I've tes...
<python><python-3.x><python-asyncio><python-unittest>
2025-01-02 14:56:42
1
61,290
Mike
79,323,979
999,162
Saving a website screenshot with pyqt6 / QtWebEngineView is always empty
<p>I'm trying to save a screenshot of a website with QtWebEngineView, but the resulting image always ends up being empty.</p> <pre><code> import sys import time from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtWidgets import QApplication, QWidget from PyQt6.QtWebEngineWidgets import QWebEngineView cla...
<python><web-scraping><pyqt><pyqt6>
2025-01-02 14:13:41
2
5,274
kontur
79,323,929
2,123,706
how do I find all polars dataframes in python
<p>I have a long script in python, predominantly pandas, but shifting to polars.</p> <p>I am reviewing memory of items.</p> <p>To find 10 largest objects currently in use <code>locals().items()</code> and <code>sys.getsizeof()</code>, I run:</p> <pre><code>import sys def sizeof_fmt(num, suffix='B'): ''' by Fred Cir...
<python><dataframe><python-polars>
2025-01-02 13:57:39
0
3,810
frank
79,323,746
11,850,322
Why keep NumPy RuntimeWarning
<p>Here is a sample data, even there is no negative or np.nan, it still show error message:</p> <p>Data:</p> <pre><code> gvkey sale ebit 4 1000 44.8 16.8 5 1000 53.2 11.5 6 1000 42.9 6.2 7 1000 42.4 0.9 8 1000 44.2 5.3 9 1000 51.9 9.7 </code></pre> <p>Function:</p> <pre><code>def calcula...
<python><pandas><numpy>
2025-01-02 12:43:34
2
1,093
PTQuoc
79,323,706
2,526,586
Jinja linking resources from separate projects
<p>With Jinja2, I can normally link to a CSS stylesheet from HTML template with something like:</p> <pre><code> &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url_for('static', filename='styles.css') }}&quot; /&gt; </code></pre> <p>given that &quot;static&quot; is the relative directory containing the styles.css.</p...
<python><visual-studio-code><flask><sass><jinja2>
2025-01-02 12:30:37
0
1,342
user2526586
79,323,535
14,754,870
aioboto3 parallel page fetching from s3
<p>I have an s3 bucket. It contains many thousands of objects. I want to use a paginator to extract all the lists of object keys in parallel using asynchio and aioboto3.</p> <p>Is this possible? It seems to not work. If it's not possible, then why?</p> <p>This is what I tried that raises an exception:</p> <pre><code>as...
<python><amazon-s3><python-asyncio><boto3>
2025-01-02 11:14:25
0
348
PurpleHacker
79,323,285
1,305,993
Executorch installation issue
<p>I am trying to set up environmenty like in tutorial: <a href="https://pytorch.org/executorch/stable/getting-started-setup" rel="nofollow noreferrer">https://pytorch.org/executorch/stable/getting-started-setup</a></p> <p>When running ./install_requirements.sh I get an error: CMake Error at CMakeLists.txt:45 (project)...
<python><pytorch>
2025-01-02 09:22:35
1
1,309
RCH
79,323,215
12,466,687
How to combine columns with extra strings into a concatenated string column in Polars?
<p>I am trying to add another column that will contain combination of two columns (Total &amp; percentage) into a result column(labels_value) which look like: <code>(Total) percentage%</code>.</p> <p>Basically to wrap <code>bracket</code> strings on <code>Total</code> column and add <code>%</code> string at the end of ...
<python><dataframe><python-polars>
2025-01-02 08:56:51
1
2,357
ViSa
79,323,147
4,745,607
Integrating Chaquopy 16.0 in kotlin multiplatform's shared module, Can not access Python in shared module
<p>I am developing a kotlin multiplatform app. In the shared module of this I want to use numpy package to do operation on some .pkl files. I am following the setup mentioned <a href="https://chaquo.com/chaquopy/doc/current/android.html" rel="nofollow noreferrer">Official Setup Link-Kotlin</a>. So far what I have done ...
<python><python-3.x><numpy><kotlin-multiplatform><chaquopy>
2025-01-02 08:23:49
1
2,524
Devendra Singh
79,323,140
11,850,322
Suggestion of sub files type for calculation
<p>I use jupyter lab for my project. I use mostly pandas, numpy, statsmodel. The number of code lines now is very long and becoming hard to manage. I want to leverage by creating sub-files for calculation, i.e.:</p> <ul> <li>Call a sub-file</li> <li>Pass input to the sub-file</li> <li>Get output from the sub-file</li> ...
<python><jupyter-notebook><jupyter><jupyter-lab>
2025-01-02 08:21:15
2
1,093
PTQuoc
79,322,845
958,580
Multiple Aliases for a Terminal or Rule
<p>Can one assign multiple aliases for a terminal or rule in Lark ?</p> <p>Consider the following grammar</p> <pre><code>coordinate : &quot;(&quot; X &quot;,&quot; Y &quot;)&quot; %import common.SIGNED_NUMBER -&gt; X %import common.SIGNED_NUMBER -&gt; Y </code></pre> <p>which returns the error</p> <pre><code>lark.exce...
<python><lark-parser>
2025-01-02 05:31:08
0
3,417
Carel
79,322,796
5,404,337
activate javascript to render Next page on website using selenium
<p>I am trying to understand how to submit request to generate the next page in a website.</p> <p>The site displays the first 10 rows of a data table, and then provides a list of page numbers and Previous and Next highlighted text (e.g., Previous 1 2 3 4 Next) at the bottom of the data table. I assume there is a javasc...
<javascript><python><selenium-webdriver>
2025-01-02 04:51:44
1
328
bici.sancta
79,322,639
562,697
Matching a QListView's background color to the window color
<p>To be clear, this has nothing to do with the items in a list view, but the default background color itself. I'd like the widget to effectively not be noticeable itself.</p> <p>According to the <a href="https://doc.qt.io/qt-6/qwidget.html#setBackgroundRole" rel="nofollow noreferrer">docs</a> setting the background ro...
<python><pyqt>
2025-01-02 02:10:21
0
11,961
steveo225
79,322,580
1,492,229
Calling huggingface APIs fails
<p>This is my first time to use huggingface.</p> <p>I want to call its API to answer a prompt.</p> <p>Here is what I have so far:</p> <pre><code>import requests # Define API details API_URL = &quot;https://api-inference.huggingface.co/models/Llama-3.3-70B-Instruct&quot; API_TOKEN = &quot;hf_***************************...
<python><huggingface>
2025-01-02 01:09:29
0
8,150
asmgx
79,322,543
7,693,707
Find the closest converging point of a group of vectors
<p>I am trying to find the point that is closest to a group of vectors.</p> <p>For context, the vectors are inverted rays emitted from center of aperture stop after exiting a lens, this convergence is meant to locate the entrance pupil.</p> <p>The backward projection of the exiting rays, while not converging at one sin...
<python><numpy><vector>
2025-01-02 00:11:21
1
1,090
Amarth GΓ»l
79,322,530
1,319,070
Unable to run a simple python application in AWS App Runner
<p>Has any deployed a python application on AWS app runner recently ? I have tried a lot of different ways and they all fail with the same error</p> <pre><code>01-01-2025 04:44:22 PM [AppRunner] Health check failed on protocol `HTTP`[Path: '/'], [Port: '8080']. Check your configured port number. For more information, s...
<python><amazon-web-services><aws-app-runner><docker-healthcheck>
2025-01-02 00:03:01
1
419
Sathiesh
79,322,486
2,936,329
Pyre: `Invalid class instantiation` on a factory pattern with ABC type hint
<p>I have implemented a factory pattern but Pyre-check trips over the type-hinting, thinking I want to instantiate the mapping dict type hint: <code>type[MyClassABC]</code></p> <p>Here is a minimum example, also a <a href="https://pyre-check.org/play?input=from%20abc%20import%20abstractmethod%0A%0A%0Aclass%20MyClassABC...
<python><abstract-class><python-typing><pyre-check>
2025-01-01 23:14:35
1
468
Rien
79,322,284
142,976
How to override inherited Odoo method?
<p>I'm trying to override a method that is inherited like this example</p> <pre><code>module school ################################################################### class BaseTest(models.AbstractModel) _name = 'base.test' score = fields.Float() def get_score(self) return score class ...
<python><odoo>
2025-01-01 20:27:12
0
4,224
strike_noir
79,322,153
10,889,650
How "unpythonic" is it for an exception to be the expected outcome?
<p>In Django I am validating a request which submits something that a user is only supposed to submit once, and in the &quot;correct behavour sequence&quot; an Exception is raised:</p> <pre><code>try: my_row = models.MyModel.objects.get(id=instance_id, user=request.logged_in_user) return HttpResponseBadRequest(...
<python><django>
2025-01-01 18:44:57
1
1,176
Omroth
79,322,044
6,140,251
How to use SQL Stored Procedures for dynamic tables in sqlalchemy with psycopg2
<p>I need execute SQL query for different dynamic tables.</p> <p>I try to do it as follows:</p> <pre><code>import sqlalchemy.pool as pool def get_conn_pool(): conn = psycopg2.connect(user=settings.POSTGRES_USER, password=settings.POSTGRES_PASSWORD, database=settings.POSTGRES_DB, host=s...
<python><stored-procedures><sqlalchemy><psycopg2>
2025-01-01 17:34:53
0
451
Vadim
79,322,039
9,128,863
Pytorch: RuntimeError: Numpy is not available
<p>I'm trying to handle train dataset from MNIST with Pytorch.</p> <pre><code> import torch from torchvision.datasets import MNIST import torchvision.transforms as transforms from torch.utils.data import DataLoader img_transforms = transforms.Compose([ transforms.ToTensor(), transforms.Norma...
<python><numpy><pytorch>
2025-01-01 17:29:54
0
1,424
Jelly
79,322,010
8,458,083
How to make mypy correctly type-check a function using functools.partial?
<p>I'm trying to create a function that returns a partially applied callable, but I'm encountering issues with mypy type checking.</p> <p>HEre Is my first implementation:</p> <p>Help me to explain my question for stackoverflow. i.e find a title and the body</p> <p>this code :</p> <pre><code>from collections.abc import ...
<python><python-typing><mypy>
2025-01-01 17:06:46
2
2,017
Pierre-olivier Gendraud
79,321,800
22,407,544
Which method is best for designing custom error pages in Django?
<p>For example, I've seen methods which design custom views with changes to URLconf, I've seen other methods that use <code>handler404 = &quot;mysite.views.my_custom_page_not_found_view&quot;</code> in URLconf with no changes to views. I've seen both of these methods explained in the docs. The easiest method I've seen ...
<python><django>
2025-01-01 14:55:29
1
359
tthheemmaannii
79,321,729
9,667,949
Does Re-initializing my list in while loop, create multiple instances of it in memory or is it simply resetting the previous list to an empty one
<p>I have this piece of code for a leetcode problem. Since I normally use c++, my python skills have degraded a little bit and as the title states, I just want to know when I am re-initializing my lists in the while loop over and over again is it creating multiple instances of the list in memory or simply over-writing ...
<python><algorithm>
2025-01-01 14:08:03
0
1,700
Mahir Islam
79,321,673
5,460,515
How to compare expected and actual database state?
<p><em><strong>Before start</strong> This question seems rather big, so you can skim over current approaches, and go directly to question, marked with bold font at the end of question.</em></p> <p>I am writing tests for some handlers in project. One of main features is to create/change/delete objects in database.</p> <...
<python><database><testing><automated-tests>
2025-01-01 13:30:10
1
398
Π’Π°Π»Π΅Ρ€ΠΈΠΉ ГСрасимов
79,321,289
9,052,139
How to show dedicated progress bar in each tab in a Gradio app?
<p>I am developing an image generation Gradio app that uses multiple models like SD3.5, Flux, and others to generate images from a given prompt.</p> <p>The app has 7 tabs, each corresponding to a specific model. Each tab displays an image generated by its respective model.</p> <p>My problem is that I am unable to show ...
<python><artificial-intelligence><stable-diffusion><gradio><image-generation>
2025-01-01 07:20:05
1
1,004
RagAnt
79,320,921
22,146,392
Adding custom filters with mkdocs-simple-hooks
<p>I'm using MkDocs and I want to add a custom filter. Based on <a href="https://stackoverflow.com/a/67278596/22146392">this answer</a>, I'm using <a href="https://github.com/aklajnert/mkdocs-simple-hooks" rel="nofollow noreferrer">mkdocs-simple-hooks</a>. The answer suggests using the <a href="https://www.mkdocs.org/d...
<python><mkdocs><mkdocs-material>
2024-12-31 23:13:05
0
1,116
jeremywat
79,320,841
11,946,505
NASDAQ Python SDK Client - How to resolve Market Open/Close Data Delay?
<p>I am using the NASDAQ Python SDK client to consume market data for the <code>NLSUTP</code> topic. The data is fetched using the <code>NCDSClient</code> and processed in real-time. I send the data received from the consumer via WebSocket. During normal market hours, I get multiple responses from WebSocket within 1 se...
<python><apache-kafka><websocket><consumer>
2024-12-31 21:31:22
0
718
abdulsaboor
79,320,792
13,971,251
When referencing imported Django model, I get 'local variable referenced before assignment' error
<p>I am trying to import a model into my Django view and then query all objects, sort them, and iterate over them. I am not getting any error when importing the model, however, when trying to query the model with <code>songs = song.objects.all()#.order_by('-release_date')</code>, I am getting an error:</p> <pre><code>U...
<python><django><django-models><django-views>
2024-12-31 20:50:10
2
1,181
Kovy Jacob
79,320,565
13,971,251
Unable to use one line statement to get a value from a dictionary in a list, and then save it as a variable Python
<p>I am pretty confused.</p> <p>I have a list of dictionaries, like so:</p> <pre><code>options = [ {'name':'Notifications','id':'1', 'url':'notifications'}, {'name':'the directory','id':'2', 'url':'directory'}, {'name':'the DBM Studios catalogue','id':'842', 'url':'dbm'}, ] </code></pre> <p>I also have ...
<python><list><dictionary>
2024-12-31 18:07:13
0
1,181
Kovy Jacob
79,320,439
4,752,874
How to update Pandas DataFrame column using string concatenation in function
<p>I have a dataframe where I would like to add a full address column, which would be the combination of 4 other columns (street, city, county, postalcode) from that dataframe. Example output of the address column would be:</p> <pre><code>5 Test Street, Worthing, West Sussex, RH5 3BX </code></pre> <p>Or if the city was...
<python><pandas><string><dataframe>
2024-12-31 16:50:21
2
349
CGarden
79,320,253
12,827,843
Extract the Procurement URL from TED using SPARQL query?
<p>I am trying to use SPARQL query to get the procurement URL or etenders Resource ID from TED</p> <pre><code>import sparqldataframe import pandas as pd # Define the SPARQL query sparql_query = &quot;&quot;&quot; PREFIX dc: &lt;http://purl.org/dc/elements/1.1/&gt; PREFIX epo: &lt;http://data.europa.eu/a4g/ontology#&gt...
<python><sparql>
2024-12-31 15:08:53
1
647
Christopher
79,320,067
7,468,566
Comparing .loc/.iloc to tuples and chained indexing
<pre><code>import pandas as pd # Creating a DataFrame with some sample data data = { 'Name': [Jason, 'Emma', 'Alex', 'Sarah'], 'Age': [28, 24, 32, 27], 'City': ['New York', 'London', 'Paris', 'Tokyo'], 'Salary': [75000, 65000, 85000, 70000] } df = pd.DataFrame(data) # Display the DataFrame print(df) ...
<python><pandas><dataframe>
2024-12-31 13:25:02
0
2,583
itstoocold
79,320,041
21,185,825
Python - Flask blueprint parameter?
<p>I need to pass a parameter (some_url) from the main app to the blueprint using Flask</p> <p>This is my (oversimplified) app</p> <pre><code>app = Flask(__name__) app.register_blueprint(my_bp, url_prefix='/mybp', some_url =&quot;http....&quot;) </code></pre> <p>This is my (oversimplified) blueprint</p> <pre><code>my_b...
<python><flask><parameters><blueprint>
2024-12-31 13:09:51
2
511
pf12345678910
79,319,985
16,136,190
Lambda Function in Widget Binding Uses Last Iteration's Values
<p>I have a loop to generate widgets dynamically, and the commands for the buttons are set using lambdas, but the event bindings for <code>Listbox</code>es don't seem to work well:</p> <pre class="lang-py prettyprint-override"><code>def fn1(): def cbf(e, param1, param2): val = param2.get(param2.curselectio...
<python><loops><tkinter><lambda>
2024-12-31 12:37:09
1
859
The Amateur Coder
79,319,878
7,358,909
Initializing Hugging Face Transformer restarts program loop
<p>Initializing hugging face transformer causes loops to restart. I have created simple loop which reads text and replies but the loop is restarting new thread when initalizing chatbot pipeline. Minimum replication example given below.</p> <pre><code>from transformers import pipeline from transformers.pipelines import ...
<python><python-3.x><chatbot><python-multithreading><huggingface-transformers>
2024-12-31 11:45:15
1
1,868
Shahir Ansari
79,319,663
629,960
FastAPI + Apache. 409 response from FastAPI is converted to 502. What can be the reason?
<p>I have a FastAPI application, which, in general, works fine. My setup is Apache as a proxy and FastAPI server behind it. This is the apache config:</p> <pre><code>ProxyPass /fs http://127.0.0.1:8000/fs retry=1 acquire=3000 timeout=600 Keepalive=On disablereuse=ON ProxyPassReverse /fs http://127.0.0.1:8000/fs </code>...
<python><apache><fastapi><reverse-proxy><http-status-code-502>
2024-12-31 09:51:23
1
2,113
Roman Gelembjuk
79,319,632
9,954,014
Return multiple values from HTTP response
<p>I am trying to create a property map in &quot;Authentik&quot; which fetches values from other services. in this case I need to use an API key to return 3 values from a request to an Emby Server. At first I tried with <code>curl</code> to see if I am able to get a response:</p> <pre class="lang-bash prettyprint-overr...
<python><httprequest>
2024-12-31 09:34:30
1
367
Asem Khen
79,319,631
6,449,621
how to decode Proto2 response python
<p>Calling an api using request &amp; the response content is in proto2 format.</p> <pre><code>r = requests.post('https://gs-loc.apple.com/clls/wloc',headers=HEADERS,data=DATA,verify=False) print(r.content) </code></pre> <p>Response:</p> <pre><code>b&quot;\x125\n\x1164:fb:92:9c:91:8d\x12\x1a\x08\x88\x90\xbf\xf0\x04\x10...
<python><protocol-buffers>
2024-12-31 09:33:49
1
465
anandyn02
79,319,503
2,897,115
Pass a list of parameter to parametrize from a function
<p>I have session scope fixture for initiating db connection</p> <pre><code>import pytest @pytest.fixture(scope=&quot;session&quot;) def dconn(): # Your database connection logic return &quot;database_connection&quot; @pytest.fixture def some_function(dconn): # Use dconn to generate data return [ ...
<python><pytest>
2024-12-31 08:26:47
1
12,066
Santhosh
79,319,434
329,829
DuplicateError with name 'null' when trying to pivot a Polars DataFrame
<p>I have this example dataframe in polars:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df_example = pl.DataFrame( { &quot;DATE&quot;: [&quot;2024-11-11&quot;, &quot;2024-11-11&quot;, &quot;2024-11-12&quot;, &quot;2024-11-12&quot;, &quot;2024-11-13&quot;], &quot;A&quot;:...
<python><dataframe><pivot><python-polars><polars>
2024-12-31 07:44:03
2
5,232
Olivier_s_j
79,319,294
188,331
BLEURT evaluation metric consumed too much RAM
<p>The BLEURT codes almost used up all the 24GB RAM of NVIDIA GeForce RTX 4090 to evaluate just 1 set of sentences.</p> <pre><code>ref = 'reference sentence here' hypo = 'hypothesis sentence here' scores = {} import evaluate metric_bleurt = evaluate.load('bleurt') bleurt = metric_bleurt.compute(predictions=[hypo], ref...
<python><out-of-memory><huggingface>
2024-12-31 06:06:52
0
54,395
Raptor
79,319,263
1,788,656
Why does geopandas dissolve function keep working forever?
<p>All, I am trying to use the Geopandas dissolve function to aggregate a few countries; the function countries.dissolve keeps running forever. Here is a minimal script.</p> <pre><code>import geopandas as gpd shape='/Volumes/TwoGb/shape/fwdshapfileoftheworld/' countries=gpd.read_file(shape+'TM_WORLD_BORDERS-0.3.shp') ...
<python><python-3.x><geopandas>
2024-12-31 05:46:50
1
725
Kernel
79,319,156
162,349
How to add Python type annotations to a class that inherits from itself?
<p>I'm trying add type annotations to an <code>ElementList</code> object that inherits from <code>list</code> and can contain either <code>Element</code> objects or other <code>ElementGroup</code> objects.</p> <p>When I run the following code through mypy:</p> <pre class="lang-py prettyprint-override"><code>from typing...
<python><python-typing><mypy>
2024-12-31 04:14:35
1
4,472
cdwilson
79,318,848
8,229,029
How to properly run Python multiprocessing pool inside larger loop and shut it down before next loop starts
<p>I have a large script where I am processing terabytes of weather/climate data that comes in gridded format. I have a script that uses an outer loop (over years - 1979 to 2024), and for each year, loops over each month (1 - 12), as data for each month comes in monthly files, and an additional loop that loops over ea...
<python><parallel-processing><multiprocessing><metpy>
2024-12-30 23:26:51
2
1,214
user8229029
79,318,845
1,141,798
Serving MMCV/MMDet on Databricks - GLIBC_2.32 not found
<p>I'm trying to host MMDetection model on <a href="https://learn.microsoft.com/en-us/azure/databricks/machine-learning/model-serving/" rel="nofollow noreferrer">Databricks Serving (on Azure)</a>. The model is trained on 15.4 LTS ML. However, during the serving endpoint update, it complains about <code>GLIBC_2.32</code...
<python><databricks><azure-databricks><openmmlab>
2024-12-30 23:23:35
1
1,302
Dominik Filipiak
79,318,707
5,109,125
SQLDatabaseChain result shows "Answer" value incorrectly?
<p>I am looking for help regarding an issue with my <code>SQLDatabasechain invoke()</code> results.</p> <p>Here is my langchain code - I created a <code>db_chain</code> with my <code>llm</code> (model) and <code>db</code> (MySQL database) using <code>SQLDatabaseChain.from_llm</code> method - then I executed <code>db_c...
<python><langchain>
2024-12-30 21:52:55
0
597
punsoca
79,318,679
3,965,828
Get all tuple permutations between two lists
<p>Given two lists of length n, I've been trying to find a pythonic way to return a list of a list of n-tuples where each list of tuples is a distinct permutation of the possible values between the two lists. So given:</p> <pre><code>a = [1, 2] b = [3, 4] </code></pre> <p>I'd expect an output of:</p> <pre><code>[ [(1, ...
<python><list><permutation>
2024-12-30 21:40:36
1
2,631
Jeffrey Van Laethem
79,318,595
10,140,821
extract file name and sub subdirectory names as variables from absolute path of file in python
<p>I have a file in <code>python</code>. Path to the path is <code>/home/user/pythonfiles/test_files/test1.py</code></p> <p>I want to find the file name and last subdirectories of the file as variables.</p> <p>I have done like below</p> <pre><code># find file name sess_name = os.path.basename(__file__).split('.')[0] pr...
<python>
2024-12-30 20:51:21
0
763
nmr
79,318,540
13,971,251
Django model foreign key to whichever model calls it
<p>I am getting back into Django after a few years, and am running into the following problem. I am making a system where there are 2 models; a survey, and an update. I want to make a notification model that would automatically have an object added when I add a survey object or update object, and the notification objec...
<python><django><django-models>
2024-12-30 20:19:52
1
1,181
Kovy Jacob
79,318,211
3,840,530
How to extract the (major/minor) ticks from a seaborn plot?
<p>I am trying to extract ticks from my python plot drawn with seaborn. I have two sets of code below which I thought would produce same results. However, one extracts the ticks correctly and the other just returns zeros.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gc...
<python><matplotlib><label><seaborn>
2024-12-30 17:28:54
0
302
user3840530
79,317,933
5,507,055
How to use multipart/form-data with requests session?
<p>I want to send data with requests as form-data. I use the request's session. However, it still send the data in application/x-www-form-urlencoded form. I started a test servver with <code>nc -kdl 8000</code>.</p> <pre><code>import requests import http.client as http_client http_client.HTTPConnection.debuglevel = 1 ...
<python><session><python-requests><form-data>
2024-12-30 15:08:00
0
2,845
ikreb
79,317,927
521,070
How to find overlapping multi-dimensional ranges?
<p>Suppose I am writing function <code>find_overlapping_ranges</code> to find overlapping ranges in a list of multi-dimensional ranges. Two multi-dimensional ranges overlap if they overlap in <strong>all</strong> dimensions.</p> <pre><code>from typing import List, Tuple from dataclasses import dataclass Interval = Tup...
<python><algorithm><range>
2024-12-30 15:04:49
1
42,246
Michael
79,317,861
2,936,329
Pyre-check error for @property: Undefined attribute: `<class>` has no attribute `<attribute>`
<p>I use <a href="https://pyre-check.org/" rel="nofollow noreferrer">pyre-check</a> for type checking my python code, with strict setting on. It works fine except for OOP properties.</p> <p>Example code:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def __init__(self, full_name: str): s...
<python><python-typing><pyre-check>
2024-12-30 14:27:07
0
468
Rien
79,317,756
13,848,874
I want %matplotlib notebook not %matplotllib widget or %matplotlib ipympl : Javascript Error: IPython is not defined
<p>I start with the usual imports and go to start an interactive plotting session:</p> <pre><code># for viewing figures interactively %matplotlib notebook # To start plotting in matplotlib import IPython import matplotlib.pyplot as plt import seaborn as sns sns.set_style(&quot;whitegrid&quot;) # Other data libraries...
<javascript><python><matplotlib><jupyter-notebook>
2024-12-30 13:39:46
1
473
Malihe Mahdavi sefat
79,317,564
10,364,071
Will python multiprocessing deep copy parameters using spawn method?
<p>Assume I am using <code>multiprocessing.set_start_method('spawn')</code>. When creating a process using <code>multiprocessing.Process(target=fun, args=(a,))</code>, I am wondering whether <code>a</code> will be deep copied. From previous questions <a href="https://stackoverflow.com/questions/5983159/python-multiproc...
<python><multiprocessing>
2024-12-30 12:19:44
0
463
zbh2047
79,317,464
10,722,752
Getting AttributeError: partially initialized module 'numpy.core.arrayprint' has no attribute 'array2string' (most likely due to circular import) eror
<p>I tried installing pandarallel but couldn't install due to some errors. Now when I try to simply import pandas and numpy, I am getting error:</p> <pre><code>import pandas as pd import numpy as np AttributeError: partially initialized module 'numpy.core.arrayprint' has no attribute 'array2string' (most likely due to...
<python><pandas><numpy>
2024-12-30 11:25:55
1
11,560
Karthik S
79,317,324
6,597,296
Handle an option only if another option is used
<p>I need to process command-line options from my Python script that correspond to the syntax</p> <pre class="lang-bash prettyprint-override"><code>tesy.py [-h] [-a [-b]] </code></pre> <p>(This is just a simplistic example illustrating the problem; in reality my script has lots of other options.)</p> <p>That is, the fo...
<python><argparse>
2024-12-30 10:25:20
1
578
bontchev
79,317,167
4,505,998
DataFrame with all NaT should be timedelta and not datetime
<p>I have a DataFrame with a column <code>min_latency</code>, which represents the minimum latency achieved by a predictor. If the predictor failed, there's no value, and therefore it returns <code>min_latency=pd.NaT</code>.</p> <p>The dataframe is created from a dict, and if and only if all the rows have a <code>pd.Na...
<python><pandas><dataframe>
2024-12-30 09:09:38
1
813
David DavΓ³
79,317,125
4,444,757
How to connect python to coinex api v2?
<p>I saw the below links, However, all of them use the <code>v1</code> API and I'd like to use the <code>v2</code> API.<br /> <a href="https://stackoverflow.com/questions/69767586/connecting-to-coinex-api-issue">Connecting to Coinex API issue</a><br /> <a href="https://stackoverflow.com/questions/68060457/how-to-connec...
<python><python-requests>
2024-12-30 08:40:55
1
1,290
Sadabadi
79,317,101
15,154,700
How to uv init without hello.py
<p>After using <code>uv init</code> in a project directory, <code>uv</code> creates these files:</p> <pre><code>.git README.md pyproject.toml hello.py .python-version .gitignore </code></pre> <p>I don't want it to generate hello.py. I want the others, but <code>hello.py</code> is unusable, and I delete it every time I ...
<python><package-managers><uv>
2024-12-30 08:24:11
1
545
Sadegh Pouriyan Zadeh
79,317,040
12,870,651
SQLAlchemy Teradata - Unable to use the df.to_sql functionality
<p>I am attempting to use SQLAlchemy to load data from a pandas dataframe into a Teradata database table using the <code>pandas.to_sql</code> method.</p> <pre class="lang-py prettyprint-override"><code>import sqlalchemy as sa username = &quot;my_username&quot; password = &quot;my_password&quot; hostname = &quot;hostna...
<python><pandas><sqlalchemy><teradata><teradatasql>
2024-12-30 07:38:07
0
439
excelman
79,316,861
14,250,641
Huggingface trainer is not showing any progress for finetuning
<p>I have a dataset I want to fine-tune a huggingface LLM with. This dataset is quite simple. It has two columns: one column has DNA sequences (each in the form of a string 5000 letters long). Another column has a binary label. My dataset is only 240 rows long.</p> <p>For some reason, the trainer.train() step is not ma...
<python><huggingface-transformers><huggingface-tokenizers><fine-tuning><huggingface-trainer>
2024-12-30 05:03:33
1
514
youtube
79,316,741
12,104,604
When using pygrabber and bleak together, the error "Thread is configured for Windows GUI but callbacks are not working." occurs
<p>In the following Python code, whether or not the line <code>from pygrabber.dshow_graph import FilterGraph</code> is included determines whether an error occurs. If I do not include it, no error appears, but if I include it, the error <code>&quot;device search error: Thread is configured for Windows GUI but callbacks...
<python><python-bleak>
2024-12-30 03:15:37
1
683
taichi
79,316,657
7,295,169
How to generate matrix funtion in sympy?
<p>I defined <code>f(At) = e^(At)</code> where <code>A = [[0, 1], [-1, 0]]</code></p> <pre class="lang-py prettyprint-override"><code>from sympy import * from sympy.abc import x,y t = symbols(&quot;t&quot;) A = Matrix([ [0, 1], [-1, 0] ])*t A1 = A.exp() </code></pre> <p><code>A1</code> outputs <code>Matrix([...
<python><sympy>
2024-12-30 02:01:48
1
1,193
jett chen
79,316,633
10,832,189
How to write the JavaScript Discorver Readers in Stripe?
<p>I'm developing an POS system and I would like to connect a Stripe physical reader, not a simulation. Here is my JavaScript codes for initializing, Redears discovering and connecting reader.</p> <pre><code>// Initialize Stripe Terminal const terminal = StripeTerminal.create({ onFetchConnectionToken: async () =&gt...
<javascript><python><stripe-payments>
2024-12-30 01:35:01
1
395
Mohamed Abdillah
79,316,554
11,505,680
matplotlib: share axes like in plt.subplots but using the mpl.Figure API
<p>I know how to make subplots with shared axes using the <code>pyplot</code> API:</p> <pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt (fig, axes) = plt.subplots(3, 1, sharex=True) </code></pre> <p><a href="https://i.sstatic.net/lGAz3vA9.png" rel="nofollow noreferrer"><img src="htt...
<python><matplotlib>
2024-12-30 00:00:17
1
645
Ilya
79,316,346
8,229,029
How to include exception handling within a Python pool.starmap multiprocess
<p>I'm using the metpy library to do weather calculations. I'm using the multiprocessing library to run them in parallel, but I get rare exceptions, which completely stop the program. I am not able to provide a minimal, reproducible example because I can't replicate the problems with the metpy library functions and b...
<python><error-handling><multiprocessing><metpy>
2024-12-29 21:06:23
1
1,214
user8229029
79,316,278
1,142,881
Is there a more elegant rewrite for this Python Enum value_of implementation?
<p>I would like to get a <code>value_of</code> implementation for the <code>StrEnum</code> (Python 3.9.x). For example:</p> <pre><code>from enum import Enum class StrEnum(str, Enum): &quot;&quot;&quot;Enum with str values&quot;&quot;&quot; pass class BaseStrEnum(StrEnum): &quot;&quot;&quot;Base Enum&quot...
<python><python-3.9>
2024-12-29 20:18:14
2
14,469
SkyWalker
79,316,088
11,277,108
Unable to create schema for Postgres database using sqlalchemy
<p>I'm able to create a schema via the command line using <code>CREATE SCHEMA test_schema;</code>.</p> <p>However, running the following code doesn't create a schema:</p> <pre><code>from sqlalchemy import create_engine from sqlalchemy.schema import CreateSchema def main(): conn_str = &quot;postgresql+psycopg2://&...
<python><postgresql><sqlalchemy><postgresql-14>
2024-12-29 18:06:59
1
1,121
Jossy
79,315,980
19,959,092
Problem Setting up a FAISS vector memory in Python with embeddings
<p>I'm trying to run an LLM locally and feed it with the contents of a very large PDF. I have decided to try this via a RAG. For this I wanted to create a vectorstore, which contains the content of the pdf. however, I have a problem here when creating, which I can not solve, because I am still quite new in this area.</...
<python><langchain><faiss><vectorstore>
2024-12-29 16:56:09
0
428
Pantastix
79,315,942
2,446,071
Performant Arrays of Objects in Python
<p>I am trying to create a sparse data structure in Python but am having a difficult time putting together the right set of primitives to get the job done.</p> <p>The data structure is a page-table, not unlike ones you find in modern computer architectures. The idea is that the data structure is sparse until it gets fi...
<python><numpy>
2024-12-29 16:29:38
1
4,918
sherrellbc
79,315,901
7,885,426
Clustering lines in bands
<p><strong>Little intro</strong></p> <p>I have data (link at the bottom), with on the y-axis the score, x-axis the position, for different labels. Now I want to know if there is one label that is &quot;significantly&quot; different than the others and the &quot;background&quot;. I have been playing with this the last f...
<python><cluster-analysis><outliers>
2024-12-29 15:55:39
1
1,840
CodeNoob
79,315,725
10,764,260
Context managers as attributes
<p>I am having a hard time to write clean code with context managers in Python without getting in a context manager hell. Imagine something like:</p> <pre class="lang-py prettyprint-override"><code>class A: def __init__(self): self.b = B() # where B is a context manager </code></pre> <p>This leaks now, because...
<python><contextmanager>
2024-12-29 14:00:05
1
308
Leon0402
79,315,687
473,347
How to Web Scrape Web Page Where Server is Replying to Get Request With Sort-of Redirected Post Request
<p>I am attempting to write a python script to perform some simple web scraping, but I am stumped by how to process (and understand) what the web server is passing me. When viewing the network traffic when submitting the get request in a browser, I see the server provides a 200 response and then the browser automatica...
<python><web-scraping>
2024-12-29 13:34:40
1
791
Mike
79,315,600
2,672,788
How to call OpenAi function from python
<p>I generated a <code>function</code> using OpenAI as below: <a href="https://i.sstatic.net/Z433ep6m.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Z433ep6m.png" alt="enter image description here" /></a></p> <p>So the function definition is (json schema):</p> <pre class="lang-json prettyprint-override"...
<python><function><openai-api>
2024-12-29 12:41:27
2
2,958
Babak.Abad
79,315,440
10,764,260
Combine Async with Parallism
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>async def run_task(...): ... semaphore = asyncio.Semaphore(cfg.concurrency_limit) async def run_single_sample(task_sample: TaskSample): async with semaphore: await run_agent(cfg, task_sample, cfg.output_di...
<python><python-asyncio>
2024-12-29 10:54:13
1
308
Leon0402
79,315,256
2,177,047
Profile selected functions in Python
<p>I can profile and visualize my entire application with:</p> <pre><code>python -m cProfile -o program.prof my_program.py snakeviz program.prof </code></pre> <p>Is it possible to write a decorator that will profile only some functions?</p> <p>In the end this would look like this:</p> <pre><code># This is the profiling...
<python><optimization><runtime><python-decorators><profiler>
2024-12-29 08:53:38
0
2,136
Ohumeronen
79,314,756
6,017,833
Limited to 5 RPM on Vertex AI
<p>I'm looking for some help on this nebulous issue please.</p> <p>I have this very simple script that invokes model generation on Vertex AI:</p> <pre class="lang-py prettyprint-override"><code>import vertexai from vertexai.preview.generative_models import GenerativeModel import asyncio PROJECT_ID = &quot;MY_PROJECT&q...
<python><google-cloud-platform><python-asyncio><google-cloud-vertex-ai>
2024-12-28 23:59:04
0
1,945
Harry Stuart
79,314,688
7,693,707
Cupy creating array using other variables
<p>I am trying to make a numpy/cupy interchange script, similar to <a href="https://github.com/rafael-fuente/diffractsim/blob/main/diffractsim/util/backend_functions.py" rel="nofollow noreferrer">this backend</a> implementation. Such that by using something like <code>from Util.Backend import backend as bd</code>, I ca...
<python><numpy><cupy>
2024-12-28 22:54:47
0
1,090
Amarth GΓ»l
79,314,406
4,451,315
"n_unique" aggregation using DuckDB relational API
<p>Say I have</p> <pre class="lang-py prettyprint-override"><code>import duckdb rel = duckdb.sql('select * from values (1, 4), (1, 5), (2, 6) df(a, b)') rel </code></pre> <pre class="lang-py prettyprint-override"><code>Out[3]: β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ a β”‚ b β”‚ β”‚ int32 β”‚ int32 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ 4 β”‚ β”‚...
<python><duckdb>
2024-12-28 19:09:13
1
11,062
ignoring_gravity
79,314,321
5,116,559
Create a new Polars column from a multiple choice of expressions by mapping values to a dictionary
<p>I want to use an expression dictionary to perform calculations for a new column. I have this Polars dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;col1&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;], &quot;x&quot;: [1,2,3], &quot;y&quot...
<python><dataframe><python-polars><coalesce>
2024-12-28 18:10:48
1
1,068
Babak Fi Foo
79,314,231
2,630,406
Restrict possible transformations for estimateAffinePartial2D
<p>I am using <code>estimateAffinePartial2D</code> to match stitch two images together. Sometimes I get a completely wrong result (scaled way too much, rotated way too much, ...) as my cameras are handheld, certain movements are impossible (like upside down, ...). Is there a way to restrict the possible transformations...
<python><opencv><computer-vision>
2024-12-28 17:14:33
0
933
perotom
79,313,973
14,667,788
Unable to run chromium in Python
<p>I would like to run chromium in my python script. Here is my test code:</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver from selenium.webdriver.chrome.service import Service service = Service(&quot;/usr/bin/chromedriver&quot;) driver = webdriver.Chrome(service=service) driver.get(...
<python><selenium-webdriver>
2024-12-28 14:43:48
1
1,265
vojtam
79,313,854
6,449,621
identify how many times same vehicle was captured in the provided video
<p>Working on Video analysis assignment where I need to capture how many times same vehicle was captured in given video.</p> <p>So far using YOLO11 was able to identify the vehicles such cars, bike, bus &amp; truck. Accordingly drawing rects as vehicles appears in the video frame.</p> <p>I could not make out, how to ma...
<python><machine-learning><computer-vision><object-detection><yolo>
2024-12-28 13:29:54
1
465
anandyn02
79,313,607
21,864,938
Why does this web scraper using Selenium not return the entire website?
<p>I tried to program a web scraper with Selenium for educational purposes that displays stock market data from β€˜The Wall Street Journal’. I want to know the number of advancing and declining issues from this link: <a href="https://www.wsj.com/market-data/stocks/us" rel="nofollow noreferrer">https://www.wsj.com/market-...
<python><selenium-webdriver><web-scraping>
2024-12-28 10:33:22
2
478
Lukinator
79,313,474
6,834,925
pybind11: how to add document the exported module?
<p>I have some c++ code, and I successfully export it to python module using pybind11. The code is:</p> <pre><code>class A { public: A() { } /** * @brief explanation from c++ */ int GetWidth() { return width; } private: int width = 0; }; PYBIND11_MODULE(module, m) ...
<python><c++><pybind11>
2024-12-28 08:47:07
1
962
Qiang Zhang
79,313,370
5,332,349
Discord.py MyClient(Commands.Bot) and commands.Greedy
<p><a href="https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#greedy" rel="nofollow noreferrer">https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#greedy</a></p> <p>I am following a tutorial that creates a child object of commands.bot in order to run a background task.</p> <p>I am...
<python><discord><discord.py>
2024-12-28 07:05:43
1
309
Reed
79,313,343
2,641,825
How to fix setuptools_scm._file_finders.git listing git files failed?
<p>I am using <code>pyproject.toml</code> to build a package. I use setuptools_scm to automatically determine the version number. I use python version <code>3.11.2</code>, setuptools <code>66.1.1</code> and setuptools-scm <code>8.1.0</code>.</p> <p>Here are the relevant parts of <code>pyproject.toml</code></p> <pre><co...
<python><setuptools><setuptools-scm>
2024-12-28 06:46:12
1
11,539
Paul Rougieux