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,401,639
498,537
I am attempting to use Django Ninja for the first time and running into a strange error
<p>I cant quite understand error I am receiving. I am simply trying to setup a model schema for my model. I am an old Django hand but ninja is new for me. What am I doing wrong here? Would love some help and feedback.</p> <p>My model is this</p> <pre><code>class Program(models.Model): mentor = models.ForeignKey...
<python><django><django-ninja>
2025-01-31 02:16:26
1
2,308
vivekv
79,401,525
9,951,273
Overloaded method invocation causes type check error
<p>I posted a <a href="https://stackoverflow.com/questions/79401185/overload-a-method-based-on-init-variables">question earlier</a> asking how to overload Python methods using generics.</p> <p>The solution provided is shown below.</p> <pre><code>from __future__ import annotations from typing import Literal, overload c...
<python><python-typing>
2025-01-31 00:10:57
1
1,777
Matt
79,401,467
10,969,942
How to trace the caller of an async function in VS Code Debug mode when the call stack is lost?
<p>I am debugging a Python <code>async</code> function in VS Code, and I have hit a breakpoint inside the function. However, the call stack in the debug panel does not show the parent function that called it. Since without <code>await</code> it clears the synchronous call stack, I cannot see who originally invoked the ...
<python><python-3.x><visual-studio-code><python-asyncio><vscode-debugger>
2025-01-30 23:28:37
1
1,795
maplemaple
79,401,282
1,165,268
Unable to import azure.kusto.ingest
<p>I’m trying to import azure.kusto.ingest in my Python script, but I’m getting an ImportError stating that the module cannot be found.</p> <p>I’ve already installed the required package using:</p> <p><code>pip install azure-kusto-ingest</code></p> <p>To confirm that the package is installed, I ran:</p> <p><code>pip sh...
<python><azure-data-explorer>
2025-01-30 21:33:50
1
1,242
Robert
79,401,186
3,245,855
Kivy Dynamic Image Grid View
<p>I'm using python kivy. I want to display cards containing a title and underneath an image, in a grid with 5 columns.</p> <p>The behavior of the following snippet is 90% of what I want. The images always fit the same space, leaving empty space up/down or left/right, so they maintain aspect ratio. The only problem is ...
<python><kivy>
2025-01-30 20:39:58
1
1,119
Andrew
79,401,185
9,951,273
Overload a method based on init variables
<p>How can I overload the <code>get_data</code> method below to return the correct type based on the init value of <code>data_type</code> instead of returning a union of both types?</p> <pre><code>from typing import Literal DATA_TYPE = Literal[&quot;wood&quot;, &quot;concrete&quot;] class WoodData: ... class Concrete...
<python><python-typing>
2025-01-30 20:39:37
1
1,777
Matt
79,401,030
5,312,606
Good way to define new Protocol for collection types
<p>I would like to define a new structural type for my code that is basically a non-mutable, ordered set.</p> <p>The following code captures the gist of it</p> <pre class="lang-py prettyprint-override"><code>from ordered_set import OrderedSet from typing import Protocol, TypeVar from collections.abc import Set, Sequen...
<python><containers><python-typing>
2025-01-30 19:28:13
0
1,897
mcocdawc
79,400,993
11,062,613
Choosing an optimal partitioning strategy for a delta lake table on a laptop
<p>I’m working on a data pipeline using Polars and Delta Lake to store and update a grouped time series on a laptop with 16GB RAM. The dataset consists of a daily time series with ~1,000 unique groups with a history of 125 years. I cannot manage the entire dataset in a single Parquet file, so I chose Delta Lake as the ...
<python><parquet><python-polars><delta-lake>
2025-01-30 19:11:47
0
423
Olibarer
79,400,976
8,365,359
Im using polars library, but I'm getting 'NameError: name 'PyLazyFrame' is not defined using polars'. Im' using python 3.9 and polars 1.21.0
<p>Im trying to get data from a parquet file using SQL syntax.</p> <p>The code:</p> <pre><code>import polars as pl # Ensure the variables are defined parquet_file = r'C:\Users\Kperez\Documents\md_curated_20250115.parquet' date = &quot;2024-12-13&quot; df3 = pl.read_parquet(parquet_file) # Register the DataFrame as a...
<python><parquet><python-polars><python-3.9><polars>
2025-01-30 19:05:37
2
430
qarly_blue
79,400,971
8,972,038
How to check total no. of tokens while using Langchain's 'create_pandas_dataframe_agent'?
<p>I am using langchain's <code>create_pandas_dataframe_agent</code> agent to analyse a dataframe. The code looks like below:</p> <pre><code>from langchain_experimental.agents import create_pandas_dataframe_agent import pandas as pd from langchain_openai import AzureOpenAI df = pd.read_csv(&quot;file_path&quot;) llm ...
<python><large-language-model><py-langchain><langchain-agents>
2025-01-30 19:03:15
1
418
Ankush Pandit
79,400,928
13,971,251
Server error when trying to access webpage with Requests, but no error with Selenium
<p>I have a script that uses the <code>requests</code> module to check a webpage for news updates. It worked up until a week ago, but now I am having a weird error. I am able to access the base url (<a href="http://www.example.com" rel="nofollow noreferrer">www.example.com</a>) using <code>requests</code>, but when I g...
<python><selenium-webdriver><python-requests>
2025-01-30 18:46:32
0
1,181
Kovy Jacob
79,400,827
2,079,306
Python FLASK Webapp zips a number of large files based on user selection, but the user doesn't know if it's hung
<p>Running a FLASK Python web application that zips up a number of files and serves them to the user based on the user's filters.</p> <p>Issue, after the user clicks download the backend pulls all the files and zip creation starts, but this can take minutes. The user won't know if it's hung.</p> <p>I decided streaming ...
<python><web-applications><http-headers><zip><content-length>
2025-01-30 18:03:30
1
1,123
john stamos
79,400,733
2,130,515
How to access Gradio components created dynamically in a global function
<p>My goal:</p> <ol> <li>drop a list of files.</li> <li>Read files and extract columns.</li> <li>Dynamically generate dropdown componenets so the user can select the source and target columns.</li> <li>I need to return (globally) all the selections, so I can use them with process_files() function. I think (3) it should...
<python><gradio>
2025-01-30 17:29:54
0
1,790
LearnToGrow
79,400,679
4,767,670
Plotting lambda functions in Python and mpmath.plot
<p>I'm using the <code>mpmath</code> plot function (which simply uses pyplot, as far as I understood).</p> <p>Consider the following code:</p> <pre><code>from math import cos, sin import mpmath as mp mp.plot([sin, cos], [0, 3]) # this is fine l = [sin, cos] mp.plot([lambda x: f(2*x) for f in l], [0, 3]) # this only p...
<python><lambda><mpmath>
2025-01-30 17:10:58
1
1,807
NYG
79,400,579
13,046,093
How to create a column with randomly generated values in a pandas dataframe
<p>I want to assign a random float (from 0 to 1) to a column that contains unique value within a Pandas dataframe.</p> <p>Below is a dataframe with unique value of &quot;region&quot;; I want to create a new column with a unique randomly generated float (between 0 to 1) corresponds to each region.</p> <p>I used random f...
<python><pandas><random><random-seed>
2025-01-30 16:31:05
1
460
user032020
79,400,574
4,725,074
How to enforce string type when reading CSVs in DuckDB?
<p>I'm trying to read a CSV in DuckDB (Python) but one of the records has a string ID while the rest of the file has the ID field as an integer.</p> <p>I'd like to force reading it as a string, how to do it?</p>
<python><csv><duckdb>
2025-01-30 16:30:39
2
5,892
Vzzarr
79,400,538
1,025,702
Import module that defines SQLAlchemy ORM models, dynamically injecting a base class, but with static type checking
<p>I'm refactoring a Python codebase to be modular, with each module defining its own SQLAlchemy models. Because the models are all defined in separate schema files which can be included or excluded based on an envfile, there needs to be a single <code>declarative_base()</code> which they all use.</p> <p>The way I've a...
<python><sqlalchemy><python-typing>
2025-01-30 16:18:26
0
9,400
Matt Fletcher
79,400,512
22,638,257
Attempting to preserve statefullness for a `st.dataframe` widget in a multipage Streamlit app
<h1>Background</h1> <p>I have a multipage Streamlit app with the following project directory structure:</p> <pre><code>β”œβ”€β”€ Home.py β”œβ”€β”€ utils.py β”œβ”€β”€ Pages β”‚ β”œβ”€β”€ Data_Entry.py </code></pre> <p>This is a multi-page app where I'm trying to preserve the statefullness of the widgets in the Data_Entry.py script.</p> <p>For ...
<python><streamlit>
2025-01-30 16:07:57
0
476
AcrKnight
79,400,489
29,295,031
how to compare two datafram and retrieve only the extre rows using pandas
<p>I have a usecase where I have two dfs :</p> <p>the first df1 :</p> <p><a href="https://i.sstatic.net/ZpP5DdmS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZpP5DdmS.png" alt="enter image description here" /></a></p> <p>the second df2 :</p> <p><a href="https://i.sstatic.net/LbMqnJdr.png" rel="nofollo...
<python><pandas><dataframe><streamlit>
2025-01-30 15:58:39
0
401
user29295031
79,400,433
1,406,168
azure function app python - Encountered an error (InternalServerError) from host runtime
<p>I have created a very simple azure function in python but keep getting folowing error when trying to run it. I cant find anything in app insights:</p> <p><a href="https://i.sstatic.net/gYkFA0iI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gYkFA0iI.png" alt="enter image description here" /></a></p> ...
<python><azure><azure-functions>
2025-01-30 15:43:07
1
5,363
Thomas Segato
79,399,929
1,221,812
How to sample Pandas DataFrame using a normal distribution by using random_state and numpy Generators
<p>I am trying to write Pandas code that would allow me to sample DataFrame using a normal distribution. The most convinient way is to use random_state parameter of the sample method to draw random samples, but somehow employ numpy.random.Generator.normal to draw random samples using a normal (Gaussian) distribution.</...
<python><pandas><numpy><random><sample>
2025-01-30 12:38:50
1
473
pjercic
79,399,822
8,477,566
Dynamic argument types in Python + argparse
<p>I want to create a CLI using Python and <code>argparse</code>. The CLI should have options to specify a list of values, and also to dynamically specify the <em>type</em> of the values (<code>str</code>, <code>int</code>, <code>float</code>, etc.) in that list (all arguments in the list have the same type). The value...
<python><command-line-interface><argparse>
2025-01-30 11:56:17
2
1,950
Jake Levi
79,399,788
8,596,146
503 error when running a python application on planet hoster / N0C
<p>I'm trying to create a simple python application on planet hoster which use the N0C interface (instead of cpanel), I didn't add any code (run.py contains only the template for the 200 ok message) I tried with several versions of Python just in case (8, 9, 11, 12) but keep getting the same 503 error when I try to lau...
<python><cpanel><wsgi><http-status-code-503>
2025-01-30 11:42:46
0
333
GG24
79,399,699
13,343,354
Is cv.findEssentialMat using matlab in someway?
<p>I was looking to find a way to get essential matrix in opencv.</p> <p>I found these two links that was for the function: <a href="https://docs.opencv.org/3.4/d9/d0c/group__calib3d.html#ga0b166d41926a7793ab1c351dbaa9ffd4" rel="nofollow noreferrer">https://docs.opencv.org/3.4/d9/d0c/group__calib3d.html#ga0b166d41926a7...
<python><matlab><opencv><image-processing><computer-vision>
2025-01-30 11:13:52
1
309
Shaig Hamzaliyev
79,399,419
5,558,497
VS code no longer displays value of variable when mouse-hovering it
<p>Sometime ago, I remember that when I was hovering over a declared variable in a python script (not in debug mode), I could see its value. That was very handy, as (I) I could see the value of the variable right away and (II) I could copy the value if necessary.</p> <p>I regularly update VS code as well as the python ...
<python><visual-studio-code>
2025-01-30 09:38:55
2
2,249
BCArg
79,399,353
859,141
Insert or update when importing from JSON
<p>My SQLAlchemy ORM model is populated by a JSON file that occasionally changes. The JSON file does not provide an integer primary key but has a unique alphanumeric ProductCode. My model:</p> <pre class="lang-py prettyprint-override"><code>class ProductDescriptor(Base): __tablename__ = 'product_descriptor' id...
<python><sqlite><sqlalchemy><upsert>
2025-01-30 09:20:53
1
1,184
Byte Insight
79,398,889
9,477,704
Issue in running pipelines associated with multiple function apps in the same ADF
<p>I'm implementing an Azure queuing mechanism to trigger multiple pipleines at the same time. I have two function apps, functiona_app1, functiona_app2. In each of these function apps, I have two pipelines created one for current customer and one for new customer. My requirement is that one pipeline should be triggered...
<python><python-3.x><azure-functions><azure-pipelines><azure-data-factory>
2025-01-30 05:38:14
0
499
Lahari
79,398,651
6,884,080
Packages do not show up in the list after running `pipenv install`
<p>Just came across a very weird behavior of pipenv that I don't quite understand.</p> <p>Here is my environment</p> <ul> <li>Running terminal and iTerm2 under Rosetta</li> <li>Python 3.11.9 installed via Pyenv (2.4.8) and set as global <code>pyenv global 3.9.11</code></li> <li>Another Python 3.11.9 installed using the...
<python><packaging><pipenv><pipfile>
2025-01-30 02:23:20
0
529
infinity_coding7
79,398,606
4,000,073
Install & use Python with any IDE offline
<p>I teach Python in a small org. where internet is disabled in the lab-systems due to some mis-usage/security issues. So pip installations OR installing any extension for any IDE is not possible.</p> <p>I have copied (using USB drive) &amp; installed python v3.13, VS-Code.I face problems executing Python scripts using...
<python><ide><offline>
2025-01-30 01:53:09
2
311
Venkata
79,398,599
6,702,598
Python testing: How can I verify that no error logs were thrown?
<p>In my test I want to verify that no error log was done during the test. How do I do that?</p> <p>I tried <code>with self.assertLogs(&quot;&quot;, level=&quot;ERROR&quot;) as error_logs:</code>. This can capture the error logs, but it will also raise if there were no error logs at all.</p>
<python><python-3.x><unit-testing><python-unittest>
2025-01-30 01:45:55
1
3,673
DarkTrick
79,398,519
6,141,238
Why do I receive an InvalidOperationError "file encoding is not UTF-8" when trying to write_csv with Polars?
<p>The code in the accepted answer of <a href="https://stackoverflow.com/questions/75272909">this</a> question is as follows:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df1 = pl.DataFrame({&quot;a&quot;: [1, 2], &quot;b&quot;: [3 ,4]}) df2 = pl.DataFrame({&quot;a&quot;: [5, 6], &quot;b&quo...
<python><dataframe><csv><utf-8><python-polars>
2025-01-30 00:25:03
0
427
SapereAude
79,398,514
8,037,521
Adjusting (center & rotation) of oriented bounding box to best fit points
<p>I have 3D points from noisy detection of one planar surface. I want to fit an oriented bounding box for these points.</p> <p>I assume (it should hold in my case) that the edges are much lighter than the inner parts (i.e. higher intensity), so I approximately filter it by intensity to get only points close to the edg...
<python><open3d>
2025-01-30 00:19:36
1
1,277
Valeria
79,398,347
6,024,187
EvalCallback hangs in stable-baselines3
<p>I'm trying to train an A2C model in stable-baselines3 and the EvalCallback appears to freeze when it is called. I cannot figure out why. Below you will find a script that recreates this problem. Before that, here is the output of the various print statements spread throughout to monitor where the program is:</p> ...
<python><python-3.x><reinforcement-learning><stablebaseline3>
2025-01-29 22:34:12
1
897
Finncent Price
79,398,345
12,609,881
How to determine if checksums are present in parquet file?
<p>I recently came across an error when reading a parquet table in pyspark:</p> <pre><code>Caused by: org.apache.parquet.io.ParquetDecodingException: could not verify page integrity, CRC checksum verification failed </code></pre> <p>This table was transferred over FTP. The error was resolved when I deleted the table in...
<python><pyspark><parquet><pyarrow>
2025-01-29 22:33:01
0
911
Matthew Thomas
79,398,317
2,955,608
Violin plot - Concatenating two violins in one
<p>I have a dataframe for which I am plotting violin plot. The dataframe has two categories A and B and highly imbalance data (one df has 1000 samples/rows and other has 200). I want to compare both categories and I believe looking at violin plot will give more information about distribution. While plotting it, I can p...
<python><seaborn><violin-plot>
2025-01-29 22:10:03
0
585
eshaa
79,398,246
1,172,907
What is meant with validation for django imagefield?
<p>The <a href="https://docs.djangoproject.com/en/5.1/ref/models/fields/#django.db.models.ImageField" rel="nofollow noreferrer">ImageField docu</a> states:</p> <blockquote> <p>Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.</p> </blockquote> <p>Yet any s...
<python><django>
2025-01-29 21:31:43
1
605
jjk
79,398,217
9,393,102
InaccessibleTensorError when using multiple TensorArrays in a list
<p>I am implementing a fairly complex network structure where I need to loop over a (possibly variable) time dimension, compute values at each step, and collect all these values, and do this for multiple layers. The values at each layer could have different shapes. I want to compile to a <code>tf.function</code> to spe...
<python><tensorflow><tensorflow2.0><tensorflow-autograph>
2025-01-29 21:19:47
1
10,639
xdurch0
79,398,178
581,467
Variable type for list and list[str] values
<p>What type should I set instead of TYPE1 and TYPE2 for x, y values?</p> <pre><code>x: TYPE1 = list y: TYPE2 = list[int] </code></pre> <p>For TYPE1 case, if I set</p> <pre><code>type T = int | str | bool x: type[list[T]] = list </code></pre> <p>mypy returns no errors, but why everything is ok here if value - &quot;lis...
<python><python-typing>
2025-01-29 20:59:22
1
896
sector119
79,398,160
1,115,716
Running two subprocesses together
<p>I need to gather some performance data on some GPU renders in Blender, some of these are very short, like under 5 seconds. I currently run the render via my benchmarking script like so:</p> <pre><code>render_command_to_run = '{} {} --background --python {} -- --number {} --save {}'.format( render_executa...
<python><nvidia><blender>
2025-01-29 20:53:16
0
1,842
easythrees
79,398,117
595,305
How does sys.getswitchinterval() work with PyQt?
<p>From <a href="https://docs.python.org/3/library/sys.html#sys.setswitchinterval" rel="nofollow noreferrer">the docs</a>: <code>setswitchinterval</code></p> <blockquote> <p>Set the interpreter’s thread switch interval (in seconds). This floating-point value determines the ideal duration of the β€œtimeslices” allocated t...
<python><multithreading><pyqt><sleep><gil>
2025-01-29 20:34:11
0
16,076
mike rodent
79,398,024
7,553,746
How to render a Jinja2 template field with correct capitalisation depending on field location?
<p>I am trying to render an HTML field with the same string, in this example it's &quot;pots and pans&quot;. I need to ensure that if the {{ example_field }} is at the beginning of sentence it is capitalised and if not it's lowercase.</p> <p>I've tried numerous iterations on the following and this is where I got to wh...
<python><jinja2>
2025-01-29 19:49:30
1
3,326
Johnny John Boy
79,398,020
2,779,479
command not found when trying to use rsync on Vercel
<p>I have a python script which runs as part of <code>yarn build</code> for my static-site project deployed to Vercel. The script uses <code>rsync</code> to do some file copying, using <code>os.system</code> to make the call to rsync from within the python script: <code>os.system(f&quot;rsync -a {full_path} dest_path&q...
<python><vercel>
2025-01-29 19:48:09
0
360
Blargian
79,397,851
10,658,339
How to resize twin axis matplotlib
<p>I'm trying to overlay two figures in a plot, but when I use the twin axes as default, the resulting plot doesn't make much sense. I need to move the second figure (the one to be overlaid) to the top of the first graph. How can I adjust the y-axis so that it also moves to the top, without losing the information, ensu...
<python><matplotlib><axis>
2025-01-29 18:44:39
0
527
JCV
79,397,808
17,837,614
"socket" has no attribute "accept"
<p>Why is mypy complaining?</p> <blockquote> <p>&quot;socket&quot; has no attribute &quot;accept&quot; [attr-defined]</p> </blockquote> <pre class="lang-py prettyprint-override"><code>import socket def a() -&gt; socket.SocketType: ... b = a() c, _ = b.accept() </code></pre> <p>It seems like <a href="https://git...
<python><python-typing><mypy><python-sockets>
2025-01-29 18:30:40
1
405
Sujay
79,397,701
14,632,200
Unable to find candidates for torch
<p>So I am trying to install torch on one of my projects and my specs are as below</p> <p>Python 3.12.3 / pip latest / Poetry (version 2.0.1)/ I am on Apple M3 Max</p> <p>Here is my <em>pyproject.toml</em></p> <pre><code>torch = { version = &quot;^2.5.1+cpu&quot;, source = &quot;pytorch-cpu&quot; } torchvision = { vers...
<python><macos><pytorch><python-poetry>
2025-01-29 17:50:17
1
459
Olsi Hoxha
79,397,624
17,837,614
Missing type parameters for generic type "StrictRedis"
<pre><code>import redis a = redis.StrictRedis(host=&quot;a&quot;, port=123, db=0, decode_response=true) </code></pre> <p>Mypy is giving error <code>Missing type parameters for generic type &quot;StrictRedis&quot; [type-arg]</code></p> <p>Python version: <code>3.9.20</code></p> <p>Mypy version: <code>1.14.1</code></p>...
<python><python-typing><mypy>
2025-01-29 17:22:31
2
405
Sujay
79,397,519
1,615,108
A solution to multiprocessing in Python without the if __name__ == '__main__' guard
<p><strong>TLDR</strong></p> <p>Normally, any Python module that internally uses multiprocessing causes all scripts that import it to have to include the &quot;guard&quot; clause.</p> <p>With the trick described, this guard is no longer necessary. People importing such a module in their scripts can write short and simp...
<python><python-3.x><multiprocessing><spawn>
2025-01-29 16:49:26
1
414
dominecf
79,397,447
7,971,750
PyCharm Flask configuration uses the wrong folder as working directory?
<p>For no apparent reason, Flask decided to use a folder one level above the actual project directory.</p> <p>Project details:</p> <ul> <li>Working directory in Run/Debug is set correctly</li> <li>Python console in PyCharm starts in the correct directory</li> <li>The parent folder is mentioned once -- in the &quot;Path...
<python><flask><pycharm>
2025-01-29 16:24:37
1
322
bqback
79,397,184
8,622,976
pip install from Git repository fails with "does not appear to be a Python project" when using branch with subdirectory
<h3>pip install Fails with &quot;does not appear to be a Python project&quot; When Installing from Git Repository with Subdirectory</h3> <p>I'm attempting to install a Python package from a specific branch of a Git repository using the following command:</p> <pre class="lang-bash prettyprint-override"><code>pip install...
<python><pip>
2025-01-29 15:06:43
1
2,103
Alon Barad
79,397,169
5,873,325
Hide sidebar buttons when switching tabs
<p>Let's say i have this small streamlit application with a sidebar that contains 4 buttons for example (Button 1, ..., Button 4). And in the main panel, I have two tabs (Tab 1 and Tab 2).</p> <p>Now I want this :</p> <ul> <li><p>When I select Tab 1, <strong>ONLY</strong> display Button 1 and Button 2 and hide Button 3...
<python><streamlit>
2025-01-29 15:02:13
0
640
Mejdi Dallel
79,397,040
857,741
Is using tempfile.mkstemp()[1] leaks open file handles?
<p>I'm using <code>tempfile.mkstemp()[1]</code> in some class frequently. I'm doing some operations on the created file and then delete it.</p> <p>I'm not using context manager with <code>with</code> or smth like that, just using the filename.</p> <p>Obviously, <code>tempfile.mkstemp()</code> returns a tuple of opened ...
<python><resource-leak>
2025-01-29 14:19:40
1
6,914
LetMeSOThat4U
79,396,950
19,369,310
Converting a pandas dataframe in wide format to long format
<p>I have a Pandas dataframe in wide format that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Class_ID': {0: 432, 1: 493, 2: 32}, 'f_proba_1': {0: 3, 1: 8, 2: 6}, 'f_proba_2': {0: 4, 1: 9, 2: 9}, 'f_proba_3': {0: 2, 1: 4, 2: 1}, ...
<python><pandas><dataframe><pandas-melt>
2025-01-29 13:50:27
1
449
Apook
79,396,916
6,573,902
Forbidden (403) CSRF verification failed. Request aborted. while logging in in Label Studio
<p>Once <code>labelstudio</code> is updated to version</p> <p>and run from commandline:</p> <pre><code>LABEL_STUDIO_DISABLE_SIGNUP_WITHOUT_LINK=true CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 HOST='https://...' nohup label-studio -b --data-dir /label-studio/data/ -db /label-studio/db.sqlite --log-level INFO --internal-host local...
<python><python-3.x><django><label-studio>
2025-01-29 13:35:26
1
17,233
sophros
79,396,714
3,873,510
How to add a format script in a Poetry project that runs the Black formatter over a specific directory?
<p>I would like to add a script to my Poetry project that runs the Black formatter over a specific directory. I wrote this:</p> <pre class="lang-ini prettyprint-override"><code>[tool.poetry.scripts] format-scripts = &quot;black:main scripts/**/*.py&quot; </code></pre> <p>But it doesn't work. I am getting this error...
<python><python-poetry>
2025-01-29 12:22:50
0
22,246
Paul Razvan Berg
79,396,708
1,046,007
How to best change the colour of the Python prompt?
<p>I have an alias for python3 and one for a Python calculator (<code>pm</code> for Python Math):</p> <pre class="lang-bash prettyprint-override"><code>alias p3='python3 -q' alias pm='python3 -qic&quot;from math import *; import sys; sys.ps1=\&quot;] \&quot;; sys.ps2=\&quot;… \&quot;&quot;' </code></pre> <p>Since Pytho...
<python><python-3.x><read-eval-print-loop><ansi-escape>
2025-01-29 12:19:05
1
12,702
Walter Tross
79,396,461
8,354,130
FAISS Db Vector Search
<p>I am combining two embeddings and both are numerical embeddings both having shape (1,1)</p> <pre><code>combined_embeddings = np.hstack((price_embeddings, location_embeddings)) index = faiss.IndexFlatL2(combined_embeddings.shape[1]) index.add(np.array(combined_embeddings, dtype=np.float32)) </code></pre> <p>Now if I ...
<python><faiss><vector-search>
2025-01-29 10:43:44
1
374
Nikhil
79,396,399
7,076,616
Checking for variable when evaluating When inside .agg
<p>I have a function <code>check_fun</code> where the user inputs one <code>table</code> and additional argumments of column names. This function later on evaluates some checks depending on which variables has been inputed in the function call. This works fine but each evaluation and append takes a lot of time. How ca...
<python><pyspark>
2025-01-29 10:24:52
1
2,579
MLEN
79,396,219
865,169
Is there (a Python implementation of) an average-consistent interpolation method?
<p>I have a time series of values at low temporal resolution where the values represent an average of the respective surrounding intervals. Let's use hourly resolution for a simple example (in Python):</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd s_resample_test = pd.Series([0, 1, 2, 1, 0, -1...
<python><time-series><resampling>
2025-01-29 09:19:26
0
1,372
Thomas Arildsen
79,396,162
1,982,032
Smart way to write dataframe into an openoffice-ods excel with an existing file?
<p>We can write dataframe into a new excel file:</p> <pre><code>x1 = np.random.randn(100, 2) df1 = pd.DataFrame(x1) with pd.ExcelWriter('/tmp/sample.xlsx') as writer: df1.to_excel(writer, sheet_name='x1') </code></pre> <p><code>/tmp/sample.xlsx</code> is a new created xlsx file containing <code>df1</code>.</p> <p...
<python><dataframe><ods>
2025-01-29 08:56:07
0
355
showkey
79,396,002
3,825,996
Inheriting from NamedTuple causes "Overloaded function signatures 1 and 2 overlap with incompatible return types" in mypy
<p>I think this is a bug in mypy but I'm not sure:</p> <pre class="lang-py prettyprint-override"><code>from typing import overload, NamedTuple class A(NamedTuple): pass class B(NamedTuple): pass @overload def frobnicate(arg: A) -&gt; A: ... @overload def frobnicate(arg: B) -&gt; B: ... def frobnicate(arg: ...
<python><overloading><python-typing><mypy><namedtuple>
2025-01-29 07:29:24
0
766
mqnc
79,395,963
9,194,121
Can I call python script in c#?
<p>I have a C# project which is a simple console application, which takes an input from the user and returns an output.</p> <p>In this solution I have created a Python file named app.py along with a virtual environment named env and a requirements.txt file. This Python file takes an input and returns an output.</p> <p>...
<python><c#>
2025-01-29 07:14:10
1
909
arman
79,395,716
7,088,487
Solving Rotor Output Issues in Enigma Machine Emulation
<p>I'm implementing an Enigma machine in Python for a course assignment. For a specific case, I’m unable to get the expected output result as explained in one of the test cases.</p> <p>To investigate further, I emulated the input and settings using the online emulator at <a href="https://www.101computing.net/enigma-mac...
<python><enigma2>
2025-01-29 04:24:35
0
700
Kamran Asim
79,395,514
10,262,805
Python Socket Communication Breaks When Removing print Statement
<p>I send multi line python string with socket:</p> <pre><code> elif command==&quot;help&quot;: help_options=''' download &lt;path&gt; -&gt; Download a File from Target Machine upload &lt;path&gt; -&gt; Upload a File to Targe get &lt;url&gt; -&gt; Download a File to T...
<python><sockets><printing><python-sockets>
2025-01-29 00:47:22
2
50,924
Yilmaz
79,395,477
4,577,688
How to save a Dataset in multiple shards using `tf.data.Dataset.save`
<p>How can I save a <code>tf.data.Dataset</code> in multiple shards using <code>tf.data.Dataset.save()</code>? I am reading in my dataset from CSV using <code>tf.data.experimental.make_csv_dataset</code>.</p> <p>The <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#save" rel="nofollow noreferrer">TF ...
<python><tensorflow><machine-learning>
2025-01-29 00:08:54
1
3,840
dule arnaux
79,395,319
4,907,639
'NoneType' object has no attribute 'encode' when loading tokenizer
<p>Error occurs when trying to load Pegasus model for text summarization</p> <pre><code>from transformers import pipeline, set_seed pipe = pipeline(&quot;summarization&quot;, model=&quot;google/pegasus-cnn_dailymail&quot;) </code></pre> <p>Error: <code>AttributeError: 'NoneType' object has no attribute 'encode' </code...
<python><huggingface-transformers><summarization>
2025-01-28 22:29:49
1
2,109
coolhand
79,395,296
1,738,399
How to select multiple columns to produce expressions using Polars LazyFrame
<p>After building up a computation with polars.LazyFrame, I have pairs of columns that I want to multiply together. The exact names can vary depending on inputs, but the pattern is consistent. For example, given</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.from_repr(&quot;&quot;&quo...
<python><python-polars>
2025-01-28 22:13:46
1
2,234
Jay Miller
79,395,117
5,312,606
Mapping cast in python
<p>What is a valid type of <code>T</code>in the following function?</p> <pre class="lang-py prettyprint-override"><code>def map_cast(T, seq: Sequence) -&gt; Sequence[T]: &quot;&quot;&quot;Cast a sequence of elements to a sequence of elements of given type.&quot;&quot;&quot; return [cast(T, x) for x in seq] </co...
<python><python-typing>
2025-01-28 20:33:47
1
1,897
mcocdawc
79,395,026
11,092,636
Different SSIM Results for 3D Microscopy Slices Using torchmetrics and skimage: Which One Should I Use?
<p>I am working with 3D microscopy data (e.g., stacks of 2D images) and trying to compute the Structural Similarity Index (SSIM) between two 3D images. The goal is to evaluate the similarity between an input stack and a ground truth stack. They both have the same dimensions.</p> <p>Here is a MRE with random tensors:</p...
<python><scikit-learn><torch><scikit-image><ssim>
2025-01-28 19:56:52
0
720
FluidMechanics Potential Flows
79,395,012
1,020,908
For every identifier select only rows with largest order column
<p>Consider the following table <code>source</code></p> <pre class="lang-none prettyprint-override"><code>id: LONG name: STRING ornum: LONG </code></pre> <p>The goal is to create a new table <code>target</code> which for each distinct id in <code>source</code> selects the row with largest <code>ornum</code>.</p> <p>The...
<python><duckdb>
2025-01-28 19:51:17
1
848
pseudo
79,394,869
10,349,888
tkinter events - shift modifier with mouse wheel?
<p>Is it possible to bind <code>Shift</code> and the mouse wheel? I would have thought so, but I'm doing something wrong.</p> <p>For example, the following code binds <code>Shift</code>, <code>Control</code>, <code>Alt</code> and no-modifier to the left mouse button (<code>Button-1</code>) and the scroll wheel turning ...
<python><tkinter><event-handling>
2025-01-28 18:33:46
0
698
wtw
79,394,835
3,906,786
Changing bar color in chart based on condition
<p>Currently I try to visualize a simple dataframe with Streamlit, but I fail to change bar colors based on the condition, if a specific value is True or False.</p> <p>The dataframe <code>df_to_display</code>:</p> <pre><code> PRODUKT CURRENT_DELAY OVERDUE 6 C 546 False 5 A ...
<python><python-3.x><streamlit><altair>
2025-01-28 18:18:13
1
983
brillenheini
79,394,822
4,271,491
Can you write pandas dataframe into an avro file without specyfing the schema?
<p>I read an excel file into a dataframe using pandas and now I have a requirement to save it as an avro file for further processing of a different step in a script. <br> As an input to each step I specify a number of parameters in a json but I don't have a real schema, only a column's names array. <br> Is there a poss...
<python><pandas><dataframe><avro>
2025-01-28 18:12:44
0
528
Aleksander Lipka
79,394,750
15,307,950
how to enable seperate action for double click and drag and drop for python files
<p>I have a simple python script and I want to enable dragging and dropping files into the python script in Windows 11. This works. But only if I set python launcher as default application for python file types. I want to launch my editor when double clicking. My idea is to create a batch file as default application fo...
<python><visual-studio-code><batch-file>
2025-01-28 17:48:00
1
726
elechris
79,394,722
1,419,224
Alternatives to run a .exe file with python
<p>I'm attempting to run the SWAT+ model executable (swatplus-61.0.2-ifx-win_amd64-Rel.exe) from Python using the subprocess module. However, I encounter the following error when running the executable through Python:</p> <pre><code>The procedure entry point for_sop_core_quiet could not be located in the dynamic link l...
<python>
2025-01-28 17:40:18
0
1,265
mcva
79,394,583
1,942,868
How to get the form-data from bytes objects
<p>I have this API</p> <pre><code>from fastapi import FastAPI,UploadFile, File,Depends,status,Body,Request, Form @app.post('/myapi') async def getmyapi(body=Body(...)): print(body) </code></pre> <p>this shows bytes code like this,</p> <pre><code>b'------WebKitFormBoundaryAVwbJDu8StWnEwnW\r\nContent-Disposition: for...
<python><fastapi>
2025-01-28 16:46:10
0
12,599
whitebear
79,394,556
13,806,869
How to run a SQL merge statement within a Python loop?
<p>I have some SQL code:</p> <pre><code>CREATE TABLE TABLE_1 AS ( SELECT ACCOUNT, 0 AS REDEEMER FROM ACCOUNTS ) WITH DATA IN MY_SCHEMA COMPRESS YES ; MERGE INTO TABLE_1 A USING ( SELECT ACCOUNT FROM REDEEMERS WHERE CATEGORY = 'x' ) B ON A.ACCOUNT = B.ACCOUNT WHEN ...
<python><merge><sqlalchemy>
2025-01-28 16:33:41
0
521
SRJCoding
79,394,290
10,767,161
How to optimize regex search across multiple patterns in Python?
<p>I have a Python script that uses multiple regular expressions to search through a file's content. Here's the relevant code snippet:</p> <pre><code>PATTERNS = { &quot;email&quot;: re.compile(r&quot;\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b&quot;), &quot;phone&quot;: re.compile(r&quot;\b\d{3}-\d{3...
<python><regex>
2025-01-28 15:08:07
4
747
Metin Bulak
79,394,276
1,416,001
How to limit the memory usage of a Python process?
<p>I'm trying to limit the memory usage of a Python service running in Kubernetes. I'm currently testing with Python 3.10 running in WSL2. I want the service to be aware of limitations set by Kubernetes, so it can throw a MemoryError when it's trying to allocate too much memory and handle that error in the code. I'm tr...
<python><kubernetes><memory><windows-subsystem-for-linux><setrlimit>
2025-01-28 15:04:51
1
985
John
79,394,058
5,462,551
Test that module is NOT imported
<p>I need to test that specific imports of my library don't import along some other heavy modules (e.g. tensorflow - we'll use it in this question). Here's a detailed description:</p> <p>The test should run some imports and check that TensorFlow is NOT imported. Preferably, it will check for each import on its own, so ...
<python><pytest><python-import>
2025-01-28 13:51:40
2
4,161
noamgot
79,393,978
17,580,381
Unable to utilise Hadoop with PySpark
<p>Let me say first of all that I have no particular need for Hadoop. I'm just trying to understand what the problem is here.</p> <p>Consider this MRE:</p> <pre><code>from pyspark.sql import SparkSession from os import environ as ENV from pathlib import Path HADOOP_DIR = Path(&quot;/Volumes/Spare/hadoop-3.4.0&quot;) H...
<python><hadoop><pyspark>
2025-01-28 13:22:32
0
28,997
Ramrab
79,393,920
567,059
How to ensure hash of zip file created locally is identical to when created during CI/CD, using exactly the same contents
<p>How can I use <code>shutil.make_archive()</code> to make zip files that are absolutely identical, including the hash?</p> <p>I am creating a zip file locally, and then through CI/CD, and I expect them to be identical, but the hashes differ. This causes CI/CD to think that the files are different and it attempts an u...
<python><hash><zip>
2025-01-28 12:58:56
0
12,277
David Gard
79,393,859
13,339,621
Get pathlib Path with symlink
<p>Let's say I open a python console inside <code>/home/me/symlink/dir</code>, which is actually a shortcut to <code>/home/me/path/to/the/dir</code>. In this console I execute the following code:</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path path = Path.cwd() print(path) # &quot;/home/me...
<python><pathlib>
2025-01-28 12:41:52
1
1,549
matleg
79,393,845
10,108,726
How to limit admin django session and renew time after user action
<p>I am improving my django admin session security and I wanted to do 2 things:</p> <ol> <li>Limit my admin session time</li> <li>Renew my session time after every user action</li> </ol> <p>What is the best way to do?</p>
<python><django>
2025-01-28 12:36:57
1
654
Germano
79,393,833
1,554,114
QDialog prevent closing when pressing return QDoubleSpinBox in focus
<p>I try to build an application based on QDialog. It contains a 'Close' button, which always seems to go back into focus when I type into a QSpinBox.</p> <p><code>QSpinBox.keyboardTracking = false</code> so I can process the final value.<br /> Now clicking somewhere else or pressing enter within the spin box will actu...
<python><qt><pyside6><qt6>
2025-01-28 12:33:16
1
4,731
Nippey
79,393,350
14,649,310
langchain_community OllamaEndpointNotFoundError when trying to access phi3:mini Model
<p>I have my ollama service running in a container. If I query it from the terminal like:</p> <pre><code>curl -X POST http://localhost:11434/v1/completions \ -H &quot;Content-Type: application/json&quot; \ -d '{ &quot;model&quot;: &quot;phi3:mini&quot;, &quot;prompt&quot;: &quot;Test query&quot; }' </code></pre> <p...
<python><langchain><ollama>
2025-01-28 09:45:54
1
4,999
KZiovas
79,393,342
2,173,750
Is it possible in a Mako template to import objects from a Python/Module block in another Mako template?
<p>I have a Mako template with Python and Module blocks, like this:</p> <pre><code>&lt;% l1 = ['a','b','c'] %&gt; &lt;%! l2 = ['d','e','f'] %&gt; </code></pre> <p>Is it possible to import <code>l1</code> or <code>l2</code> from another Mako template? <code>&lt;%namespace</code>, <code>&lt;%import</code> and other tradi...
<python><mako>
2025-01-28 09:44:18
1
3,404
durum
79,393,186
2,879,720
Convolving with a gaussian kernel vs Gaussian blur
<p>While looking for a way to generate spatially varying noise, I came across <a href="https://stackoverflow.com/a/63868276/2879720">this answer</a>, which is able to do what I wanted. But I am getting confused about how the code works.</p> <p>From what I understand, the first step of the code generates a gaussian kern...
<python><numpy><convolution><gaussianblur>
2025-01-28 08:49:17
1
373
MollieVX
79,393,140
21,049,944
How to transform pyarrow integer column to categorical without mapping every value
<p>I have a pyarrow table with a int column. Is it possible to transform it to categorical string without having to call <code>col.map(dict)</code> -&gt; <code>cast(&quot;categorical&quot;)</code>?</p> <p>I would basicaly like to just pass the dict to the table to make it know how to interpret the integers.</p>
<python><pyarrow>
2025-01-28 08:25:56
1
388
Galedon
79,393,122
4,706,952
Transforming Data with implicit categories in header with pandas
<p>I have a table like:</p> <pre><code> | 2022 | 2022 | 2021 | 2021 class | A | B | A | B -----------|------|------|------|------ X | 1 | 2 | 3 | 4 Y | 5 | 6 | 7 | 8 </code></pre> <p>How can I transform it to following form?</p> <pre><code>year | cate...
<python><pandas>
2025-01-28 08:20:39
2
7,517
symbolrush
79,392,747
5,312,606
Confusion about type-checking nested Sequence
<p>I have code that in a minimal example looks like this.</p> <pre class="lang-py prettyprint-override"><code>from ordered_set import OrderedSet from collections.abc import Sequence from typing import NewType, TypeAlias SeqOverFrag: TypeAlias = Sequence MotifIdx = NewType(&quot;MotifIdx&quot;, int) AOIdx = NewType(&q...
<python><python-typing><mypy>
2025-01-28 04:33:37
0
1,897
mcocdawc
79,392,684
10,024,860
Pytest chain mocking between sync and async functions
<p>I want to mock:</p> <pre><code>async with aiohttp.ClientSession() as session: async with session.post(&quot;xyz.com&quot;) as resp: x = await resp.json() </code></pre> <p>Currently, I am doing:</p> <pre><code># patched aiohttp as mock_aiohttp mock_session = Mock() mock_session_post_cm = AsyncMock() mock_...
<python><unit-testing><pytest><python-unittest>
2025-01-28 03:32:42
1
491
Joe C.
79,392,672
4,330,537
Trying to use chrome_undetected selenium driver and portable chrome
<p>I have the code below and I have chrome portable installed at C:\temp\GoogleChromePortable64\App\Chrome-bin\chrome.exe how do I tell undetected_chromedriver to use it?</p> <pre><code># Import the required libraries import undetected_chromedriver as uc from selenium.webdriver.chrome.service import Service as ChromeSe...
<python><google-chrome><selenium-webdriver>
2025-01-28 03:18:38
1
835
RobM
79,392,607
3,063,547
install of python-for-android failing: "No module named 'setuptools" when using "python3 setup.py build"
<p>I want to install python-for-android. Downloaded the source via git clone of the repos. Tried <code>python3 setup.py build</code>, but get</p> <pre><code>&quot;Traceback (most recent call last): File &quot;/home/me/python-for-android/setup.py&quot;, line 7, in &lt;module&gt; from setuptools import setup, find_...
<python><android>
2025-01-28 02:08:22
0
853
user3063547
79,392,590
8,458,083
How to select a NixOS WSL Python interpreter(from a virtual environment) in Visual Studio Code on Windows
<p>I'm using NixOS on WSL2 and Visual Studio Code on Windows with the WSL extension. I've created a virtual environment in NixOS, and I want to use the python command of the virtual environment as the Python interpreter in VS Code. However, I'm encountering issues selecting the correct interpreter.</p> <p>My setup:</p...
<python><visual-studio-code><windows-subsystem-for-linux><nix><nix-flake>
2025-01-28 01:47:09
1
2,017
Pierre-olivier Gendraud
79,392,577
1,997,852
How to make paho-mqtt loop timeout?
<p>Using python paho-mqtt, I'm trying to receive exactly 1 message from a topic and then exit. If no messages are received in 5 seconds then I want to timeout and exit. The problem I have is that this code always waits 5 seconds, even if the message was received sooner. If I remove the <code>sleep()</code> line then it...
<python><mqtt><paho>
2025-01-28 01:38:35
1
1,217
Elliott B
79,392,549
2,061,886
can't figure out how to shrink docker image after pip install
<p>I have a docker file that looks like this:</p> <pre><code>FROM python:3.12-slim RUN apt-get update \ &amp;&amp; apt-get install -y --no-install-recommends git \ &amp;&amp; apt-get purge -y --auto-remove \ &amp;&amp; rm -rf /var/lib/apt/lists/* RUN pip3 install --no-cache-dir --upgrade \ pip poetry WORKDIR /ap...
<python><docker>
2025-01-28 01:10:24
1
3,347
lightweight
79,392,545
626,664
What is giving Azure document intelligence a TypeError?
<p>I am using Azure Doc Intelligence to analyze PDFs. I am trying the code from <a href="https://learn.microsoft.com/en-us/python/api/overview/azure/ai-documentintelligence-readme?view=azure-python" rel="nofollow noreferrer">here.</a></p> <p>Code:</p> <pre><code>from azure.core.credentials import AzureKeyCredential fro...
<python><azure><typeerror><azure-document-intelligence>
2025-01-28 01:06:21
1
1,559
Droid-Bird
79,392,330
7,425,756
Is there an add-element-to-a-set method returning whether the element was actually added?
<p>I would like to achieve in Python the following semantics which is present in Kotlin:</p> <pre><code>myset = set() for elem in arr: if not myset.add(elem): return 'duplicate found' </code></pre> <p>I am looking for a way to get a slight performance boost by 'hijacking' add-to-set operation by analysing the returne...
<python><python-3.x>
2025-01-27 22:31:16
4
528
Alexander Ites
79,392,160
1,903,416
Sphinxcontrib.Autoprogram Module Not Found with Python
<p>I'm using <a href="https://pythonhosted.org/sphinxcontrib-autoprogram/" rel="nofollow noreferrer">https://pythonhosted.org/sphinxcontrib-autoprogram/</a> to try to generate documentation for my CLI automatically from my configuration of argparse.</p> <p>It looks like it should work, but after I do everything as the ...
<python><module><python-sphinx>
2025-01-27 20:54:30
0
497
time e. less
79,392,129
2,140,256
How to make an asynchronous python call from within scala
<p>I am trying to access the <a href="https://github.com/dydxprotocol/v4-clients/tree/main/v4-client-py-v2" rel="nofollow noreferrer">Python Client V4 for DyDx</a> from within a scala project. I integrated the previous V3 using <a href="https://scalapy.dev/" rel="nofollow noreferrer">scalapy</a> library. But V4 contain...
<python><scala>
2025-01-27 20:43:40
2
5,402
user79074