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,647,636
2,307,570
How to get formula of matrix product from formulas of matrices?
<p>I have formulas defining matrices.<br> The result I want is the formula defining their matrix product.</p> <p>At no point do I want actual matrices. Those shown below are just for illustration.</p> <p>The examples I use are Pascal's triangle <strong>A</strong> and <a href="https://oeis.org/A038207" rel="nofollow nor...
<python><sympy><matrix-multiplication><symbolic-math>
2025-06-01 14:35:33
2
1,209
Watchduck
79,647,627
2,718,067
grid_search.fit() report exception with RAPIDS api
<p>Got exceptions from the code. Develop enviroment is: win10, WSL2, RAPIDS 24.02. Please help to check. I have puzzled for long time.</p> <blockquote> <p>Implicit conversion to a host NumPy array via <strong>array</strong> is not allowed, To explicitly construct a GPU matrix, consider using .to_cupy() To explicitly co...
<python><rapids>
2025-06-01 14:29:22
0
1,663
user2718067
79,647,350
3,170,530
Looking for an efficent JAX function to reconstruct an image from patches
<p>I have a set of images in (c, h, w) jax arrays. These arrays have been converted to (patch_index, patch_dim) arrays where patch_dim == c * h * w.</p> <p>I am trying to reconstruct the original images from the patches. Here is vanilla python code that works:</p> <pre class="lang-py prettyprint-override"><code>kernel ...
<python><machine-learning><deep-learning><computer-vision><jax>
2025-06-01 08:49:34
1
448
user3170530
79,647,470
3,904,031
Is there a way to turn off Python's "Did you mean...?" guessing feature appended to error messages?
<p>Since I upgraded my Python (to 3.12.2), error messages have become more difficult for me to read.</p> <p>I understand that this is a popular feature for many people, but for me it is not. It gives me more text to read through, and it causes me to loose my (coding) train of thought because it makes me to shift to con...
<python><python-3.x><runtime-error>
2025-06-01 08:36:59
1
3,835
uhoh
79,647,185
15,072,863
Llama_cookbook: why are labels not shifted for CausalLM?
<p>I'm studying the <a href="https://github.com/meta-llama/llama-cookbook" rel="nofollow noreferrer">llama_cookbok</a> repo, in particular their <a href="https://github.com/meta-llama/llama-cookbook/blob/main/getting-started/finetuning/quickstart_peft_finetuning.ipynb" rel="nofollow noreferrer">finetuning example</a>. ...
<python><large-language-model><llama><attention-model><fine-tuning>
2025-06-01 04:29:02
1
340
Dmitry
79,647,131
219,153
How to split NumPy array with dimensionality reduction?
<p>This script:</p> <pre><code>import numpy as np a = np.arange(8).reshape(2, 2, 2) b = np.split(a, 2) print(b[0].shape) </code></pre> <p>produces:</p> <pre><code>(1, 2, 2) </code></pre> <p>I would like to split array <code>a</code> into a list of constituent subarrays with shape <code>(2, 2)</code>, reducing their di...
<python><arrays><numpy>
2025-06-01 02:42:10
2
8,585
Paul Jurczak
79,647,006
13,706,389
Can't close psycopg ConnectionPool
<p>I tried <a href="https://www.psycopg.org/psycopg3/docs/advanced/pool.html#basic-connection-pool-usage" rel="nofollow noreferrer">this example</a> from the psycopg documentation:</p> <pre class="lang-py prettyprint-override"><code>from psycopg import conninfo from psycopg_pool import ConnectionPool from config impor...
<python><psycopg2><psycopg3>
2025-05-31 21:22:13
0
684
debsim
79,646,981
12,415,855
Opening site only possible in non-headless mode?
<p>i try to run the below code in headless-mode. In non headless-mode everything works fine.</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.web...
<python><selenium-webdriver><headless>
2025-05-31 20:52:27
1
1,515
Rapid1898
79,646,918
16,383,578
How to efficiently compute the exact value of prime counting function for n?
<p>I want to know the exact count of prime numbers no greater than n, without finding all these prime numbers first.</p> <p>I know of a very efficient method to find all primes no greater than n, using Sieve of Eratosthenes with Wheel Factorization, I use 2310-based wheel to skip all multiples of 2, 3, 5, 7, 11, so tha...
<python><algorithm><primes><number-theory>
2025-05-31 19:14:13
0
3,930
Ξένη Γήινος
79,646,778
948,866
How do you extract key/value from a function in a dict comprehension?
<p>I have a function <code>foo</code> that generates a key and value from a string. I want to use that function in a dict comprehension, but haven't figured out how to extract multiple values from a single iteration of the function.</p> <p>The catch is that <code>foo</code> could be expensive or stateful or executed re...
<python><dictionary-comprehension>
2025-05-31 16:16:18
4
3,967
Dave
79,646,439
9,818,388
Youtube video upload - issues with special characters
<p>Not able to resolve issues with special characters in title and description. I'm using official google example code to upload videos to youtube like below example:</p> <pre><code>python upload_video.py --file=&quot;DU.mp4&quot; --title=&quot;Rozporządzenie&quot; --description=&quot;Zapraszamy do odsłuchania nowej pu...
<python><youtube><upload><youtube-api>
2025-05-31 08:26:36
1
2,859
Szelek
79,646,367
806,160
Django + Celery + PySpark inside Docker raises SystemExit: 1 and NoSuchFileException when creating SparkSession
<p>I'm running a Django application that uses Celery tasks and PySpark inside a Docker container. One of my Celery tasks calls a function that initializes a SparkSession using getOrCreate(). However, when this happens, the worker exits unexpectedly with a SystemExit: 1 and a NoSuchFileException.</p> <p>Here is the rele...
<python><django><pyspark>
2025-05-31 06:06:10
1
1,423
Tavakoli
79,646,161
4,907,188
cannot open shared object file: No such file or directory with pybind11
<p>I have a python script <code>myscript.py</code>:</p> <pre><code>import pydmy as tp </code></pre> <p><code>pydmy</code> is my pybind11 wrapper dynamic library. <code>pydmy</code> will load another C++ library <code>libabc.so</code>. <code>libabc.so</code> is under the same directory as <code>pydmy</code>.</p> <ol> <l...
<python><dll><pybind11>
2025-05-30 22:32:02
0
626
Taitai
79,646,075
499,990
difflib.SequenceMatcher suddenly returns different similarity ratio without code or environment changes
<p>We're using Python’s difflib.SequenceMatcher to compare strings in a production system. Here's the simplified relevant code:</p> <pre><code>from difflib import SequenceMatcher similarity = SequenceMatcher( None, normalized_transcript, normalized_expected ).ratio() </code></pre> <p>Until 4:10 PM UTC to...
<python><openai-api><difflib><sequencematcher>
2025-05-30 20:45:53
1
16,482
MatterGoal
79,645,815
14,179,793
How to connect to Postgres docker container via python
<p>I am trying to use the postgresql docker container to create some integration tests but trying to connect fails. I added a password because if I do not I get a different error about it requiring a password.</p> <pre><code>import psycopg2 db = psycopg2.connect(dbname='pytest', user='pytest', password='pytest', host=...
<python><postgresql><docker-compose>
2025-05-30 16:39:09
1
898
Cogito Ergo Sum
79,645,772
1,246,366
TCP Messages starting with REST verb are not send
<p>I am making a very strange observation while using python sockets to send TCP data:</p> <p>When sending a TCP packet over a new connection that starts with &quot;PUT &quot;, &quot;POST &quot;, &quot;DELETE &quot; or &quot;GET &quot;, the messages are only send much later when the socket is closed.</p> <p>Some detail...
<python><sockets>
2025-05-30 16:01:21
0
368
Sloothword
79,645,726
1,361,752
How to disable automatic groupby widget in hvplot?
<p><code>hvplot</code> has a <code>groupby</code> parameter that lets you pick what variables to group the output by. This results in a widget you use to select the data subset you want to plot.</p> <p>If groupby is not specified, <code>hvplot</code> often infers what variables you want to group by. For example:</p> <p...
<python><python-xarray><hvplot>
2025-05-30 15:31:55
1
4,167
Caleb
79,645,489
4,281,664
Pylance is not recognizing "Methods:" section in a Python class docstring
<p>Consider this Python class with docstring:</p> <pre><code>class TestClass: ''' Summary line of docstring Additional lines of docstring. Attributes: attr1 (int): this is the desc of a public attribute attr2 (bool): another desc for a second attribute Methods: calculate ...
<python><visual-studio-code><docstring><pylance>
2025-05-30 12:49:53
0
421
Alberto Jiménez
79,645,306
1,860,805
How to stop converting into complex
<p>End of this calculation the result automatically turns into complex type in Python 3.</p> <pre><code>$ cat test.py #!/usr/bin/python curryield =-100.0 frequency = 2 coupons = 4 days_to_next = -4.0 days_period = 180.0 part1 = (100.0/((1+curryield/frequency)**(coupons-1+(days_to_next/days_period)))) print(&quot;Part ...
<python>
2025-05-30 10:31:37
1
523
Ramanan T
79,645,288
11,738,400
How to efficiently retrieve xy-coordinates from image
<p>I have an image <code>img</code> with 1000 rows and columns each.<br /> Now I would like to consider each pixel as x- and y-coordinates and extract the respective value.</p> <p>An illustrated example of what I want to achieve:</p> <p><a href="https://i.sstatic.net/Z4Iba79m.png" rel="nofollow noreferrer"><img src="ht...
<python><numpy><performance>
2025-05-30 10:20:25
1
612
mri
79,645,187
15,175,627
How can I check if `src` and `dst` are the same when writing with `rasterio.open()`
<p>I want to read a geotiff, reproject, and write to a new geotiff based on the code from the <code>rasterio</code> docs (<a href="https://rasterio.readthedocs.io/en/stable/topics/reproject.html" rel="nofollow noreferrer">https://rasterio.readthedocs.io/en/stable/topics/reproject.html</a>) (the actual transformation is...
<python><writefile><rasterio>
2025-05-30 09:16:12
0
511
konstanze
79,645,144
5,320,906
How can I extend an annotated type
<p>Using Python 3.10, I have a base type definition that I use in many models:</p> <pre class="lang-py prettyprint-override"><code>Alpha = Annotated[str, Field(pattern=r'[A-Za-z]')] </code></pre> <p>I want to create additional specialised types based on this type, for example by adding a <code>max_length</code> constra...
<python><python-typing><pydantic><pydantic-v2>
2025-05-30 08:36:38
0
56,990
snakecharmerb
79,645,053
5,320,591
The Type Point in geojson_pydantic is not hashable
<p>I'm using Python 3.11 and I am struggling a lot to understand this.</p> <p>When I try to access to the Swagger documentation of my service, in localhost, I have this error:</p> <pre><code>generate_definitions definitions_remapping = self._build_definitions_remapping() File \&quot;/app/.venv/lib/python3.11/site-p...
<python><swagger><geojson><pydantic>
2025-05-30 07:26:58
0
1,546
RobyB
79,645,043
595,305
limiting value for int in pyqtSignal?
<p><strong>NOT A DUPLICATE AS THIS INVOLVES A COMPLETELY SILENT ERROR</strong></p> <p>I have a signal which looks like this:</p> <pre><code>add_history_row_signal = QtCore.pyqtSignal(int, int) </code></pre> <p>The first int is a key for a dict, to retrieve a value. And in fact this int is the object id of a given objec...
<python><c++><qt><pyqt><signals-slots>
2025-05-30 07:18:46
0
16,076
mike rodent
79,645,029
12,520,740
Running pythonpy installed via pipx gives: ImportError
<h2>The problem</h2> <p>I recently tried installing pythonpy using <code>pipx</code>, but whenever I run any command using <code>py</code>, I see the following traceback:</p> <pre class="lang-bash prettyprint-override"><code>$ py '2-3' Traceback (most recent call last): File &quot;/home/m/.local/bin/py&quot;, line 5...
<python><python-3.x><pipx><python-py>
2025-05-30 07:05:40
1
1,156
melvio
79,644,972
5,657,705
Getting attribute error in Django BaseCommand- Check
<p>I am working on a tutorial project. The same code works for the instructor but doesn't work for me.</p> <p>I have a file for custom commands:</p> <pre><code>import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCo...
<python><django><django-testing><django-tests>
2025-05-30 06:06:01
0
1,113
The Bat
79,644,894
2,289,710
Python doctests for a colored text output
<p>Is it possible to write a docstring test for a function that prints out the colored text into the command line? I want to test only the content ignoring the color or to add somehow the information on color into the docstring. In the example below the test has failed, but it should not.</p> <p><strong>Example</strong...
<python><command-line><colors><docstring><doctest>
2025-05-30 04:22:26
1
3,894
freude
79,644,830
10,461,632
Password hashes do not match with bcrypt (python)
<p>I am trying to compare two passwords using bcrypt. The hashed password is stored in the database as a string. When I compare the two hashed passwords (the one from the database and the one from the user), I make sure they are both encoded, but the passwords still do not match.</p> <p>Why do the hashed passwords not ...
<python><python-3.x><bcrypt>
2025-05-30 02:57:04
1
788
Simon1
79,644,734
44,330
Why does inspect fail to get source file for classes in a dynamically-imported module?
<p><code>inspect.getsource()</code> and <code>inspect.getsourcefile()</code> can access source info for a function, but not for a class, when they are in a module that is imported dynamically with <code>importlib</code>.</p> <p>Here are two files, <code>thing1.py</code> and <code>thing2.py</code>:</p> <ul> <li><p><code...
<python><python-importlib><python-inspect>
2025-05-29 23:33:53
1
190,447
Jason S
79,644,621
7,479,675
Is it possible to use browser-use with undetected-chromedriver?
<p>I’m trying to drive an automated web search with the browser-use library, but I need to swap out the default Playwright for an undetected-chromedriver instance so that I can interact with pages guarded by reCAPTCHA (e.g. <a href="https://recaptcha-demo.appspot.com/recaptcha-v2-invisible.php" rel="nofollow noreferrer...
<python><browser-use>
2025-05-29 20:56:07
0
392
Oleksandr Myronchuk
79,644,068
4,235,960
Meta (Facebook) API - products - start_date and "Date of last edit" field
<p>I have been reading the following page of Meta (Facebook): <a href="https://developers.facebook.com/docs/marketing-api/reference/product-item/" rel="nofollow noreferrer">https://developers.facebook.com/docs/marketing-api/reference/product-item/</a> this is the page for products.</p> <p>There is a field <code>start_d...
<python><facebook><facebook-graph-api><facebook-marketing-api>
2025-05-29 14:23:46
0
3,315
adrCoder
79,643,973
13,946,204
How to check it an object is an instance of dict_itemiterator in python?
<p>I have a some library that is returning <code>dict_itemiterator</code> object.</p> <p>Since I'm working with multiple types of objects I need to know what is actual type of my object.</p> <p>So I found that it is possible to get <code>dict_itemiterator</code> using this code:</p> <pre class="lang-py prettyprint-over...
<python>
2025-05-29 13:29:55
1
9,834
rzlvmp
79,643,242
3,814,008
How do I create thread-safe asyncio background tasks?
<p>I have an event loop running in a separate thread from the main thread, and I would like to add a background task to this event loop from the main thread using the <code>asyncio.create_task</code> function.</p> <p>I am able to achieve this using the <code>asyncio.run_coroutine_threadsafe</code> function, but that en...
<python><multithreading><python-asyncio><event-loop>
2025-05-29 03:25:24
3
703
Yamen Alghrer
79,643,162
3,036,367
Non-integral optimizer parameters in scipy.stats.fit
<p>I am trying to fit a distribution to some data using <code>scipy.stats.fit</code>. I specifically need the <code>stats.nbinom</code> distribution to be fit using a non-integer value for parameter <code>n</code>.</p> <p>I've made this minimal example of what I'd like to achieve. I can't see what I've done incorrectly...
<python><scipy><scipy.stats>
2025-05-29 01:00:04
1
2,020
JasTonAChair
79,643,014
2,953,544
Can Pixi use locally installed Python libraries?
<p>I'm managing a Python project with Pixi, because I have both Conda and Pypi dependencies. I need to install arcpy, which is ArcGIS's Python API. It's a closed-source library, and it is only available from the Python installation that comes with ArcGIS Pro, a desktop program.</p> <p>So, my question is, can pixi add a...
<python><arcgis><arcpy><pixi-package-manager>
2025-05-28 21:20:46
1
468
AJSmyth
79,642,975
6,856,019
Discord py slash command only visible to certain people
<p>I've seen a few discord bots that have 'hidden' commands available to only server owners. I have searched the internet on how this but so far it's eluded me.</p> <p>I know I can add checks, but this doesn't hide the command from the slash command list.</p> <pre><code>/leaderboard View leaderboard /leave Tell bot to...
<python><discord><discord.py>
2025-05-28 20:36:47
1
551
Mike
79,642,829
15,006,061
Python urllib.request.urlopen with Bearer authentication in redirected request
<p>The following command successfully downloads an artifact file from a GitHub workflow run:</p> <pre><code>curl -L -H &quot;Authorization: Bearer ghp_XXXX&quot; -o arti.zip \ https://api.github.com/repos/OWNER/REPO/actions/artifacts/ID/zip </code></pre> <p>The following Python code fails, with the same URL and au...
<python><urllib><bearer-token>
2025-05-28 18:42:16
1
867
Thierry Lelegard
79,642,757
3,357,935
How do I make pandas.read_csv() parse one column as datetime while treating all others as strings?
<p>I am using <a href="https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>pandas.read_csv</code></a> to load a CSV file. I want to have my file read mostly as-is to avoid any <a href="https://stackoverflow.com/q/16988526/3357935">automatic data type conversions</a>, excep...
<python><python-3.x><pandas><dataframe><dtype>
2025-05-28 17:50:21
1
27,724
Stevoisiak
79,642,719
44,330
Why make cls a position-only argument in __init_subclass__?
<p>The <a href="https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__" rel="nofollow noreferrer">docs for the <code>__init_subclass__</code> hook</a> (see <a href="https://peps.python.org/pep-0487/#proposal" rel="nofollow noreferrer">PEP-0487</a> for background) give this example:</p> <pre><code>c...
<python><parameters><positional-argument>
2025-05-28 17:21:16
1
190,447
Jason S
79,642,441
1,900,950
Explicitly stating the type of a loop variable
<p>I'm quite new to Python (and its duck typing), but am currently working on a Python project that needs serious refactoring. In a <code>for</code> loop, I need to discriminate between items of a list based on their type, and call functions defined in the derived class. What is the Python way of doing this? Consider t...
<python><python-typing>
2025-05-28 14:31:29
0
346
hschmauder
79,642,222
10,886,283
How to compute the power spectral density of a vector-valued process without mirroring the autocorrelation function?
<p>I'm simulating a 2D Ornstein-Uhlenbeck process (Langevin equation for velocity), and I'm interested in computing the power spectral density (PSD) of the vector-valued velocity process.</p> <p>Following the Wiener–Khinchin theorem, I compute the velocity autocorrelation function (VACF) defined as:</p> <p>$$ R(\tau) =...
<python><scipy><fft><autocorrelation><spectral-density>
2025-05-28 12:36:01
1
509
alpelito7
79,641,847
1,866,038
Reducing PostgreSQL CPU load using sqlalchemy
<p>I am using a PostgreSQL database and a big pandas DataFrame (~3500 records) that has to be uploaded into one of the tables in the database.</p> <p>First, I have to test for existing records in the database and, afterwards, upload non existing ones.</p> <p>The problem is that the CPU gets heavily loaded and sometimes...
<python><pandas><postgresql><sqlalchemy>
2025-05-28 08:55:50
2
517
Antonio Serrano
79,641,660
2,829,863
Merge table cells in a column if the text of the cells is the same using python-docx library
<p>I am using python and the <a href="https://python-docx.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">python-docx</a> library to create tables in a docx file. I want to merge cell values in a column if the value in the previous row is the same as the current value. I also want to remove duplicate val...
<python><docx>
2025-05-28 06:54:25
1
787
Comrade Che
79,641,614
9,826,710
ModuleNotFoundError: No module named 'NSKeyedUnarchiver'
<p>I struggle with the error</p> <pre><code>ModuleNotFoundError: No module named 'NSKeyedUnarchiver' </code></pre> <p>which raises on import, after installing the module <a href="https://pypi.org/project/NSKeyedUnArchiver/" rel="nofollow noreferrer"><code>NSKeyedUnArchiver</code></a> via <code>pip</code>.</p> <p>Projec...
<python><python-3.x><pip><modulenotfounderror><nskeyedunarchiver>
2025-05-28 06:23:03
1
700
Abid
79,641,592
11,188,210
Hash function converted from JS to python hangs up on large strings
<p>I've been using this cyrb53 hash function in js from this answer: <a href="https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript">Generate a Hash from string in Javascript</a></p> <p>The idea is to create hashes from image strings like this:</p> <pre><code>data:image/png;base64,iVBORI...
<python>
2025-05-28 06:08:44
1
2,052
Phaelax
79,641,447
8,278,075
Running Uvicorn on Mac command line results in error uvicorn: error: unrecognized arguments
<p>When I run my FastAPI app with the Uvicorn command, the command line args are not recognized:</p> <pre class="lang-bash prettyprint-override"><code>(env) mydir$ uvicorn main:app --port 8000 --host 0.0.0.0 --reload ... uvicorn: error: unrecognized arguments: main:app --port 8000 --host 0.0.0.0 --reload ... </code></p...
<python><fastapi><argparse><uvicorn>
2025-05-28 03:08:25
2
3,365
engineer-x
79,641,403
188,331
Using evaluate library to evaluate BertScore only uses 1 busy GPU
<p>I'm using <code>evaluate</code> library to evaluate the <code>BertScore</code>. Here are my codes:</p> <pre><code>import evaluate bertscore = evaluate.load(&quot;bertscore&quot;) bertscore_result = bertscore.compute(predictions=[sentence], references=references_sentence) bertscore_avg = np.mean(bertscore_result[&quo...
<python><tensorflow><gpu><huggingface-evaluate>
2025-05-28 01:53:18
1
54,395
Raptor
79,641,325
1,754,273
win32com pywintypes.datetime in Pandas DataFrame
<p>I am using <code>win32com</code> to pull some data out of large excel files and am running into an issue with <code>pywintypes.datetime</code> and subsequent Pandas DataFrame creation. <code>DataBody = tbl.DataBodyRange()</code> gives a large tuple which I convert into a numpy array using <code>DataBody_array = np....
<python><pandas><numpy><win32com>
2025-05-27 23:26:08
1
5,554
Radical Edward
79,641,126
17,411,406
ModelViewSet does not overwrite DEFAULT_PERMISSION_CLASSES'
<p>Hello I'm working on making all urls requires user to be authenticate , but some urls i want them to be accessible by public, so i use <code>permission_classes = [AllowAny] </code> and <code>authentication_classes = ([]) </code> to overwrite default configurations it work in APIVIEW but not in <code>viewsets.Mo...
<python><django><django-rest-framework>
2025-05-27 19:56:23
2
307
urek mazino
79,641,119
13,860,719
How to broadcast operation to Numpy array of objects?
<p>Say I have a Numpy array of 500 lists with random sizes ranging from 0 to 9:</p> <pre><code>import numpy as np a = np.array([[i for i in range(np.random.randint(10))] for _ in range(500)], dtype=object) </code></pre> <p>Now I want to append a value <code>100</code> to indices <code>[0,10,20,30,40,50]</code>, I tried...
<python><arrays><list><numpy><array-broadcasting>
2025-05-27 19:51:52
1
2,963
Shaun Han
79,641,078
4,659,442
Pylance type error supplying SQLAlchemy NVARCHAR length
<p>Pylance is raising a type error when I include a length for the <code>NVARCHAR</code> column in the below script:</p> <pre class="lang-py prettyprint-override"><code>import urllib.parse import uuid import pandas as pd from sqlalchemy import create_engine from sqlalchemy.types import NVARCHAR from sqlalchemy.dialect...
<python><pandas><sqlalchemy><python-typing><pyright>
2025-05-27 19:13:03
0
727
philipnye
79,640,701
5,322,739
How can I specify Python type hint for a tuple whose first element is Callable and subsequent arguments are Any?
<p>How can I specify a Python type hint for a tuple whose first element is <code>Callable</code> and subsequent elements are <code>Any</code>?</p> <p>I tried <code>var: tuple[Callable, Any, ...]</code>, but got the following warning in VS Code:</p> <p><code>&quot;...&quot; is allowed only as the second of two arguments...
<python><python-typing>
2025-05-27 14:44:03
0
532
Geoff Alexander
79,640,638
29,295,031
how to pass RunnableConfig as arg when call langchain invoke method
<p>I'm trying to make a RAG application using langchain and streamlit,I trying to manage the chathistory within this app,but I came across an unexpeted issue, I will explain :</p> <pre><code>from langchain.schema.runnable import RunnableConfig from langchain.callbacks.tracers.run_collector import RunCollectorCallbackHa...
<python><streamlit><langchain><langsmith>
2025-05-27 14:00:19
1
401
user29295031
79,640,542
13,860,719
Fastest way to find the least amount of subsets that sum up to the total set in Python
<p>Say I have a dictionary of sets like this:</p> <pre><code>d = {'a': {1,2,8}, 'b': {3,1,2,6}, 'c': {0,4,1,2}, 'd': {9}, 'e': {2,5}, 'f': {4,8}, 'g': {0,9}, 'h': {7,2,3}, 'i': {5,6,3}, 'j': {4,6,8}} </code></pre> <p>Each set represents a subset of a total set <code>s = set(range(10))</code>. I would like an effic...
<python><algorithm><performance><dictionary><set>
2025-05-27 13:02:34
3
2,963
Shaun Han
79,640,494
1,779,895
Inexplicit random state in statsmodels holtwinters exponential smoothing?
<p>I am dealing with getting different results locally and in databricks most probably from fitting of <code>statsmodels.tsa.holtwinters.ExponentialSmoothing</code> . Based on the <a href="https://www.statsmodels.org/stable/generated/statsmodels.tsa.holtwinters.ExponentialSmoothing.html" rel="nofollow noreferrer">docum...
<python><statsmodels><random-seed><holtwinters><exponential-smoothing>
2025-05-27 12:37:25
0
817
Veliko
79,640,369
5,452,365
How to initialized dataframe without infering schema in polars?
<p>The current <code>pl.DataFrame(iterable, infer_schema_length=None)</code> or <code>pl.from_dicts(iterable, infer_schema_length=None)</code> is unreliable and documentation is also ambiguous (reads: The maximum number of rows to scan for schema inference. If set to None, the full data may be scanned (this is slow).)<...
<python><dataframe><python-polars>
2025-05-27 11:20:45
1
11,652
Rahul
79,640,192
4,083,037
PNG image to vector graphic conversion method with recognition of 1px lines?
<p>I am trying to find a way to convert a .png image with 1px lines to a vector file. The issue I am having is that my approaches are very inconsistent due to the thin lines I am trying to recognize.</p> <p>One idea was to use potrace, but I get very blobby results.</p> <p>The other was to use OpenCV, with the result t...
<python><opencv><vector-graphics><potrace>
2025-05-27 09:35:54
1
746
pcace
79,639,750
2,780,906
How can I assign iterables to columns in pandas dataframes?
<p>I have a dataframe containing rows which describe financial stocks. The following is a simplified version:</p> <pre><code>df = pd.DataFrame( { &quot;stockprice&quot;: [100, 103, 240], &quot;Characteristic1&quot;: [1, 3, 3], &quot;Characteristic2&quot;: [5, 7, 1], &quot;Characteri...
<python><pandas><dataframe>
2025-05-27 02:50:30
2
397
Tim
79,639,578
10,262,805
Why does adding token and positional embeddings in transformers work?
<p>In transformer models, I've noticed that token embeddings and positional embeddings are added together before being passed into the attention layers:</p> <pre><code>import torch import torch.nn as nn class TransformerModel(nn.Module): def __init__(self,vocab_size,emb_dim,context_length,dropout_rate): su...
<python><torch><large-language-model><embedding><transformer-model>
2025-05-26 21:21:11
0
50,924
Yilmaz
79,639,543
2,153,235
Test for multiple variables in locals().keys() fails
<p>I am testing the existence of local variables <code>LatLim</code> and <code>LongLim</code> at the Spyder console:</p> <pre><code>&gt;&gt;&gt; LatLim = (36.033333,36.2333) &gt;&gt;&gt; LongLim = (-5.5333,-5.25) &gt;&gt;&gt; locals().keys() dict_keys(['__name__', '__builtin__', ... 'LatLim', 'LongLim', ... ]) </code><...
<python><dictionary><local-variables>
2025-05-26 20:31:24
0
1,265
user2153235
79,639,410
12,468,387
Low RPS when perfomance testings django website
<p>I have a code like this that caches a page for 60 minutes:</p> <pre><code>import os import time from django.conf import settings from django.core.cache import cache from django.core.mail import send_mail from django.contrib import messages from django.http import FileResponse, Http404, HttpResponse from django.short...
<python><django><performance><gunicorn><wsgi>
2025-05-26 18:11:31
1
449
Denzel
79,639,365
4,375,983
Trouble with installing uv subpackages within monorepo
<h2>Context</h2> <p>I'm setting up a Python monorepo using uv for dependency management. When I run <code>uv sync</code> in the root directory, only the root package's dependencies are installed - none of the subpackages' dependencies are being installed.</p> <p>I'm building a data platform monorepo using Python 3.12 a...
<python><uv>
2025-05-26 17:30:34
1
2,811
Imad
79,639,259
9,915,497
Using PVLIB to computer weather adjusted expected generation
<p>I am attempting to use PVLIB to compute Weather-Adjusted Expected Generation hourly for a 24 hours.</p> <p>However, the function I have used is not working well and I am looking to figure out why. The data being used is from the previous day. The input to the function has GHI, Air Temp, &amp; Wind Temp at sampling ...
<python><pvlib><solar>
2025-05-26 15:57:46
0
415
Kris
79,639,089
497,649
How to add tooltips to the column headers of a DataGrid table?
<p>Given the UI component as defined in</p> <p><a href="https://shiny.posit.co/py/components/outputs/data-grid/" rel="nofollow noreferrer">https://shiny.posit.co/py/components/outputs/data-grid/</a></p> <p>how to add a tooltip to each column header, or a subset of?</p>
<python><tooltip><py-shiny>
2025-05-26 14:19:40
1
640
lambruscoAcido
79,639,054
1,430,550
Access states as plain Python value for serialization
<p>I am using the Python reflex package to build a frontend (<a href="https://github.com/reflex-dev/reflex" rel="nofollow noreferrer">https://github.com/reflex-dev/reflex</a>). I am trying to serialize the state values on a button click, which does not seem to work as expected. The values seem to be encapsulated in som...
<python><python-reflex>
2025-05-26 13:52:10
1
2,791
toobee
79,639,008
18,220,526
Byte Shifting Error White Reading Safetensor File in C
<p>I'm trying to read safetensors file in C. As a read on Huggingface's documentation, I'm taking first 8 byte of file for header size;</p> <pre class="lang-c prettyprint-override"><code>... uint64_t header_size = 0; int read_header_size = fread(&amp;header_size, sizeof(uint64_t), 1, fp); ... </code></pre> <p>And after...
<python><c><keras><io><safe-tensors>
2025-05-26 13:24:41
0
342
Ömer Faruk Demirel
79,638,943
15,163,418
How to globally configure just on Windows to run and edit scripts using short aliases with automatic interpreter detection?
<p>I'm trying to globally configure <a href="https://github.com/casey/just" rel="nofollow noreferrer"><code>just</code></a> on my Windows machine to simplify running and editing scripts from anywhere using short aliases.</p> <h3>Folder Structure</h3> <p>I have a folder <code>D:\Scripts</code> with subfolders containing...
<python><powershell><just>
2025-05-26 12:53:27
1
541
Raghavan Vidhyasagar
79,638,927
6,473,092
Alphalens get_clean_factor_and_forward_returns throws Length mismatch: Expected axis has 34 elements, new values have 36 elements
<p>I'm using alphalens.utils.get_clean_factor_and_forward_returns() to compute forward returns from a factor series and price DataFrame. But I'm hitting the following error:</p> <pre><code>ValueError: Length mismatch: Expected axis has 34 elements, new values have 36 elements </code></pre> <p><strong>My Input Data:</st...
<python><time-series><multi-index><valueerror><quantitative-finance>
2025-05-26 12:41:01
0
394
Aboriginal
79,638,800
10,846,467
How Ray async actors handle calls to sync methods
<p>I'm working with Ray async actors and I want to understand exactly what happens—at a deep technical level—when a synchronous method is called on such an actor.</p> <p>I know that calling a synchronous method will block, but am looking for clarity on how exactly this blocking occurs within the actor's architecture.</...
<python><multithreading><python-asyncio><distributed-computing><ray>
2025-05-26 11:00:13
2
893
hegash
79,638,787
16,405,935
Plotly dashboard logout after refreshing page
<p>I'm trying to make a Dashboard with Login, Register and Dashboard with Navbar and Tabs. With below code everything working well but I have a problem that if I refreshed page, Dashboard will return to login screen.</p> <pre><code>from dash import Dash, dcc, html, Input, Output, State, ctx import dash_mantine_componen...
<python><plotly><plotly-dash>
2025-05-26 10:49:39
0
1,793
hoa tran
79,638,749
607,407
How do I tell tensorflow to throw an error if I am trying to do a non-differentiable operation on a variable?
<p>I am learning tensorflow and spent a good amount of time trying to find what is causing this error:</p> <pre><code>No gradients provided for any variable. </code></pre> <p>In the end I tracked that it was caused by using <code>argmax</code> at the very start of my gradient calculation.</p> <p>Is there some sort of g...
<python><tensorflow><neural-network><gradient-descent>
2025-05-26 10:24:19
0
53,877
Tomáš Zato
79,638,747
5,443,120
How to join/map a polars dataframe to a dict?
<p>I have a polars dataframe, and a dictionary. I want to map a column in the dataframe to the keys of the dictionary, and then add the corresponding values as a new column.</p> <pre><code>import polars as pl my_dict = { 'a': 1, 'b': 2, } my_df = pl.DataFrame({'region': ['a', 'b', 'a']}) </code></pre> <pre><c...
<python><dataframe><dictionary><python-polars><polars>
2025-05-26 10:22:07
1
4,421
falsePockets
79,638,659
247,696
What tools use the .python-version file?
<p>Heroku recommmends including a file named <code>.python-version</code> in the project directory, with contents that specify a Python version, like this:</p> <pre><code>$ cat .python-version 3.13 </code></pre> <p><a href="https://devcenter.heroku.com/articles/python-runtimes" rel="nofollow noreferrer">Heroku's docume...
<python>
2025-05-26 09:29:02
1
153,921
Flimm
79,638,455
12,045,291
Torch: how to insert a tensor into another tensor at certain index
<p>I have a padded tensor <strong>X</strong> with shape <em>(B, T1, C)</em> and a padded tensor <strong>Y</strong> with shape <em>(B, T2, C)</em>, I also know the sample lengths <strong>L</strong> for <strong>X</strong>. I want to insert the samples of <strong>X</strong> into <strong>Y</strong> at certain index <em>I</...
<python><indexing><pytorch><tensor>
2025-05-26 07:06:05
1
412
junhuizh
79,638,441
172,131
Suds throwing exception on "type not found"
<p>We are using <a href="https://github.com/suds-community/suds" rel="nofollow noreferrer">SUDS</a> v1.1.1 and recently starting getting a &quot;Type not found&quot; exception as the response to a request contains a field not in the wsdl. I tried initializing the client as follows but the exception is still occurring:<...
<python><django><suds>
2025-05-26 06:57:03
1
20,218
RunLoop
79,638,347
607,407
How to convert discrete choices (of a color) from neural network output to colors directly in tensorflow?
<p>Context: I am learning to use tensorflow and want to do a simple experiment where I provide a neural network with 4 color choices for each pixel. The network should learn to pick the best colors from choices available for each pixel to represent the image it is given. Basically, a dithering neural network.</p> <p>I ...
<python><numpy><tensorflow><keras><neural-network>
2025-05-26 05:29:41
0
53,877
Tomáš Zato
79,638,169
3,599,283
osxphoto photo.export(testDIR) does not output anything
<p><strong>NOTE</strong>: Description changed. Previous problem of photodb.export() is null issue. Export seems to be per photo.export() but does not seem to be outputing any image.</p> <hr /> <p>Why is photo.export() not working.</p> <p>Using <a href="https://pypi.org/project/osxphotos/" rel="nofollow noreferrer"><c...
<python><iphone><image><photo>
2025-05-26 00:26:36
0
1,267
frankr6591
79,638,103
10,262,805
Why is attention scaled by sqrt(d_k) in Transformer architectures?
<p>I have this code in transformer model:</p> <pre class="lang-py prettyprint-override"><code>keys = x @ W_key queries = x @ W_query values = x @ W_value attention_scores = queries @ keys.T # keys.shape[-1]**0.5: used to scale the attention scores before applying the softmax attn_weights = torch.softmax(attention_scor...
<python><torch><transformer-model><attention-model>
2025-05-25 21:48:12
0
50,924
Yilmaz
79,638,044
19,293,506
How to insert Text+ clips on specific video tracks using DaVinci Resolve Python API?
<p>I'm working on a DaVinci Resolve automation project where I want to create a dialogue-style video. The idea is to overlay lines of dialog (generated audio and corresponding text) using <strong>Text+ titles</strong> programmatically through the Resolve scripting API.</p> <h3>What I'm trying to do:</h3> <ul> <li>I hav...
<python><python-3.x><davinci-resolve>
2025-05-25 20:29:14
1
631
kawa
79,637,884
1,719,931
Pylance doesn't like calling `[]` on a dict-inherited class
<p>PyAlex has the class <a href="https://github.com/J535D165/pyalex/blob/1517794516571b45ae345a842e6dcdf55ff291dd/pyalex/api.py#L277" rel="nofollow noreferrer">OpenAlexEntity</a>:</p> <pre class="lang-py prettyprint-override"><code>class OpenAlexEntity(dict): &quot;&quot;&quot;Base class for OpenAlex entities.&quot...
<python><python-typing><pyright><pyalex>
2025-05-25 16:54:30
2
5,202
robertspierre
79,637,820
12,102,460
Dynamically parsing API response into the correct types with msgspec
<p>Below is a toy example I am unable to get working. How to properly configure msgspec so it will automatically select the correct types (structs)? I can't change the JSON input as it it something that I don't have any control over. I provided 2 examples how that JSON may look like: <code>image</code> or <code>video</...
<python><msgspec>
2025-05-25 15:37:31
1
1,135
miran80
79,637,562
29,295,031
How to remove the <think> tag in reasoning model DeepSeek responses
<p>I'm using deepseek llm for my AI app, the responses will include its thinking process.</p> <p>It looks something like this: <a href="https://i.sstatic.net/Yjcc6R9x.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Yjcc6R9x.png" alt="enter image description here" /></a></p> <p>the code generate the respo...
<python><langchain><large-language-model><deepseek>
2025-05-25 10:13:06
2
401
user29295031
79,637,492
5,276,890
Use tkinter in an existing window
<p>I have an existing open window, created by SDL 2 in C/C++. I would like the process to call a python script (using Boost/Python) to add some GUI elements to it.</p> <p>Here's a non-working example:</p> <pre class="lang-py prettyprint-override"><code>import sys import sdl2 import sdl2.ext import tkinter as tk from t...
<python><tkinter><sdl-2>
2025-05-25 08:18:01
2
1,729
Roy Falk
79,637,340
1,034,974
obtaining column from another shard using jax.lax.gather()
<p>I'm trying to distribute large computation to multiple shards using jax. I have 2x2 tiles of shards. Each shard has 3x3 array (with distinct integers), e.g. in shard (0,0):</p> <pre><code>x = jnp.array([[40, 54, 70], [14, 3, 94], [44, 54, 88]]) </code></pre> <p>and in shard (1,0):</p> <pre><code>x = jnp.array([[50,...
<python><mesh><jax>
2025-05-25 03:22:24
0
348
Terry
79,637,323
3,636,292
Python in MS excel: show the output dataframe
<p>I have a dataframe which I filtered and stored. I can use the filtered dataframe to do calculations. But, I cannot use it as a table in the excel.</p> <p>I want to show the filtered dataframe in the excel file. How to do that?</p> <p>Example:</p> <pre><code>df_original = xl(&quot;G4:H12&quot;, headers=True) conditio...
<python><excel>
2025-05-25 02:29:30
1
1,714
Neeraj Hanumante
79,637,322
388,506
How to dynamically adjust the selection?
<p>I've been trying to do these, but as I've browsed the answers, most of these problem ended up with deprecated one, or simply no solution.</p> <pre class="lang-py prettyprint-override"><code>job_id = fields.Many2one('inw_asset.job_orders', string='Service request', required=True, store=True) owner_id = fields.Many2on...
<python><odoo><odoo-18>
2025-05-25 02:17:18
1
2,157
Magician
79,637,243
2,386,113
How to display an image in a GUI using Trame, Vuetify
<p>I am new to <a href="https://kitware.github.io/trame/examples/" rel="nofollow noreferrer">Trame and Vuetify</a>. I need to show an image in the GUI. The GUI would run on a localhost. My MWE is given below:</p> <pre><code>from trame.app import get_server from trame.widgets import html, vuetify, vtk as vtk_widgets fro...
<python><vue-component><vuetify.js><trame>
2025-05-24 23:17:18
0
5,777
skm
79,637,226
82,287
Has handling of escape characters in quoted strings changed between Python 3.10 and 3.13?
<p>I have a program that works under Python 3.10.2 Windows that contains a line like this:</p> <pre><code>outfilename = outpathname+&quot;\cfile.txt&quot; </code></pre> <p>outfilename ends up looking like c:\some\path\cfile.txt&quot;</p> <p>This code runs clean on 3.10.2.</p> <p>I moved this code to another Windows sys...
<python><escaping>
2025-05-24 22:41:10
0
2,033
tim11g
79,637,061
784,804
Creating nested JSON objects from a flat Python object using Marshmallow and SQLAlchemy
<p>Given a simple model (in reality SQLAlchemy):</p> <pre class="lang-py prettyprint-override"><code>class Thing(): name: str attr1: int attr2: str </code></pre> <p>How would I write the associated Marshmallow Schema class such that it produced JSON like this - ideally <em>without</em> using fields.Method so that I ...
<python><marshmallow>
2025-05-24 18:22:20
1
431
Umm
79,636,956
17,411,406
setup dj_rest_auth and all allauth not working
<p>Hello i'm trying to setup dj_rest_auth and allauth with custom user model for login for my nextjs app but it seems not working the backend part</p> <p>besides it not working i get this warning</p> <pre><code>/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:228: UserWarning: app_setti...
<python><django><dj-rest-auth>
2025-05-24 16:10:01
1
307
urek mazino
79,636,897
29,295,031
UserWarning: Importing verbose from langchain root module is no longer supported
<p>I'm using <code>langchain==0.1.9</code> with streamlit and python <code>3.11</code>,when I try to run the streamlit app I got this error :</p> <pre><code>C:\\rag-groq-strteamlit\RAG-PROD\rag\Lib\site-packages\langchain\__init__.py:29: UserWarning: Importing verbose from langchain root module is no longer supported. ...
<python><streamlit><langchain>
2025-05-24 15:09:30
0
401
user29295031
79,636,672
14,909,621
If you add _metadata to a custom subclass of Series, the sequence name is lost when indexing
<p><kbd>pandas 2.2.3</kbd></p> <p>Let’s consider two variants of defining a custom subtype of <code>pandas.Series</code>. In the first one, no <a href="https://pandas.pydata.org/pandas-docs/stable/development/extending.html#define-original-properties" rel="nofollow noreferrer">custom properties</a> are added, while in ...
<python><pandas>
2025-05-24 10:30:33
1
7,606
Vitalizzare
79,636,582
3,427,866
Python lxml xpath not working on some elements
<p>I'm having trouble extracting a specific element text from a soap response. Other elements seems to be working fine.</p> <p>I have tried the following:</p> <pre><code>Python 3.13.3 (main, Apr 8 2025, 13:54:08) [Clang 16.0.0 (clang-1600.0.26.6)] on darwin Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&q...
<python><xml><lxml><elementtree>
2025-05-24 08:48:52
2
1,743
ads
79,636,426
2,233,608
How to type a generic callable in python
<p>I am trying to do something like this:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Callable, Coroutine from typing import Any, Generic, TypeVar CRT = TypeVar(&quot;CRT&quot;, bound=Any) class Command(Generic[CRT]): pass CommandHandler = Callable[[Command[CRT]], Coroutine[Any, A...
<python><python-typing><mypy>
2025-05-24 04:09:36
2
1,178
niltz
79,636,345
1,135,775
Finding shifts required between two arrays elements
<p>I have two arrays, and I am trying to find the displacement for each elements to make them match. An example:</p> <pre><code>a = np.array([1, 0, 2, 0, 0, 1, 0, 2, 0, 0, 1, 0, 2, 0, 0 ] ) b = np.array([2, 0, 0, 1, 0, 2, 0, 0, 1, 0, 2, 0, 0, 1, 0] ) # expected c = np.array ([3, 0, 2, 1, 0, 2, 0, 2, 1, 0, 2, 0,2, 1, 0...
<python><arrays><numpy><scipy>
2025-05-24 01:26:21
4
739
Mansour
79,636,250
2,662,901
QueueListener breaks logging level filter?
<p>It appears that <code>logging.handlers.QueueHandler</code>/<code>.QueueListener</code> is breaking the <code>.setLevel</code> of an attached <code>logging.FileHandler</code> in Python 3.12.9 on Windows.</p> <p>Running the following minimal example results in both INFO and WARNING messages getting into the <code>Test...
<python><logging><python-multiprocessing>
2025-05-23 22:06:01
1
3,497
feetwet
79,636,095
9,818,388
Coqui-ai TTS in Jenkins job
<p>Trying to use Coqui-ai TTS in Jenkins job, and Im getting below err:</p> <pre><code>C:\ProgramData\Jenkins\.jenkins\workspace\Dziennik\scripts&gt;python tts.py --input_text_file_path DU/2025/658 Traceback (most recent call last): File &quot;C:\ProgramData\Jenkins\.jenkins\workspace\Dziennik\scripts\tts.py&quot;, ...
<python><jenkins><artificial-intelligence><text-to-speech><coqui>
2025-05-23 19:25:25
1
2,859
Szelek
79,635,993
11,515,528
Pandas insert row if value is missing
<p>Simple one but tired brain is letting me see the solution. I can not pivot because there are repeat values in 'number'.</p> <pre><code>pd.DataFrame({'KeyID':[1,1,1,1,2,2,2,3,3,3], 'number':['a','a','c','d','a','b','c','a','b','c']}) </code></pre> <p>I need each KeyID to have a 'd' if it does not then a row with NAN ...
<python><pandas>
2025-05-23 17:41:48
3
1,865
Cam
79,635,896
3,696,153
How to mimic Python's dict.items() functionality in a custom class
<p>In Python, I am creating a quasi-dictionary like thing (custom class that looks or acts like a dictionary in many ways, but is not a <code>dict</code> subclass).</p> <p>I would like to support the standard <code>foo.items()</code> found in a dictionary</p> <p>But what I do not know is the <code>self.__magic__()</cod...
<python><dictionary>
2025-05-23 16:26:04
0
798
user3696153
79,635,887
11,609,834
Why is python trace not completely written to a log, and how to fix?
<p>I am running a VM on Google Cloud Compute Engine with the following (MRE) script:</p> <pre><code>#!/bin/bash set -e exec &gt; /var/log/startup-script.log 2&gt;&amp;1 source /opt/env/bin/activate python3 main.py </code></pre> <p>In some cases, the python script has failed with a long trace. When it does, the trace it...
<python><bash><google-cloud-compute-engine>
2025-05-23 16:20:38
1
1,013
philosofool