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,543,228
9,680,534
(fields.E331) Field specifies a many-to-many relation through model, which has not been installed
<p>When I run <code>makemigrations</code> I get the error</p> <blockquote> <p>teams.Team.members: (fields.E331) Field specifies a many-to-many relation through model 'TeamMember', which has not been installed.</p> </blockquote> <pre class="lang-py prettyprint-override"><code>from django.db import models from django.con...
<python><django>
2025-03-29 12:20:40
1
9,087
Avin Kavish
79,543,099
5,722,359
What is the difference between "Run Python File" vs "Run Python File in Terminal" vs "Python File in Dedicated Terminal" in VS Code?
<p>I am new to VS Code. When I do <kbd>Ctrl</kbd>+<kbd>K</kbd>+<kbd>S</kbd> and type in <code>run python</code>, I noticed that there are three ways of running a Python file:</p> <ol> <li>Run Python File</li> <li>Run Python File in Terminal</li> <li>Run Python File in Dedicated Terminal</li> </ol> <p>May I know what is...
<python><visual-studio-code>
2025-03-29 10:21:53
1
8,499
Sun Bear
79,542,988
4,977,821
Fastest and cleaner ways to insert, update, delete 2-dimensional array
<p>I'm newbie in python language and have some prolem here. I have a list of name and score for example:</p> <pre><code>score = [['Andy', 80], ['John', 70], ['Diana', 100]] </code></pre> <p>I want to Delete or Update score based on it's name. So I can update score if name 'Andy' to 70 or Delete data where name is 'John...
<python><arrays><list>
2025-03-29 08:45:36
1
367
Tommy Sayugo
79,542,824
6,024,753
avoiding Python overhead in solve_ivp LSODA
<p>I'm using the <code>solve_ivp</code> module in scipy. The LSODA option offers a Python wrapper to a Fortran integration package. The issue is that the Python wrapper integrates using LSODA timestep-by-timestep. So, there can be a lot of Python overhead to the integration if there are many timesteps.</p> <p>I would l...
<python><scipy><numerical-integration>
2025-03-29 05:24:02
0
453
billbert
79,542,806
267,265
Stable fluid simulation with Python and Taichi has strange drifting
<p>I'm trying to implement Jos Stam's stable fuild in paper: <a href="https://graphics.cs.cmu.edu/nsp/course/15-464/Spring11/papers/StamFluidforGames.pdf" rel="nofollow noreferrer">https://graphics.cs.cmu.edu/nsp/course/15-464/Spring11/papers/StamFluidforGames.pdf</a> I want to do it in 2D but do wraparound when you hi...
<python><fluid-dynamics><taichi>
2025-03-29 04:54:38
1
10,454
German
79,542,742
16,383,578
How can I correctly implement AES-256-ECB from scratch in Python?
<p>I am using Windows 11 and I plan to implement the code in C++. As you might know, building C++ libraries on Windows is very complicated, so I want to make sure it uses the least amount of dependencies possible.</p> <p>For more context about the larger project this will be a part of, see <a href="https://superuser.co...
<python><encryption><aes>
2025-03-29 03:08:17
1
3,930
Ξένη Γήινος
79,542,733
10,262,805
Why do we reshape key, query, and value tensors in multi-head attention?
<p>In my PyTorch implementation of multi-head attention, i have those in <code>__init__()</code></p> <pre><code>class MultiHeadAttentionLayer(nn.Module): def __init__(self,d_in,d_out,context_length,dropout,num_heads,use_bias=False): super().__init__() self.d_out=d_out self.num_heads=num_head...
<python><pytorch><neural-network><tensor><multihead-attention>
2025-03-29 02:58:57
2
50,924
Yilmaz
79,542,721
14,121,186
How can I create a closed loop curve in Manim?
<p>I'm trying to make a curved shape that passes through a set of points and forms a closed loop. I was able to create a VMobject with the points and use <code>.make_smooth()</code> to form the curve, but the first point has a sharp angle in it. Is there a way to make the entire curve smooth?</p> <p>Here's the script:<...
<python><manim>
2025-03-29 02:37:57
1
873
Caleb Keller
79,542,528
22,146,392
How to strip quotes from CSV table?
<p>I'm using the <a href="https://pandas.pydata.org/docs/reference/index.html" rel="nofollow noreferrer">pandas library</a> to convert CSVs to other data types. My CSV has the fields quoted, like this:</p> <pre class="lang-none prettyprint-override"><code>&quot;Version&quot;, &quot;Date&quot;, &quot;Code&quot;, &quot;D...
<python><pandas><csv>
2025-03-28 22:38:03
4
1,116
jeremywat
79,542,515
7,085,818
Comments on columns in Postgres table is Null
<p>I added comments in my postgres table using this method, statement ran successfully.</p> <pre><code>COMMENT ON TABLE statements IS 'Table storing bank transaction data imported from statements sheet'; COMMENT ON COLUMN statements.id IS 'Unique identifier for each transaction'; COMMENT ON COLUMN statements.customer_i...
<python><postgresql><sqlalchemy>
2025-03-28 22:29:12
1
610
Kundan
79,542,328
4,869,375
Predicting `re` regexp memory consumption
<p>I have a large (gigabyte) file where an S-expression appears, and I want to skip to the end of the S-expression. The depth of the S-expression is limited to 2, so I tried using a Python regexp (<code>b'\\((?:[^()]|\\((?:[^()]|)*\\))*\\)'</code>). This turned out to consume too much RAM, and digging deeper I found th...
<python><python-3.x><python-re>
2025-03-28 20:05:06
1
910
Erik Carstensen
79,542,324
4,907,639
Constrain Llama3.2-vision output to a list of options
<p>I have several images of animals in the same directory as the script. How can I modify the following script to process an image but force the output to only be a single selection from a list:</p> <pre><code>from pathlib import Path import base64 import requests def encode_image_to_base64(image_path): &quot;&quo...
<python><large-language-model><ollama>
2025-03-28 20:01:06
1
2,109
coolhand
79,542,118
4,470,126
Convert dataframe column if its datetime to longType, otherwise keep the same column
<p>I have a dataframe with columns <strong>entry_transaction, created_date, updated_date, transaction_date</strong>.</p> <p><code>Created_date</code>, <code>Updated_date</code> are strings with <code>YYYY-MM-dd HH:mm:ss.SSS</code>, and transaction_day is in long milliseconds. I need to loop through the columns and if ...
<python><pyspark><databricks><azure-databricks>
2025-03-28 17:57:01
1
3,213
Yuva
79,542,086
5,054,175
SessionNotCreatedException when launching Selenium ChromeDriver with FastAPI Slack bot on AWS Lightsail
<p>I have a FastAPI server with a Slack chatbot that launches Selenium for automating certain tasks. However, I'm encountering an issue when initializing the ChromeDriver with the <code>--user-data-dir</code> argument:</p> <pre class="lang-py prettyprint-override"><code>user_data_dir = tempfile.mkdtemp() chrome_options...
<python><amazon-web-services><ubuntu><selenium-webdriver><selenium-chromedriver>
2025-03-28 17:39:17
1
1,000
miorey
79,542,042
648,345
Python Flask WSGI failure with deprecated imp module
<p>When I attempt to deploy a Flask app on a shared hosting site, using cPanel, the deployment fails with this message: &quot;ModuleNotFoundError: No module named 'imp'.&quot;</p> <p>As other posts have indicated, the <code>imp</code> module has been removed from Python and a different module, <code>importlib</code>, s...
<python><flask><wsgi><imp>
2025-03-28 17:17:38
1
637
macloo
79,541,975
967,621
Fix a specific rule in ruff
<p>How do I fix only specific rule violations in <a href="https://docs.astral.sh/ruff/" rel="nofollow noreferrer"><code>ruff</code></a>?</p> <p>For example, I need to fix only rule <code>F401</code>.</p>
<python><ruff>
2025-03-28 16:47:33
1
12,712
Timur Shtatland
79,541,781
967,621
Prevent conda from using the defaults channel in `conda update conda`
<p>Conda apparently is trying to use the <code>defaults</code> channel when I run</p> <pre class="lang-sh prettyprint-override"><code>conda update conda </code></pre> <p>or</p> <pre class="lang-sh prettyprint-override"><code>conda create --name python python pyaml pytest </code></pre> <p>The output is:</p> <pre><code>C...
<python><conda><miniconda>
2025-03-28 15:06:20
1
12,712
Timur Shtatland
79,541,776
11,462,274
Open a webpage popup window in Microsoft Edge browser using Python without Selenium
<p>I can't use <code>Selenium</code> or any other type of option that controls the browser, because I need to use it on sites that have strict restrictions against bots and automations, so I need to use the browser itself as it is originally.</p> <p>I currently use the following pattern code to open websites:</p> <pre ...
<python><microsoft-edge><python-webbrowser>
2025-03-28 15:00:47
0
2,222
Digital Farmer
79,541,683
11,313,748
Getting Infeasibility while solving constraint programming for shelf space allocation problem
<p>I'm trying to allocate shelf space to items on planogram using constraint programming. It is a big problem and I'm trying to implement piece by piece. At first we're just trying to place items on shelf.</p> <p>The strategy is dividing whole planogram into multiple sections. For example if my planogram width is 10 cm...
<python><linear-programming><or-tools><constraint-programming><cpmpy>
2025-03-28 14:24:05
1
391
Anand
79,541,446
13,280,838
Does Snowflake ODBC Driver Support fast_executemany - Issue with varchar(max) columns
<p><strong>Scenario:</strong></p> <p>I am trying to create a simple Python script that utilizes <code>pyodbc</code> and works with various datasources say sqlserver, azuresql, snowflake etc. Basically any source that supports ODBC connections. We have an issue when trying to load from SQL Server to Snowflake. The sourc...
<python><snowflake-cloud-data-platform><odbc><pyodbc>
2025-03-28 12:36:40
0
669
rainingdistros
79,541,287
6,212,999
How to write type hints for recursive function computing depth in Python?
<p>I wrote the following function in Python 3.12:</p> <pre><code># pyright: strict from collections.abc import Iterable, Mapping from typing import Any type Nested = Any | Mapping[str, Nested] | Iterable[Nested] def _get_max_depth(obj: Nested) -&gt; int: if isinstance(obj, Mapping): return max([0] + [_g...
<python><python-typing><pyright>
2025-03-28 11:22:55
2
405
Marcin Barczyński
79,541,208
189,247
Printing numpy matrices horizontally on the console
<p>Numpy has many nice features for formatted output, but something I miss is the ability to print more than one array/matrix on the same line. What I mean is easiest to explain with an example. Given the following code:</p> <pre><code>A = np.random.randint(10, size = (4, 4)) B = np.random.randint(10, size = (4, 4)) ni...
<python><numpy><matrix><pretty-print>
2025-03-28 10:44:59
2
20,695
Gaslight Deceive Subvert
79,541,197
355,401
Migrating Python sync code to asyncio - difference between asyncio.run vs asyncio.Runner
<p>I'm working on migrating a Python 3 codebase from complete sync to partially asyncio.<br /> The reason it is partial is because the part of the service that read messages is not compatible with asyncio, yet so it has to remain something like this:</p> <pre class="lang-py prettyprint-override"><code>for message in re...
<python><python-asyncio>
2025-03-28 10:38:16
1
11,544
Ido Ran
79,541,027
577,288
python - how to center tkinter fileDialog window
<p>I would like to open an audio file in python using a tkinter fileDialog. How can I center the fileDialog window?</p> <pre><code>import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() root.attributes('-topmost', True) audio1 = &quot;*.mp3 *.wav&quot; videos1 = &quot;*.mp4 *.mkv&quot; ...
<python><tkinter>
2025-03-28 09:30:39
1
5,408
Rhys
79,540,913
7,465,516
How do I write out an anchor using ruamel.yaml?
<p><strong>I want to create data in python and write it to a file as a yaml-document using anchors and merges in the output.</strong></p> <p>I think this could be possible with ruamel YAML, because, as described in <a href="https://yaml.dev/doc/ruamel.yaml/example/#top" rel="nofollow noreferrer">ruamels official exampl...
<python><yaml><ruamel.yaml>
2025-03-28 08:41:31
1
2,196
julaine
79,540,796
10,395,747
How to reuse a function from a python module into another module?
<p>My directory structure is like this :-</p> <pre><code> project - code - betacode - naming - test - test.py - test1.py </code></pre> <p>So i have a func within test.py</p> <pre><code> def give_date(): return &quot;1991-01-01&quot; </code></pre> <p>And i want to call this f...
<python><import>
2025-03-28 07:36:39
2
758
Aviator
79,540,631
9,768,643
Implement Pagination In Graphql instead of Graphene Python
<p>here is my Gateway.py for Gateway Model</p> <pre><code>from datetime import datetime import graphene from models.v0100.util import get_query_types, stop_timestamps_w_timezone from sqlalchemy.orm import joinedload from graphene_sqlalchemy import SQLAlchemyObjectType from graphene_sqlalchemy_filter import FilterSet f...
<python><graphql><graphene-python>
2025-03-28 05:54:20
0
836
abhi krishnan
79,540,627
6,699,447
Why does pathlib.Path.glob function in Python3.13 return map object instead of a generator?
<p>I was playing around with <code>Path</code> objects and found an interesting behaviour. When testing with python3.11, <code>Path.glob</code> returns a <code>generator</code> object.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from pathlib import Path &gt;&gt;&gt; &gt;&gt;&gt; cwd = Path.cwd() &...
<python><glob><pathlib><python-3.11><python-3.13>
2025-03-28 05:52:11
1
25,841
user459872
79,540,595
4,710,828
Unable to suppress scientific notation in datarame, which in turn is causing pyodbc.ProgrammingError "Error converting data type nvarchar to numeric."
<p>Below is what I'm trying to accomplish:</p> <ol> <li>Get data from API</li> <li>Clean the data</li> <li>Insert the data into SQL Server</li> </ol> <p>Issue that I'm facing:</p> <ul> <li>I convert the data that I receive from api to a pandas dataframe</li> </ul> <pre class="lang-py prettyprint-override"><code>respons...
<python><sql-server><pandas><dataframe><scientific-notation>
2025-03-28 05:28:32
1
373
sdawar
79,540,481
10,964,685
Spatial clustering with two separate datasets
<p>I'm hoping to get some advice on approaching a clustering problem. I have two separate spatial datasets, being real data and modelled data. The real data contains a binary output (0,1), which is displayed in the figure below. The green scatter points represent 1 and red is 0.</p> <p>Is it possible to assign a probab...
<python><cluster-analysis><scatter-plot>
2025-03-28 03:48:49
1
392
jonboy
79,540,471
2,825,403
Filter sequences of same values in a particular column of Polars df and leave only the first occurence
<p>I have a very large Polars LazyFrame (if collected it would be tens of millions records). I have information recorded for a specific piece of equipment taken every second and some location flag that is either 1 or 0.</p> <p>When I have sequences where the location flag is equal to 1, I need to filter out and only le...
<python><python-polars>
2025-03-28 03:40:33
2
4,474
NotAName
79,540,321
6,227,035
Google Calendar API on EC2 (AWS) - webbrowser.Error: could not locate runnable browser
<p>I am developing a Django App where a user can access his Google Calendar using this script</p> <pre><code>credentials = None token = os.path.join(folder, &quot;token.pickle&quot;) if os.path.exists(token): with open(token, 'rb') as tk: credentials = pickle.load(tk) if not credentials or not...
<python><django><amazon-web-services><amazon-ec2>
2025-03-28 01:10:52
0
1,974
Sim81
79,540,264
10,550,998
Install pplpy in a conda environment on Ubuntu 24.04
<p>I would like to install <a href="https://pypi.org/project/pplpy/" rel="nofollow noreferrer">pplpy</a> (ideally version <code>0.8.7</code>) in a conda environment.</p> <p>What I have tried so far:</p> <ul> <li>Different versions of pplpy.</li> <li>Install PPL from source</li> <li>Set the <code>LD_LIBRARY</code> and <...
<python><pip><conda><ppl>
2025-03-28 00:09:26
0
1,372
cherrywoods
79,540,127
3,174,075
How can I run DeepFace in a docker container on a mac?
<p>I am trying to install deepface in docker container to do image comparison and I am close to getting it to run... however, I think I am probably missing dependencies... but cannot figure out which ones I need.</p> <p>In my main.py... If I comment <em>from deepface import DeepFace</em> the app starts up and runs... w...
<python><image><deepface>
2025-03-27 22:05:32
1
729
MrLister
79,540,025
6,100,177
How to materialize Polars expression into Series?
<p>Working with a single series instead of a dataframe, how can I materialize an expression on that series? For instance, when I run</p> <pre class="lang-py prettyprint-override"><code>time = pl.Series([pl.datetime(2025, 3, 27)]) (time + pl.duration(minutes=5)).to_numpy() </code></pre> <p>I get</p> <pre><code>Attribute...
<python><python-polars>
2025-03-27 20:55:28
1
1,058
mwlon
79,539,902
1,445,660
return 401 from lambda non-proxy api gateway and return headers
<p>How do I return 401 to the client, based on the statusCode returned from the lambda? (non-proxy integration). How do I return the headers from the <code>headers</code> field? (for 401 and 200)</p> <pre><code>return { &quot;statusCode&quot;: 401, &quot;headers&quot;: {&quot;myHeader&quot;: 'abcd &quot;efg&quot;'} }...
<python><python-3.x><aws-lambda><aws-api-gateway>
2025-03-27 19:51:16
0
1,396
Rony Tesler
79,539,856
6,365,949
AWS Glue 5.0 "Installation of Python modules timed out after 10 minutes"
<p>I have an AWS Glue 5.0 job where I am specifying <code>--additional-python-modules s3://my-dev/other-dependencies /MyPackage-0.1.1-py3-none-any.whl</code> in my job options. My glue job itself is just a <code>print(&quot;hello&quot;)</code> job, because when I save and run this glue job, it runs for 10 minutes 7 sec...
<python><amazon-web-services><aws-glue>
2025-03-27 19:27:35
0
1,582
Martin
79,539,642
6,409,943
I updated to Spyder 6.05, and my kernel is now not loading
<p>I have been regularly updating my Spyder via the automatic updater (it is on a Windows), and today I updated Spyder to the newest version, and got the following error in the Console saying that it could not load the Konsole:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\user1\AppData\Local\sp...
<python><spyder>
2025-03-27 17:34:19
1
427
A. N. Other
79,539,574
1,697,288
SQLAlchemy mssql: Drop/Create Table on the Fly
<p>I've created a SQLAlchemy (2.0.39), Python (3.10.11) definition on the fly:</p> <pre><code> dynamic_class = type(table_name, (Base,), attributes) </code></pre> <p>This is working, now I want to drop any existing table and recreate it using the current definition (and where the problems kick in)</p> <pre><code> ...
<python><sql-server><sqlalchemy>
2025-03-27 17:04:15
1
463
trevrobwhite
79,539,458
3,120,501
How to prevent 3D Matplotlib axis extension past set_[x/y/z]lim()?
<p>I have an issue where the 3D axis limits set in Matplotlib are not respected in the plot, as shown by the minimal working example below. It can be seen that the extent of the plot goes beyond zero, where the 2D plane is plotted, despite x- and y- axis limits of zero being set in the code. This seems like a trivial i...
<python><matplotlib><matplotlib-3d>
2025-03-27 16:14:15
0
528
LordCat
79,539,387
7,483,211
browser-use agent stuck in loop at Step 1
<p>I'm using the quickstart code for the <code>browser-use</code> library in Python. However, the agent gets stuck in an infinite loop, repeatedly logging <code>INFO [agent] 📍 Step 1</code> without progressing or providing clear errors.</p> <p>I've added <code>BROWSER_USE_LOGGING_LEVEL=debug</code> but the extra log l...
<python><browser-use>
2025-03-27 15:51:04
1
10,272
Cornelius Roemer
79,539,046
785,494
How to use Jupyter notebooks or IPython for development without polluting the venv?
<p>Best practice for Python is to use <code>venv</code> to isolate to the imports you really need. I use <code>python -m venv</code>.</p> <p>For development, it's very convenient to use IPython and notebooks for exploring code interactively. However, these need to be installed into the venv to be used. That defeats ...
<python><jupyter-notebook><ipython><development-environment><python-venv>
2025-03-27 13:36:54
5
9,357
SRobertJames
79,539,001
8,622,053
How can I use a local Python package during development while keeping a Git dependency in pyproject.toml?
<p>I'm developing two Python projects:</p> <ul> <li>xxx: A Python library I maintain, hosted on GitHub.</li> <li>yyy: An open-source project that depends on xxx.</li> </ul> <p>In yyy's pyproject.toml, I declare the dependency as:</p> <pre><code>[tool.uv.sources] xxx = { git = &quot;git+https://github.com/myuser/xxx.git...
<python><dependency-management><pyproject.toml><uv>
2025-03-27 13:19:51
2
318
Daniel Chin
79,538,993
3,973,269
Azure Function app (python) deployment from github actions gives module not found
<p>I have the following github workflow which builds and deploys according to expectation. The only thing is that when I run a function, I get the following error message:</p> <pre><code>Result: Failure Exception: ModuleNotFoundError: No module named 'azure.storage'. Cannot find module. Please check the requirements.tx...
<python><azure><azure-functions><github-actions>
2025-03-27 13:18:02
1
569
Mart
79,538,804
3,062,183
Using explicit mocks for Typer CLI tests
<p>I want to write unit-tests for a Typer based CLI, that will run the CLI with different inputs and validate correct argument parsing and input validation. The point isn't to test Typer itself, but rather to test my code's integration with Typer.</p> <p>In addition, my CLI has some logic which I would like to mock dur...
<python><mocking><typer>
2025-03-27 12:11:06
0
1,142
Dean Gurvitz
79,538,656
25,413,271
Python Asyncio Condition: Why DeadLock appears?
<p>I learn python asyncio and now struggling with Conditions. I wrote a simple code:</p> <pre><code>import asyncio async def monitor(condition: asyncio.Condition): current_task_name = asyncio.current_task().get_name() print(f'Current task {current_task_name} started') async with condition: await c...
<python><python-asyncio>
2025-03-27 11:09:01
1
439
IzaeDA
79,538,611
3,225,420
How can I concatenate columns without quotation marks in the results while avoiding SQL injection attacks using psycopg?
<p>I want to concatenate with results like <code>concat_columns</code> here:</p> <p><a href="https://i.sstatic.net/4goxNALj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4goxNALj.png" alt="Results formatted properly" /></a></p> <p>In the example code below the results have quotation marks: <code>Housto...
<python><python-3.x><postgresql><psycopg3>
2025-03-27 10:52:48
2
1,689
Python_Learner
79,538,469
8,621,823
Is with concurrent.futures.Executor blocking?
<p>Why</p> <ul> <li>when using separate <code>with</code>, the 2nd executor is blocked until all tasks from 1st executor is done</li> <li>when using a single compound <code>with</code>, the 2nd executor can proceed while the 1st executor is still working</li> </ul> <p>This is confusing because i thought <code>executor....
<python><multithreading><multiprocessing><concurrent.futures><contextmanager>
2025-03-27 09:52:35
1
517
Han Qi
79,538,354
2,176,819
How to ignore forced obsolete syntax under Ruff v0.11
<p>I'm maintaining a code that is used under Python versions 3.12 and 3.13. Ruff from version 0.11 started to complain:</p> <pre><code>SyntaxError: Cannot reuse outer quote character in f-strings on Python 3.9 (syntax was added in Python 3.12) </code></pre> <p>Not a problem, as the code was not intended to be compatibl...
<python><ruff>
2025-03-27 09:13:50
0
403
gridranger
79,538,343
5,168,534
Remove Duplicate Dictionaries from a list based on certain numeric value
<p>I have a list of dictionary values which has duplicate name values. I would like to remove only the one whose value is less for the same name. For example, I have an input like below.</p> <pre><code>[{'name': 'x', 'value': 0.6479667110413355}, {'name': 'x', 'value': 1.0}, {'name': 'y', 'value': 0.9413355}, {'name...
<python><python-3.x><dictionary>
2025-03-27 09:09:59
2
311
anshuk_pal
79,538,310
8,472,781
Nondeterministic behaviour of openpyxl
<p>I have a Python script, that basically looks like this:</p> <pre><code>import mypackage # this function generates always the same pandas.DataFrame df = mypackage.create_the_dataframe() # write the DataFrame to xlsx and csv df.to_excel(&quot;the_dataframe_as.xlsx&quot;, index=False, engine=&quot;openpyxl&quot;) df....
<python><python-3.x><pandas><openpyxl>
2025-03-27 08:56:51
1
586
d4tm4x
79,538,217
1,256,529
Typing recursive type annotation
<p>I have a function which takes a value, a type annotation, and validates that the value is of the type.</p> <p>It only takes a certain subset of type annotations: <code>int</code>, <code>float</code>, <code>str</code>, <code>bool</code>, a <code>list</code> of any of these, or a (potentially nested) <code>list</code>...
<python><python-typing>
2025-03-27 08:12:16
1
3,817
samfrances
79,538,081
3,050,164
Second client connect() on unix domain socket succeeds even when listen() set to zero and server only accepts a single connection
<p>I am writing a Python 3-based server/client program using a Unix-domain socket. I am trying to build the server such that only a single client can connect to the server and subsequent connect() calls should return connection refused error until the connected client disconnects.</p> <p>The client behaves exactly as e...
<python><linux><unix-socket>
2025-03-27 07:10:30
0
590
Anirban
79,538,005
20,240,835
snakemake public remote s3 without secret key
<p>I am using snakemake with rule need visit public read-only s3 storage</p> <pre><code># test $ aws s3 ls 1000genomes/phase1/phase1.exome.alignment.index.bas.gz --no-sign-request 2012-05-01 03:58:41 423691 phase1.exome.alignment.index.bas.gz $ aws s3 cp s3://1000genomes/phase1/phase1.exome.alignment.index.bas.gz ....
<python><amazon-s3><storage><snakemake>
2025-03-27 06:28:53
0
689
zhang
79,537,989
6,862,601
Do we need to have a separate getter while using @property?
<p>I have these two methods inside a class:</p> <pre><code>@property def config_dict(self): return self._config_dict @config_dict.getter def config_dict(self): return self._config_dict </code></pre> <p>Do we really need the getter? Isn't it superfluous?</p>
<python>
2025-03-27 06:18:30
1
43,763
codeforester
79,537,934
1,397,843
Dot notation access in pd.Series() but with priority on elements in the index
<p>My aim is to implement a class that inherits from <code>pd.Series</code> class and acts as a container object. This object will hold varied objects as its elements in the form of</p> <pre><code>container = Container( a = 12, b = [12, 10, 20], c = 'string', name='this value', ) </code></pre> <p>I will be ...
<python><pandas><overriding>
2025-03-27 05:54:53
1
386
Amin.A
79,537,816
200,304
Editing two dependent Python projects simultaneously using Visual Studio Code
<p>I have a project <code>mylib</code> (a Python library) and a project <code>myapp</code> (an application that uses <code>mylib</code>). The two code bases live in unrelated directories. I'm trying to find a setup by which I can edit code in both simultaneously with support from Visual Studio Code.</p> <p>My plan had ...
<python><visual-studio-code>
2025-03-27 04:16:32
1
3,245
Johannes Ernst
79,537,654
875,806
Python typing for method that adds a property to some other type
<p>I'm trying to define types to indicate that a method returns the same type with additional property/properties.</p> <pre class="lang-py prettyprint-override"><code>class BaseModel(Protocol): @classmethod def model_validate(cls, db_entry) -&gt; Self: ... T = TypeVar('T', bound=BaseModel) class _HasDatabaseI...
<python><python-typing><mypy>
2025-03-27 01:49:00
0
4,388
CoatedMoose
79,537,648
2,063,900
How to get the session data in POS screen in odoo 18
<p>I make some user option and I want to read it from POS screen in version 18</p> <p>this is my code</p> <pre><code>class PosSession(models.Model):     _inherit = 'pos.session'     def _load_pos_data(self, data):         res = super(PosSession, self)._load_pos_data(data)         res['hide_product_information'] = self....
<javascript><python><odoo-18><odoo-owl>
2025-03-27 01:44:10
1
361
ahmed mohamady
79,537,560
280,002
Flasgger schema definition doesn't show in swagger-ui when using openapi 3.0.2
<p>I have an endpoint defined as such:</p> <pre class="lang-py prettyprint-override"><code>def process_document(): &quot;&quot;&quot; Process document --- definitions: JobSubmissionResponse: type: object properties: job_id: type: string...
<python><flask><openapi><swagger-ui><flasgger>
2025-03-27 00:21:24
0
1,301
alessandro ferrucci
79,537,461
16,563,251
Test that unittest.Mock was called with some specified and some unspecified arguments
<p>We can check if a <a href="https://docs.python.org/3/library/unittest.mock.html#the-mock-class" rel="nofollow noreferrer"><code>unittest.mock.Mock</code></a> <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_any_call" rel="nofollow noreferrer">has any call</a> with some specifie...
<python><python-unittest><python-unittest.mock>
2025-03-26 23:02:53
1
573
502E532E
79,537,428
219,153
Can I multiply these Numpy arrays without creating an intermediary array?
<p>This script:</p> <pre><code>import numpy as np a = np.linspace(-2.5, 2.5, 6, endpoint=True) b = np.vstack((a, a)).T c = np.array([2, 1]) print(b*c) </code></pre> <p>produces:</p> <pre><code>[[-5. -2.5] [-3. -1.5] [-1. -0.5] [ 1. 0.5] [ 3. 1.5] [ 5. 2.5]] </code></pre> <p>which is my desired output. Ca...
<python><arrays><numpy>
2025-03-26 22:42:55
5
8,585
Paul Jurczak
79,537,217
2,893,712
Nodriver Get Page Status Code and Refresh
<p>I am using nodriver to automate a website login. Sometimes the page will return a 403 error but refreshing the page will solve the issue. I am trying to add logic in my code to do this. Here is my code currently:</p> <pre><code>import nodriver as uc browser = await uc.start() async def myhandler(event: uc.cdp.netwo...
<python><undetected-chromedriver><nodriver>
2025-03-26 20:28:57
0
8,806
Bijan
79,537,198
1,875,932
When using venv, packages I'm building suddenly disappear when others are installed
<p>This is more of a where in pip could this be happening, not a question about the repos/packages.</p> <p>I'm building several pytorch related repos using their setup.py scripts. For example, <a href="https://github.com/pytorch/vision/blob/main/setup.py" rel="nofollow noreferrer">https://github.com/pytorch/vision/blob...
<python><python-3.x><pip><virtualenv><python-venv>
2025-03-26 20:22:17
1
793
NorseGaud
79,537,094
2,299,692
Failure to authenticate a SharePoint connection with AuthenticationContext
<p>I have the following python code in my Matillion PythonScript component:</p> <pre class="lang-py prettyprint-override"><code>from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.authentication_context import AuthenticationContext authority_url = “https://login.microsoftonline.us/...
<python><sharepoint><office365><etl><matillion>
2025-03-26 19:26:41
0
1,938
David Makovoz
79,537,070
2,072,516
Using alembic cli to build test database
<p>I'm attempting to build a pytest fixture that drops my test database, recreates it, and then runs my alembic migrations. When I run it, I get errors that my relationships don't exist, which seems to indicate alembic never ran:</p> <pre><code>@pytest.fixture(scope=&quot;session&quot;, autouse=True) def setup_database...
<python><database><testing><alembic>
2025-03-26 19:16:03
0
3,210
Rohit
79,537,058
22,285,621
Getting Authentication failed error while connecting with MS Fabric data Warehouse Using Node js and Python
<p>First I ahve used Node.js and tedious but it didn't work becase tedious library can't connect to fabric dwh because fabric has a bit different security layers and protocols, that tedious so far do not have. Now I have used ODBC library but got Authentication Error</p> <blockquote> <p>Microsoft][ODBC Driver 17 for SQ...
<python><sql><node.js><microsoft-fabric>
2025-03-26 19:11:18
1
988
M Junaid
79,536,999
4,897,557
Files written by Colab not appearing in finder
<p>I have written a function to download certain files to both a local directory and a google drive directory. The files do not appear in Finder, nor via an &quot;ls -la&quot; command in Terminal.<br /> When I run a Terminal Listing within my colab notebook, the files are listed in the expected directory structure:</...
<python><google-colaboratory>
2025-03-26 18:39:41
1
2,495
GPB
79,536,827
610,375
How can I specify console_scripts that are to be installed for a "variant"?
<p>The <a href="https://setuptools.pypa.io/en/latest/userguide/dependency_management.html#optional-dependencies" rel="nofollow noreferrer">Setuptools documentation</a> describes how to specify &quot;optional dependencies&quot; for what it calls a &quot;variant&quot; of a Python package.</p> <p>In <code>pyproject.toml</...
<python><setuptools>
2025-03-26 17:38:44
0
509
sappjw
79,536,740
889,053
In python: oracledb.connect simply hangs, even when the local client succeeds. Why?
<p>I am trying to connect to an Oracle DB using the <code>oracledb</code> connection library and when I try it It simply hangs on <code>with oracledb.connect</code> even when following the <a href="https://python-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html" rel="nofollow noreferrer">documentat...
<python><python-oracledb>
2025-03-26 17:02:03
1
5,751
Christian Bongiorno
79,536,730
2,110,463
mypy complains for static variable
<p>mypy (v.1.15.0) complains with the following message <code>Access to generic instance variables via class is ambiguous</code> for the following code:</p> <pre><code>from typing import Self class A: B: Self A.B = A() </code></pre> <p>If I remove <code>B: Self</code>, then is says <code>&quot;type[A]&quot; h...
<python><python-typing><mypy>
2025-03-26 16:59:22
1
2,225
PinkFloyd
79,536,716
2,287,458
Expand Struct columns into rows in Polars
<p>Say we have this dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({'EU': {'size': 10, 'GDP': 80}, 'US': {'size': 100, 'GDP': 800}, 'AS': {'size': 80, 'GDP': 500}}) </code></pre> <pre><code>shape: (1, 3) ┌───────────┬──────────...
<python><dataframe><python-polars><unpivot>
2025-03-26 16:53:00
5
3,591
Phil-ZXX
79,536,694
8,963,682
Alembic Autogenerate Incorrectly Trying to Drop alembic_version Table
<h2>Problem</h2> <p>I'm facing a strange issue with Alembic's autogenerate command when setting up the initial database migration for a PostgreSQL database with a public schema.</p> <p>When running <code>alembic revision --autogenerate -m &quot;Initial schema setup&quot;</code> against a database containing only an emp...
<python><database><postgresql><amazon-rds><alembic>
2025-03-26 16:42:34
1
617
NoNam4
79,536,571
8,954,691
Why does mypy not complain when overloading an abstract method's concrete implementation in the child class?
<p>I am trying to wrap my head around the <code>@overload</code> operator, generics and the Liskov Substitution Principle. I usually make my abstract classes generic on some typevar <code>T</code> which is followed by concrete implementations of child classes.</p> <p>For example please consider the following code:</p> ...
<python><python-typing><mypy><liskov-substitution-principle>
2025-03-26 13:28:14
1
703
Siddhant Tandon
79,536,473
2,806,338
Python, search from where import is call
<p>For managing transition from an old import to a new import, I search to log from where my module is used.</p> <p>By example, my old is name m_old.py. With a simple print in file m_old.py, I display a message &quot;used of old module&quot;. So each time there is &quot;import m_old.py&quot;, I have a message &quot;use...
<python>
2025-03-26 12:51:06
2
739
Emmanuel DUMAS
79,536,439
2,322,961
How to use an index URL in pip install when both the package and index are stored in Azure Storage
<p>I have stored both a Python package (<code>mypackage.whl</code>) and an <code>index.html</code> file (listing the package) in an Azure Storage Account (Blob Storage). I want to use <code>pip install</code> with --index-url to install the package directly from Azure Storage. However, <code>pip</code> does not recogni...
<python><azure><pip><azure-blob-storage>
2025-03-26 12:39:47
1
428
Jayesh Tanna
79,536,363
1,719,931
Logging operation results in pandas (equivalent of STATA/tidylog)
<p>When I do an operation in STATA, for example removing duplicated rows, it will tell me the number of rows removed, for instance:</p> <pre><code>. sysuse auto.dta (1978 automobile data) . drop if mpg&lt;15 (8 observations deleted) . drop if rep78==. (4 observations deleted) </code></pre> <p>For the tidyverse, the p...
<python><pandas>
2025-03-26 12:13:53
2
5,202
robertspierre
79,536,321
2,521,423
PySide6 signal not emitting properly when passed to decorator
<p>I have this decorator in python 3.11 that sends a signal encoding the arguments to a function call that it decorates, here:</p> <pre><code>def register_action(signal=None): def decorator(func): def wrapper(self, *args, **kwargs): # self is the first argument for instance methods result = fun...
<python><signals><python-decorators><pyside6><python-logging>
2025-03-26 11:55:14
1
1,488
KBriggs
79,536,212
14,498,767
How to send CSRF token using Django API and a Flutter-web frontend ? HeaderDisallowedByPreflightResponse
<p>I have a python/django web API with a single endpoint, let's call it <code>/api/v1/form</code>. That API is called from a Flutter-web frontend application. I currently use the following configuration that disables CSRF token verification, and it works :</p> <p><strong>requirements.txt</strong></p> <pre class="lang-n...
<python><django><flutter><csrf><django-csrf>
2025-03-26 11:06:27
0
549
SpaceBurger
79,535,943
7,599,215
How serve JS locally with folium JSCSSMixin class?
<p>I have modified ja/css of Leaflet.Measure plugin, and I want to use them in folium.</p> <p>So, I took <a href="https://github.com/python-visualization/folium/blob/main/folium/plugins/measure_control.py" rel="nofollow noreferrer">https://github.com/python-visualization/folium/blob/main/folium/plugins/measure_control....
<python><folium><folium-plugins>
2025-03-26 09:31:42
1
2,563
banderlog013
79,535,914
7,431,005
matplotlib latex text color
<p>I want to partially color some LaTeX text in my plot using the <code>\textcolor{}</code> command. I tried the following, but the text still appears black:</p> <pre><code>import matplotlib matplotlib.use('TKAgg') from matplotlib import rc rc('text',usetex=True) rc('text.latex', preamble=r'\usepackage{color}') import...
<python><matplotlib><latex>
2025-03-26 09:19:47
1
4,667
user7431005
79,535,841
11,829,002
Add a button to jump to location on the map
<p>I have a <code>folium.Map</code>, and I'd like to add buttons in the exported HTML file, so that when I click on them, it would change the view to the locations selected.</p> <p>Here is the Python code to generate the HTML map, with two buttons:</p> <pre class="lang-py prettyprint-override"><code>import folium m = ...
<python><html><folium>
2025-03-26 08:47:31
0
398
Thomas
79,535,789
149,900
SaltStack custom state: How to download file from "salt:" URI
<p>I'm trying to write a custom SaltStack state. It will be used like this:</p> <pre class="lang-yaml prettyprint-override"><code>Example of my.state usage: my.state: - name: /some/path - source: salt://path/to/dsl/file </code></pre> <p>This state is planned to grab a <code>file</code> from the Salt Master fi...
<python><salt-project>
2025-03-26 08:23:29
1
6,951
pepoluan
79,535,226
28,063,240
How to use csv module to make a generator of lines of a csv?
<pre class="lang-py prettyprint-override"><code>import csv from typing import Generator def get_csv_lines(rows: list[list[str]]) -&gt; Generator[str, None, None]: &quot;&quot;&quot; Generates lines for a CSV file from a list of rows. Args: rows (list[list[str]]): A list where each element is a l...
<python><python-3.x><csv>
2025-03-26 01:40:55
2
404
Nils
79,535,147
1,613,983
How do I avoid CPU for loops when inputs are a function of previous outputs?
<p>I have a simple reinforcement model in <code>pytorch</code> that makes decisions about where it wants to be and receives its current position (e.g. from a GPS) as an input. For the sake of this example let's just assume it can just move anywhere at any point (ie. it can just specify its position). In the real exampl...
<python><pytorch>
2025-03-26 00:21:43
0
23,470
quant
79,535,064
2,140,971
How to specificy custom serialization code for a specific query parameter when generating a python wrapper with openapi-generator-cli?
<p>In a OpenAPI v3 specification file, one query parameter expects a comma-separated list of strings:</p> <pre class="lang-yaml prettyprint-override"><code>paths: /content: get: description: Returns data for all given ids parameters: - description: Comma-separated list of ids in: query ...
<python><openapi><openapi-generator><openapi-generator-cli>
2025-03-25 23:21:28
0
753
Charles
79,534,956
11,233,365
Installing Rust-dependent Python packages by passing a custom `crates.io` mirror through `pip`
<p>I am trying to install <code>maturin</code> and other Python packages that depend on Rust backends on a firewalled PC that can only see a server that my team manages. We have previously been able to set up API endpoints that the PC can poke in order to install Python <code>pip</code> packages, but we have thus far b...
<python><pip><rust-cargo><mirror><maturin>
2025-03-25 21:57:44
1
301
TheEponymousProgrammer
79,534,809
11,062,613
How to overload numpy.atleast_2d in Numba to include non-ndarray data types?
<p>Numba does not have an implementation for numpy.atleast_1d() and numpy.atleast_2d() which includes other data types than arrays. I've attempted to overload atleast_2d, but I'm having trouble handling 2D reflected and typed lists correctly. I need help with the proper type checks for 2D reflected and typed lists to p...
<python><numpy><numba>
2025-03-25 20:32:03
0
423
Olibarer
79,534,761
5,413,581
GLMNET gives different solutions for lasso-based algorithms when I expect the same solution
<p>There are many ways to implement an adaptive lasso model. One of them would be to:</p> <ol> <li>Solve an unpenalized regression model and extract the <code>betas</code></li> <li>Define <code>w=1/abs(beta)</code></li> <li>Use these weights in an adaptive lasso model and obtain <code>beta2</code></li> </ol> <p>Another...
<python><r><glmnet><lasso-regression>
2025-03-25 20:12:30
0
769
Álvaro Méndez Civieta
79,534,562
6,439,229
PyQt 6.8 blank button bug?
<p><strong>Edit:</strong> This bug is fixed in PyQt 6.9</p> <p>After upgrading from PyQt 6.7 to 6.8, I noticed a strange thing in my app:<br /> Some, not all, of the disabled <code>QPushButtons</code> were blank (white and no text).</p> <p>It took some time to figure out the conditions for this bug.<br /> This was need...
<python><pyqt><pyqt6>
2025-03-25 18:27:06
0
1,016
mahkitah
79,534,333
6,843,153
Make stramlit-aggrid height dynamic
<p>I have a streamlit-aggrid grid and I want the height of it to be as much as rows are in the grid, but I haven't found how to set the grid, the only documental reference I have found is <a href="https://streamlit-aggrid.readthedocs.io/en/docs/AgGrid.html" rel="nofollow noreferrer">this</a>, and it says the <code>hei...
<python><ag-grid><streamlit>
2025-03-25 16:43:08
0
5,505
HuLu ViCa
79,534,318
778,533
dask: looping over groupby groups efficiently
<p>Example DataFrame:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import dask.dataframe as dd data = { 'A': [1, 2, 1, 3, 2, 1], 'B': ['x', 'y', 'x', 'y', 'x', 'y'], 'C': [10, 20, 30, 40, 50, 60] } pd_df = pd.DataFrame(data) ddf = dd.from_pandas(pd_df, npartitions=2) </code></pre...
<python><dataframe><group-by><dask><dask-dataframe>
2025-03-25 16:37:19
0
9,652
tommy.carstensen
79,534,138
5,422,354
How to compute the analytical leave-one-out cross-validation score of a polynomial chaos decomposition in Python?
<p>I have a function y = g(x1, ..., xd) where x1, ..., xd are the inputs and y is the output of the function g. I have a multidimensional multivariate sample X and the corresponding output sample Y from the function g. I have computed the polynomial chaos expansion of this function. How to estimate the Q2 leave-one-out...
<python><openturns>
2025-03-25 15:28:13
1
1,161
Michael Baudin
79,534,021
1,588,847
Modify function args with mypy plugin (for lazy partial functions)
<p>I have a python decorator. All functions it decorates must accept a <code>magic</code> argument. If the <code>magic</code> argument is supplied, the decorated function is evaluated immediately and returned. If the <code>magic</code> argument is not supplied, a partial function is returned instead, allowing for lazy...
<python><mypy>
2025-03-25 14:42:59
0
2,124
Jetpac
79,533,927
539,490
Elegantly handling python type hint for Shapely polygon.exterior.coords
<p>I'm using Python 3.12 and I would like to return <code>polygon.exterior.coords</code> as a type of <code>list[tuple[float, float]]</code> so that I can correctly enforce typing later in the program. I'm wondering if there is a more elegant solution:</p> <pre class="lang-py prettyprint-override"><code>from shapely i...
<python><python-typing><shapely>
2025-03-25 14:07:02
2
29,009
AJP
79,533,867
9,112,151
How to display both application/json and application/octet-stream content types in Swagger UI autodocs in FastAPI?
<p>I have an endpoint that can return JSON or a file (xlsx):</p> <pre class="lang-py prettyprint-override"><code>class ReportItemSerializer(BaseModel): id: int werks: Annotated[WerkSerializerWithNetwork, Field(validation_alias=&quot;werk&quot;)] plu: Annotated[str, Field(description=&quot;Название PLU&quot;...
<python><swagger><fastapi><openapi><swagger-ui>
2025-03-25 13:48:18
1
1,019
Альберт Александров
79,533,856
8,240,910
FastAPI StreamingResponse not sending message without putting sleep
<p>I am creating simple proxy for streaming, It works but I need to put sleep, without sleep it only sending last message, I tried to sleep 0, and other approaches but not working.</p> <pre class="lang-py prettyprint-override"><code>import logging import yaml import httpx import json from fastapi import FastAPI, Reques...
<python><streaming>
2025-03-25 13:42:22
0
712
Bhautik Chudasama
79,533,301
9,622,249
Accessing an element inside an iframe using nodriver
<p>I have recently switched from selenium to nodriver for speed and stealth reasons. I am having trouble accessing elements inside an iframe even though material on this site and elsewhere says that 'Using nodriver, you don't need to switch to iframe to interact with it. nodriver's search methods automatically switch t...
<python><web-scraping><iframe><nodriver>
2025-03-25 10:03:30
0
352
Stephen Smith
79,533,209
5,547,553
Simplest way to convert aggregated data to visualize in polars
<p>Suppose I have aggregated the mean and the median of some value over 3 months, like:</p> <pre><code>df = (data.group_by('month_code').agg(pl.col('value').mean().alias('avg'), pd.col('value').median().alias('med') ) .sort('month_cod...
<python><dataframe><python-polars><altair><unpivot>
2025-03-25 09:28:14
2
1,174
lmocsi
79,533,113
3,813,371
Apps aren't loaded yet
<p>I'm using Visual Studio 2022 as the IDE. It has 2 projects:</p> <ol> <li>CLI - A Python Application</li> <li>Common - A Blank Django Project</li> </ol> <p>The classes are created in Common &gt; app &gt; models.py.<br /> <code>app</code> is a <code>Django app</code></p> <p><a href="https://i.sstatic.net/oTOMgucA.png"...
<python><django><visual-studio><django-models><visual-studio-2022>
2025-03-25 08:49:39
2
2,345
sukesh