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,481,158
4,451,315
Keep rows where a field of a list[struct] column contains a message
<p>Say I have the following data:</p> <pre class="lang-py prettyprint-override"><code>import duckdb rel = duckdb.sql(&quot;&quot;&quot; FROM VALUES ([{'a': 'foo', 'b': 'bta'}]), ([]), ([{'a': 'jun', 'b': 'jul'}, {'a':'nov', 'b': 'obt'}]) df(my_col) SELECT * &quot;&quot;&quot;) </...
<python><duckdb>
2025-03-03 14:03:52
1
11,062
ignoring_gravity
79,481,080
1,195,909
Special many to many relation in SQLAlchemy
<p>I am trying to use <code>sqlalchemy</code> to model a database consisting of two classes <code>A</code> and <code>B</code>. The <code>B</code> class has two fields: <code>B.a</code> (1 to n) and <code>B.alist</code> (n to n).</p> <p>I am trying to follow the <a href="https://docs.sqlalchemy.org/en/20/orm/basic_relat...
<python><database-design><sqlalchemy>
2025-03-03 13:25:13
0
3,463
msampaio
79,481,011
4,752,874
Unable to Upload csv into Azure Blob Storage with LocationParseError label empty or too long
<p>Trying to load a dataframe as a csv into azure blob storage but getting the below error. I have had a look online but can't see what I am doing wrong. Some advice would be much appreciated.</p> <blockquote> <p>'DefaultEndpointsProtocol=https;AccountName=test;AccountKey=Test==;EndpointSuffix=core.windows.net', label ...
<python><azure><azure-blob-storage>
2025-03-03 12:42:48
1
349
CGarden
79,480,448
20,770,190
What is the default value of temperature parameter in ChatOpenAI in Langchain?
<p>What is the default value of the temperature parameter when I create an instance of <code>ChatOpenAI</code> in Langchain?</p> <pre class="lang-py prettyprint-override"><code>from langchain_openai import ChatOpenAI llm = ChatOpenAI(model=&quot;gpt-4o&quot;) print(llm.temperature) # it is None! llm=ChatOpenAI(model...
<python><openai-api><langchain>
2025-03-03 08:01:16
1
301
Benjamin Geoffrey
79,480,411
6,006,584
External API call in async handler
<p>I have the following code in FastAPI route handler. <code>client</code> is <code>aiohttp.ClientSession()</code>. The service is singleton, meaning all use the same class where I have this client.</p> <pre><code>async def handler(): log... async with client.post( f&quot;{config.TTS_SERVER_ENDP...
<python><fastapi>
2025-03-03 07:41:29
0
1,638
ddor254
79,480,260
275,002
TA-lib is not properly detecting Engulfing candle
<p>As you see in the attached image, there was a Bearish Engulfing candle on December 18. <a href="https://i.sstatic.net/iVfTUclj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iVfTUclj.png" alt="enter image description here" /></a></p> <p>But when I see the same data and engulfing value, it shows somet...
<python><ta-lib><candlesticks>
2025-03-03 05:53:25
1
15,089
Volatil3
79,480,121
1,141,601
Bitunix API Signature Failure with Python
<p>I have a code snippet I am trying to prove works and allows me to connect to the bitunix futures API. I have an idea for a bot I want to write.</p> <p>Instructions for creating the signature: [https://openapidoc.bitunix.com/doc/common/sign.html]</p> <p>Api I want to call: [https://openapidoc.bitunix.com/doc/account...
<python><digital-signature><sha256>
2025-03-03 03:41:20
0
431
S.A.Jay
79,480,120
9,983,652
why result of scaling each column always equal to zero?
<p>I am using minmaxscaler trying to scaling each column. The scaled result for each column is always all zero. For example , below the values of df_test_1 after finishing scaling is all zero. But even with all values of zero, using inverse_transferm from this values of zero can still revert back to original values. B...
<python><pandas>
2025-03-03 03:41:18
1
4,338
roudan
79,480,081
398,348
Getting Numpy error on VSCode (Windows11) even though numpy is installed
<p>reference: <a href="https://code.visualstudio.com/docs/python/python-tutorial#_start-vs-code-in-a-project-workspace-folder" rel="nofollow noreferrer">https://code.visualstudio.com/docs/python/python-tutorial#_start-vs-code-in-a-project-workspace-folder</a></p> <p>I created file hello.py</p> <pre><code>import numpy a...
<python><numpy><visual-studio-code>
2025-03-03 03:02:33
1
3,795
likejudo
79,480,032
12,883,179
In numpy find a percentile in 2d with some condition
<p>I have this kind of array</p> <pre><code>a = np.array([[-999, 9, 7, 3], [2, 1, -999, 1], [1, 5, 4, 6], [0, 6, -999, 9], [1, -999, -999, 6], [8, 4, 4, 8]]) </code></pre> <p>I want to get 40% percentile of each row in that array where it is not equal -999</p> <p>If I use <code>np.percentile(a, 40, axis=...
<python><numpy>
2025-03-03 02:06:50
1
492
d_frEak
79,479,888
651,174
How to initialize dict cursor in mysql.connector
<p>I used to be able to do something like:</p> <pre><code>self.conn = MySQLdb.connect(user=...) self.dict_cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) </code></pre> <p>However, now it's not so simple with the new mysql-python connector. How would I do a similar pattern to initialize a dict cursor?</p> <pre><co...
<python><mysql-connector>
2025-03-02 23:03:47
1
112,064
David542
79,479,705
8,774,513
How to make a custom diagram with python for data analysis
<p>I am looking for an idea how to change a diagram to make it fit to that picture:</p> <p><a href="https://i.sstatic.net/cwVZTYig.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cwVZTYig.png" alt="enter image description here" /></a></p> <p>Maybe it would make sense to make the output in a table to klic...
<python><pandas><data-analysis><mathlib>
2025-03-02 20:27:34
3
419
0x53olution
79,479,426
11,277,108
Create a function to use elimination logic to split a list of strings into substrings
<p>I have a list of strings where each string represents the names of two tennis players that played in a match. The list of strings collectively is all known matches in a tournament. An example of a string would be:</p> <pre><code>&quot;halep-simona-williams-serena&quot; </code></pre> <p>I'd like to split each string ...
<python><text-parsing>
2025-03-02 16:58:08
1
1,121
Jossy
79,479,405
12,663,117
Why is my virtual environment not working?
<p>I have a Python virtual environment (created with venv) kept in a directory in my project. I created it and sourced the activate script. I am sure that it worked, because my terminal prompt starts with <code>(venv)</code>. Running <code>which pip</code> points to the pip installed in the venv, however, when I run <c...
<python><linux><python-venv><venv>
2025-03-02 16:44:25
2
869
Nate T
79,479,392
2,302,485
What frame rate to expect using Python sounddevice.InputStream on macbook?
<p>I record audio on a macbook using this code:</p> <pre class="lang-py prettyprint-override"><code> def callback(indata, frame_count, time_info, status): if status: print('Error:', status) frames.append(indata.copy()) ... with sd.InputStream(callback=callback, channels=1, sa...
<python><macos><python-sounddevice>
2025-03-02 16:31:32
0
402
egor10_4
79,479,376
405,017
How to output an empty attribute in FastHTML?
<p>In <a href="https://fastht.ml/" rel="nofollow noreferrer">FastHTML</a> I want to output <code>&lt;option value=&quot;&quot;&gt;(select)&lt;/option&gt;</code> for a <a href="https://docs.fastht.ml/explains/explaining_xt_components.html" rel="nofollow noreferrer">FastTag component</a>. However, this code…</p> <pre cla...
<python><html><fasthtml>
2025-03-02 16:15:40
1
304,256
Phrogz
79,478,980
7,729,531
Use Flask-SocketIO to send messages continuously
<p>I would like to build an application to monitor files on my local computer through the browser. I have written a minimalistic example to illustrate this.</p> <p>The frontend should be able to request messages from the backend on events. In my example below, I am calling these &quot;standard messages&quot;. They are ...
<javascript><python><flask><flask-socketio>
2025-03-02 11:11:34
2
440
tvoirand
79,478,834
13,742,665
ModuleNotFoundError: No module named 'bs4' but in pip list is already installed
<p>in here try to install beautifulSoup using pip, but the module is not found,</p> <p>I try to verify python path and pip on my computer here us the result</p> <pre class="lang-bash prettyprint-override"><code>/Users/macbookairm2/Code/Dev/Fiverr/Scraping/project/AAMUProject/RosterBio/venv/bin/python venv➜ RosterBio g...
<python><python-3.x><beautifulsoup><pip><modulenotfounderror>
2025-03-02 09:11:36
1
833
perymerdeka
79,478,810
2,604,247
How Come Memory Footprint of a Tensorflow Model is Increasing After tflite Conversion?
<p>Trained a simple tensorflow model containing some LSTM and Dense feed-forward layers. After training, I am quantising and converting the model to a <code>tf.lite</code> format for edge deployment. Here is the relevant part of the code.</p> <pre class="lang-py prettyprint-override"><code>... model_size:int = sum(weig...
<python><tensorflow><machine-learning><tflite>
2025-03-02 08:44:09
0
1,720
Della
79,478,793
11,748,924
Change placeholder based on latest chat input streamlit
<p>I have this code that supposed to change placeholder dynamically based on latest user input:</p> <pre><code>def main(): last_prompt = st.session_state.get( &quot;last_prompt&quot;, &quot;A cat detective interrogating a suspicious goldfish in a bubble-filled aquarium courtroom.&quot;) prompt_input = st.chat...
<python><streamlit>
2025-03-02 08:23:17
2
1,252
Muhammad Ikhwan Perwira
79,478,562
6,312,979
Polars import from list of list into Colums
<p>I am trying to import a list of lists into Polars and get the data in seperate columns.</p> <p>Example.</p> <pre><code>numbers = [['304-144635', 0], ['123-091523', 7], ['305-144931', 12], ['623-101523', 16], ['305-145001', 22], ['623-111523', 27], ['9998-2603', 29]] </code></pre> <p>Does not work like Pandas and thi...
<python><dataframe><python-polars>
2025-03-02 02:47:34
2
2,181
diogenes
79,478,541
18,769,241
Longest palindrome substring algorithm not working properly for even palindromes
<p>The algorithm I wrote in Python seems to be working fine when it comes to extracting longest palindromes that have even number of characters but not for their odd counterparts:</p> <pre><code>some_input_2 = &quot;abdbaabeeba&quot; size_of_some_input_2 = len(some_input_2) max = 0 final_max = 0 idx_center_letter = 0 f...
<python><algorithm>
2025-03-02 02:14:02
3
571
Sam
79,478,025
5,320,122
ActiveMQ Artemis with STOMP: Same message from a queue is consumed by two consumers
<p>ActiveMQ Artemis version 2.27</p> <p>Consumers spin up as pods automatically by KEDA when it sees unread messages in the activemq broker. One consumer process one message, send ACK and disconnect. More frequently than always, I am seeing the same message is read by 2 or more consumers even though ACK is sent. What s...
<python><activemq-artemis><stomp>
2025-03-01 17:53:54
1
496
Amit
79,477,980
12,663,117
How can I install PyQt5 in python venv?
<p>I am on Ubuntu 20.04 and have made several attempts to install using pip. For some reason, pip just errors out. I have 3 different versions of pip on my system, and when I first tried installing PyQt5 into the system's main site-packages folder, I couldn't get any of them to install it successfully. I finally got it...
<python><linux><pip><pyqt><pyqt5>
2025-03-01 17:29:38
1
869
Nate T
79,477,784
12,357,035
Fatal Python error: GC object already tracked when invoking set constructor
<p>I have following Python2 function in a big Python-Cython project (print statements added for debugging):</p> <pre><code>import gc def e_closure (startstate): &quot;&quot;&quot;Return all states reachable from startstates on epsilon transitions. &quot;&quot;&quot; print('eclos1', startstate) print(len...
<python><garbage-collection><cython><cythonize>
2025-03-01 14:55:53
0
3,414
Sourav Kannantha B
79,477,586
2,881,548
How to Convert 'data.ilearner' Model to 'model.pkl' in Azure ML?
<p>I created a pipeline in Azure ML that trains a model using <strong>Boosted Decision Tree Regression</strong>. From my understanding, the model is saved as <strong><code>data.ilearner</code></strong>.</p> <p>However, I am unable to convert this model into a <strong><code>model.pkl</code></strong> format that can be l...
<python><azure><machine-learning>
2025-03-01 12:45:07
1
681
THM
79,477,559
4,306,541
Eliminating list elements having string from another list
<p>I'm trying to a get a subset of elements of L1, which do not match with any element of another list</p> <pre><code>&gt;&gt;&gt; L1 = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;] &gt;&gt;&gt; L2 = [&quot;bananaana&quot;, &quot;datedate&quot;] &gt;&gt;&gt; </code></pre> <p>For instanc...
<python><list><list-comprehension>
2025-03-01 12:30:19
4
469
Susanta Dutta
79,477,454
5,722,359
Why is the greyscale & B&W images created by Pillow giving a numpy.ndarray that has a 3D shape?
<p>Input:</p> <pre><code>import numpy as np from PIL import Image with Image.open(&quot;testimage.png&quot;) as img: img.convert('L') # convert to greyscale #img.convert('1') # convert to B&amp;W image_pil = np.asarray(img) print(f'{image_pil.shape=}') </code></pre> <p>Output:</p> <pre><code>image_pi...
<python><numpy><python-imaging-library>
2025-03-01 11:01:36
1
8,499
Sun Bear
79,477,395
8,040,369
Getting count of unqiue column values based on another column in df
<p>I have df as below</p> <pre><code>User Action AA Page1 AA Page1 AA Page2 BB Page2 BB Page3 CC Page3 CC Page3 </code></pre> <p>Is there a way to get the count for different Pages for each user as a df. something like below</p> <pre><code>User Page1 Page2 Page3 AA 2 1 0...
<python><pandas>
2025-03-01 10:06:27
1
787
SM079
79,476,892
1,980,208
Pandas groupby make all elements 0 if first element is 1
<p>I have the following df:</p> <pre><code>| day | first mover | | -------- | -------------- | | 1 | 1 | | 2 | 1 | | 3 | 0 | | 4 | 0 | | 5 | 0 | | 6 | 1 | | 7 | 0 | | 8 | 1 ...
<python><pandas>
2025-02-28 23:29:23
5
439
prem
79,476,789
11,609,834
How to get the dot product of inner dims in numpy array
<p>I would like to compute the dot product (matmul) of the inner dimension of two 3D arrays. In the following example, I have an array of 10 2x3 matrixes (X) and an array of 8 1x3 matrixes. The result Z should be a 10 element array of an 8 x 2 matrix (you might also think of this as an 10 x 8 array of 2-d vectors.)</p>...
<python><numpy>
2025-02-28 22:04:35
1
1,013
philosofool
79,476,753
62,225
Apache Beam: Use S3 bucket for Snowflake CSV output when using apache_beam.io.snowflake.ReadFromSnowflake in Python
<p>I'm trying to figure out how to work around an issue I've encountered with the Snowflake connector in Python.</p> <p>Basically, the issue boils down to the fact that to use Snowflake in Python it seems you're required to use Google Cloud Storage to store the temporary CSV files that get generated. However, my requir...
<python><amazon-s3><snowflake-cloud-data-platform><apache-beam>
2025-02-28 21:47:44
0
752
Sean Hagen
79,476,729
7,373,440
How to launch a FastAPI webserver from Dagster?
<p>I am creating an MLOps pipeline which process data, train model, and deploy model into an inference service. I am trying to create this all without Cloud services such as S3. I am using Dagster as the automated training pipeline.</p> <p>I have managed to process data, train model, and output model artifacts, all wri...
<python><mlops><dagster>
2025-02-28 21:29:42
0
3,071
addicted
79,476,711
536,538
Avoid having my custom button bound to multiple instances of that button when pressed
<p>My example seems to pass <code>self</code> in the button object (based on printing <code>my_id</code> to debug and it matching the <code>my_id</code> for each button, but when I click on &quot;Option A&quot; all 3 buttons animate. When I click on &quot;Option B&quot;, B and C animate.</p> <p>Why is the on_touch_down...
<python><python-3.x><kivy><kivymd>
2025-02-28 21:14:46
1
4,741
Marc Maxmeister
79,476,701
11,354,959
TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType. Huggingface model locally
<p>I'm trying to run a LM locally I don't really have much knowledge of huggingface. What I did is creating account there then creating a token that can read/write. I created a project did <code>pip install transformers tensorflow</code> After that I created a fily test.py:</p> <pre class="lang-py prettyprint-override"...
<python><tensorflow><huggingface>
2025-02-28 21:07:43
0
370
El Pandario
79,476,595
4,175,822
Is it possible to type hint a callable that takes positional arguments only using a generic for the positional type?
<p>In python, is it possible to type hint a callable that takes positional arguments only using a generic for the positional type?</p> <p>The context is that I want a to ingest positional args only. See this temporalio code:</p> <pre><code>@overload async def execute_activity( activity: Callable[..., Awaitable[Retu...
<python><python-typing><temporal-workflow>
2025-02-28 20:14:06
1
2,821
spacether
79,476,468
11,092,636
mypy exclude option is not working - bug?
<p>MRE:</p> <ul> <li>Make a folder (let's call it <code>MyProjectFolder</code>).</li> <li>Make a <code>helloroot.py</code> empty file.</li> <li>Make a subfolder named <code>FolderNotIgnored</code>.</li> <li>Make a <code>hello.py</code> in that subfolder.</li> <li>Make a <code>mypy.ini</code> file containing:</li> </ul>...
<python><mypy>
2025-02-28 19:04:31
1
720
FluidMechanics Potential Flows
79,476,439
5,029,763
Groupby column with relativedelta value
<p>I have a dataframe with a column of the <code>dateutil.relativedelta</code> type. When I try grouping by this column, I get the error <code>TypeError: '&lt;' not supported between instances of 'relativedelta' and 'relativedelta'</code>. I didn't find anythind in the pandas <a href="https://pandas.pydata.org/docs/ref...
<python><pandas><python-dateutil>
2025-02-28 18:48:58
1
1,935
user5029763
79,476,420
5,431,734
Finding original indices for rearranged arrays
<p>Given two numpy arrays of equal shape, I want to track how elements from the first array have moved in the second array. Specifically, for each element in the second array, I want to find its original position in the first array. The arrays are not sorted.</p> <p><strong>Example 1: All elements present</strong></p> ...
<python><numpy>
2025-02-28 18:42:00
4
3,725
Aenaon
79,476,158
6,003,629
How can I perform a calculation on a rolling window over a partition in polars?
<p>I have a Dataset containing GPS Coordinates of a few planes. I would like to calculate the bearing of each plane at every point in time.</p> <p>The Dataset as among others these columns:</p> <ol> <li><code>event_uid</code></li> <li><code>plane_no</code></li> <li><code>timestamp</code></li> <li><code>gps_lat</code></...
<python><window-functions><python-polars>
2025-02-28 16:32:47
2
385
jimfawkes
79,476,105
7,391,480
segment-geospatial installation breaks jupyter lab in Ubuntu
<p>I would like to install jupyter inside a conda environment and then install <code>segment-geospatial</code>, a python library from <a href="https://samgeo.gishub.org/" rel="nofollow noreferrer">samgeo</a>.</p> <p>However installing <code>segment-geospatial</code> breaks something that causes jupyter notebooks to sto...
<python><jupyter-notebook><conda><geospatial><pysqlite>
2025-02-28 16:12:25
1
1,364
edge-case
79,476,089
310,298
managing multi-component project with uv package manager
<p>I have an application that is made of a crawler, api, and data sub projects. crawler populates data in a DB, and an API serves data from that DB, so both depends on the data project. I am new with uv package manager and think thought this is a good use case for workspaces. My dir structure is as follows (simplified...
<python><uv>
2025-02-28 16:04:59
0
6,354
itaysk
79,476,088
20,895,654
Python dictionary vs dataclass (and metaclasses) for dynamic attributes
<p>Less object oriented snippet (1):</p> <pre><code>class Trickjump(TypedDict): id: int name: str difficulty: str ... </code></pre> <p>Dataclass snippet (2):</p> <pre><code>@dataclass class Trickjump(): id: IdAttr name: NameAttr difficulty: DifficultyAttr ... </code></pre> <p>My issue l...
<python><attributes><metaprogramming><python-dataclasses>
2025-02-28 16:04:09
1
346
JoniKauf
79,475,564
3,577,502
Powershell and CMD combining command-line filepath arguments to Python
<p>I was making user-entered variable configurable via command line parameters &amp; ran into this weird behaviour:</p> <pre><code>PS D:&gt; python -c &quot;import sys; print(sys.argv)&quot; -imgs &quot;.\Test V4\Rilsa\&quot; -nl 34 ['-c', '-imgs', '.\\Test V4\\Rilsa&quot; -nl 34'] PS D:&gt; python -c &quot;import sys...
<python><powershell><command-line>
2025-02-28 12:42:04
1
887
Lovethenakedgun
79,475,440
2,266,881
How can I convert a Polars dataframe to a column-oriented JSON object?
<p>I'm trying to convert a Polars dataframe to a JSON object, but I can't seem to find a way to change the format of it between row/col orientation. In Pandas, by default, it creates a column-oriented JSON object, and it can be changed easily, but in Polars it's row-oriented and I can't seem to find a way to change tha...
<python><json><dataframe><python-polars>
2025-02-28 11:54:07
2
1,594
Ghost
79,475,378
3,437,721
Azure function Open Telemetry
<p>I currently have an Azure APIM which uses the event-metric policy to send custom metrics to application insights:</p> <pre><code>&lt;emit-metric name=&quot;appid-info&quot; namespace=&quot;app-stats&quot;&gt; &lt;dimension name=&quot;api-name&quot; value=&quot;@(context.Api.Name)&quot; /&gt; &lt;dimension na...
<python><azure><azure-functions><open-telemetry>
2025-02-28 11:31:28
0
2,329
user3437721
79,475,261
4,759,736
Slack sdk OAuth 2 redirect url not working
<p>I created a Slack app and I'm trying to get OAuth 2.0 to work. I'm using Python with flask to try and exchange tokens but I can't seem to get the redirect url to open properly.</p> <p>Slack requires the redirect to be https, and I'm using localhost to redirect at <code>http://127.0.0.1:5000/slack/oauth/callback</cod...
<python><flask><slack-api>
2025-02-28 10:45:31
2
4,772
Green Cell
79,475,225
12,825,882
Azure documen intelligence python SDK doesn't separate pages
<p>When trying to extract content from a MS Word .docx file using Azure Document Intelligence, I expected the returned response to contain a page element for each page in the document and for each of those page elements to contain multiple lines in <a href="https://learn.microsoft.com/en-us/azure/ai-services/document-i...
<python><azure><azure-document-intelligence>
2025-02-28 10:29:35
1
624
PangolinPaws
79,475,116
6,265,680
UnicodeDecodeError when using SHAP 0.42 and xgboost 2.1.1
<p>I am trying to explain my xgboost (v 2.1.1) model with shap (v 0.42) but I get this error:</p> <pre><code>UnicodeDecodeError Traceback (most recent call last) Cell In[53], line 1 ----&gt; 1 shap_explainer = shap.TreeExplainer(model) File ~/anaconda3/envs/geoproc/lib/python3.8/site-packages/sh...
<python><xgboost><shap>
2025-02-28 09:48:32
1
321
Christin Abel
79,475,093
5,615,873
How to get the duration of a note as a number in music21?
<p>In <strong>music21</strong>, if I want to get the duration of a note, I get an object, of the form <em>'music21.duration.Duration {number}'</em>. I can't find anywhere how to get this {number} alone. Is there some other music21 property or method (not one's own) that provides such a value?</p>
<python><music21>
2025-02-28 09:41:59
1
3,537
Apostolos
79,475,051
6,666,611
What's the difference between uv lock --upgrade and uv sync?
<p>Being a total newbie in the python ecosystem, I'm discovering uv and was wondering if there was a difference between the following commands :<br /> <code>uv lock --upgrade</code><br /> and<br /> <code>uv sync</code></p> <p>If there's any, what are the exact usage for each of them ?</p>
<python><dependency-management><uv>
2025-02-28 09:28:12
1
1,176
n3wbie
79,474,670
338,479
How can I wait for any one thread out of several to finish?
<p>Say I want to launch multiple threads to perform tasks, and as they finish I want to process their work units. And optionally launch more threads to do more work units.</p> <p>Is there any standard way to tell Python that I want to wait for any one of my threads to complete? Bonus points if it's easy to know which o...
<python><multithreading>
2025-02-28 06:12:30
1
10,195
Edward Falk
79,474,514
9,743,391
How to remove xarray plot bad value edge colour
<p>I know set_bad can colour the pixel into a specific colour but in my example I only want to have edge colour for blue and grey pixels with values and not the bad pixels (red)</p> <pre><code>import matplotlib.pyplot as plt import xarray as xr import numpy as np from matplotlib import colors fig, ax = plt.subplots(1,...
<python><matplotlib><python-xarray>
2025-02-28 04:28:47
1
626
Jane
79,474,503
10,262,805
Why does my Keras model show 4 parameters instead of 2?
<p>I'm training a simple Keras model with one Dense layer, but when I call model.summary(), it shows 4 parameters instead of 2.</p> <pre><code>import tensorflow as tf import numpy as np # Generate dummy data X_train = np.random.rand(40) # Shape (40,) y_train = np.random.rand(40) # Define a simple model model = tf.ke...
<python><tensorflow><machine-learning><keras><deep-learning>
2025-02-28 04:18:51
2
50,924
Yilmaz
79,474,354
188,331
Debug a dead kernel using ipykernel kernel --debug
<p>I just added a new kernel to Juypter Notebook using:</p> <pre><code>python -m ipykernel install --user --name=venv3.12 </code></pre> <p>and edited the path of Python to the Python executable at a <code>venv</code> folder. The contents of the <code>kernel.json</code> is as follows:</p> <pre><code>{ &quot;argv&quot;:...
<python><ubuntu><jupyter-notebook><python-venv>
2025-02-28 02:11:59
0
54,395
Raptor
79,474,175
10,034,073
Why does RawPy/Libraw increase the brightness range when postprocessing?
<p>I'm processing a raw photo<sup>1</sup> with <code>RawPy</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import rawpy with rawpy.imread('my_picture.nef') as rpy: raw = rpy.raw_image print('Raw:', raw.shape, np.min(raw), np.max(raw)) image = rpy.postprocess( ...
<python><image-processing><libraw><demosaicing><rawpy>
2025-02-27 23:37:28
0
444
kviLL
79,473,967
23,260,297
How to merge two dataframes based on condition
<p>I have 2 dataframes:</p> <p>df1:</p> <pre><code>BA Product FixedPrice Vintage DeliveryPeriod A foo 10.00 Vintage 2025 Mar25 B foo 11.00 Vintage 2025 Dec25 B foo 12.00 Vintage 2024 Sep25 C bar 2.00 None Nov25 </code></pre> <p>df2:</p> <p...
<python><pandas>
2025-02-27 21:22:11
2
2,185
iBeMeltin
79,473,943
1,028,270
How do I get the _env_file param of an instantiated BaseSettings object?
<p>When instantiating a class like this:</p> <pre><code>settings = Settings(_env_file='some/path/prod.env', _env_file_encoding='utf-8') </code></pre> <p>I want to store <code>some/path/prod.env</code> in a property somewhere. Does pydantic settings track this? If not how can I do this? I shouldn't have to override init...
<python><pydantic><pydantic-settings>
2025-02-27 21:09:10
1
32,280
red888
79,473,884
2,986,153
how to set truncated t-distribution prior in bambi
<pre><code>%pip install bambi==0.15.0 %pip install numpy==1.26.4 </code></pre> <pre><code>import bambi as bmb import polars as pl from polars import col, lit import pandas as pd import numpy as np import arviz as az np.random.seed(42) num_rows = int(10e3) # Generate random data shape, scale = 10, 6 # Gamma paramet...
<python><bambi>
2025-02-27 20:36:53
0
3,836
Joe
79,473,854
2,804,645
Type narrowing via exception in function
<p>I'm trying to understand why an exception raised based on the type of a variable doesn't narrow down the type of this variable.</p> <p>I'd like to do something like this:</p> <pre class="lang-py prettyprint-override"><code>def ensure_int(obj: int | str) -&gt; None: if isinstance(obj, str): raise ValueErr...
<python><python-typing><mypy>
2025-02-27 20:19:30
2
410
Stan
79,473,710
11,318,930
Can polars have a boolean in a 'with_columns' statement?
<p>I am using polars to hash some columns in a data set. One column is contains lists of strings and the other column strings. My approach is to cast each column as type string and then hash the columns. The problem I am having is with the type casting.</p> <p>I am using the with_columns method a follows:</p> <pre><c...
<python><python-polars><polars>
2025-02-27 19:19:14
1
1,287
MikeB2019x
79,473,667
118,195
Would it ever make sense to use multithreading for I/O bound operations in modern Python?
<p>I often hear that it in some circumstances it makes sense to use multi-threading for I/O operations (file operations, network communications, etc.). But why not just use asyncio for all I/O bound operations and stick to threads/processes for CPU-bound operations?</p> <p>Are there any scenarios you can think of when ...
<python>
2025-02-27 18:55:23
1
2,107
Zoman
79,473,549
996,309
Aborted gRPC requests erroring in the frontend with "RpcError: missing status"
<p>I'm using python (3.12), grpcio (1.64.0), and @protobuf-ts (2.9.3).</p> <p>I'm trying to set up auth in my python gRPC server, following the example here: <a href="https://github.com/grpc/grpc/blob/master/examples/python/auth/token_based_auth_server.py" rel="nofollow noreferrer">https://github.com/grpc/grpc/blob/mas...
<python><authentication><grpc>
2025-02-27 18:00:22
1
3,719
Tom McIntyre
79,473,547
4,198,514
Tkinter - resize parent after grid_remove()
<p>Either I did misread some of the documentation or I still do not quite understand some concepts of Tkinter.</p> <p>If I add widgets (e.g. Labels) to a frame using <code>grid()</code> the frame gets resized to fit them. (so far as expected)</p> <p>If I call grid_remove on all the children (using <code>frame.winfo_chi...
<python><tkinter><grid><resize><autoresize>
2025-02-27 17:59:30
4
2,210
R4PH43L
79,473,519
1,422,058
DB connections stay in idle state using psycopg2 Postgres driver with Python
<p>When running the following code to insert data to a database table, each time a DB connection appears in <code>pg_stat_activity</code> which remains there in state idle:</p> <pre class="lang-none prettyprint-override"><code>column_names = &quot;, &quot;.join(columns) query = f&quot;INSERT INTO {table_name} ({column...
<python><python-3.x><postgresql>
2025-02-27 17:45:15
2
1,029
Joysn
79,473,274
3,663,124
FastAPI hide sql session in object
<p>I want to hide the usage of sql model behind a class, let's call it Repository. So that an endpoint would be something like:</p> <pre class="lang-py prettyprint-override"><code>@router.get(&quot;/&quot;) def list() -&gt; list[Resource]: return repository.list() </code></pre> <p>And then have a Repository class w...
<python><pytest><fastapi>
2025-02-27 16:06:03
0
1,402
fedest
79,473,246
4,463,825
Automate initializing random integers for various columns in data frame Python
<p>I am trying to minimize the following code to a for loop, as I have 14 of the similar columns, or something in a fewer number of code lines. What would be a pythonic way to do it?</p> <pre><code>df['fan1_rpm'] = np.random.randint(5675, 5725, 30) df['fan2_rpm'] = np.random.randint(5675, 5725, 30) df['fan3_rpm'] = np....
<python><pandas><numpy>
2025-02-27 15:55:43
2
993
Jesh Kundem
79,473,192
5,666,203
Disagreement between SciPy quaternion and Wolfram
<p>I'm calculating rotation quaternions from Euler angles in Python using SciPy and trying to validate against an external source (Wolfram Alpha).</p> <p>This Scipy code gives me one answer:</p> <pre><code>from scipy.spatial.transform import Rotation as R rot = R.from_euler('xyz', [30,45,60], degrees=1) quat = rot.as_...
<python><validation><scipy><quaternions><wolframalpha>
2025-02-27 15:38:36
1
1,144
AaronJPung
79,473,140
8,223,979
Add edges to colorbar in seaborn heatmap
<p>I have the following heatmap:</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Create a sample heatmap data = np.random.rand(10, 12) ax = sns.heatmap(data) plt.show() </code></pre> <p>How can I add a black edge to the colormap? Is there any way to do this without needing t...
<python><seaborn><heatmap><colorbar><color-scheme>
2025-02-27 15:22:21
1
1,097
Caterina
79,473,134
8,223,979
Extend bbox in heatmap
<p>I have the following heatmap:</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt import numpy as np # Create a sample heatmap data = np.random.rand(10, 12) ax = sns.heatmap(data) # Set the x-axis label ax.set_xlabel('X Axis Label') # Change the background color of the x-axis label ax...
<python><matplotlib><seaborn><heatmap><x-axis>
2025-02-27 15:19:54
0
1,097
Caterina
79,473,066
3,663,124
Pytest mocker not mocking
<p>I have the following structure for my code which is a fastapi app:</p> <pre><code>/repo /src main.app /routes /resource resource.py /repository repository.py /tests /routes /resource resource_test.py </code></pre> <p>/src/routes/resource/resource.py</p> <pre class="lang-py...
<python><mocking><pytest>
2025-02-27 14:58:06
1
1,402
fedest
79,473,058
4,048,657
PyTorch - Efficiently computing the per pixel gradient of an image with respect to some parameter?
<p>I have a function that takes a single parameter (alpha) as an input an outputs a N by N image (2048x2048). I want to obtain the gradient of this image with respect to the parameter (alpha). I'm not talking about a sobel filter, I'm looking to see how my image changes as I change alpha. The function takes around 2 se...
<python><pytorch>
2025-02-27 14:55:22
0
1,239
Cedric Martens
79,473,015
1,745,001
How to gracefully stop an asyncio server in python 3.8
<p>As part of learning <code>python</code> and <code>asyncio</code> I have a simple TCP client/server architecture using <code>asyncio</code> (I have reasons why I need to use that) where I want the server to completely exit when it receives the string 'quit' from the client. The server, stored in <code>asyncio_server....
<python><python-3.x><python-asyncio>
2025-02-27 14:35:52
2
208,382
Ed Morton
79,472,665
1,987,477
how to access a dictionary key storing a list in a list of lists and dictionaries
<p>I have the following list:</p> <pre><code>plates = [[], [], [{'plate ID': '193a', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441297986560, 99.28418829069784, 11.821604434173034], [3352465726807951744, 100.86164898224092, 12.756149587760696]]}], [{'plate ID': '194b', 'ra': 98.0, 'dec': 11.0, 'sources': [[3352102441...
<python><pandas>
2025-02-27 12:21:27
2
1,325
user123892
79,472,606
125,673
Cannot install pysqlite3
<p>Trying to install pysqlite3 in VS Code and I get this error;</p> <pre><code>PS E:\Gradio&gt; pip install pysqlite3 --user WARNING: Ignoring invalid distribution ~ip (C:\Python312\Lib\site-packages) DEPRECATION: Loading egg at c:\python312\lib\site-packages\vboxapi-1.0-py3.12.egg is deprecated. pip 25.1 will enforce ...
<python><pip><pysqlite>
2025-02-27 12:01:16
0
10,241
arame3333
79,472,181
10,873,394
Page number in PyMuPDF multiprocessing with extract_text
<p>So in pymupdf documentation states that <a href="https://pymupdf.readthedocs.io/en/latest/recipes-multiprocessing.html#multiprocessing" rel="nofollow noreferrer">PyMuPDF does not support running on multiple threads</a></p> <p>So they use multiprocessing, and they do this weird thing with segments in example code:</p...
<python><python-3.x><pdf><multiprocessing><pymupdf>
2025-02-27 09:26:24
0
424
MichaΕ‚ Darowny
79,472,150
5,049,813
How to extend type-hinting for a class in a stub file
<p>I have this code, and it annoys me that I have to cast <code>f</code> twice:</p> <pre class="lang-py prettyprint-override"><code> with h5py.File(computed_properties_path, &quot;r&quot;) as f: # get the set of computed metrics computed_metrics = set() # iterating through the file iterates t...
<python><python-typing><h5py>
2025-02-27 09:15:50
1
5,220
Pro Q
79,472,096
2,516,892
Parsing of CSV-File leads to "NBSP" and "SPA" Characters in Windows
<p>I am parsing a CSV document to write a specification in SysML v2, which is essentially just a simple text file. Parsing it on Linux I get the result I desire. I use a SysOn-Docker to display my SysML v2 file and everything works as it's supposed to.</p> <p>However, when I parse create the file in Windows there are s...
<python><python-3.x><encoding><character-encoding><sysml2>
2025-02-27 08:55:56
1
1,661
Qohelet
79,471,816
2,072,676
Working directory structure for a Django-Python project used as an API backend only
<p>I'm a newbie in Django Python and I need to create an API backend for a frontend done in React. I'm forced by the customer to use Django Python, no options on this!</p> <p>The project is very simple: it needs to expose <strong>~15 endpoints</strong>, use Django <strong>ORM</strong> to connect to a <strong>PostgreSQL...
<python><django><directory-structure>
2025-02-27 06:53:34
1
5,183
Giox
79,471,693
191,064
Difference in output of sympy.binomial vs scipy.special.comb
<p>Why does the following code that calls <code>comb</code> produce the wrong output?</p> <pre><code>from scipy.special import comb from sympy import binomial def coup(n=100, m=10): expectation = 0 for j in range(1, n + 1): coeff = ((-1)**(j-1)) * comb(n, j) denominator = 1 - (comb(n - j, m) /...
<python><scipy><sympy><numerical-methods>
2025-02-27 05:47:02
1
2,599
bettersayhello
79,471,516
243,755
Intermittent SSLCertVerificationError when using requests
<p>It is very weird to me that this SSLCertVerificationError not always happens, it happens sometimes. (e.g. The first request run well, but the second request may hit this issue)</p> <p>I have installed <code>certifi</code>, env <code>SSL_CERT_FILE</code> is also set. Not sure why this error happens Intermittently, an...
<python><python-requests><ssl-certificate>
2025-02-27 03:00:00
0
29,674
zjffdu
79,471,221
3,310,237
In Python GDAL, why I get two EPSG attributes in ExportToWkt?
<p>I'm processing some satellite <a href="https://lpdaac.usgs.gov/products/mod13q1v006/" rel="nofollow noreferrer">MOD13Q1</a> images. If I print the ExportToWkt output, I get:</p> <p><code>PROJCS[&quot;unnamed&quot;,GEOGCS[&quot;Unknown datum based upon the custom spheroid&quot;,DATUM[&quot;Not_specified_based_on_cust...
<python><gdal><projection>
2025-02-26 23:06:02
0
465
Mauro Assis
79,471,135
2,904,824
Generating Keys
<p>Using PyJWT, how do you generate a new key from scratch?</p> <p>I cannot find a single example of how to do this in PyJWT. I can find examples with jwcrypto, but porting that looks tedious at best.</p> <p>EDIT: I'm deep in OIDC, and I need asymmetric crypto and actual JWKs.</p>
<python><pyjwt>
2025-02-26 22:12:27
1
667
AstraLuma
79,471,079
3,745,677
How to handle malformed API request in Flask?
<p>There is quite an old game (that no longer works) that has to make some API calls in order to be playable. I am creating a Flask mock server to handle those requests, however it turned out that the requests are not compliant with HTTP standard and are malformed. For example:</p> <pre><code>Get /config.php http/1.1 <...
<python><flask>
2025-02-26 21:37:45
1
802
lolbas
79,470,854
2,005,559
supply extra parameter as function argument for scipy optimize curve_fit
<p>I am defining a <code>piecewise</code> function for some data,</p> <pre><code>def fit_jt(x, e1, e2, n1, E1, E2, N1, N2): a = 1.3 return np.piecewise(x, [x &lt;= a, x &gt; a], [ lambda x: 1 / e1 + (1 - np.float128(np.exp(-e2 * x / n1))) / e2, lambda x: 1 / E1 + (1 - np.float128(np.exp(-E2 * x / ...
<python><scipy><scipy-optimize>
2025-02-26 19:31:13
1
3,260
BaRud
79,470,828
2,893,712
Nodriver Cannot Start Headless Mode
<p>I found <a href="https://github.com/ultrafunkamsterdam/nodriver/" rel="nofollow noreferrer">Nodriver</a>, which is the successor <a href="https://github.com/ultrafunkamsterdam/undetected-chromedriver/" rel="nofollow noreferrer">Undetected-Chromedriver</a>. I am trying to run in headless mode but am having problems.<...
<python><python-3.x><undetected-chromedriver><nodriver>
2025-02-26 19:19:47
2
8,806
Bijan
79,470,747
4,363,864
Combine dataframe columns elements by pair
<p>I have this dataframe, already sorted by ID then SEQ:</p> <pre><code>x = pd.DataFrame({ 'ID': [1, 1, 1, 1, 2, 2, 2], 'SEQ': [1, 2, 3, 4, 1, 3, 4] }) </code></pre> <p>Inline:</p> <pre><code> ID SEQ 0 1 1 1 1 2 2 1 3 3 1 4 4 2 1 5 2 3 6 2 4 </code></pre> <p>And I want to combin...
<python><pandas><dataframe>
2025-02-26 18:31:18
1
10,820
obchardon
79,470,598
1,552,080
Writing complex Pandas DataFrame to HDF5 using h5py
<p>I have a Pandas DataFrame with mixed scalar and array-like data of different raw types (int, float, str). The DataFrame's types look like this:</p> <pre><code>'col1', dtype('float64') 'col2', dtype('O') &lt;-- array, item type str 'col3', dtype('int64' 'col4', dtype('bool') ... 'colA', dtype('O') &lt;-- array, item ...
<python><arrays><pandas><hdf5><h5py>
2025-02-26 17:31:44
1
1,193
WolfiG
79,470,526
12,162,229
Grouped Rolling Mean in Polars
<p>Similar question is asked <a href="https://stackoverflow.com/questions/76164821/how-to-group-by-and-rolling-in-polars">here</a></p> <p>However it didn't seem to work in my case.</p> <p>I have a dataframe with 3 columns, date, groups, prob. What I want is to create a 3 day rolling mean of the prob column values group...
<python><dataframe><python-polars><rolling-computation><polars>
2025-02-26 17:08:21
1
317
AColoredReptile
79,470,488
3,267,763
bazel build and run grpc server with python
<p>I am trying to setup a larger bazel infrastructure to</p> <ol> <li>Create .py files from a <code>.proto</code> file for gRPC using <code>rules_proto_grpc_python</code></li> <li>Run the server code that implements the interfaces defined in 1 via a <code>py_binary</code></li> </ol> <p>However, I am getting the error</...
<python><grpc><bazel><grpc-python><bazel-python>
2025-02-26 16:54:53
1
682
kgully
79,470,483
1,778,537
Tkinter: Canvas item color change on state change
<p>The Tkinter code below displays a root window containing a canvas and a blue rectangle. Clicking on the rectangle toggles its state between 'normal' and 'disabled'.</p> <p>I'd like to also toggle its color. I know how to do it using <code>canvas.itemconfig(rect, fill='red')</code> for example, by checking its state....
<python><tkinter><tkinter-canvas>
2025-02-26 16:51:14
1
354
Sigur
79,470,417
1,628,971
How to add a group-specific index to a polars dataframe with an expression instead of a map_groups user-defined function?
<p>I am curious whether I am missing something in the Polars Expression library in how this could be done more efficiently. I have a dataframe of protein sequences, where I would like to create k-long substrings from the protein sequences, like the <code>kmerize</code> function below.</p> <pre class="lang-py prettyprin...
<python><dataframe><bioinformatics><python-polars><polars>
2025-02-26 16:25:20
2
1,694
Olga Botvinnik
79,470,369
2,123,706
when creating a table using sql alchemy in python, why do string columns become varchar(max) in SQL?
<p>I have a dataframe that I want to write to a table in SQL Server. I use SQL alchemy:</p> <pre><code>import pandas as pd import sqlalchemy from sqlalchemy import create_engine, text server = database = driver = database_con = f'mssql://@{server}/{database}?driver={driver}' engine = create_engine(database_con...
<python><sqlalchemy>
2025-02-26 16:09:46
1
3,810
frank
79,470,149
7,615,872
Custom ValidationError message for extra fields
<p>I have defined a model using Pydantic V2 as follows:</p> <pre><code>from pydantic import BaseModel class Data(BaseModel): valid: bool = False name: str | None = None model_config = ConfigDict(extra=&quot;forbid&quot;) </code></pre> <p>When I use this model to validate some data using <code>model_validat...
<python><pydantic><pydantic-v2>
2025-02-26 14:51:09
1
1,085
Mehdi Ben Hamida
79,470,120
459,888
How to override txnVersion in Spark?
<p>Following the instructions for idempotency in <a href="https://docs.delta.io/latest/delta-streaming.html" rel="nofollow noreferrer">Idempotent table writes in foreachBatch</a>, I set the txnVersion and txnApp options. It works as intended. However, those options keep their values even after foreachBatch ends.</p> <p...
<python><scala><apache-spark><databricks><delta>
2025-02-26 14:43:58
0
786
pgrandjean
79,470,048
2,840,125
Pandas DataFrame conditional formatting function with additional inputs
<p>I developed a Qt GUI that reads data from a database and displays it on the screen in a table. The table includes conditional formatting which colors cell backgrounds based on cell contents. For example, if the cell contains the letter 'G' for good, then the cell background gets colored green.</p> <p>I'm currently w...
<python><pandas><dataframe><formatting>
2025-02-26 14:18:04
2
477
Kes Perron
79,469,894
4,444,546
polars cum sum to create a set and not actually sum
<p>I'd like to use a function like cumsum, but that would create a set of all values contained in the column up to the point, and not to sum them</p> <pre><code>df = pl.DataFrame({&quot;a&quot;: [1, 2, 3, 4]}) df[&quot;a&quot;].cum_sum() shape: (4,) Series: 'a' [i64] [ 1 3 6 10 ] </code></pre> <p>but I'...
<python><python-polars><cumsum>
2025-02-26 13:24:52
1
5,394
ClementWalter
79,469,787
243,031
Change required fields to non-required fields
<p>We are using <a href="https://docs.pydantic.dev/latest/" rel="nofollow noreferrer"><code>pydantic</code></a> to validate our API request payload. We have <code>insert</code> and <code>update</code> endpoint.</p> <p>Both endpoint have same payload requirements. We created model for that:</p> <pre><code>from pydantic ...
<python><pydantic><pydantic-v2>
2025-02-26 12:50:17
0
21,411
NPatel
79,469,031
12,036,671
Does `clickhouse_connect.get_client` return a new client instance every time?
<p>As the question mentions, does <code>clickhouse_connect.get_client</code> in the python client return a new client instance every time it is called? I can't seem to find if it is explicitly mentioned as such in the documentation, but it seems implied. I'm a little confused because of the name <code>get_client</code>...
<python><clickhouse><clickhouse-client>
2025-02-26 08:40:02
1
825
Sandil Ranasinghe
79,468,879
680,074
How to fetch the records using ZOHO CRM API filtering on Created_time Criteria
<p>I am trying to fetch the deals from ZOHO CRM API unfortunately the Created_Time criteria is not working, its giving 200 records everytime and its not in the real case only 3 or 4 records exists greater than the below date. But when I am passing the if-modified-since clause in the header it works perfectly.</p> <pre>...
<python><crm><zoho>
2025-02-26 07:40:58
0
1,672
Tayyab Vohra