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,359,253
13,259,162
Jupyter gives 404 errors on Debian and I'm unable to open any notebook
<p>I'm currently unable to use jupyter on my Dell laptop that runs Debian 12. I'm running jupyter lab in a python virtualenv.</p> <p>When I run <code>jupyter lab</code> I first get the following error message that is recurrent:</p> <pre><code>[W 2025-01-15 18:44:52.720 ServerApp] 404 GET /api/collaboration/room/Jupyter...
<python><jupyter><virtualenv><http-status-code-404>
2025-01-15 17:57:28
1
309
NoΓ© Mastrorillo
79,359,228
2,531,068
Matplotlib bar graph incoherent behavior when using bottom and height parameters
<p>I am trying to plot a bar chart where for each day, used as X axis, we see the activity between different periods of time as a bar going from the time of the start of the activity to the time of the end of the activity. So Y axis goes from 0 to 24, and for example I could have a bar from 1AM to 2AM and a second bar ...
<python><matplotlib>
2025-01-15 17:46:22
1
609
Loufylouf
79,359,213
2,731,076
Efficient parsing and processing of millions of json objects in Python
<p>I have some working code that I need to improve the run time on dramatically and I am pretty lost. Essentially, I will get zip folders containing tens of thousands of json files, each containing roughly 1,000 json messages. There are about 15 different types of json objects interspersed in each of these files and so...
<python><json><python-asyncio><python-multiprocessing>
2025-01-15 17:38:39
2
813
user2731076
79,359,116
7,906,206
Issues with pip install pyodbc SyntaxError: invalid syntax
<p>I am trying to run pip install pyodbc using Visual Studio Code Terminal and it says syntax error. I am doing exactly as Microsoft documentation here:</p> <p><a href="https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-1-configure-development-environment-for-pyodbc-python-development?view=sql-server-ver1...
<python>
2025-01-15 17:03:21
1
1,216
Immortal
79,358,829
1,540,967
How can I make "ruff check" assume a specific Python version for allowed syntax?
<p>I am on Linux, created a Python 3.9 venv, installed ruff in the venv, wrote this code:</p> <pre class="lang-py prettyprint-override"><code>def process_data(data: list[int]) -&gt; str: match data: case []: return &quot;No data&quot; case [first, *_] if (average := lambda: sum(data) / l...
<python><ruff>
2025-01-15 15:34:07
1
389
Sebastian Elsner
79,358,781
1,358,603
`OSError: [Errno 24] Too many open files` with python3.12.3 multiprocessing on ubuntu 24.04 terminal
<p>The following code always gives me the error <code>OSError: [Errno 24] Too many open files</code> when reaching 508 processes executed, which means every process leaves two file descriptors open, and then I reach the system's limit:</p> <pre><code>from multiprocessing import Process def do_job(task): print(&quo...
<python><ubuntu><multiprocessing>
2025-01-15 15:21:28
1
757
Kyriakos
79,358,688
788,349
Expensive django calculation needs to run on model change
<p>I am working on a django application that has a model with a field that needs to be calculated when the model changes. The calculation itself is relatively expensive (1+ seconds) especially if/when this field is recalculated for a large queryset. It is important that this field is recalculated immediately following ...
<python><django>
2025-01-15 14:58:36
1
513
acmisiti
79,358,613
7,007,547
Additional Python Files in azure Function
<p>I have a python Funktion <code>function_app.py</code>(triggered every minute) in Azure Like this</p> <pre><code>import azure.functions as func import logging app = func.FunctionApp() @app.timer_trigger(schedule=&quot;0 */1 * * * *&quot;, arg_name=&quot;myTimer&quot;, run_on_startup=False, use_monitor...
<python><azure><azure-functions>
2025-01-15 14:35:07
2
1,140
mbieren
79,358,567
1,520,991
Polars - Replace letter in string with uppercase letter
<p>Is there any way in polars to replace character just after the <code>_</code> with uppercase using regex replace? So far I have achieved it using <a href="https://docs.pola.rs/api/python/version/0.19/reference/expressions/api/polars.Expr.map_elements.html#polars.Expr.map_elements" rel="nofollow noreferrer">polars.Ex...
<python><string><python-polars><camelcasing><snakecasing>
2025-01-15 14:22:43
3
3,125
dikesh
79,358,525
10,958,326
How to resolve vscode python REPL ModuleNotFoundError
<p>In vscode I’m encountering a <code>ModuleNotFoundError</code> when trying to import a module (<code>src</code>) located in my project workspace folder in a Python REPL. Here's the situation:</p> <ol> <li><p>When I run:</p> <pre class="lang-py prettyprint-override"><code>import os os.getcwd() </code></pre> <p>I get t...
<python><visual-studio-code><read-eval-print-loop>
2025-01-15 14:10:28
1
390
algebruh
79,358,216
4,875,641
Python v3.13 has broken Email delivery due to an SSL change
<p>I have only seen one online report of this to date, but perhaps others have run into this and found a way around it. Email delivery using the Python email package has worked in prior versions of Python, but fails in version 3.13. The problem is not with the email package but with SSL.</p> <p>It appears that version ...
<python><email><ssl>
2025-01-15 12:28:54
1
377
Jay Mosk
79,358,206
2,114,932
get value from current row in rolling window
<p>Given the following data structure</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( { &quot;order_id&quot;: [&quot;o01&quot;, &quot;o02&quot;, &quot;o03&quot;, &quot;o04&quot;, &quot;o10&quot;, &quot;o11&quot;, &quot;o12&quot;, &quot;o13&quot;], &quot;cu...
<python><python-polars>
2025-01-15 12:26:44
2
1,817
dpprdan
79,358,078
2,287,458
Take unique values horizontally across a Polars DataFrame to create a new string column
<p>I have this dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.from_repr(&quot;&quot;&quot;shape: (4, 3) β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β” β”‚ ccy1 ┆ ccy2 β”‚ β”‚ --- ┆ --- β”‚ β”‚ str ┆ str β”‚ β•žβ•β•β•β•β•β•β•ͺ══════║ β”‚ USD ┆ USD β”‚ β”‚ EUR ┆ USD β”‚ β”‚ EUR ┆ EUR β”‚ β”‚ USD ┆ JPY β”‚ β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜ &quot;&quot...
<python><dataframe><python-polars>
2025-01-15 11:38:37
0
3,591
Phil-ZXX
79,357,992
2,018,094
Crashing matplotlib with special chars in strings
<p>matplotlib crashes when a Pandas Serie contains specific special chars in a string, in my case <code>$$</code>.</p> <pre><code>import matplotlib.pyplot as plt import random import pandas as pd list_= 'abcdefghijklmnopqrstuvwxyz' l = pd.Series() for i in range(0,100): l[i] = random.choice(list_) l[50] = '$$' l.v...
<python><pandas><matplotlib><special-characters>
2025-01-15 11:13:04
2
1,012
Jb Drucker
79,357,784
5,211,833
Generate a PDF from Excel through Python, without opening Excel
<p>We generate PDFs from Excel through Python. We currently do this using the Win32com library as per <a href="https://stackoverflow.com/a/66422276/5211833">this Stack Overflow answer</a>. In summary, we explicitly call <code>o = win32com.client.Dispatch(&quot;Excel.Application&quot;)</code>, opening an actual Excel in...
<python><excel><pdf-generation>
2025-01-15 10:08:54
1
18,235
Adriaan
79,357,654
6,930,340
Polars write_excel: rotate some header columns
<p>When using <code>pl.write_excel</code>, I am looking for a possibility to rotate SOME header columns by 90Β°.</p> <p>I am applying a bunch of input arguments provided by <code>pl.write_excel</code> in order to style the exported dataframe. Among others, I am using <code>header_format</code>.</p> <pre class="lang-py p...
<python><excel><python-polars><xlsxwriter><polars>
2025-01-15 09:24:45
1
5,167
Andi
79,357,541
2,000,548
CUDA_ERROR_NO_DEVICE in WSL2
<p>I am trying to run cuML in WSL2 in Windows.</p> <ul> <li>Ubuntu 22.04</li> <li>amd64</li> <li>NVIDIA RTX A2000 8GB Laptop GPU</li> <li>CUDA 12.6</li> </ul> <p><strong>main.py</strong></p> <pre class="lang-py prettyprint-override"><code>import logging import cudf from cuml.ensemble import RandomForestClassifier from...
<python><cuda><cuml><wsl2>
2025-01-15 08:43:30
1
50,638
Hongbo Miao
79,357,409
7,945,506
How to patch a conditionally imported module in pytest?
<p>I have Python code that works locally and when run on Databricks. For saving the results, a different function is used depending on where to code is run.</p> <p>On Databricks, several things are automatically initialized when running a notebook; among these is the <code>pyspark</code> library.</p> <p>Therefore, in o...
<python><mocking><databricks><python-unittest>
2025-01-15 07:48:31
0
613
Julian
79,356,820
7,447,542
SSIS Process Task Return Value
<p>I have python script saved in server1 which returns code 0 on success and 1 on failure. And I'm calling this python script from server2 via SSIS execute process task.</p> <p><a href="https://i.sstatic.net/LhCfKWcd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LhCfKWcd.png" alt="enter image descripti...
<python><ssis><sql-server-data-tools>
2025-01-15 01:23:21
0
424
Nikhil Ravindran
79,356,622
886,895
Access files in the directory running the conan create command
<p>Trying to create a conan (v2.11) package from a zip archive to store in a gitlab conan registry. However in my conanfile.py I can't seem to copy or access files from the directory where I'm running conan as it appears to have set the current directory to within the .conan2/p/ cache directory structure.</p> <p>These ...
<python><c++><package-managers><conan>
2025-01-14 22:59:08
1
1,926
simgineer
79,356,278
1,737,830
Merging lists of dictionaries based on nested list values
<p>I'm struggling to create a new list based on two input lists. Here's an example:</p> <pre class="lang-py prettyprint-override"><code>data_1 = [ { &quot;title&quot;: &quot;System&quot;, &quot;priority&quot;: &quot;medium&quot;, &quot;subtitle&quot;: &quot;mason&quot;, &quot;files&quot;: [ {&qu...
<python><python-3.x>
2025-01-14 20:13:39
2
2,368
AbreQueVoy
79,356,143
8,547,986
How to narrow types in python with Enum
<p>In python, consider the following example</p> <pre class="lang-py prettyprint-override"><code>from enum import StrEnum from typing import Literal, overload class A(StrEnum): X = &quot;X&quot; Y = &quot;Y&quot; class X: ... class Y: ... @overload def enum_to_cls(var: Literal[A.X]) -&gt; type[X]: ... @o...
<python><python-typing>
2025-01-14 19:15:37
1
1,923
monte
79,356,141
2,813,687
How to properly type callbacks each accepting different subtypes of an overarching type
<p>Right now I have this code:</p> <pre><code>class A(abc.ABC): pass class B(A): pass class C(A): pass def fn_b(b: B) -&gt; None: pass def fn_c(c: C) -&gt; None: pass d : dict[type[A], Union[Callable[[A], None], Callable[[B], None]]] = { B: fn_b, C: fn_c, } </code></pre> <p>Now ...
<python><python-typing>
2025-01-14 19:15:17
0
1,018
foo
79,356,109
10,634,126
Python selenium (firefox/geckodriver) not working in Docker Linux/Ubuntu container
<p>I am trying to run a Linux/Ubuntu/Debian Docker container that will run web scrapers using Python Seleniumβ€”I am driver-agnostic, but I am starting with trying to run a Firefox/Geckodriver scrape.</p> <p>My Dockerfile is currently as follows:</p> <pre><code>FROM ubuntu:jammy WORKDIR /testdir COPY requirements.txt req...
<python><linux><docker><selenium-webdriver><firefox>
2025-01-14 19:01:34
0
909
OJT
79,355,881
19,356,117
How to extinguish cycle in my code when calculating EMWA?
<p>I'm calculating EWMA values for array of streamflow, and code is like below:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import numpy as np streamflow_data = np.arange(0, 20, 1) adaptive_alphas = np.concatenate([np.repeat(0.3, 10), np.repeat(0.6, 10)]) streamflow_series = pl.Series(strea...
<python><python-3.x><algorithm><numpy><python-polars>
2025-01-14 17:39:15
4
1,115
forestbat
79,355,866
2,801,187
Optimizing The Exact Prime Number Theorem
<p>For example, given this sequence of the first 499 primes, can you predict the next prime?</p> <pre><code>2,3,5,7,...,3541,3547,3557,3559 </code></pre> <p>The 500th prime is <code>3571</code>.</p> <hr /> <h2>Prime Number Theorem</h2> <p>The <a href="https://en.wikipedia.org/wiki/Prime_number_theorem" rel="nofollow n...
<python><performance><optimization><primes>
2025-01-14 17:30:45
1
2,457
vengy
79,355,830
373,091
Python SQLAlchemy mapping column names to attributes and vice versa
<p>I have a problem where I need to access a MS SQL DB, so naturally it's naming convention is different: TableName(Id, ColumnName1, ColumnName2, ABBREVIATED,...)</p> <p>The way I got the model constructed in Python:</p> <pre><code>class TableName(Base): __tablename__ = 'TableName' id = Column('Id', BigInt...
<python><sqlalchemy>
2025-01-14 17:17:13
1
2,849
Carmageddon
79,355,720
700,663
Trying to Install Python via Visual Studio Installer. Python seems to be in limbo. I don't know if it's installed or not
<p>I used to be able to install python.</p> <p><a href="https://i.sstatic.net/JTCsMA2C.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JTCsMA2C.png" alt="enter image description here" /></a></p> <p>See.</p> <p>Just click Python 3 64 bit and installed.</p> <p>Now no matter how many times I did that Python...
<python><installation><visual-studio-2022>
2025-01-14 16:43:29
1
33,271
user4951
79,355,648
4,637,141
AttributeError: Cannot set attribute. from marshmallow with peewee alias
<p>I have this peewee query</p> <pre><code>transaction_base = ( Transaction.select( (Transaction.amount - Transaction.amount_refunded).alias('net_amount'), Transaction.created, ) .where(Transaction.merchant_id == merchant_account.id...
<python><peewee><marshmallow>
2025-01-14 16:15:35
0
1,074
Jrow
79,355,625
17,837,614
Passing StringIO object to TextIOWrapper object is giving mypy error
<p>I wasn't getting any Mypy error with Mypy 0.812. But after upgrading Mypy to latest (1.14.1) I am getting below error. <code>error: Argument 1 to &quot;_redirect_stdout&quot; has incompatible type &quot;StringIO&quot;; expected &quot;TextIOWrapper[_WrappedBuffer]&quot; [arg-type]</code></p> <p>Please help me to und...
<python><python-typing><mypy>
2025-01-14 16:10:12
1
405
Sujay
79,355,372
20,591,261
How to get the day / month name of a column in polars
<p>I have a polars dataframe <code>df</code> which has a datetime column <em>date</em>. I'm trying to get the name of the day and month of that column.</p> <p>Consider the following example.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from datetime import datetime df = pl.DataFrame({ &q...
<python><datetime><python-polars>
2025-01-14 14:39:50
1
1,195
Simon
79,355,047
19,024,379
Multiprocessing with tkinter progress bar, minimal example
<p>I'm looking for a way to track a multiprocessing task with Tkinter progress bar. This is something that can be done very straightforwardly with <code>tqdm</code> for display in the terminal.</p> <p>Instead of using <code>tqdm</code> I'd like to use <code>ttk.Progressbar</code>, but all attempts I have made at this, ...
<python><tkinter><progress-bar><python-multithreading>
2025-01-14 12:50:02
1
1,172
Mark
79,354,732
9,869,695
aiohttp post request h11._util.LocalProtocolError: can't handle event type ConnectionClosed when role=SERVER and state=SEND_BODY
<ul> <li>I'm using aiohttp==3.10.10 with python 3.8</li> <li>For context I'm running a fastAPI app and on every request the app receives it creates an async background task to send a post request to another external API</li> <li>I create a shared aiohttp.ClientSession for the background tasks (I need this for connectio...
<python><fastapi><aiohttp>
2025-01-14 10:45:15
0
1,514
Arran Duff
79,354,646
2,342,292
pydantic v2 - aggregate errors when using mix of native and custom types with Annotated
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>from .consts import BASE_URL, HOSTNAME_PATTERN class GenericParseException(Exception): pass def validate_hostname(value: str) -&gt; str: if value.startswith(&quot;http://&quot;) or value.startswith(&quot;https://&quot;): ...
<python><python-3.x><pydantic><pydantic-v2>
2025-01-14 10:16:51
0
932
EldadT
79,354,638
1,202,172
Remove leading space from Shell GPT code output?
<p>I'm using <a href="https://github.com/TheR1D/shell_gpt/tree/main/sgpt" rel="nofollow noreferrer">Shell GPT</a> to send queries to GPT from Linux terminal. One problem - it prints a space before each line of code it gives, for example:</p> <pre><code> #!/bin/bash # Get the current date and time current_date_time=$...
<python><openai-api><chatgpt-api>
2025-01-14 10:14:20
1
8,684
Danijel
79,354,624
7,959,614
Use Gurobi to create networkx.Graph that has highest edge connectivity
<p>I have the following graph <code>G</code></p> <p><a href="https://i.sstatic.net/bZz0pTvU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bZz0pTvU.png" alt="enter image description here" /></a></p> <p><code>G</code> is created using the following code</p> <pre><code>import networkx as nx import matplot...
<python><networkx><graph-theory><mathematical-optimization><gurobi>
2025-01-14 10:07:26
1
406
HJA24
79,354,528
9,815,792
What value is given to constant in Scipy splantider?
<p>Im using <code>BSpline</code>s from SciPy and computing their antiderivatives using the <code>antiderivative()</code> method of the <code>BSpline</code> object. The <code>antiderivative()</code> method computes the antiderivative through a call to the funciton <a href="https://docs.scipy.org/doc/scipy-1.15.0/referen...
<python><scipy><spline>
2025-01-14 09:34:43
0
409
Joppe De Jonghe
79,354,459
25,413,271
Apply operation to all elements in matrix skipping numpy.nan
<p>I have an array filled with data only in lower triangle spaces, the rest is np.nan. I want to do some operations on this matrix, more precisely- with data elements, not nans, because I expect the behaviour when nans elements are skipped in vectorized operation to be much quicker.</p> <p>I have two test arrays:</p> <...
<python><numpy><matrix>
2025-01-14 09:04:16
1
439
IzaeDA
79,354,405
12,011,020
Polars Schema: TypeError: dtypes must be fully-specified, got: Datetime
<p>Hi I want to define a polars schema.</p> <p>It works fine without a datetime format. However it fails with <code>pl.Datetime</code>.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl testing_schema: pl.Schema = pl.Schema( { &quot;date&quot;: pl.Datetime, &quot;some_int&quot...
<python><dataframe><python-polars>
2025-01-14 08:43:19
1
491
SysRIP
79,354,384
20,895,654
Convert Base64 ImageStream in .NET WinForms to images with Python
<p>I have a very big WinForms application in the company I'm at and I want to extract all the images that are contained in it. I already wrote a program in python to extract basic images that are of type <code>Image</code> and <code>Icon</code>, but I struggle to turn an <code>ImageStream</code> base64 string into its ...
<python><.net><decoding><resx><imagestream>
2025-01-14 08:32:03
0
346
JoniKauf
79,354,186
2,210,825
What null hypothesis is rejected by the value of statsmodels RLM
<p>I am using statsmodels to perform a robust linear regression on some data I have. I wanted to understand whether the slope of my regression is significantly different from 0. In <code>scipy</code> I due this by looking at the p-value.</p> <p>In statsmodels, is the same null hypothesis being tested? I can get the pva...
<python><scipy><statistics><linear-regression><statsmodels>
2025-01-14 06:54:49
0
1,458
donkey
79,353,843
2,132,478
stable_baselines3: why the reward does not match comparing ep_info_buffer vs evaluation?
<p>I was working with stable_baselines3 library, when I found something that i did not expect.</p> <p>Here a simple code to reproduce the issue:</p> <pre><code>import gymnasium as gym from stable_baselines3 import DQN env = gym.make(&quot;CartPole-v1&quot;) model = DQN(&quot;MlpPolicy&quot;, env, verbose=0, stats_wi...
<python><machine-learning><reinforcement-learning><stable-baselines><dqn>
2025-01-14 02:14:32
1
575
Alfonso_MA
79,353,817
3,476,463
move email from one yahoo folder to another
<p>I'm running python 3.10 on ubuntu desktop 22. I'm running the code below. In the code I'm trying to move an email from one yahoo mail folder to another folder. The code does this by copying the email to the new folder then marking it for deletion in the older folder. When I run the code I'm getting the error mes...
<python><email><imaplib><yahoo-mail>
2025-01-14 01:52:42
0
4,615
user3476463
79,353,789
871,096
Workaround for jsbeautifier yielding invalid negative numbers for JSON
<p>I am working with Python 3.10.12 on a Linux (Ubuntu) system. I have installed the package <code>jsbeautifier</code> version 1.15.1.</p> <p><code>jsbeautifier.beautify</code> outputs invalid JSON for lists of numbers which include negative numbers; sometimes there is a line break between the minus sign and the rest o...
<python><json>
2025-01-14 01:17:19
0
17,677
Robert Dodier
79,353,713
9,632,470
Jupyter Command Not Recognized in MacOS
<p>I am attempting to install Jupyter on my MacBook Air (OS Sonoma 14.7) but am having difficulties. Below I will list the criteria of my situation and also reference several related questions and point out why they do not help me. I am very novice with OS / installation / path issues / advanced use of the zsh terminal...
<python><terminal><jupyter-lab>
2025-01-14 00:05:11
1
441
Prince M
79,353,665
8,229,029
How to create an array of length n in R where each element has two elements (example given)
<p>I would like to create an array in R that looks like the following array made in Python. This may be a very simple question, but it's giving me trouble!</p> <pre><code>array([[19358, 19388], [19389, 19416], [19417, 19447], [19448, 19477], [19478, 19508], [19509, 19538], [195...
<python><r><arrays><netcdf>
2025-01-13 23:28:11
2
1,214
user8229029
79,353,603
5,852,964
Changing multiple variables in Python
<p>Say I have three groups of variables a1, a2, a3 , b1, b2, b3, c1, c2, c3 and I want to change the first in each group using a loop rather than individual assignments.<br /> Putting each group in a list doesn't work:</p> <pre><code>a1, a2, a3 = 1, 2, 3 b1, b2, b3 = 4, 5, 6 c1, c2, c3 = 7, 8, 9 ls = [[a1, a2, a3], [b...
<python><list><variable-assignment>
2025-01-13 22:42:38
1
331
Patrick Dennis
79,353,446
1,438,045
Fabric 2 - how to configure a default host?
<p>I have some Fabric tasks in my <code>fabfile.py</code> such as:</p> <pre><code>@task def my_task(c): c.run(&quot;hostname&quot;) </code></pre> <p>which work fine if I run them like this:</p> <pre><code>fab -H user@host my_task </code></pre> <p>But I would like to run them with a default host, so I don't need to ...
<python><fabric>
2025-01-13 21:11:46
1
1,922
Martin Massera
79,353,295
662,285
No overload variant of subprocess.run matches argument types list[str], dict[str,object]
<p>Below is my python code where I am trying to pass kubeseal_cmd and run_options to subprocess.run method, but it's giving me error</p> <blockquote> <p>No overload variant of subprocess.run matches argument types list[str], dict[str,object].</p> </blockquote> <p>What am I missing? I am using python 3.12</p> <pre><cod...
<python><python-typing><mypy>
2025-01-13 19:51:46
1
4,564
Bokambo
79,353,281
7,531,433
Type aliasing Python's `typing.Annotated` type
<p>Assuming, I have some generic type <code>Foo[T]</code>. How can I create an alias <code>AFoo[T, x] = Annotated[Foo[T], x]</code> or something similar, which works with pyright, but also let's me extract the metadata and type hint <code>x</code> and <code>T</code>?</p> <p>What I've tried so far:</p> <ul> <li>Using an...
<python><python-typing><pyright>
2025-01-13 19:38:08
0
709
tierriminator
79,353,192
1,788,656
Getting into the definition of the Pandas.Series super().reindex
<p>I am interested in seeing the source code of the <code>pandas.Series.reindex</code>, so I jumped to the source code using the link in the <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.reindex.html" rel="nofollow noreferrer">documentation page</a>, yet I found a return to other function <a href...
<python><pandas><super>
2025-01-13 18:54:12
1
725
Kernel
79,353,092
4,721,937
How to parametrize class-scoped fixtures with inputs and expected outputs?
<p>I'm writing tests for my flask application endpoints. The first endpoint takes a multipart request and stores provided files on the server. The second endpoint retrieves the metadata of the stored files.</p> <p>I want to create extensible tests for these endpoints, but I don't know how to properly arrange fixtures a...
<python><flask><pytest>
2025-01-13 18:08:39
0
2,965
warownia1
79,352,963
1,128,648
Upload file to onedrive personal using python in non-interactive way
<p>I have seen some older method using onedrive sdk, seems like those are not working now. This is one of the method I got after some research. But it is not working</p> <pre><code>import msal import requests # Azure AD app credentials client_id = 'xxx9846xxxx' client_secret = 'xxxTdxxx' tenant_id = 'xxx-xxxx' # Auth...
<python><azure><file-upload><onedrive>
2025-01-13 17:09:04
1
1,746
acr
79,352,669
1,672,429
How/why are {2,3,10} and {x,3,10} with x=2 ordered differently?
<p>Sets are unordered, or rather their order is an implementation detail. I'm interested in that detail. And I saw a case that surprised me:</p> <pre><code>print({2, 3, 10}) x = 2 print({x, 3, 10}) </code></pre> <p>Output (<a href="https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3kwqKMvNKNKqNdBSMdRQMDWo1uSoUbBWMuKD...
<python><cpython><python-internals>
2025-01-13 15:24:07
1
28,999
Stefan Pochmann
79,352,565
1,788,656
Vectorizing three nested loops that calculate the daily mean of hourly data
<p>Is there a way to vectorize the following three-nested loop that calculate the daily mean of hourly data? The function below loops first over the year, then months, and finally over days. It also check for the last month and day to ensure that the loop does not go beyond the last month or day of the data.</p> <pre><...
<python><python-3.x><pandas><vectorization>
2025-01-13 14:50:57
2
725
Kernel
79,352,553
15,307,950
BeautifulSoup prettify changes content, not just layout
<p>BeautifulSoup <code>prettify()</code> modifies significant whitespace even if the attribute <code>xml:space</code> is set to <code>&quot;preserve&quot;</code>.</p> <p>Example xml file with significant whitespace:</p> <pre><code>&lt;svg viewBox=&quot;0 0 160 50&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt; ...
<python><xml><svg><beautifulsoup>
2025-01-13 14:46:13
2
726
elechris
79,352,276
25,413,271
Apply function for lower triangle of 2-d array
<p>I have an array:</p> <pre><code>U = np.array([3, 5, 7, 9, 11]) </code></pre> <p>I want to get a result like:</p> <pre><code>result = np.array([ [ np.nan, np.nan, np.nan, np.nan, np.nan], [U[0] - U[1], np.nan, np.nan, np.nan, np.nan], [U[0] - U[2], U[1] - U[2], np.nan, ...
<python><arrays><numpy><matrix>
2025-01-13 13:06:00
2
439
IzaeDA
79,352,069
315,168
Detecting if Python code is run under Visual Studio Code (or other) Python debugger
<p>I have Python and Pandas code <a href="https://github.com/tradingstrategy-ai/getting-started/blob/master/notebooks/single-backtest/base-meme-index.ipynb" rel="nofollow noreferrer">which does complex Pandas series calculations for thousands of series and runs these calculations parallel for speedup</a> using multipro...
<python><visual-studio-code><pdb>
2025-01-13 11:42:24
0
84,872
Mikko Ohtamaa
79,351,991
20,298,890
Azure authentication failure in spawned processes from multiprocessing pool
<p>I have a very specific issue with the combination of multiprocessing + azure authentication and could not find a valuable open issue, so here I go:</p> <p>I am working on a python program that uses <strong>multiprocessing.Pool</strong> to accelerate computations.</p> <p>The data is read from and uploaded to <strong>...
<python><azure><python-multiprocessing>
2025-01-13 11:12:33
0
503
marting
79,351,922
2,457,483
Can't Access Spotify Song Features Despite Successfully Generating Token and Being Logged I
<p>I am trying to access audio features of a song using the Spotify Web API, but I keep getting a 403 Forbidden error even though:</p> <ul> <li>I am successfully logging in using OAuth.</li> <li>I can retrieve a valid access token using sp.auth_manager.get_access_token().</li> </ul> <p>The token has the correct scop...
<python><oauth><spotify><spotify-app>
2025-01-13 10:46:13
0
5,411
Daniel
79,351,880
19,155,645
RAG on Mac (M3) with langchain (RetrievalQA): code runs indefinitely
<br> I'm trying to run a RAG system on my mac M3-pro (18gb RAM) using langchain and `Llama-3.2-3B-Instruct` on a jupyter notebook (and the vector storage is Milvus).<br> When I am invoking RetrievalQA.from_chain_type, the cell is running indefinitely (at least 15 mins, did not let it run longer...).<br> <pre><code>from...
<python><macos><gpu><langchain><retrieval-augmented-generation>
2025-01-13 10:32:04
0
512
ArieAI
79,351,811
2,071,807
Pydantic restrict string to literal values and convert to lower case
<p>How can I restrict the value of a string field to certain values in a case insensitive way?</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; Animal(species=&quot;antelope&quot;) &gt;&gt;&gt; Animal(species=&quot;AnTeLoPe&quot;) &gt;&gt;&gt; Animal(species=&quot;frog&quot;) # ValidationError: `specie...
<python><pydantic>
2025-01-13 10:08:18
3
79,775
LondonRob
79,351,658
13,040,314
Binary file base64 encode in js and decode in python
<p>I want save an excel file as json in database. It is then downloaded in the python backend later on to create the excel file.</p> <p>My frontend to save excel file as json:</p> <pre><code> const fileReader: FileReader = new FileReader(); fileReader.onloadend = (_x) =&gt; { const input: any = {...
<javascript><python><json><encoding><decoding>
2025-01-13 09:09:07
1
325
StaticName
79,351,120
3,765,883
Python3: how can I print value of 'tools.staticdir.dir' to console?
<p>I'm working my way through Python Cherrypy tutorials. Tut06 demonstrates serving static content with the following example</p> <pre><code>import os, os.path import random import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self): return &quot;&quot;&quot;...
<python><cherrypy>
2025-01-13 03:23:55
0
327
user3765883
79,351,075
869,809
how can I generate a python environments's minimum requirements?
<p>I keep coming up with different ways to do this and it ends up being a PITA no matter how I do it and I cannot be the only one trying to deal with this.</p> <p>Say that I do this:</p> <pre><code>virtualenv .venv alias tp='./.venv/bin/python3' tp -m pip install AAA tp -m pip install BBB tp -m pip install CCC tp -m pi...
<python><installation><pip>
2025-01-13 02:38:24
1
3,616
Ray Kiddy
79,350,990
20,295,949
How can I scrape data from a website into a CSV file using Python Playwright (or alternatives) while avoiding access errors and improving speed?
<p>I'm trying to scrape data from this website using Python and Playwright, but I'm encountering a few issues. The browser runs in non-headless mode, and the process is very slow. When I tried other approaches, like using requests and BeautifulSoup, I ran into access issues, including 403 Forbidden and 404 Not Found er...
<python><selenium-webdriver><beautifulsoup><python-requests><playwright>
2025-01-13 01:09:24
1
319
HamidBee
79,350,912
14,923,227
Nearest neighbor interpolation
<p>Say that I have an array:</p> <pre><code>arr = np.arange(4).reshape(2,2) </code></pre> <p>The array <code>arr</code> contains the elements</p> <pre><code>array([[0, 1], [2, 3]]) </code></pre> <p>I want to increase the resolution of the array in such a way that the following is achieved:</p> <pre><code>np.arra...
<python><numpy>
2025-01-12 23:51:01
1
3,418
Kevin
79,350,895
2,927,848
Sql Alchemy 2.x not parsing ORM objects
<p>I'm building a little sqlite database to manage some web scraping I'm doing. I have queries like this.</p> <pre><code>async def get_by_title(session: AsyncSession, title: str) -&gt; Optional[Manga]: query = select(Manga).where(Manga.title == title).limit(1) result = await session.scalar(query) return res...
<python><sqlalchemy>
2025-01-12 23:21:53
1
2,317
Chase R Lewis
79,350,850
327,026
How to get legacy NumPy repr in Sphinx docs examples?
<p>This question considers <a href="https://numpy.org/neps/nep-0051-scalar-representation.html" rel="nofollow noreferrer">NEP 51</a>, which changed NumPy's string representation. This document describes some potential backward compatibility issues:</p> <blockquote> <p>An exception to this are downstream libraries with ...
<python><pytest><python-sphinx><repr><numpy-2.x>
2025-01-12 22:44:23
1
44,290
Mike T
79,350,811
3,045,351
Python code running across multiple venvs where different versions of the same package are stored
<p>I have a situation where I have one set of Python scripts running in a virtual environment, calling another set of scripts running in a different virtual environment. This is to handle package conflicts etc.</p> <p>There is a core system (in this case the ComfyUI back end) running in a venv called 'comfyui' and a sl...
<python><python-3.x><python-venv>
2025-01-12 22:16:42
0
4,190
gdogg371
79,350,780
1,624,552
cannot connect to vpn using python-openvpn-client api
<p>I have a pyhton program from which I am using python-openvpn-client API to connect to a vpn server using an .ovpn configuration file.</p> <p>I have installed python 3.13.1 from the official website. Then I have created a virtual python environment to use in my python project.</p> <p>I have successfully installed the...
<python><openvpn>
2025-01-12 21:52:48
2
10,752
Willy
79,350,773
54,873
Using xlwings, is there a way to collapse all the groups on a sheet?
<p>I'm using <code>xlwings</code> with python to copy one excel sheet to another. As part of the copying, however, I'd like to collapse all the grouped columns.</p> <p>This is different than hiding the relevant columns and rows; I want them to be non-hidden, but just have the outlines collapsed to level 0!</p> <p>And ...
<python><macos><xlwings>
2025-01-12 21:49:24
2
10,076
YGA
79,350,584
6,594,668
Pythonic way to conditionally replace values in a numpy array based on neighbour's values
<p>I am processing a greyscale (8 bit) black-and-white image in Python with OpenCV.</p> <p>The image (2D numpy array with shape (100,200) ) contains pixels of only 2 colors - black (0) and white (255).</p> <p>Here is my Python code:</p> <pre><code>img = cv2.imread(filename) # 2 dims, pixel type: np.uint8 (and only 2 po...
<python><numpy><opencv><neighbours>
2025-01-12 19:39:02
3
2,406
prograils
79,350,545
9,128,863
sympy plot does't draw points
<p>I use the following code with sympy lib to illustrate lines of function and some points at this graph:</p> <pre><code>from sympy.plotting.plot import plot_contour import sympy as sy x_1, x_2 = sy.symbols('x_1 x_2') y = sy.sqrt((x_1 - 3) ** 2 + (x_1 - 2) ** 2) + sy.sqrt((x_2 - x_1) ** 2 + x_1 ** 2) + sy.sqrt( (...
<python><plot><sympy>
2025-01-12 19:17:21
0
1,424
Jelly
79,350,430
13,968,392
Check if all values of Polars DataFrame are True
<p>How can I check if all values of a polars DataFrame, containing only boolean columns, are True?<br /> Example <code>df</code>:</p> <pre><code>df = pl.DataFrame({&quot;a&quot;: [True, True, None], &quot;b&quot;: [True, True, True], }) </code></pre> <p>The reason for my question is that sometime...
<python><dataframe><conditional-statements><python-polars><boolean-logic>
2025-01-12 18:07:30
2
2,117
mouwsy
79,350,396
21,440,243
How can I fix the error "Java gateway process exited before sending its port number." in Python when running PySpark?
<p>I have some code I'm trying to run with PySpark in Python 3.13, here's the least amount of code needed to reproduce my problem:</p> <pre><code>from pyspark.sql import SparkSession pyspark = SparkSession.builder.master(&quot;local[8]&quot;).appName(&quot;example&quot;).getOrCreate() </code></pre> <p>Whenever I run it...
<python><java><pyspark><runtime-error>
2025-01-12 17:41:46
0
1,302
Starship
79,350,359
2,962,444
Implementation of += for Python lists as related to argument passing
<p>I am reviewing a Python workbook for an author who claims the following:</p> <p><em>Immutable parameters like integers, strings, or tuples are passed by value and any changes to these parameters within the function do not change their respective values outside the function Mutable objects, like lists and dictionarie...
<python><list><parameter-passing>
2025-01-12 17:25:20
0
672
quizdog
79,349,992
8,618,818
How am I supposed to get just the close price and date from this data returned by yfinance?
<p>I am fetching the data of the S&amp;P index for every day and I want to insert the close price and the date into my database, however, I am new to Python and I have no idea how to navigate this weird data structure. This is what print(spxHistoricalData) returns:</p> <pre><code>Price Close High ...
<python><yfinance>
2025-01-12 13:46:16
2
5,810
Onyx
79,349,541
4,451,315
DuckDB Python Relational API equivalent of `select sum(a) filter (where b>1)`
<p>If I have</p> <pre class="lang-py prettyprint-override"><code>rel = duckdb.sql('select * from values (1, 4), (1, 2), (2, 3), (2, 4) df(a, b)') </code></pre> <p>I'd like to do the equivalent of</p> <pre class="lang-py prettyprint-override"><code> In [9]: duckdb.sql('select sum(a) filter (where b&gt;1) from rel') Out[...
<python><duckdb>
2025-01-12 08:02:00
2
11,062
ignoring_gravity
79,349,238
654,142
Deleting Personal Emails from Gmail Efficiently
<p>My Gmail reached the 15 GB limit, so I archived old emails with Thunderbird and I want to delete all the emails that are older than two weeks. Using the GUI is cumbersome because it seems like I can only delete 100 at a time. So I thought I could create a test app and add my Google Account as a test user to speed ...
<python><gmail-api><google-workspace><google-api-python-client>
2025-01-12 02:20:27
1
711
Paul Lewallen
79,349,147
427,942
Included App URLs not showing in DRF browsable API
<p>I'm using the Django Rest Framework to provide an API, which works great.</p> <p>All needed URLs for routers and others too are hold in the root urls.py To better handle the growing number of routes I tried to move routes from Apps to their related app folders - as one would do with pure Django.</p> <pre><code># url...
<python><django><django-rest-framework>
2025-01-12 00:26:57
1
1,568
normic
79,349,133
12,828,249
How to architect the external evnets and Django models?
<p>I'm building a django backend app and I have a few different models in my app. One of these models is a <code>Driver</code> and I want to do the following when calling the <code>create-driver</code> endpoint:</p> <ol> <li>create the driver in database</li> <li>create a user account for the driver in my B2C directory...
<python><django><architecture><domain-driven-design>
2025-01-12 00:11:08
0
2,249
Morez
79,349,081
3,696,153
vscode, python - step through code being 'exec'ed
<p>So I have a python app that reads/loads a file that is sort of like a plugin for the main application.</p> <p>I would really like to be able to debug (step into) the code from VSCODE - which I'm using as an IDE</p> <p>I've tried a number of things, described here (and related posts)</p> <p><a href="https://stackover...
<python><visual-studio-code><plugins><vscode-debugger>
2025-01-11 23:17:32
0
798
user3696153
79,348,814
9,182,405
How do I include a custom component in a spaCy training pipeline using the CLI?
<p>I'm trying to implement a simple custom component in my spaCy training pipeline. I'm using the spaCy CLI for training, which means I'm directing the pipeline configuration through the config.cfg file, though I do have scripts for generating and annotating training and evaluation data. The custom component I've creat...
<python><machine-learning><nlp><spacy-3>
2025-01-11 20:14:52
0
656
Dumas.DED
79,348,677
10,985,257
Calculating CrossEntropyLoss over sparse tensors
<p>While the following works as expected:</p> <pre class="lang-py prettyprint-override"><code>import torch from torch.nn import CrossEntropyLoss loss = CrossEntropyLoss() T1 = torch.randn(10, 20, 4, 4) # The BatchSize is a 10 times repeated tensor (1,20,4,4) T2 = torch.randint(1,20, (10, 4, 4)) loss(T1, T2) </code><...
<python><pytorch><sparse-matrix>
2025-01-11 18:40:10
0
1,066
MaKaNu
79,348,454
9,999,861
Visual Studio Code does not find python unit tests in sub folders
<p>I am setting up a Python project in VisualStudio Code. My folder and file structure looks like follows:</p> <ul> <li>Base project folder <ul> <li>source_folder <ul> <li>package1_folder <ul> <li>module1.py</li> </ul> </li> <li>package2_folder <ul> <li>module2.py</li> </ul> </li> </ul> </li> <li>source_folder_unittest...
<python><visual-studio-code><python-unittest><test-discovery>
2025-01-11 16:20:25
1
507
Blackbriar
79,348,399
15,100,030
Twilio Return gathering after client press star
<p>I'm trying to create a fallback gathering if the interpreter hangup from the conference while the client is still on the line, I have to return the gathering to the client to ask him if he wants another interpreter or disconnect</p> <p>everything work perfect but, when the client pressed star, the gather said the fi...
<python><django><twilio>
2025-01-11 15:40:48
0
698
Elabbasy00
79,348,313
7,920,004
pytest throwing module no found in Databricks' notebook
<p>I'm recreating below test scenario but constantly getting below error:</p> <p><a href="https://learn.microsoft.com/en-us/azure/databricks/notebooks/testing" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/databricks/notebooks/testing</a></p> <pre><code>ImportError while importing test module '/Work...
<python><pytest><databricks>
2025-01-11 14:48:20
1
1,509
marcin2x4
79,348,304
6,583,936
Ipywidgets Controller not working properly, fields empty
<p>I want to use my Xbox controller in Jupyter environment. I initialized controller, there widget said press any button, then, widget started displaying all of my controls. as on Screenshot. <a href="https://i.sstatic.net/MAvWXIpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MAvWXIpB.png" alt="enter ...
<python><jupyter-notebook><ipython><ipywidgets>
2025-01-11 14:42:38
1
320
mcstarioni
79,348,281
3,008,410
Spark JDBC table to Dataframe no partitionCol to use
<p>I have a MySQL RDBMS table (3 Million rows, only 209K returned) like this that I need to Python to load into a Spark dataframe. The issue is that I need to load it concurrently as it is REALLY slow (1.5H min), but as you can see I have no way to set an &quot;upperbound&quot; and &quot;lowerbound&quot; that JDBC need...
<python><apache-spark><pyspark>
2025-01-11 14:28:39
0
856
user3008410
79,348,233
1,473,517
Why is the output from tqdm+concurrent.futures such a mess and what can be done about it?
<p>I want to run processes in parallel and show their progress. I have this code:</p> <pre><code>from math import factorial from decimal import Decimal, getcontext from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm import time def calc(n_digits, pos, total): # number of iteration...
<python><concurrent.futures><tqdm>
2025-01-11 13:55:51
1
21,513
Simd
79,348,168
1,142,881
How to on a rolling window pass two column vectors instead of one?
<p>I'm computing technical indicators on a rolling basis to avoid any look-ahead bias, for example, for model training and back-testing. To that end I would like to compute the indicator <a href="https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html?highlight=forceindexindicator#ta.volume.ForceI...
<python><pandas>
2025-01-11 13:22:19
2
14,469
SkyWalker
79,347,968
8,425,824
What are the differences between the various Python base 85 functions?
<p>Python has three sets of base 85 functions, in the <a href="https://docs.python.org/3/library/base64.html" rel="nofollow noreferrer"><code>base64</code></a> module.</p> <ul> <li><a href="https://docs.python.org/3/library/base64.html#base64.a85encode" rel="nofollow noreferrer"><code>base64.a85encode</code></a> and <a...
<python><ascii85><base85>
2025-01-11 11:25:42
2
4,486
LeopardShark
79,347,483
865,883
VSCode Python Debugger Not Using the Correct Python Binary with launch.json "justMyCode=false"
<p>I have a small project where I'd like to use the launch.json with a pipenv-created environment, but VSCode appears to be using an invalid python binary location. This happens when I set &quot;justMycode&quot; to &quot;false&quot;. Setting it true, works fine.</p> <p>Confusingly, when running the command &quot;Python...
<python><visual-studio-code><vscode-debugger>
2025-01-11 03:20:07
0
9,567
funseiki
79,347,405
3,614,460
How to avoid matplot subplot from overlapping?
<p>Code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt maxRow = 23 fig, axes = plt.subplots(maxRow, 1) for x in range(maxRow): axes[x].plot(1,1) plt.show() </code></pre> <p>Running it shows all the plot overlapping like this. <a href="https://i.sstatic.net/DAuhdX4E.png" rel="nofollow norefe...
<python><matplotlib>
2025-01-11 02:08:20
1
442
binary_assemble
79,347,389
5,404,620
Pandas adds "." + digit to the header of a csv
<p>I would like to import a csv file with headers to pandas. Somehow, pandas appends a &quot;.7&quot; to the last headers name</p> <p>The last header in the csv contains a &quot;<code>?</code>&quot; as the last character (on purpose, the question mark is part of the last column's header)</p> <pre><code>EXAMPLE XXXXXXXX...
<python><pandas><dataframe><csv>
2025-01-11 01:58:53
1
2,887
Adler
79,347,041
1,018,226
Process a large separated file with different Python readers
<p>I want to handle text files which contain multiple documents in different formats. The documents are <a href="https://yaml.org/spec/1.2.2/#example-two-documents-in-a-stream" rel="nofollow noreferrer">separated by three dashes, similar to as in YAML</a>.</p> <pre class="lang-yaml prettyprint-override"><code>Example: ...
<python><parsing><yaml><stringio>
2025-01-10 21:12:46
1
2,574
XZS
79,347,027
20,295,949
How to Prevent Twitter Blocking Page Refreshes While Scraping Tweets Using Selenium or Alternatives?
<p>I'm trying to scrape new tweets from a Twitter account using Selenium (I'm not sure if selenium is the best way to do this). My script logs into Twitter, navigates to the user's profile, and captures the latest tweets. While Selenium works to an extent, I’ve encountered issues with bot detection and page blocking af...
<python><selenium-webdriver><web-scraping>
2025-01-10 21:06:43
1
319
HamidBee
79,346,879
533,104
Selenium - Attempting to invoke "next" button on search results
<p>I'm using Selenium to scrape the results from this game search page.</p> <p><a href="https://www.igt.com/products-and-services/gaming/games#gs:category=1" rel="nofollow noreferrer">https://www.igt.com/products-and-services/gaming/games#gs:category=1</a></p> <p>I am able to load the page, set my search parameters, an...
<python><selenium-webdriver>
2025-01-10 19:56:22
2
2,005
dakamojo
79,346,871
6,067,528
Memory leak explanation for Python service making lots of outbound calls with `aiohttp`
<p>I have an issue with ever-increasing memory in Python-based service that uses celery tasks. These tasks make a tonne of outbound calls using something like the below...</p> <pre><code>async with aiohttp.ClientSession() as session: async with session.request( method, url, json=data, auth=self.basic_auth, ...
<python><memory-leaks>
2025-01-10 19:53:33
0
1,313
Sam Comber