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
78,240,527
9,428,990
Linux service stops logging
<p>I have a service running. The service invokes a long running python script which &quot;prints&quot; some status messages. I can see these status messages with <code>journalctl -u myservice.service</code>. But after about 6 hours I am no longer able to see new outputs from the service.</p> <p>If I run <code>systemctl...
<python><linux><service><systemd-journald>
2024-03-28 19:42:11
1
719
Frankster
78,240,320
15,370,142
Workaround for "TypeError: 'NoneType' object is not subscriptable" in ArcGIS Import data Tutorial
<p>I'm trying to follow <a href="https://developers.arcgis.com/python/guide/import-data/" rel="nofollow noreferrer">this ArcGIS tutorial</a>. I'm receiving a <code>TypeError: 'NoneType' object is not subscriptable</code>. This happens when I try to execute <code>csv_item = gis.content.add(trailhead_properties, csv_file...
<python><typeerror><gis><arcgis><nonetype>
2024-03-28 18:55:02
1
412
Ted M.
78,240,203
9,795,817
Display node and edge attributes in interactive Networkx graph using Pyvis
<h1>Edit</h1> <p>I updated <code>pyvis</code> to version 0.3.2 and the plot is working as expected now.</p> <p>Read on if you're interested in displaying node and edge attributes on a Pyvis visualization of a Networkx graph.</p> <hr /> <h1>Original question</h1> <p>I have two Pandas dataframes: <code>edges_df</code> an...
<python><networkx><pyvis>
2024-03-28 18:20:35
0
6,421
Arturo Sbr
78,239,967
11,001,751
Efficiently Turn Matrix of Intersecting Routes Into Simplified Spatial Network (Graph)
<p>I have a matrix of real detailed routes which I want to efficiently turn into a simple spatial network. Simple means that I don't care about the intricacies of local transport and possible intersections of routes near the start and end points. I do want to add major intersections outside the start and end points as ...
<python><r><geospatial><qgis>
2024-03-28 17:30:13
1
1,379
Sebastian
78,239,855
5,546,046
How to specify the default project to use with the BigQuery python client?
<p>Writing a python cloud functions such as</p> <pre class="lang-py prettyprint-override"><code>from google.cloud.bigquery import Client client = Client( project=&quot;my_gcloud_project&quot;, location=&quot;my_zone&quot;, ) sql_statement = &quot;SELECT * FROM `my_dataset.my_table`&quot; query_job = client...
<python><google-bigquery>
2024-03-28 17:06:39
3
2,455
Noan Cloarec
78,239,756
749,973
register_buffer a dict object in PyTorch
<p>I thought this was a simple question but I couldn't find an answer.</p> <p>I want a member variable of a pytorch module to be saved/loaded with model state_dict. I can do that in <strong>init</strong> with the following line.</p> <pre><code> self.register_buffer('loss_weight', torch.tensor(loss_weight)) </cod...
<python><pytorch><state-dict>
2024-03-28 16:46:48
1
20,660
Tae-Sung Shin
78,239,746
2,326,139
how in python create a type based on return type of a function
<p>I'm using a library that doesn't have any stub</p> <p>so I created a stub for it but now I have issue to use those types that I've created for the stub since it's not part of the original library I can't import them</p> <p>here is an example</p> <p>here is the stub:</p> <pre class="lang-py prettyprint-override"><cod...
<python><python-typing>
2024-03-28 16:44:08
0
2,065
Mohammad Hossein Amri
78,239,584
4,894,593
Speed up finding the cell to which a point belongs in interpolation from curvilinear to rectangular grid
<p>I'm trying to set up a method for interpolating points from a curvilinear grid to a regular grid. To do this, I'm trying to find out which cell of the curvilinear grid each point of the regular grid belongs to. The cells of the curvilinear grid are random quadrilaterals.</p> <p>Grids are created as follows, for exam...
<python><cython>
2024-03-28 16:15:34
0
1,080
Ipse Lium
78,239,484
9,635,098
Why does Dataframe.to_sql() slow down after certain amount of rows?
<p>I have a very large <code>Pandas</code> Dataframe ~9 million records, 56 columns, which I'm trying to load into a MSSQL table, using <code>Dataframe.to_sql()</code>. Importing the whole Dataframe in one statement often leads to errors, relating to memory.</p> <p>To cope with this, I'm looping through the Dataframe ...
<python><sql-server><pandas><sqlalchemy>
2024-03-28 16:00:20
1
406
Beek
78,239,380
14,230,633
Polars apply same custom function to multiple columns in group by
<p>What's the best way to apply a custom function to multiple columns in Polars? Specifically I need the function to reference another column in the dataframe. Say I have the following:</p> <pre><code>df = pl.DataFrame({ 'group': [1,1,2,2], 'other': ['a', 'b', 'a', 'b'], 'num_obs': [10, 5, 20, 10], 'x':...
<python><dataframe><python-polars>
2024-03-28 15:46:13
1
567
dfried
78,239,173
4,647,519
Python Dash App is Not Rendering in Browser
<p>I tried to run the following example code from <a href="https://dash.plotly.com/tutorial" rel="nofollow noreferrer">https://dash.plotly.com/tutorial</a> but it just gives me a blank browser tab which seems to infinitely load:</p> <pre><code>from dash import Dash, html app = Dash(__name__) app.layout = html.Div([ ...
<python><plotly-dash>
2024-03-28 15:08:40
2
545
tover
78,238,984
11,092,636
Lower triangle mask with seaborn clustermap bug
<p>To reproduce the bug you can use this dataframe (made with the <code>.to_clipboard</code> method of the <code>pandas.DataFrame</code> object so you can import it easily).</p> <pre class="lang-py prettyprint-override"><code> 01:01 01:02 01:03 01:04 01:05 01:06 01:07 01:10 01:12 01:21 02:01 03...
<python><pandas>
2024-03-28 14:40:28
1
720
FluidMechanics Potential Flows
78,238,983
18,178,867
Font weights in Matplotlib
<p>I have a figure and I want to make the axes labels bold. The problem is that the text contains mathematical expressions that do not turn into bold font face. Other parts are Ok.</p> <pre><code>fig = plt.figure(figsize=(4,3)) predicts = np.random.random(1000)*10e9 plt.plot(predicts,predicts, &quot;.&quot;, ms=6) plt....
<python><matplotlib>
2024-03-28 14:40:16
1
443
Reza
78,238,743
6,221,742
Implement filtering in RetrievalQA chain
<p>I have been working on implementing the <a href="https://cloud.google.com/blog/products/databases/using-pgvector-llms-and-langchain-with-google-cloud-databases/" rel="nofollow noreferrer">tutorial</a> using RetrievalQA from Langchain with LLM from Azure OpenAI API. I've made progress with my implementation, and belo...
<python><azure><langchain><large-language-model><azure-openai>
2024-03-28 14:03:12
1
339
AndCh
78,238,607
14,894,361
How to detect changes in custom types in sqlalchemy
<p>I am working on custom types in sqlalchemy columns using <code>TypeDecorator</code>. I'm storing my data in <code>JSONB</code> inside Postgres DB, but in code I am serializing and deserializing it in a data class. But when I change any field of that data class, it didn't detect changes on that column. How can I achi...
<python><postgresql><sqlalchemy>
2024-03-28 13:39:26
2
320
Cdaman
78,238,508
616,460
setup.py code to run on `pip install` but not on `python -m build`
<p>I have some code in a <em>setup.py</em> file that checks for a third-party SDK that must be manually installed before the application is installed:</p> <pre class="lang-py prettyprint-override"><code>import sys from setuptools import setup # ---- BEGIN SDK CHECK try: import pyzed.sl except ImportError: pri...
<python><pip><setup.py><python-packaging>
2024-03-28 13:24:05
1
40,602
Jason C
78,238,444
307,283
Add proxy configuration to tracking_uri in MLFlow
<p>I'm using MLFlow and I'm behind a proxy. How can I add the proxy information to the tracking_uri for <code>MlFlowClient</code> call? I tried using environment variables but that also didn't work:</p> <pre><code>os.environ[&quot;MLFLOW_TRACKING_URI&quot;] = &quot;https://mlflow-sandbox.dev.server&quot; os.environ[&qu...
<python><network-programming><proxy><mlflow>
2024-03-28 13:12:39
0
20,221
Ivan
78,238,366
9,251,158
OpenTimelineIO FCP XML import fails to find clips
<p>I have several video projects in Final Cut Pro and Adobe Premiere that I want to convert to Kdenlive. I found <a href="https://github.com/AcademySoftwareFoundation/OpenTimelineIO" rel="nofollow noreferrer">OpenTimelineIO</a> and, through trial-and-error and thanks to StackOverflow, got this code:</p> <pre class="lan...
<python><python-3.x><xml><finalcut>
2024-03-28 13:02:29
0
4,642
ginjaemocoes
78,238,308
12,271,381
Find Gradient Magnitude using skimage.feature.hog module
<p>I am trying to print total gradient magnitude for 100 in the below array</p> <pre><code>img=[[150,50,121],[12,100,25],[201,243,244]] </code></pre> <p>Below is the code I tried</p> <pre><code>from skimage.feature import hog from skimage import data, exposure fdt, hog_image = hog([[150,50,121],[12,100,25],[201,243,244...
<python><image-processing><scikit-image><feature-extraction>
2024-03-28 12:51:07
0
1,079
sakeesh
78,238,126
2,924,334
Accessing slide background in python-pptx
<p>It seems straightforward, but I am not able to access the slide background.</p> <pre><code>from pptx import Presentation presentation = Presentation() slide_layout = presentation.slide_layouts[5] # 5 corresponds to a blank slide slide = presentation.slides.add_slide(slide_layout) print(slide) # this prints: &lt;...
<python><python-pptx>
2024-03-28 12:14:27
0
587
tikka
78,237,938
5,305,512
llama-cpp-python with metal acceleration on Apple silicon failing
<p>I am following the instructions from the <a href="https://llama-cpp-python.readthedocs.io/en/latest/install/macos/" rel="nofollow noreferrer">official documentation</a> on how to install llama-cpp with GPU support in Apple silicon Mac.</p> <p>Here is my Dockerfile:</p> <pre><code>FROM python:3.11-slim WORKDIR /code...
<python><docker><macos><cmake><llama-cpp-python>
2024-03-28 11:43:46
0
3,764
Kristada673
78,237,761
9,659,620
import torch.utils.tensorboard causes tensorflow warnings
<p>As stated <a href="https://stackoverflow.com/questions/57547471/does-torch-utils-tensorboard-need-installation-of-tensorflow">here</a> tensorboard is part of tensorflow but does not depend on it. One can use it in pytorch such as</p> <pre class="lang-py prettyprint-override"><code>from torch.utils.tensorboard import...
<python><pytorch><tensorboard>
2024-03-28 11:13:26
2
1,601
Klops
78,237,443
1,095,202
Executable under GDB invokes different embedded Python
<p>I have code that embeds Python. That embedded Python uses NumPy and hence, I need to explicitly load <code>libpython</code>, to make NumPy work.</p> <p>The driving code is in C++ (tests in Google Test). There is a bug somewhere, and I try to use <code>gdb</code> for debugging. However, something strange happens as e...
<python><linux><gdb><python-c-api>
2024-03-28 10:21:11
1
927
Dmitry Kabanov
78,237,399
15,368,670
mypy: error: No overload variant of "..." matches argument types "list[DataFrame]", "str" when using axis="rows"
<p>I was running</p> <pre><code>pd.concat(dfs, axis=&quot;rows&quot;) </code></pre> <pre><code>pd.median(dfs, axis=&quot;rows&quot;) </code></pre> <p>basically any function from pandas which can accept axis and mypy will raise:</p> <pre><code>error: No overload variant of &quot;concat&quot; matches argument types &quot...
<python><pandas><mypy><python-typing>
2024-03-28 10:16:36
2
719
Oily
78,237,398
5,553,963
Stomp connection using JWT token in Python
<p>We have a cli written in python (using typer) and we want to add consuming websocket over stomp to it so the cli can connect to the RabbitMQ and consume the messages. I have to mention that there is an Nginx + Oauth2proxy sitting in front of our RabbitMQ and we have an entry in our Nginx for websocket over STOMP.</p...
<python><websocket><stomp>
2024-03-28 10:16:34
0
5,315
AVarf
78,237,049
6,281,366
define the input FPS of a stream using ffmpeg-python
<p>Im creating an HLS playlist using ffmpeg, reading my input from an RTSP stream.</p> <p>When probing the RTSP stream, i get an FPS which is not the true FPS, and i want to &quot;tell&quot; ffmpeg the actual real FPS.</p> <p>In the command line, im using the -r flag, which works fine:</p> <pre><code>ffmpeg -rtsp_trans...
<python><ffmpeg><ffmpeg-python>
2024-03-28 09:16:37
1
827
tamirg
78,236,745
3,433,875
Plot only labels in selected positions in matplotlib pie/donut chart
<p>I have the following half pie chart:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(8,6),dpi=100) ax = fig.add_subplot(1,1,1) pie_labels = [&quot;Label 1&quot;, &quot;Label 2&quot;, &quot;Label 3&quot;] pie_values = [1,2,3] pie_labels.append(&quot;Label 0&quot;) pie_val...
<python><matplotlib>
2024-03-28 08:25:27
1
363
ruthpozuelo
78,236,663
1,788,656
AttributeError: crs attribute is not available
<p>All, I am using metpy 0.10.0, I am trying to calculate the laplacina of a field using mpcalc.laplacian function, yet I get the following error : AttributeError: crs attribute is not available.</p> <p>Here is my minmal code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import xarray as xr import ...
<python><python-3.x><metpy>
2024-03-28 08:06:31
1
725
Kernel
78,236,646
6,376,297
Linear program solver CBC seems to give 'optimal' solutions with different objective for the exact same problem (and code)
<p>I ran the <em>exact same</em> python notebook twice (using the PULP_CBC_CMD solver that comes with pulp), and I got the results I pasted below.</p> <p><strong>How can a solution be called 'optimal' if the very same solver with the very same data and code finds a better one on another run?</strong></p> <p>Any ideas?<...
<python><linear-programming><coin-or-cbc>
2024-03-28 08:02:08
1
657
user6376297
78,236,642
1,384,464
Using python OpenCV to crop an image based on reference marks
<p>I have an image I would like to crop based on reference marks of the image which are black squares at the layout margins.</p> <p>While my code can detect the reference marks, there seem to be a persistent error which I can't seem to get around: I cannot get the exact accurate co-ordinates of the reference marks to c...
<python><opencv><image-processing><computer-vision><omr>
2024-03-28 08:01:51
1
1,033
Timothy Tuti
78,236,491
986,612
Output both to console and file
<p>BUT:</p> <ol> <li>No external shell commands, e.g. <code>| tee</code>.</li> <li>No new functions and a change of syntax, e.g., keep using <code>print()</code> as is.</li> </ol>
<python>
2024-03-28 07:29:10
1
779
Zohar Levi
78,236,271
65,889
How can I tell pytest that for a function it is the correct behaviour (and only the correct behaviour) to have a failed assertion?
<p><strong>Background:</strong> In one project I use <code>pytest</code> with a helper function which for many tests does the final assert. So it is something like this source code:</p> <p>tsthelper.py:</p> <pre class="lang-py prettyprint-override"><code>def check(obj1, obj2, *args): # do stuff calculate (using arg...
<python><unit-testing><pytest><pytest-fixtures>
2024-03-28 06:43:37
1
10,804
halloleo
78,236,141
14,586,554
How can I apply scipy.interpolate.RBFInterpolator on an image / ndarray?
<p>For example how do I apply <code>RBFInterpolator</code> on image loaded by opencv? I need to apply interpolation using vector-operations of numpy (which is fast)</p> <p>I need to do non-affine transformation on image by defining interpolation between image points.</p> <p>How do I do it?</p>
<python><numpy><scipy><interpolation>
2024-03-28 06:07:49
1
620
Kemsikov
78,235,920
10,620,003
A question on recursion -finding the parents of the taxon
<p>I have this dictionary:</p> <pre><code>tax_dict = { 'Pan troglodytes': 'Hominoidea', 'Pongo abelii': 'Hominoidea', 'Hominoidea': 'Simiiformes', 'Simiiformes': 'Haplorrhini', 'Tarsius tarsier': 'Tarsiiformes', 'Haplorrhini': 'Primates', 'Tarsiiformes': 'Haplorrhini', 'Loris tardig...
<python>
2024-03-28 04:54:02
2
730
Sadcow
78,235,911
480,118
pandas: sorting/re-ordering columns for a multi-level column dataframe
<p>I have the following data:</p> <pre><code>from pandas import Timestamp values = [['IDX100', 'field1', Timestamp('1999-02-01 05:00:00'), '101'], ['IDX100', 'field1', Timestamp('1999-02-02 05:00:00'), '102'], ['IDX100', 'field1', Timestamp('1999-02-03 05:00:00'), '103'], ['IDX200', 'field1', Time...
<python><pandas>
2024-03-28 04:50:29
2
6,184
mike01010
78,235,551
6,509,519
Looking for Regex pattern to return similar results to my current function
<p>I have some pascal-cased text that I'm trying to split into separate tokens/words. For example, <code>&quot;Hello123AIIsCool&quot;</code> would become <code>[&quot;Hello&quot;, &quot;123&quot;, &quot;AI&quot;, &quot;Is&quot;, &quot;Cool&quot;]</code>.</p> <h1>Some Conditions</h1> <ul> <li>&quot;Words&quot; will alwa...
<python><regex><pascalcasing>
2024-03-28 02:21:46
5
3,325
Ian Thompson
78,235,371
893,411
Creating a reminder task in langchain
<p>I'm trying to create a studying tutor with LLMs and langchain. What I'm looking for is that the app reminds the student once in a while during the conversation if he/she has done his/her homework, and based on the answer remind him/her later or don't remind her again. I'm looking for a clue on how to achieve such a ...
<python><langchain><large-language-model>
2024-03-28 01:12:45
0
4,283
m0j1
78,234,756
480,118
bulk insert data into table where cell can be empty string for a column that is part of a composite primary key, using psycopg3
<p>I have the following table - note there is a composite primary key consisting of 5 columns.</p> <pre><code>test_ts = Table('test_ts', meta, Column('metric_id', ForeignKey('metric.id'), primary_key = True), Column('entity_id', Integer, primary_key = True), Column('date', DateTime, primary_key = True), ...
<python><postgresql><sqlalchemy><psycopg2><psycopg3>
2024-03-27 21:43:33
0
6,184
mike01010
78,234,711
9,476,887
Visible not detected with Selenium in Python for element in a shadow root
<p>I would like to find with Selenium the following <code>button</code> element:</p> <pre><code>&lt;button class=&quot;walla-button__button walla-button__button--full-width walla-button__button--large walla-button__button--primary&quot; role=&quot;button&quot; type=&quot;submit&quot; part=&quot;button&quot;&gt; &lt...
<python><selenium-webdriver>
2024-03-27 21:33:53
0
522
ForEverNewbie
78,234,592
8,863,970
'X' object has no attribute 'functionName' - Pyspark / Python
<p>I'm new to Pyspark so just learning as I go.</p> <p>I'm trying to experiment with UnitTest and I am getting some error below:</p> <pre><code>def drop_duplicates(df): df = df.dropDuplicates(df) return df </code></pre> <pre><code>import unittest class TestNotebook(unittest.TestCase): def test_drop_du...
<python><pyspark>
2024-03-27 21:07:28
1
1,013
Saffik
78,234,590
903,188
How do I find a specific Python anytree descendant?
<p>The following Python anytree construction</p> <pre><code>top = Node(&quot;top&quot;) a = Node(&quot;a&quot;, parent=top) b = Node(&quot;b&quot;, parent=top) c = Node(&quot;c&quot;, parent=a) d = Node(&quot;d&quot;, parent=a) e1 = Node(&quot;e&quot;, parent=c) e2 = Node(&quot;e&quot;, parent=a) c1 = Node(&quot;c&quot...
<python><anytree>
2024-03-27 21:06:09
1
940
Craig
78,234,541
4,926,275
How to control the font size in Kivy settings panel for the menu item name in settings menu list
<p>I tried to use the Kivy settings panel in my application, but I found that the font size of some settings panel items is related to the font size setting in my application, currently I can not set the font size of settings panel directly. In my application for displaying effect it uses a large font size, then in set...
<python><kivy><settings><font-size>
2024-03-27 20:56:29
1
385
phchen2
78,234,490
7,233,155
Github workflow Python project with Maturin fails to build
<p>I have a Python project with rust extension module using pyo3 bindings. The project successfully builds and compiles locally, and it builds and compiles on readthedocs. It uses a <code>pip install .</code> method and builds local wheels after rust and all dependencies built on the local architecture.</p> <p>However,...
<python><rust><github-actions><maturin>
2024-03-27 20:43:38
1
4,801
Attack68
78,234,170
2,816,272
How I can search a string in a JSON file with an word-embedding list and return the nearest occurrences?
<p>I’m saw a code in Python that generates a file with a representation of embeddings (vectors that represent a string).</p> <p>The format of the file generates in the model &quot;all-MiniLM-L6-v2&quot; is:</p> <pre><code>[ { &quot;codigo&quot;:1, &quot;descricao&quot;:&quot;Alain Prost&quot;, &quo...
<python><c#><.net><word-embedding>
2024-03-27 19:35:41
1
621
Jean J. Michel
78,233,905
11,384,233
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
<p>I'm facing an installation issue with pip on CentOS while utilizing Python version 3.10.0. I attempted to install pip by executing the <code>get-pip.py</code> script. However, during the process, I encountered errors related to the SSL module, preventing the installation from completing successfully.</p> <p>To proce...
<python><python-3.x><ssl><pip>
2024-03-27 18:46:02
1
6,782
Tharindu Lakshan
78,233,900
7,601,346
Am I mistakenly setting up my project to use system Python interpreter instead of virtual environment? How do I tell?
<p>I'm trying to set up my repository to use an older version of Python for compatibility.</p> <p>I was able to select my system Python interpreter from this menu:</p> <p><a href="https://i.sstatic.net/1haOW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1haOW.png" alt="enter image description here" /><...
<python><python-3.x><pycharm><virtualenv>
2024-03-27 18:45:13
1
1,200
Shisui
78,233,826
8,863,970
Reset previous run for Unit tests for functions in a Jupyter notebook?
<p>I have the following simple function in a Jupyter Notebook:</p> <pre><code>def add(a, b): return a + b </code></pre> <p>and then I do some UnitTest as follows in same notebook below:</p> <pre><code>import unittest class TestNotebook(unittest.TestCase): def test_add(self): self.assertEqual(add(2...
<python><unit-testing><jupyter-notebook><python-unittest>
2024-03-27 18:29:28
0
1,013
Saffik
78,233,643
7,658,051
AttributeError: Can't get attribute 'PySparkRuntimeError' as I try to apply .collect() to some RDD.map(...).distinct()
<p>I am a beginner with Spark.</p> <p>I am running spark on local machine, with no cluster.</p> <p>I have developed the following script.</p> <p>The aim is to get the unique values of the keys &quot;license&quot;.</p> <p>Everything goes well past the lines</p> <pre><code>licenses_collected = rdd.map(lambda x: x[&quot;l...
<python><apache-spark><pyspark>
2024-03-27 17:46:53
2
4,389
Tms91
78,233,587
6,606,057
Unable to Create Polynomial Features for regression using numpy.plyfit -- AttributeError: 'numpy.ndarray' object has no attribute 'to_numpy'
<p>Excuse my ignorance I have never used polynomial regression with numpy before.</p> <p>I am attempting to use the variable &quot;CPU_frequency&quot; to create Polynomial features. Using three different values of polynomial degrees.</p> <pre><code>import numpy X = X.to_numpy().flatten() f1 = np.polyfit(X, Y, 1) p1 = ...
<python><python-3.x><numpy><polynomials>
2024-03-27 17:33:56
2
485
Englishman Bob
78,233,520
1,862,861
Best way to iterate over variable that can be a single object or list/iterator of objects
<p>Suppose I have a Python function that takes in an argument that can either be, e.g., an <code>int</code> or list of <code>int</code>s and I want to loop over that argument:</p> <pre class="lang-py prettyprint-override"><code>from typing import List, Union def myfunc(arg: Union[int, List[int]]) -&gt; List[int]: ...
<python>
2024-03-27 17:19:45
0
7,300
Matt Pitkin
78,233,264
2,779,432
A way to warp an image based on a map
<p>I'm looking for a method where, given an two images (A and B, with A being an RGB image and B being a greyscale image storing the warping information) I can warp A relative to B. To give you some context, this is pretty much the same technique used to artificially create a stereo image from a single image given dept...
<python><image-processing><graphics><3d><textures>
2024-03-27 16:37:52
0
501
Francesco
78,232,975
13,518,907
RAG with Langchain and FastAPI: Stream generated answer and return source documents
<p>I have built a RAG application with Langchain and now want to deploy it with FastAPI. Generally it works tto call a FastAPI endpoint and that the answer of the LCEL-chain gets streamed. However I want to achieve that my answer gets streamed and if streaming is done I want to return the source documents. Here is the ...
<python><fastapi><langchain><llama-cpp-python>
2024-03-27 15:50:44
1
565
Maxl Gemeinderat
78,232,806
17,523,373
How can I convert GeoTIFF to sqlite database in python
<p>I have a GeoTIFF file that i want to extract its latitude and longitude with altitude and store it in a sqlite database, this sqlite database will be later used in a mobile application, For now this is the code that will give me latitude and longitude with altitude</p> <pre><code>import rasterio def get_elevation_...
<python><sqlite><openstreetmap><geotiff>
2024-03-27 15:24:48
0
731
Pannam
78,232,787
5,269,892
Python unexpected non-zero returncode when checking alias command set in .bashrc file
<p>I want to call an alias command set in a <em>.bashrc</em> file from python. However, the returncode of <code>source ~/.bashrc; command -v command</code> is for some reason 1 instead of 0 which is the case if the same command is executed directly in the shell. It should be noted that with a default command like <code...
<python><bash><shell><subprocess><alias>
2024-03-27 15:22:17
1
1,314
silence_of_the_lambdas
78,232,689
6,524,326
Reducing Overhead When Calling Python Functions from Node.js Using spawnSync
<p>I am using Python 3.10 and have a file named <code>utilities.py</code> in my project directory that contains several functions and import statements. I import its content to use in other Python files as shown in the snippet below where I am showing you the content of the <code>validate_user.py</code> file. I am doin...
<python>
2024-03-27 15:06:06
2
828
Wasim Aftab
78,232,655
2,610,841
How to Configure Ray to Use Standard Python Logger for Multiprocessing?
<p>I am trying to use Ray to improve the speed of a process and I want the log messages to be passed to the standard Python logger. This way, the application can handle formatting, filtering, and saving the log messages. However, when I use Ray, the log messages are not formatted according to my logger configuration an...
<python><logging><multiprocessing><ray>
2024-03-27 15:00:53
3
1,661
gabrown86
78,232,522
14,179,793
bot3 ecs.execute_command: Task Identifier is invalid
<p>I have defined a task in AWS ECS. I have copied the task ARN into the API call:</p> <pre><code>rsp = ecs.execute_command( container='test', command=json.dumps(event), task='arn:aws:ecs:##-####-#:############:task-definition/test:1', interactive=True ) </code></pre> <p>I receive th...
<python><amazon-web-services><boto3><amazon-ecs>
2024-03-27 14:40:47
1
898
Cogito Ergo Sum
78,232,434
1,305,688
Seaborn boxplot color outliers by hue variable using seaborn =< 0.12.2
<p>I would like to color my boxplot-outliers in my Seaborn Boxplot when using a hue variables. Something along the line of this, from <a href="https://seaborn.pydata.org/generated/seaborn.boxplot.html#" rel="nofollow noreferrer">seaborn boxplot examples</a>, but I am stuck on seaborn ver. 0.12.2</p> <p><a href="https:/...
<python><plot><seaborn>
2024-03-27 14:26:55
0
8,018
Eric Fail
78,232,352
6,243,129
Error decoding data matrix code using pylibdmtx in Python
<p>I am trying to decode data matrix qr codes using <code>pylibdmtx</code>. I have below image</p> <p><a href="https://i.sstatic.net/l4VRO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/l4VRO.png" alt="enter image description here" /></a></p> <p>and using the below code:</p> <pre><code>import cv2 from p...
<python><qr-code><datamatrix>
2024-03-27 14:14:51
1
7,576
S Andrew
78,232,346
2,090,481
Invalid websocket upgrade
<p>I've set up a server with the help of NiceGUI and Nginx on a VPS. The requests are coming through a subdomain and routed correctly: The server receives the request and prints the html elements.</p> <p>However, upon making use of the websockets, I can see the following error on my server's out: <code>ERROR:engineio.s...
<python><websocket><web-frameworks><nicegui>
2024-03-27 14:13:29
1
402
j4nSolo
78,232,318
19,366,064
Pytest: in memory data doesn't persist through fixture
<p>Here is my project setup</p> <pre><code>project/ app.py test_app.py </code></pre> <p>app.py</p> <pre><code>from pydantic import BaseModel from sqlalchemy.orm import Session from fastapi import Depends, FastAPI, HTTPException class UserCreateModel(BaseModel): username: str password: str def get_databa...
<python><unit-testing><pytest><fastapi><fixtures>
2024-03-27 14:09:51
1
544
Michael Xia
78,232,295
14,230,633
Manually set values shown in legend for continuous variable of seaborn/matplotlib scatterplot
<p>Is there a way to manually set the values shown in the legend of a seaborn (or matplotlib) scatterplot when the legend contains a continuous variable (hue)?</p> <p>For example, in the plot below I might like to show the colors corresponding to values of <code>[0, 1, 2, 3]</code> rather than <code>[1.5, 3, 4.5, 6, 7....
<python><matplotlib><plot><seaborn><visualization>
2024-03-27 14:06:37
3
567
dfried
78,232,223
22,221,987
How to generate a single key-press event signal with tkinter.bind method
<p>I have a simple ui, which should print every key that I've pressed.<br /> I need to generate signal <strong>once</strong> per real key-press.<br /> How can I achieve that?<br /> In default, tkinter generates signal once, than waits about 0.5 sec and starts generate signal in loop, until <em>KeyRelease</em> event hap...
<python><python-3.x><user-interface><tkinter><signals>
2024-03-27 13:56:45
1
309
Mika
78,232,037
4,721,937
How to use dictConfig to configure the logging handler extending QueueHandler?
<p>TL;DR <em>dictConfig</em> does not work with custom <em>QueueHandler</em> implementations in Python 3.12</p> <p>Following the <a href="https://docs.python.org/3/howto/logging-cookbook.html#subclass-queuehandler" rel="nofollow noreferrer">logging cookbook</a>, I implemented a custom QueueHandler which uses ZMQ to sen...
<python><python-logging><python-3.12>
2024-03-27 13:25:04
0
2,965
warownia1
78,232,013
3,834,415
How do I obtain a raw json string from an environment variable in python?
<p>In BASH, I can store JSON into an environment variable via jq:</p> <pre><code>export FOO=$(curl ... | jq -Rs) </code></pre> <p>Now, if I load that into python:</p> <pre><code>bar=os.environ[&quot;FOO&quot;] </code></pre> <p><code>bar</code> will have something like: <code>{\\&quot;this\\&quot;:\\&quot;that\\&quot;}<...
<python><json><environ>
2024-03-27 13:20:50
2
31,690
Chris
78,231,896
7,259,176
Powerset where each element can be either "positive" or "negative"
<p>I'm looking for a simple way to generate the powerset of an iterable where each element can be &quot;positive&quot; or &quot;negative&quot;, but not both in the same combination. There are no duplicates in the iterable and only the element or it's negative. Order doesn't matter.</p> <p>Here is an example with a list...
<python><powerset>
2024-03-27 12:59:19
2
2,182
upe
78,231,633
11,152,653
How to add image upload with text in LangServe api
<p>I am creating a LLM Chat API using LangServe. What I want is to offer user functionality to either upload image or use text to chat. So how to create a chatbot in LangServe that uses image and text input and can also have a option to add image in LangServe Playground.</p> <p>I was able to create a simple chatbot wit...
<python><openai-api><langchain><large-language-model>
2024-03-27 12:17:50
0
497
DevPy
78,231,321
2,255,491
In DRF, How to inject full `ErrorDetail` in the response, using a custom exception handler?
<p>I'm using a pretty complex custom handler in DRF. For example, for a given response, <code>response.data</code> could look like to:</p> <pre class="lang-py prettyprint-override"><code>{'global_error': None, 'non_field_errors': [], 'field_errors': {'important_field': [ErrorDetail(string='Ce champ est obligatoire.', c...
<python><django><django-rest-framework>
2024-03-27 11:25:26
2
11,222
David Dahan
78,231,305
3,433,875
Move labels to the beginning of the wedge in matplotlib pie chart
<p>I would like to move the labels from the center to the beginning of each wedge in my pie chart:</p> <pre><code>import matplotlib.pyplot as plt # Setting labels for items in Chart Employee = ['A', 'B', 'C', 'D', 'E'] # Setting size in Chart based on # given values Salary = [40000, 50000, 70000, 54000...
<python><matplotlib>
2024-03-27 11:22:55
1
363
ruthpozuelo
78,231,207
7,746,472
Skip level in nested JSON and convert to Pandas dataframe
<p>I have json data that is structured like this, which I want to turn into a data frame:</p> <pre><code>{ &quot;data&quot;: { &quot;1&quot;: { &quot;Conversion&quot;: { &quot;id&quot;: &quot;1&quot;, &quot;datetime&quot;: &quot;2024-03-26 08:30:00&quot; ...
<python><python-3.x><pandas><dataframe>
2024-03-27 11:06:23
2
1,191
Sebastian
78,230,664
792,015
Python Tkinter resize all ttkbootstrap or ttk Button padding for a specific style, applied to all themes
<p>I want to alter padding for all buttons using a particular style (danger). For some reason this change is only applied to the currently active theme, switching themes reverts the Button padding to default. You can see the issue by running the following and switching themes ...</p> <pre><code>import tkinter as tk fr...
<python><tkinter><ttk><ttkbootstrap>
2024-03-27 09:40:26
2
1,466
Inyoka
78,230,430
713,200
How to resolve BadHostKeyException with paramiko?
<p>I have following code to connect to a linux box and run a command, But I'm facing BadHostKeyException even after I have added <code>WarningPolicy</code> and <code>AutoAddPolicy</code>.</p> <pre><code> print(&quot;---CCCCCCCCCCCCC---&quot;,commands) client = paramiko.SSHClient() cli...
<python><linux><paramiko><ssh-keys>
2024-03-27 09:00:31
1
950
mac
78,230,261
18,107,780
PyQt5 heading and subheading
<p>I'm trying to recreate this <a href="https://i.sstatic.net/VI6t7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VI6t7.png" alt="enter image description here" /></a> in PyQt5. The problem is the space between the 2 labels (the heading and the subheading).</p> <p>This is my current code:</p> <pre><code...
<python><pyqt><pyqt5>
2024-03-27 08:27:11
1
457
Edoardo Balducci
78,230,229
10,122,048
When vercel deploying my python app gives Error: Unable to find any supported Python versions
<p>While installing the web app I prepared using python, vertex ai google chat bison model and fastapi, I constantly get Error: Unable to find any supported Python versions error and the installation does not complete. I also specified the Python version in the Requirements file, but it did not help. I use Vercel with ...
<python><fastapi><vercel><google-cloud-vertex-ai>
2024-03-27 08:21:11
4
458
webworm84
78,230,010
1,002,097
How to change the size and spacing of Plotly's sublopts?
<p>How is it possible to manipulate the <strong>spacing between rows</strong>(e.g. increasing the space between fist two rows and final two rows) and the <strong>size of charts inside the figure</strong> (e.g. making pie chart bigger)?</p> <p>In my example, I'm trying to visualize multiple data columns from <a href="ht...
<python><plotly><subplot><plotly.graph-objects>
2024-03-27 07:40:22
1
632
Tohid
78,229,687
12,238,655
What is the difference between pipx and using pip install inside a virtual environment?
<p>I recently used <a href="https://github.com/pypa/pipx#overview-what-is-pipx" rel="nofollow noreferrer">pipx</a> to install a package (that was the recommended install approach for the package). I installed using pip in a virtual environment.</p> <p>I was with the assumption that pipx is in that environment, and then...
<python><python-3.x><pip><python-venv><pipx>
2024-03-27 06:22:16
1
381
skaarfacee
78,229,557
7,601,346
Pytest KeyError: '__spec__' During handling of the above exception, another exception occurred: AttributeError: __spec__ Empty suite
<p>I'm trying to execute some pytest tests on a python repo in pycharm. I've tried just executing the tests individually from command line but I get the same errors.</p> <p>I'm using python and my python interpreter is set to 3.11</p> <pre><code>/usr/local/bin/python3.11 /Applications/PyCharm.app/Contents/plugins/pytho...
<python><python-3.x><pycharm><pytest>
2024-03-27 05:43:50
1
1,200
Shisui
78,229,489
8,325,579
Advanced type hints in Python - how do I avoid mypy being angry when the type is not specific enough
<p>I have some functions that return dictionaries:</p> <pre class="lang-py prettyprint-override"><code>def get_metadata_from_file(filepath:str)-&gt;dict[str, bool|dict[str, Any]]: '''Get metadata about a file if it exists''' answer = {} if os.path.isfile(filepath): answer['exists'] = True answe...
<python><mypy><python-typing>
2024-03-27 05:22:27
1
1,048
Myccha
78,229,273
14,553,366
Unable to convert Speech to Text using Azure Speech-to-Text service
<p>I'm using the below code to convert speech to text using Azure Speech-to-Text service.I want to convert my audio files into text.Below is the code for the same:</p> <pre><code>import os import azure.cognitiveservices.speech as speechsdk def recognize_from_microphone(): # This example requires environment va...
<python><azure><speech-recognition><speech-to-text>
2024-03-27 04:01:57
1
430
Vatsal A Mehta
78,229,141
10,792
Grouping Multiple Rows of Data For Use In scikit-learn Random Forest Machine Learning Model
<p>I'm having a difficult time phrasing my question, so if there's anything unclear that I can improve upon, please let me know. My goal is ultimately to determine the location of an RF transmitter using a machine learning model. There are many other techniques that could be used to identify the source of an RF signal ...
<python><machine-learning><scikit-learn>
2024-03-27 03:07:34
1
29,132
senfo
78,228,895
7,225,171
How to use memray with Gunicorn or flask dev server?
<p>I want to profile my flask project memory using <a href="https://github.com/bloomberg/memray" rel="nofollow noreferrer">memray</a>. In the documentation it is said to use the command as:</p> <pre><code>memray run my_script.py </code></pre> <p>But when I run flask (using dev server) or gunicorn I don't define the en...
<python><flask><memory><gunicorn>
2024-03-27 01:21:42
0
1,091
Serob
78,228,705
10,953,274
Issue with Loading Pre-trained DQN Model Resulting in Lower Performance
<p>Context: I've been working with a Deep Q-Network (DQN) model for a reinforcement learning project. After training the model, I saved it and later loaded it for further evaluation. However, I noticed that the performance of the loaded model is significantly worse compared to the original pre-trained model's performan...
<python><tensorflow>
2024-03-26 23:54:00
1
705
Unknown
78,228,640
978,288
How to make pythontex see PYTHONPATH
<p>I've been working with <code>pythontex</code> for some time and I'm quite happy with the results. After reinstalling the system, however, serious difficulties began.</p> <p><strong>THE PROBLEM</strong>: while compiling code (in .tex documents) and trying to <em>import local modules</em> I get <code>ModuleNotFoundErr...
<python><linux><latex><tex>
2024-03-26 23:23:28
0
462
khaz
78,228,609
10,466,743
AWS Sagemaker MultiModel endpoint additional dependencies
<p>I am trying to deploy a <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html#how-multi-model-endpoints-work" rel="nofollow noreferrer">multi model endpoint</a> on aws sagemaker. However some of my models have additional dependencies. I am following the <a href="https://huggingface.co/d...
<python><amazon-web-services><amazon-sagemaker><huggingface>
2024-03-26 23:11:49
1
344
Lucas
78,228,608
8,863,970
How to groupBy on two columns and work out avg total value for each grouped column using pyspark
<p>I have the following DataFrame and using Pyspark, I'm trying to get the following answers:</p> <ol> <li>Total Fare by Pick</li> <li>Total Tip by Pick</li> <li>Avg Drag by Pick</li> <li>Avg Drag by Drop</li> </ol> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Pick</th> <th>Drop</th> <th>Fare...
<python><pyspark><apache-spark-sql>
2024-03-26 23:11:02
2
1,013
Saffik
78,228,565
1,474,327
Python TCP Server that both sends and or receives data (independently) using asyncio streams?
<p>I've a python-based TCP server using asyncio, but it has an specific behavior: The TCP client (a PLC) connects to the app, but actually both the server or the client can start data flows. Once the data flow starts, it will be finished via specific-designed ACK messages.</p> <p>The TCP server part is connected to a R...
<python><tcp><stream><python-asyncio>
2024-03-26 22:56:09
1
727
Alberto
78,228,535
10,705,248
Fixed effect panel regression gives coefficients for each year
<p>I am trying to use Entity fixed panel regression for my data set. I have cross sectional data for each county in the US and for 1971 to 2020 (yearly). I have two indices: <code>STCTID</code> which is county ID and <code>Date</code>. Below is how my dataset looks like:</p> <p><a href="https://i.sstatic.net/WCKwE.png"...
<python><regression><statsmodels><panel-data><linearmodels>
2024-03-26 22:44:50
1
854
lsr729
78,228,326
547,231
Converting a torch.Tensor to a float pointer and vice versa
<p>I have an image <code>x</code> (as a <code>torch.Tensor</code>) of shape <code>(512, 512, 3)</code> (the first dimension being the color channel count). When I save it as an <code>*.exr</code>-file, using <code>imageio.imsave</code>, the output is the correct image:</p> <p><a href="https://i.sstatic.net/UjMsY.png" r...
<python><pytorch><ctypes><python-imageio>
2024-03-26 21:45:37
0
18,343
0xbadf00d
78,228,257
8,378,817
How to create citation, co-citation and bibliographic coupling networks in python?
<p>I am working currently in a small passion project to understand citation network. After some research, I came across three types of major citation analyses: direct citation, co-citation and bibliographic coupling.</p> <p>I was able to produce direct citation network in python. But creating co-citation and bibliograp...
<python><charts><networkx><igraph><network-analysis>
2024-03-26 21:27:16
0
365
stackword_0
78,228,165
832,490
Untyped decorator makes function "add" untyped [misc] (celery & mypy)
<p>I do not own the decorator.</p> <pre><code>from celery import Celery app = Celery(&quot;tasks&quot;, broker=&quot;pyamqp://guest@localhost//&quot;) @app.task def add(x: int, y: int) -&gt; int: return x + y </code></pre> <blockquote> <p>tasks.py:6: error: Untyped decorator makes function &quot;add&quot; untype...
<python><celery><mypy>
2024-03-26 21:04:25
0
1,009
Rodrigo
78,228,119
3,015,186
How to test a wheel against multiple versions of python?
<h3>Problem description</h3> <p>I'm writing a python library and I am planning to upload both sdist (.tar.gz) and wheel to PyPI. The <a href="https://build.pypa.io/" rel="nofollow noreferrer">build docs say</a> that running</p> <pre><code>python -m build </code></pre> <p>I get sdist created from the source tree and <em...
<python><python-packaging><tox>
2024-03-26 20:52:20
1
35,267
Niko Fohr
78,228,053
5,818,059
How to prevent Pandas from plotting index as Period?
<p>A common task I have is plotting time series data and creating gray bars that denote NBER recessions. For instance, <code>recessionplot()</code> from Matlab will do exactly that. I am not aware of similar funcionality in Python. Hence, I wrote the following function to automate this process:</p> <pre><code>def add_n...
<python><pandas><matplotlib><plot><time-series>
2024-03-26 20:37:46
1
815
Raul Guarini Riva
78,227,667
7,564,952
Get start and end time of a window based on a condition in pyspark
<p>using PySpark and Databricks. Starting from Minimum DateUpdated in dataset, check when Comp_BB_Status = 1 , from this DateUpdated check how much time duration did it took to change Comp_BB_Status = 0 I want to find time windows where Comp_BB_Status was 1, and calculate time duration in seconds and minutes for that p...
<python><python-3.x><pyspark><azure-databricks>
2024-03-26 19:09:46
2
455
irum zahra
78,227,504
525,916
Pandas - resample timeseries with both mean and max
<p>Given this sample timeseries:</p> <pre><code> price vol 2017-01-01 08:00:00 56 1544 2017-01-01 11:00:00 70 1680 2017-01-01 14:00:00 92 1853 2017-01-02 08:00:00 94 1039 2017-01-02 11:00:00 81 1180 2017-01-02 14:00:00 70 1443 2017-01-03 08:00:00 56 1621 2017-01-...
<python><pandas><time-series>
2024-03-26 18:32:59
2
4,099
Shankze
78,227,479
955,273
Add a column to a polars LazyFrame based on a group-by aggregation of another column
<p>I have a LazyFrame of <code>time</code>, <code>symbols</code> and <code>mid_price</code>:</p> <p>Example:</p> <pre class="lang-none prettyprint-override"><code>time symbols mid_price datetime[ns] str f64 2024-03-01 00:01:00 &quot;PERP_SOL_USDT@… 126.1575 2024-03-0...
<python><dataframe><window-functions><python-polars>
2024-03-26 18:27:48
1
28,956
Steve Lorimer
78,227,408
4,579,980
TypeError: str expected, not NoneType - Docker run problem with .env file in python
<p>I have a python RAG script that works fine locally (Windows).</p> <p>My understanding is that the problem is related to the .env file when it is called in basic_rag.py</p> <pre><code>os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') </code></pre> <p>When I run it with docker:</p> <pre><code>TypeError: str e...
<python><windows><docker><operating-system><.env>
2024-03-26 18:12:55
1
655
Diego
78,227,322
48,956
How can I interrupt or send signals to python Threads without cooperation from the thread?
<p>Previously I thought this wasn't possible to non-cooperatively interrupt a Thread in Python. A example might be the main thread asking to immediately cancel other theads in the process. But, from the signal docs:</p> <blockquote> <p>Python signal handlers are always executed in the main Python thread of the main int...
<python><python-multithreading>
2024-03-26 17:57:23
1
15,918
user48956
78,227,199
4,549,682
Cannot prevent azure function Python cold starts
<p>I cannot figure out how to completely stop azure function cold starts on the dedicated or premium plans. I have a ML function returning a prediction on input data. What I've tried:</p> <ul> <li>using the Python V2 model so all code is in the same .py file (e.g. all dependencies loaded together)</li> <li>warmupTrigge...
<python><azure><azure-functions>
2024-03-26 17:31:13
1
16,136
wordsforthewise
78,227,162
1,592,380
What is the unit of elevation in glo_30 Digital elevation map data
<p><a href="https://i.sstatic.net/B1qOZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B1qOZ.png" alt="enter image description here" /></a></p> <p>I'm trying to learn how to create elevation contour lines on a map in python following some of the ideas in <a href="https://medium.com/analytics-vidhya/crea...
<python><jupyter-notebook><leaflet><gis><folium>
2024-03-26 17:25:56
0
36,885
user1592380
78,227,144
13,491,504
Simulation of a Pendulum hanging on a spinning Disk
<p>Can anybody get this code to run? I know, that it is very long and maybe not easy to understand, but what I am trying to do is to write a simulation for a problem, that I have already posted here: <a href="https://math.stackexchange.com/questions/4876146/pendulum-hanging-on-a-spinning-disk">https://math.stackexchang...
<python><validation><math><sympy>
2024-03-26 17:23:18
1
637
Mo711