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,914,940
6,439,229
Is it possible to adjust QlineEdit icon spacing?
<p>I'm planning to use a <code>QLineEdit</code> with three actions added via <code>addAction()</code>.<br /> Easy enough and it looks like this: (squares as icons for the example)</p> <p><a href="https://i.sstatic.net/6ldQzHBM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6ldQzHBM.png" alt="enter image...
<python><pyqt6><qlineedit>
2024-08-26 14:24:41
1
1,016
mahkitah
78,914,882
6,930,340
Replace a cell in a column based on a cell in another column in a polars DataFrame
<p>Consider the following <code>pl.DataFrame</code>:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;symbol&quot;: [&quot;s1&quot;, &quot;s1&quot;, &quot;s2&quot;, &quot;s2&quot;], &quot;signal&quot;: [0, 1, 2, 0], &quot;trade&quot;: [None, 1, None, -1], } ) shape: (4, 3)...
<python><dataframe><python-polars>
2024-08-26 14:10:19
3
5,167
Andi
78,914,875
17,174,267
python overlaying information on base class
<p>I have a base class <code>ASTNode</code> and a bunch of subclasses. I cannot/want not modify these classes. The <code>ASTNode</code>s represent a tree.</p> <p>Now I'd like to add type checking to my AST (meaning I need to add new data to every node.)</p> <p>A) I create a new Typed-variant for every ASTNode subclass ...
<python>
2024-08-26 14:08:20
0
431
pqzpkaot
78,914,836
4,965,381
Is there a way to include column index name with Pandas dataframe to CSV?
<p>Is there a way to include the column (not rows!) index name in the output when calling Pandas' <code>dataframe.to_csv()</code> method? For example:</p> <pre><code>import pandas as pd iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv') pivot_iris = iris.pivot_table(index='spe...
<python><pandas><csv>
2024-08-26 13:59:45
1
1,067
voiDnyx
78,914,357
14,358,734
Merge a multi index of year, then month into one index year-month
<p>My code so far</p> <pre><code>import random import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os from scipy.stats import shapiro import scipy.stats as stats ios = pd.read_csv('iOS.csv') ios.replace(',','', regex=True, inplace=True) ios = ios.astype({'Total Impres...
<python><pandas><dataframe>
2024-08-26 12:16:24
1
781
m. lekk
78,914,204
3,103,399
webRTC video streaming - Chrome chooses wrong candidates with ubuntu 20
<p>I am streaming video over webRTC in AWS environments, all ports are open, no firewall.</p> <p><strong>Server 1:</strong> Ubuntu 18.04.5 LTS</p> <p><strong>Server 2:</strong> Ubuntu 20.04.6 LTS</p> <p>With Server 1 after at most 2-3 retries, webRTC chooses the correct candidate pair that has my pc public IP and the r...
<javascript><python><ubuntu><webrtc><aiortc>
2024-08-26 11:42:50
2
5,386
jony89
78,914,111
22,479,232
How to use "--" as an argument in python argparser
<p>I have the following python code set up, in which the program would return <strong>&quot;something&quot;</strong> whenever the user pass <code>--</code> as an argument:</p> <pre class="lang-py prettyprint-override"><code>#script.py import argparse parser = argparse.ArgumentParser() parser.add_argument( &quot;...
<python><argparse>
2024-08-26 11:20:37
1
351
Epimu Salon
78,914,064
9,002,568
Plotly table object on Colab
<p>In colab, I generate plotly table object as a part of subplot in all graph object is in Ipywidgets.output like:</p> <p><a href="https://i.sstatic.net/f0gQF56t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/f0gQF56t.png" alt="picture 1" /></a></p> <p>But I couldn't see first column values. When I clic...
<python><plotly><google-colaboratory>
2024-08-26 11:07:24
1
593
kur ag
78,913,870
6,509,922
Potentially biased sampling in Tree-Parzen optimization from Hyperopt
<p>I'm using the Tree-Parzen algo implementation from Hyperopt for blackbox optimization task that I have and I'm consistently observing an odd phenomenon.</p> <p>The plot below displays the phenomenon. You can see that the sampler is focusing on a low-loss region (the dark ball near the top right). This is normal, ind...
<python><hyperopt>
2024-08-26 10:16:31
0
688
Jed
78,913,797
4,050,510
Iterating a Huggingface Dataset from disk using Generator seems broken. How to do it properly?
<p>I have a strange behavior in HuggingFace Datasets. My minimal reproduction is as below.</p> <pre class="lang-py prettyprint-override"><code># main.py import datasets import numpy as np generator = np.random.default_rng(0) X = np.arange(1000) ds = datasets.Dataset.from_dict( mapping={&quot;X&quot;:X}, ) ds.s...
<python><huggingface><huggingface-datasets>
2024-08-26 09:55:43
0
4,934
LudvigH
78,913,782
14,729,820
How can I run python package using Google Collab?
<p>I want to run the <a href="https://github.com/FactoDeepLearning/DAN/tree/main" rel="nofollow noreferrer">DAN</a> repo. I am using Google Cloud Collab. I cloned the project on my Google Drive in the following directory <code>/content/drive/MyDrive/DAN/DAN</code> Trying to run An example script file is available at <c...
<python><deep-learning><package><google-colaboratory>
2024-08-26 09:52:02
1
366
Mohammed
78,913,556
1,363,960
How to evaluate a string as tcl command
<p>I'm using Foundry Nuke and try to work with tcl command.</p> <p>I have this code :</p> <pre><code>[lindex [split &quot;xx_cc&quot; &quot;_&quot;] 0] </code></pre> <p>If I put this code into a text node. I will output the correct result which is 'xx'</p> <p>But in this case I put the code in the project setting (root...
<python><tcl><nuke>
2024-08-26 08:55:48
1
1,828
andio
78,913,527
5,790,653
How to find a name with conditions ending with some strings and divide them
<p>I have these lists:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ {'itemid': '264', 'name': 'Interface Gi1/17(Port1:TP TPIA-CL03-017-G15-14): Bits sent', 'some_other_keys': 'some_more_values'}, {'itemid': '215', 'name': 'Interface Te1/50(&quot;Port1:CL-PO-G22-23&quot;): Bits received', 'some_...
<python>
2024-08-26 08:47:17
1
4,175
Saeed
78,913,464
17,729,094
How to filter on uniqueness by condition
<p>Imagine I have a dataset like:</p> <pre><code>data = { &quot;a&quot;: [1, 4, 2, 4, 7, 4], &quot;b&quot;: [4, 2, 3, 3, 0, 2], &quot;c&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;], } </code></pre> <p>and I want to keep only the rows for which <code>a + b...
<python><dataframe><python-polars>
2024-08-26 08:27:52
2
954
DJDuque
78,913,267
2,307,441
Extracting tables from a PDF with empty cells and no visible edges
<p>I am using <code>pdfplumber</code> to extract data from the following PDF page:</p> <p><a href="https://i.sstatic.net/YjVmA3hx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YjVmA3hx.png" alt="Data in the test pdf file" /></a></p> <pre class="lang-py prettyprint-override"><code>import pdfplumber p...
<python><pdf><pdfplumber>
2024-08-26 07:28:21
2
1,075
Roshan
78,913,241
13,987,643
Python Azure Search contains filter isn't working
<p>I'm trying to filter documents in my azure search index using the filter expression. I specifically want to filter the file names using a 'contains' filter and this is the search parameter I'm providing via langchain.</p> <pre><code>search_kwargs={'k': 8, 'search_type': 'semantic_hybrid', 'filters': f&quot;search.is...
<python><azure><langchain><azure-cognitive-search>
2024-08-26 07:21:57
1
569
AnonymousMe
78,913,109
1,444,073
Process asyncio events in callbacks from within asyncio-unaware code?
<p>I have a Python function <code>foo</code>, that actually is a layer of many functions, and makes regular callbacks to a Python function <code>bar</code> that I supply, like <code>foo(bar)</code>. I also have an <em>asyncio event loop</em> running on the main thread, but the internals of <code>foo</code> are not awar...
<python><python-asyncio>
2024-08-26 06:38:15
1
4,334
kostrykin
78,912,904
17,519,895
Emit gets stuck while another thread is being executed
<p>This is a Flask Socket-io App, In this particular code, A stream of response is being carried out by an AI model and chunks are being emitted regularly.</p> <p>The issue here is that the Emit gets called successfully for each chunk but is not received by the front end unless the previous thread is finished.</p> <p>...
<python><multithreading><flask><flask-socketio>
2024-08-26 04:54:52
0
421
Aleef
78,912,876
139,150
google search using playwright
<p>I am trying to perform google search using playwright. But getting this error:</p> <pre><code>playwright._impl._errors.TimeoutError: Page.fill: Timeout 60000ms exceeded. Call log: waiting for locator(&quot;input[name=\&quot;q\&quot;]&quot;) </code></pre> <p>Here is the code:</p> <pre><code>from playwright.async_api ...
<python><playwright><playwright-python>
2024-08-26 04:41:28
1
32,554
shantanuo
78,912,816
68,846
Installing old version of scikit-learn: ModuleNotFoundError: No module named 'numpy'
<p>I have an old Python project that uses scikit-learn version <code>0.22.2.post1</code>. Unfortunately I am unable to update to a newer version of scikit-learn as the training data has long been lost, and I understand that the version of scikit-learn is tied to the model (stored as a .pkl file).</p> <p>The project use...
<python><numpy><scikit-learn><pip><python-3.9>
2024-08-26 03:54:31
1
700
Justin
78,912,599
1,447,953
Bokeh: how to create customJS button to clear DataTable selection?
<p>I have a DataTable that I am using to select points in a plot, and I have created a &quot;clear selection&quot; button that is suppose to &quot;unselect&quot; all points, i.e. reset the selection. However, it appears to only operate on data that is in the current &quot;view&quot; of the DataTable, despite my customJ...
<python><bokeh>
2024-08-26 01:28:54
0
2,974
Ben Farmer
78,912,403
5,692,012
Analyse application audio with Python
<p>I have some audio that's played from some applications (Firefox in my example), and I'd like to analyze it with Numpy.</p> <p>I've came up with this code:</p> <pre class="lang-py prettyprint-override"><code>import pyaudio import numpy as np p = pyaudio.PyAudio() BUFFER = 1024 for i in range(p.get_device_count()): ...
<python><linux><audio><pyaudio>
2024-08-25 22:47:16
0
5,694
RobinFrcd
78,912,354
3,456,812
Cannot resolve "missing" Djanjo when trying to run label-studio
<p>I want to use the popular package label-studio to build training data using images that I'll apply the AI labelling steps on.</p> <p>The problem is that after cloning the repo from github and following all the instructions, I'm getting the following error:</p> <pre><code>Traceback (most recent call last): File &qu...
<python><django><labeling>
2024-08-25 21:59:11
0
1,305
markaaronky
78,912,286
3,710,004
Why use await and wait_for() in the same line in Playwright?
<p>I am following an online tutorial for scraping with Playwright (<a href="https://jsoma.github.io/advanced-scraping-with-playwright/" rel="nofollow noreferrer">https://jsoma.github.io/advanced-scraping-with-playwright/</a>). There is one line that uses both await and wait_for(), and I don't understand why. Isn't that...
<python><web-scraping><playwright><playwright-python>
2024-08-25 21:14:00
1
686
user3710004
78,912,249
338,044
Basic Advanced Stats Table in NBA API
<p>I am trying to do something that I thought would be simple but seems somewhat complicated, although maybe I'm missing something. I'm trying to use <a href="https://github.com/swar/nba_api/tree/master" rel="nofollow noreferrer">NBA API</a> to get a dataframe that just shows the standard advanced stats from NBA.com fo...
<python><nba-api>
2024-08-25 20:51:25
1
733
Jake
78,912,227
5,287,011
TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'list'>
<p>I am experimenting with LLM development.</p> <p>Here is my code:</p> <pre><code>import langchain, pydantic, transformers from langchain import HuggingFacePipeline from langchain_core.prompts import PromptTemplate from langchain_core.runnables.base import RunnableSequence, RunnableMap, RunnableLambda from langchain....
<python><langchain><runnable><large-language-model><huggingface>
2024-08-25 20:40:18
1
3,209
Toly
78,912,212
7,884,305
How to make CPython report vectorcall as available only when it will actually help performance?
<p>The <a href="https://docs.python.org/3/c-api/call.html#the-vectorcall-protocol" rel="noreferrer">Vectorcall</a> protocol is a new calling convention for Python's C API defined in <a href="https://peps.python.org/pep-0590/" rel="noreferrer">PEP 590</a>. The idea is to speed up calls in Python by avoiding the need to ...
<python><c><rust><python-c-api>
2024-08-25 20:35:22
1
75,761
Chayim Friedman
78,912,175
17,729,094
Combine cross between 2 dataframe efficiently
<p>I am working with 2 datasets. One describes some time windows by their start and stop times. The second one contains a big list of events with their corresponding timestamps.</p> <p>I want to combine this into a single dataframe that contains the start and stop time of each window, together with how many events happ...
<python><dataframe><python-polars>
2024-08-25 20:14:30
4
954
DJDuque
78,912,140
6,141,238
In Keras, how can I save and load a neural network model that includes a custom loss function?
<p>I am having difficulty saving and reloading a neural network model when I use a custom loss function. For example, in the code below (which integrates the suggestions of the related questions <a href="https://stackoverflow.com/questions/48373845/loading-model-with-custom-loss-keras">here</a> and <a href="https://st...
<python><tensorflow><keras><loss-function>
2024-08-25 19:57:58
1
427
SapereAude
78,912,109
8,954,109
Python shortcut for overloading functions over an input union type?
<p>aka: <em>How do I make a function return the same type as an Optional input?</em></p> <p>I started with this:</p> <pre class="lang-py prettyprint-override"><code>import random import typing def get_maybe_str(): return random.choice([&quot; &quot;, None]) def optional_upper(s: typing.Optional[str]): if s i...
<python><python-typing>
2024-08-25 19:42:38
2
693
plswork04
78,911,935
12,466,687
How to delimit text stored in variable to create a dataframe in python?
<p>I have parsed a <code>pdf file</code> using ai models and got parsed <code>markdown</code> results which is saved in a <strong>variable</strong> <code>doc_parsed</code>. Printing below its sample contents by code <code>print(doc_parsed[2].text[:1000])</code></p> <pre><code># Details |Name|Mr. XYZ| |---|---| |Age/Se...
<python><pandas><csv><markdown><delimiter>
2024-08-25 18:25:06
3
2,357
ViSa
78,911,781
823,633
numba doesn't work with numpy.polynomial.polynomial.Polynomial?
<p>This code</p> <pre><code>import numba import numpy @numba.jit def test(*coeffs): poly = numpy.polynomial.polynomial.Polynomial(coeffs) return poly(10) c = (2,1) test(*c) </code></pre> <p>Generates the error</p> <pre><code>No implementation of function Function(&lt;class 'numpy.polynomial.polynomial.Polynom...
<python><numba>
2024-08-25 17:00:42
1
1,410
goweon
78,911,751
25,874,132
How to find the minimum distance between two matrices in python? (special definitions)
<p>I have 4 permutation matrices A, B, C, D. we define the distance d(C, D) to be the minimal number of matrix multiplications needed to satisfy the equation D = X.C.Y where the dot is matrix multiplication and X and Y are some sort of product of A, B, A^-1, B^-1 (for example X = A.A.B^-1, Y = B.B^-1.A^-1).</p> <p>We ...
<python><numpy><matrix><breadth-first-search>
2024-08-25 16:47:53
0
314
Nate3384
78,911,506
209,387
using instaloader to only download the instagram post caption
<p>Is it possible to only download the caption (the description) of a post, given the post short code, using python 3.12 and the latest version of the <a href="https://github.com/instaloader/instaloader" rel="nofollow noreferrer">instaloader</a> library? I am insterested in using instaloder as a library module, not the...
<python><instagram><caption><instaloader>
2024-08-25 15:01:40
1
1,453
Michael Kariv
78,911,390
595,305
Is the Python Mariadb connector module capable of using prepared statements?
<p>I'm confused about this. By &quot;prepared statement&quot;, I mean an object which is delivered by going something like</p> <pre><code>prep_stmt = cursor.prepared_statement(&quot;INSERT INTO my_table (field1, field2) VALUES (%1 %2)&quot;) </code></pre> <p>... and where you then use that object multiple times, insert...
<python><mariadb><prepared-statement>
2024-08-25 14:03:40
1
16,076
mike rodent
78,911,258
2,697,895
How to include system-wide pakages in PyInstaller?
<p>I am running <code>PyInstaller</code> on a Raspberry Pi device to compile a standalone Python script. My script is intended to always run with <code>sudo</code>. It requires <code>smbus, psutil, pyudev, netifaces</code> libraries installed system wide with <code>sudo apt install python3-...</code>.</p> <p>Now to use...
<python><python-3.x><raspberry-pi><pyinstaller>
2024-08-25 12:52:53
1
3,182
Marus Gradinaru
78,911,146
1,673,574
JAX 3d convolution kernel speedup
<p>I am trying to solve a diffusion kernel with JAX and this is my JAX port of existing GPU CUDA code. JAX gives the correct answer, but it is about 5x slower than CUDA. How can I speed this up further? Not sure if my implementation of the <code>diff</code> function is the best. I tried to use the same formulation as t...
<python><convolution><jax>
2024-08-25 11:53:16
0
6,204
Chiel
78,911,032
1,042,646
Azure DevOps pipeline fails with [error]Cmd.exe exited with code '1'
<p>I am trying to run pytests using Azure DevOps pipeline.</p> <pre><code> - task: PipAuthenticate@1 inputs: artifactFeeds: '&lt;Feed Name&gt;' - script: | pip install --upgrade pip pip list displayName: 'Verify Pip Authentication' ...
<python><azure-devops><azure-pipelines><pytest>
2024-08-25 10:49:58
0
17,162
Punter Vicky
78,910,951
3,247,006
Does `unbind()` return the views of tensors in PyTorch?
<p><a href="https://pytorch.org/docs/stable/generated/torch.unbind.html" rel="nofollow noreferrer">The doc</a> of <code>unbind()</code> just says below:</p> <blockquote> <p>Returns a tuple of all slices along a given dimension, already without it.</p> </blockquote> <p>So, does it mean that <code>unbind()</code> returns...
<python><pytorch><tuples><slice><tensor>
2024-08-25 10:08:15
1
42,516
Super Kai - Kazuya Ito
78,910,896
4,852,094
How can I get a type from a list of Generics
<p>say I have a type like:</p> <pre><code>T = TypeVar(&quot;T&quot;) class MyType(Generic[T]): ... </code></pre> <p>and I have a class:</p> <pre><code>class Foo: def __init__(self, vals: list[MyType]): self.vals = vals </code></pre> <p>But I want to say &quot;The Union of all Generic Args in the list.&quot...
<python><python-typing>
2024-08-25 09:40:44
2
3,507
Rob
78,910,846
8,964,393
Export statsmodels summary() to .png
<p>I have trained a <code>glm</code> as follows:</p> <pre><code> fitGlm = smf.glm( listOfInModelFeatures, family=sm.families.Binomial(),data=train, freq_weights = train['sampleWeight']).fit() </code></pre> <p>The results looks good:</p> <pre><code>print(fitGlm.summary()) Generalized Linea...
<python><export><png><statsmodels><summary>
2024-08-25 09:11:18
1
1,762
Giampaolo Levorato
78,910,833
4,451,315
Make another Series with the same index as current Series but with different values
<p>I have</p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd import pandas as pd s = dd.from_pandas(pd.Series([1,2,3])) </code></pre> <p>I'm trying to make another Series <code>s_other</code> which should be just like <code>s</code>, but:</p> <ul> <li>all values should be <code>999</code><...
<python><dask>
2024-08-25 09:05:56
2
11,062
ignoring_gravity
78,910,797
11,748,924
PACF built-in plot utils returning different result compared to manual plot
<p>Using packages:</p> <pre><code>from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.stattools import acf, pacf </code></pre> <p>Performing manual and built-in plot utils, give different values. No, I don't mean picture scale, but the actual value seems different between manual plot and ...
<python><statistics><statsmodels><autocorrelation>
2024-08-25 08:35:55
1
1,252
Muhammad Ikhwan Perwira
78,910,478
219,153
Iterate over Polygon vertices as Points with Shapely?
<p>Shapely's <code>Polygon</code> and <code>LinearRing</code> are not iterable (any longer, if I remember the history correctly). I often need to iterate over their vertices as <code>Point</code> objects (not tuple), and my current solution seems cumbersome. Is there a simpler way than this, without NumPy magic?</p> <p...
<python><polygon><shapely><vertices>
2024-08-25 05:13:44
3
8,585
Paul Jurczak
78,910,231
417,896
How to get the epoch time in eastern time?
<p>How do I get the time in seconds since epoch of a python datetime in eastern time?</p> <pre><code>import pytz from datetime import datetime, timedelta et_tz = pytz.timezone('America/New_York') initial_start_dt = et_tz.localize(datetime(2024, 8, 24, 4, 0, 0)).astimezone(et_tz) initial_end_dt = et_tz.localize(date...
<python><time><epoch>
2024-08-25 00:34:42
0
17,480
BAR
78,910,117
3,906,483
yt_dlp FileNotFoundError when Renaming Subtitle File
<p>I’m using <code>yt_dlp</code> to download subtitles for a video, but I’m encountering a <code>FileNotFoundError</code> when attempting to rename the subtitle file. Here’s the relevant portion of my code:</p> <pre class="lang-py prettyprint-override"><code>import yt_dlp import os def download_video(self, url): y...
<python><yt-dlp>
2024-08-24 22:42:10
0
704
Zachzhao
78,910,091
9,620,095
Issue with Access Rules for Attachments / odoo 17
<p>In a custom module , I add new field ir_attchment_ids . When connecting wih other user (not admin) , I got this error .</p> <pre><code>Uh-oh! Looks like you have stumbled upon some top-secret records. Sorry, user (id=8) doesn't have 'read' access to: - Attachment (ir.attachment) If you really, really need access, ...
<python><xml><security><odoo-17>
2024-08-24 22:22:49
3
631
Ing
78,910,042
10,037,470
Having some trouble with ForwardRef in python with fastapi and ormar
<p>I have an api that has been built in fastapi and uses ormar for ORM.</p> <p>My database models are defined as follows:</p> <pre><code>database = databases.Database(config.database_url) metadata = sqlalchemy.MetaData() base_ormar_config = ormar.OrmarConfig( metadata=metadata, database=database, ) ProjectRe...
<python><fastapi><pydantic><ormar>
2024-08-24 21:37:42
0
875
Devon Ray
78,910,012
1,473,517
How to read in and print out standard input until a string occurs and still capture a line?
<p>I have code (let's say a bash script called dots.sh) that I want to run from a python script. I would like the python script to print out the output of dots.sh as it occurs. This is my attempt at a wrapper script.</p> <pre><code>import subprocess import sys def run_dot_script(): # Command to run the bash scri...
<python>
2024-08-24 21:13:13
1
21,513
Simd
78,909,971
6,357,360
Exponential plot in python is a curve with multiple inflection points instead of exponential
<p>I am trying to draw a simple exponential in python. When using the code below, everything works fine and the exponential is shown</p> <pre><code>import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np def graph(func, x_range): x = np.arange(*x_range) y = func(x) plt.plot(x, y) g...
<python><numpy><matplotlib>
2024-08-24 20:53:44
1
6,749
meJustAndrew
78,909,704
66,490
How to draw lines with a color gradient in Pygame?
<p>I wish to draw a sequence of lines with a color gradient, so that the color fades from bright white to either black or fully transparent:</p> <p><a href="https://i.sstatic.net/BVXJbmzu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BVXJbmzu.png" alt="enter image description here" /></a></p> <p>Ideall...
<python><pygame>
2024-08-24 18:15:58
1
7,505
TrayMan
78,909,690
2,835,640
functools partial with bound first argument and *args and **kwargs interprets calls as multiple values
<p>Using python 3.10:</p> <p>I have a function with a first argument and then <code>*args</code> and <code>**kwargs</code>. I want to bind the first argument and leave the <code>*args</code> and <code>**kwargs</code> free. If I do this and the bound function gets called using a list of arguments, python interprets it a...
<python><arguments><partial><keyword-argument><functools>
2024-08-24 18:10:09
1
2,526
crogg01
78,909,656
8,554,833
Is my password safe in a pyinstaller .exe?
<p>So I built a program to run reports. I put credentials in the python script. I want to distribute this to user without python so I converted it to a .exe using pyinstaller. I wasn't able to find the credential by looking at the .exe in notepad, since it doesn't appear human readable. However, I wanted to ask, can th...
<python><security><pyinstaller>
2024-08-24 17:53:11
1
728
David 54321
78,909,221
364,595
How to underline text using `borb`
<p>I am using the <code>borb</code> library, which has classes to represent textual content, such as <code>ChunkOfText</code>, <code>LineOfText</code>, <code>HeterogeneousParagraph</code> and <code>Paragraph</code>.</p> <p>Although these have attributes (in their constructor) that enable me to choose the font, font siz...
<python><pdf><borb>
2024-08-24 14:31:58
1
9,217
Joris Schellekens
78,909,215
8,025,936
Using Hatch, is there a way I can have a local dependency whose location is not hard-coded?
<p>I have two non-public Hatch projects A and B. B depends on A. I want developers to be able to clone A and B to locations of their choice and have B depend on A without having to rewrite <code>pyproject.toml</code>. Can I do this? I’d be okay with a prompt asking for a location, or an auxiliary file that can be ignor...
<python><build><hatch>
2024-08-24 14:28:30
1
2,390
schuelermine
78,909,027
2,268,543
How to Convert Invalid JSON String with Single Quotes to Valid JSON
<p>I accidentally saved a JSON-like string in my database that uses single quotes instead of double quotes, and JSON formatters don't recognize it as valid JSON. Here is the string that I have:</p> <pre><code>import json json_string = &quot;&quot;&quot; {'author': 'Hebbars Kitchen', 'canonical_url': 'https://hebbarski...
<python>
2024-08-24 12:56:57
1
2,519
Rasik
78,908,629
4,451,315
How to zip together two PyArrow arrays?
<p>In Polars, I can use <code>zip_width</code> in order to take values from <code>s1</code> or <code>s2</code> according to a mask:</p> <pre class="lang-py prettyprint-override"><code>In [1]: import polars as pl In [2]: import pyarrow as pa In [3]: import pyarrow as pc In [4]: s1 = pl.Series([1,2,3]) In [5]: mask =...
<python><pyarrow>
2024-08-24 09:39:07
1
11,062
ignoring_gravity
78,908,337
7,429,461
How to use the parameter "allow_dash" in "typer.Option" or "typer.Argument" in the Python package "typer"?
<p>I don't understand how to use the parameter <code>allow_dash</code> in <code>typer.Option</code> or <code>typer.Argument</code> in the Python package <code>typer</code>.</p> <p>I can only find this page <a href="https://typer.tiangolo.com/tutorial/parameter-types/path/#advanced-path-configurations" rel="nofollow no...
<python><python-3.x><typer>
2024-08-24 06:51:50
0
819
liaoming999
78,908,264
11,692,124
Pydantic doesn't allow mutable variables to get changed with Optional
<p>The code below is a modified version of pydantic func argument validation. and the pydantic version is 1.10.17 and I guess, not sure, this was not a problem in other versions. so please if the current code works fine with your pydantic version notify me in comments.</p> <pre><code>import inspect import typing from t...
<python><pydantic>
2024-08-24 06:15:00
1
1,011
Farhang Amaji
78,908,148
3,718,065
PyQt D-BUS add multiple output arguments to the method
<p>I want to add several output arguments in a <strong>PyQt5 D-BUS</strong> method. I cloned the example from <a href="https://github.com/baoboa/pyqt5/tree/master/examples/dbus/remotecontrolledcar" rel="nofollow noreferrer">qt example</a>. In class <code>CarInterfaceAdaptor</code>, I added a new method <code>control</c...
<python><c++><qt><pyqt5><dbus>
2024-08-24 04:50:57
1
791
sfzhang
78,907,944
16,703,774
Ansible can't find python lib -- python3-rpm -- which already installed
<p>I'm using Ansible and testing a module: ansible.builtin.package_facts</p> <pre class="lang-yaml prettyprint-override"><code>- name: Gather the package facts ansible.builtin.package_facts: manager: auto - name: Print the package facts ansible.builtin.debug: var: ansible_facts.packages - name: Check whethe...
<python><ansible>
2024-08-24 01:18:53
1
393
EisenWang
78,907,748
3,398,536
How to upload a ssl certificate into google chrome webdriver in selenium python
<p>I need to use selenium python with an uploaded personal security certificate every time my service launch a new process, and for some reason is not possible to click at import in the Google Chrome settings.</p> <p>I try to use XPATH, ID and other By options, and no way to work. If anyone has experience with this typ...
<python><google-chrome><selenium-webdriver><ssl-certificate>
2024-08-23 22:45:58
0
341
Iron Banker Of Braavos
78,907,668
2,118,290
Problems with trying to download a webpage and click a button with selenium in docker using python
<p>I cannot get this to work right for the life of me. I'm trying to load a web-page and click a button on it and I cant get it to work. Either Selenium complains, does not load, complains it cant make a session, complains that it does not have proper options, loads forever or just straight up does not work.</p> <p>Doc...
<python><docker><selenium-webdriver><flask>
2024-08-23 22:00:53
1
674
Steven Venham
78,907,519
2,153,235
Having trouble seeing the motive for decorators in *simple* examples
<p>I've surfed some tutorials online about decorators. I'm having trouble seeing their benefit for simple examples. Here is a common example of a function crying out to be decorated, taken from <a href="https://www.programiz.com/python-programming/decorator" rel="nofollow noreferrer">this page</a>:</p> <pre><code># U...
<python><python-decorators>
2024-08-23 20:46:13
1
1,265
user2153235
78,907,515
4,376,643
Error with a python recursively user-defined type
<p>I am using the recursively defined type &quot;Json&quot; type as suggested in <a href="https://stackoverflow.com/a/76701025/4376643">this answer</a> to <a href="https://stackoverflow.com/q/58400724/4376643">this SO question</a>.</p> <p>However I am running into unexpected errors as shown in the code below. The first...
<python><python-typing>
2024-08-23 20:45:47
0
2,658
Craig Hicks
78,907,444
3,078,502
Is it possible use VS Code to pass multiple command line arguments to Python script?
<p>According to the official documentation <a href="https://code.visualstudio.com/docs/python/debugging" rel="noreferrer">&quot;Python debugging in VS Code&quot;</a>, launch.json can be configured to run with specific command line arguments, or you can use <code>${command:pickArgs}</code> to input arguments at run time...
<python><visual-studio-code><vscode-debugger>
2024-08-23 20:13:41
2
609
Lee Hachadoorian
78,907,380
4,867,193
Removing Spikes from Spectra
<p>The question is; how to remove spikes from spectroscopy data, in an efficient way, <em>using Numpy or SciPy</em> only.</p> <p>[Aside, before going further, it may be necessary to mention that the question with a similar title at, https://stackoverflow.com/questions/37556487, is not the same question. The data has c...
<python><numpy><scipy>
2024-08-23 19:43:28
4
2,587
DrM
78,907,265
20,591,261
Polars keep the biggest value using 2 categories
<p>I have a polars dataframe that contain some ID, actions, and values :</p> <p>Example Dataframe:</p> <pre><code>data = { &quot;ID&quot; : [1, 1, 2,2,3,3], &quot;Action&quot; : [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;A&quot;, &quot;A&quot;], &quot;Where&quot; : [&quot;Office&quot...
<python><dataframe><python-polars>
2024-08-23 19:00:47
4
1,195
Simon
78,906,970
2,886,575
Retain image resolution in matplotlib sublots
<p>I have a set of images that I would like to show in a grid. I am using <code>matplotlib</code> for this, but am not super picky about the plotting library. However, I am using <code>matplotlib</code> because it allows me to put labels and such.</p> <p>I would like for the resulting figure to retain the resolution ...
<python><matplotlib>
2024-08-23 17:24:31
1
5,605
Him
78,906,960
825,227
Retrieve data from an existing barplot figure/axis in Python
<p>I'm creating a barplot that I'm subsequently updating over time with new values.</p> <pre><code>import pandas as pd import seaborn as sns import matplotlib.pyplot as plt f, ax = plt.subplots() sns.set_color_codes('muted') sns.barplot(data = d[d.Side==0], x = 'Size', y = 'Price', color = 'b', orient = 'h', native...
<python><pandas><matplotlib><seaborn>
2024-08-23 17:20:54
0
1,702
Chris
78,906,909
6,597,296
How to rate limit a deferred HTTP client in Twisted?
<p>I have an HTTP client written in Twisted that sends requests to an API of some site from a deferred. It goes something like this (somewhat simplified):</p> <pre class="lang-py prettyprint-override"><code>from json import loads from core import output from twisted.python.log import msg from twisted.internet import ...
<python><twisted><rate-limiting><deferred>
2024-08-23 17:04:28
2
578
bontchev
78,906,798
11,462,274
Mapping pattern and correct codes to install a library/package in Python that only targets the functions within a code
<p>I'm trying to generate a local library/package that only has the functions that exist within the code, but when I try to use <code>from .my_functions import *</code> as the <code>__init__</code> default, when installing and trying to use it in a new code, not only the functions that are in the code appear, but also ...
<python><python-import><python-packaging>
2024-08-23 16:30:15
1
2,222
Digital Farmer
78,906,780
3,042,398
PyHanko - Invalid signature with error "Unexpected byte range values defining scope of signed data" in interrupted mode
<p>I try to setup a pades signature flow in our Flask API.</p> <p>As we use PKCS11 devices on the clients computers, we need to use the interrupted signing flow :</p> <ul> <li>User POST on <code>/pades/start</code> with his certificate as a PEM file and the PDF to sign.</li> <li>The API return the digest to the client,...
<python><flask><pades><pyhanko>
2024-08-23 16:25:34
1
1,408
Varkal
78,906,647
2,393,452
pyvisa equivalent for serial.serial.rts=False
<p>I have a specific instrument that needs to deassert the RTS line before communication can work. On an old script I was doing a basic <code>serial.serial.rts=False</code>. What is the equivalent with <code>pyvisa</code>?</p> <p>I tried with <code>pyvisa.constants.LineState</code> but could not manage to replicate the...
<python><pyserial><pyvisa>
2024-08-23 15:43:04
0
540
bserra
78,906,590
8,960,078
Why does an rdkit function only work when I import something else?
<p>There is something seriously strange going on here with RDKit's imports that I don't understand.</p> <p>I am using some basic functionality (as per their <a href="https://www.rdkit.org/docs/source/rdkit.Chem.Descriptors.html#rdkit.Chem.Descriptors.ExactMolWt" rel="nofollow noreferrer">documentation</a>) like so:</p>...
<python><python-3.x><rdkit>
2024-08-23 15:26:31
3
1,103
QuantumChris
78,906,565
8,954,109
mypy operator "+" not supported for ctypes Structure._fields_
<p>I was handed code that basically describes inheritance via copy pasting all the base fields to every sub struct:</p> <pre class="lang-py prettyprint-override"><code>class Base(ct.Structure): _fields_ = [ (&quot;hello&quot;, ct.c_int32) ] class Foo(ct.Structure): _fields_ = Base._fields_ + [ ...
<python><ctypes><python-typing><mypy><pyright>
2024-08-23 15:18:36
2
693
plswork04
78,906,183
4,108,376
Getting buffer_info from py::memoryview
<p>Using Pybind11, is there a way to get the <code>py::buffer_info</code> object from a <code>py::memoryview</code>? Or some other way to get the data pointer, number of dimensions, shape, strides, item size from the python <code>memoryview</code>, without creating a copy of the array?</p> <p>It is for a function that ...
<python><c++><pybind11><memoryview>
2024-08-23 13:35:35
0
9,230
tmlen
78,905,974
1,131,165
PermissionDenied: 403 You do not have permission to access tuned model
<p>I have tuned a gemini base model and wrote a python code to access it but unfortunatelly I keep getting the error &quot;PermissionDenied: 403 You do not have permission to access tuned model&quot;. I have read instructions to set a OAuth 2.0 Client ID and I think I did it right since the authentication worked, but t...
<python><google-gemini><google-generativeai>
2024-08-23 12:41:17
1
864
Jonathan Livingston Seagull
78,905,921
275,088
How to properly annotate the `call_next` parameter to a FastAPI middleware?
<p>I'm trying to adapt an example from the FastAPI <a href="https://fastapi.tiangolo.com/tutorial/middleware/#create-a-middleware" rel="nofollow noreferrer">docs</a> to create a middleware:</p> <pre><code>@app.middleware(&quot;http&quot;) async def add_process_time_header(request: Request, call_next): start_time = ...
<python><fastapi><python-typing><mypy>
2024-08-23 12:30:03
1
16,548
planetp
78,905,811
15,416
Can random.sample handle the case k=0?
<p>In code, can I assume:</p> <pre><code>assert random.sample((1,2,3), k=0) == [] </code></pre> <p>I suspect the answer is yes, but I don't see explicit documentation confirming it.</p> <p>I've got a case where <code>k = desired_length - current_length</code> is the number of extra random elements that I need to add to...
<python><random>
2024-08-23 12:07:48
2
181,617
MSalters
78,905,650
16,759,116
Why/when/where was `mydict[*mylist]` introduced?
<p>This shorthand to use lists as dict keys works in Python 3.12:</p> <pre><code>mydict = {(1, 2, 3): 'works!'} mylist = [1, 2, 3] print(mydict[*mylist]) </code></pre> <p>In 3.10 it gives <code>SyntaxError</code> and in 3.11 it works (at least in the versions I tried). I searched <a href="https://docs.python.org/3/what...
<python><syntax>
2024-08-23 11:21:25
0
10,901
no comment
78,905,620
3,599,283
TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard'
<p>Pls help. I need help setting up spacy inside jupyter enviornment</p> <p>I am trying to use spacy to summarize youtube transcripts but finding lots of problems with spacy and python 3.12.4/3.12.3.<br /> I started with 3.12.4, then installed python 3.12.3 onto conda environment <code>py3.12.3</code>.</p> <p>I install...
<python><python-3.x><nlp><spacy><sentence>
2024-08-23 11:14:15
1
1,267
frankr6591
78,905,442
8,077,619
Qml set context property for child item
<p>I want to set a context property of a Qml Button from PySide6 but I get an error. Here are the relevant files:</p> <p>main.py</p> <pre><code>import sys from PySide6.QtCore import QObject, Slot from PySide6.QtGui import QGuiApplication from PySide6.QtQml import (QQmlApplicationEngine, QmlElement, QQmlComponent, ...
<python><qml><pyside><pyside6>
2024-08-23 10:30:07
0
303
Anonimista
78,905,436
17,721,722
How can I safely use multiprocessing in a Django app?
<p>I've read the <a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer">docs</a> suggesting that multiprocessing may cause unintended side effects in Django apps or on Windows, especially those connected to multiple databases. Specifically, I'm using a function, <code>load_to_table</...
<python><django><debugging><multiprocessing>
2024-08-23 10:29:40
1
501
Purushottam Nawale
78,905,419
6,068,731
Python type hinting and being explicit is still throwing a warning
<p>PyCharm is throwing a yellow warning in the following code, it seems to think that the output of the function is <code>ndarray[Any, dtype]</code>. Should I ignore this error or is there a Pythonic way of dealing with this?</p> <p>I have also tried <code>np.array(articles, dtype=str)</code> or <code>np.array(articles...
<python><numpy><pycharm><python-typing>
2024-08-23 10:24:11
1
728
Physics_Student
78,905,356
18,215,498
How to properly quantize model with quanto?
<p>I am trying to quantize Qwen model, but it seems to be not working.</p> <p>This is my snippet in Google Colab (runtime-&gt; free T4 GPU):</p> <pre class="lang-py prettyprint-override"><code>from transformers import AutoModelForCausalLM from optimum.quanto import QuantizedModelForCausalLM, qint8 model = AutoModelFor...
<python><pytorch><huggingface-transformers><large-language-model>
2024-08-23 10:09:05
1
533
mcdominik
78,905,311
5,758,423
How can I get the _true_ signature of a Python function?
<h3>tldr;</h3> <p><code>inspect.signature</code> gives us a function's signature, but this signature can lie (as assigning to the <code>__signature__</code> attribute of a function will reveal.</p> <p>Is there a python function (builtin if possible) that will give me the <em>true</em> signature?</p> <h3>a bit more abou...
<python><python-inspect>
2024-08-23 09:56:34
1
2,432
thorwhalen
78,905,276
12,439,683
Generate pyi stubfile for not importable C module
<p>I have a package <code>A</code> that uses a special package <code>A.B</code>, both are 3rd and 4th party packages written in C using Boost. Because it there is some special setup <strong><code>A.B</code> is not included as a submodule but only as a some variable. Both <code>import A.B</code></strong> and also first ...
<python><python-typing><python-c-api><stub><pyi>
2024-08-23 09:49:18
1
5,101
Daraan
78,905,269
1,235,577
How to acheive true wildcard functions in python
<p>For python classes it is possible to define the <code>__getattr__()</code> method to be able to call any function using that class.</p> <p>ex:</p> <pre><code># testclass/__init__.py def x(*args, **kwargs): print(&quot;hello&quot;) def __getattr__(name): return x </code></pre> <p>can be use like this:</p> <p...
<python>
2024-08-23 09:47:39
1
503
Pownyan
78,904,852
961,631
pypandoc does not keep images nor formatting when converting
<p>I try to convert a .rtf file to .docx using pypandoc</p> <pre><code>import pypandoc # Specify the input RTF file and output DOCX file input_file = 'test.rtf' output_file = 'test.docx' # Convert the RTF file to DOCX pypandoc.convert_file(input_file, 'docx', outputfile=output_file) print(f&quot;Conversion complete....
<python><pandoc><pypandoc>
2024-08-23 07:54:13
1
15,427
serge
78,904,801
2,315,319
Polars DataFrame - Decimal Precision doubles on mul with Integer
<p>I have a Polars (v1.5.0) dataframe with 4 columns as shown in example below. When I multiply decimal columns with an integer column, the scale of the resultant decimal column doubles.</p> <pre class="lang-py prettyprint-override"><code>from decimal import Decimal import polars as pl df = pl.DataFrame({ &quot;a&...
<python><dataframe><decimal><python-polars>
2024-08-23 07:38:57
3
313
fishfin
78,904,771
11,764,097
Pydantic model_validator that can leverage the type-hints before initialisation
<p>I have a use-case where I will use Pydantic classes to send information between different services using a messaging service (PubSub). Since the pydantic classes as serializable, Pydantic's BaseModel becomes very convinient to use to serialize and deserialize data. However, as part of my models I have a lot of Enums...
<python><python-3.x><python-typing><pydantic><pydantic-settings>
2024-08-23 07:30:12
0
1,023
Marcus
78,904,263
596,922
Better way to get list of keys which has the same value from a output dict
<p>I'm trying to get all keys from a python dict which has the same value. as part of this, I have made the below attempt and it works. but checking if there is a neater way to do this. I have gone through the thread <a href="https://stackoverflow.com/questions/42438808/finding-all-the-keys-with-the-same-value-in-a-pyt...
<python><python-3.x><dictionary>
2024-08-23 04:05:34
3
1,865
Vijay
78,903,748
9,328,846
Youtube transcript API not working on server
<p>I have a Django web app. This code works perfectly fine on localhost but stops working when I run it on cloud (DigitalOcean) App Platform.</p> <pre><code>from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound, VideoUnavailable def transcribe(video_url): video_id = video_...
<python><python-3.x><django><django-views><youtube-api>
2024-08-22 22:35:41
1
2,201
edn
78,903,730
2,893,712
Pandas List All Unique Values Based On Groupby
<p>I have a dataframe that has worksite info.</p> <pre><code>District# Site# Address 1 1 123 Bayview Ln 1 2 456 Example St 2 36 789 Hello Dr 2 44 789 Hello Dr </code></pre> <p>I am trying to transform this dataframe to add a column w...
<python><pandas><dataframe><transform>
2024-08-22 22:26:52
3
8,806
Bijan
78,903,713
960,115
Python Replace XML Text with Escape Sequence
<p>I have a third-party application that is parsing magic strings within an XML file, even though it should be treating them as character literals. As an example, suppose my XML contained the following segment:</p> <pre class="lang-xml prettyprint-override"><code>&lt;element&gt;Sentence containing magicString&lt;/elem...
<python><python-3.x><xml><xml-parsing>
2024-08-22 22:20:20
2
4,735
Jeff G
78,903,671
893,254
Is there any method of uploading a file downloaded using requests to AWS using boto3 without writing to a temporary file?
<p>I'm currently working with some Python code which does the following:</p> <ul> <li>uses <code>requests</code> to download a file from the web</li> <li>saves the contents to a temporary file on disk</li> <li>uses the boto3 library to upload this file to an AWS S3 bucket</li> <li>in more detail: <code>requests.get</co...
<python><amazon-web-services><boto3>
2024-08-22 22:06:36
1
18,579
user2138149
78,903,663
7,776,212
Can't execute a remote Python script with sleep(.) from SSH
<p>I am trying to execute a Python script on a remote server via SSH. The script is supposed to run a certain function every few seconds. A minimal working snippet is as follows:</p> <pre><code># test.py (this is on the remote server in $HOME) import sys import time def test(num_samples): # First start with a moni...
<python><ssh><remote-server>
2024-08-22 22:02:59
0
779
diviquery
78,903,558
14,720,380
Faust consumer/agent doesnt run on the first initialization
<p>When I run my docker-compose for the first time and run my faust app for the first time after that, the producer sends messages ok but the consumer doesn't get the messages. If I restart the app, it works fine. My app looks like:</p> <pre class="lang-py prettyprint-override"><code>import random import faust from da...
<python><docker><apache-kafka><faust>
2024-08-22 21:19:00
0
6,623
Tom McLean
78,903,407
4,112,085
Share Environment with uv that has private git dependencies
<p>I am trying out the <code>uv</code> package in python for the first time. One of the key issues I'm concerned with is being able to share my virtual environment to other colleagues. So, up to this point I can successfully do the following via the CLI:</p> <pre><code>uv init &lt;project name&gt; --python 3.12 cd &l...
<python><git><virtual-environment><uv>
2024-08-22 20:28:04
1
362
rhozzy