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,814,853
10,677,643
Create a widget factory in Qt
<p>Hello~ I'm creating a set of custom widgets that extend the native widgets in Qt. My custom widgets are supposed to be constructed from a data source, and they all provide a custom function <code>Foobar</code>. For example:</p> <pre class="lang-cpp prettyprint-override"><code>class CheckBox: public QCheckBox, public...
<python><c++><qt>
2024-07-31 07:07:09
2
574
neo-mashiro
78,814,811
7,227,146
SSLError: HTTPSConnectionPool(host='huggingface.co', port=443)
<p>I have the following script:</p> <p><strong>test.py</strong>:</p> <pre><code>from transformers import AutoTokenizer checkpoint = &quot;kevinscaria/joint_tk-instruct-base-def-pos-neg-neut-combined&quot; tokenizer = AutoTokenizer.from_pretrained(checkpoint) </code></pre> <p>When I run <code>python test.py</code> I ge...
<python><ssl><huggingface>
2024-07-31 06:54:51
0
679
zest16
78,814,672
9,879,534
Differentiating two tuple types based on their first elements
<p>I have a function, it's return type is <code>tuple[bool, set[int] | str]</code>. If the 0th item is <code>True</code>, then the 1st item is the result <code>set[int]</code>, else the 1st item is a str showing the reason why it failed.</p> <p>It's like this:</p> <pre class="lang-py prettyprint-override"><code>def cal...
<python><python-typing>
2024-07-31 06:14:59
3
365
Chuang Men
78,814,532
7,984,318
How to pass value between steps? 'Context' object has no attribute
<p>Code:</p> <pre><code>@then('the user should see the generated survey code') def step_then_user_sees_generated_survey_code(context): context.survey_code = context.driver.find_element(By.CSS_SELECTOR, &quot;input#survey_code&quot;).get_attribute('value') print(22222222,context.survey_code) assert context.s...
<python><python-behave>
2024-07-31 05:21:48
1
4,094
William
78,814,397
16,525,263
How to handle FileNotFoundException in python
<p>I have a function to read avro files(day-wise folders) from a path and write it to same path(aggregating to month-wise folders). The function works fine if the folders have .avro files.</p> <p>But I get an error if the folders are empty.</p> <pre><code>java.io.FileNotFoundException: No avro files found. If files don...
<python><exception><filenotfoundexception>
2024-07-31 04:10:45
0
434
user175025
78,814,350
3,966,456
Under what circumstance can `sys.getrefcount()` return zero?
<p>I was reading the Python 3.12 official documentation on the <code>sys</code> module, and <a href="https://docs.python.org/3.12/library/sys.html#sys.getrefcount" rel="nofollow noreferrer">the part about <code>getrefcount()</code></a> seems rather confusing to me (emphasis mine).</p> <blockquote> <p>Return the referen...
<python><cpython><reference-counting><python-3.12>
2024-07-31 03:42:25
0
5,550
Weijun Zhou
78,813,947
1,324,833
adding buttons to a PyQT/Matplotlib NavigationToolbar2QT
<p>I've successfully added a button to the standard navigation toolbar using the following function, however my new button appears at the right side of the toolbar, and I would like it to follow the existing buttons on the left side. I can't find any reference to positioning or aligning the buttons.</p> <p>I'm guessing...
<python><matplotlib><pyqt>
2024-07-30 23:09:05
1
1,237
marcp
78,813,933
13,802,418
Kivy 2.3 VideoPlayer Android Crash
<p>I'm trying to create video .apk which includes <code>Video</code> or <code>VideoPlayer</code>.</p> <p>main.py</p> <pre><code>import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.videoplayer import VideoPlayer import os os.environ[&quot;KIVY_VI...
<python><android><video><kivy><buildozer>
2024-07-30 23:02:28
1
505
320V
78,813,866
799,927
How to Traverse a Python Dictionary While Avoiding KeyErrors?
<p>While parsing a large JSON, it's possible that some keys may only exist in certain circumstances, such as when an error is present. It's not uncommon to get a <code>200 OK</code> from the server's API, but then the response you got contains errors that should be checked for.</p> <p>What's the best way to handle this...
<python><dictionary>
2024-07-30 22:31:15
3
966
mire3212
78,813,844
214,526
"process died unexpectedly" with cythonized version of multiprocessing code
<p>This is an offshoot of <a href="https://stackoverflow.com/questions/78520245/redundant-print-with-multiprocessing">this question</a>. The code in python runs fine. When I tried the cythonized version, I started getting &quot;Can't pickle &lt;cyfunction init_worker_processes at 0x7fffd7da5a00&gt;&quot; even though I ...
<python><python-3.x><multiprocessing><cython><python-multiprocessing>
2024-07-30 22:17:13
1
911
soumeng78
78,813,619
1,390,639
regex to interpret awkward scientific notation
<p>Ok, so I'm working with this <code>ENDF</code> data, see <a href="https://www.nndc.bnl.gov/endf-b8.0/download.html" rel="nofollow noreferrer">here</a>. Sometimes in the files they have what is quite possibly the most annoying encoding of scientific notation floating point numbers I have ever seen<sup>1</sup>. There ...
<python><regex><scientific-notation>
2024-07-30 20:46:07
4
1,259
villaa
78,813,476
17,174,267
python function: argument after argument with asterisk
<p>I was wondering why defining the following function is considered fine.</p> <pre><code>def foo(*x, y): pass </code></pre> <p>As far as I know there is now way of calling this function, since it's always missing the value for y. (Please correct me if I'm wrong.)</p> <p>Does this have any utility I'm not ware of?<...
<python>
2024-07-30 19:57:03
0
431
pqzpkaot
78,813,418
21,905,651
How do upload an image from URL to Discord to be used for an embed?
<p>I have a Discord embed for Instagram posts but the <a href="https://scontent-sjc3-1.cdninstagram.com/v/t51.29350-15/449322999_988059366331988_1840488979349194447_n.webp?stp=dst-jpg_e35_s1080x1080&amp;_nc_ht=scontent-sjc3-1.cdninstagram.com&amp;_nc_cat=108&amp;_nc_ohc=Ip7b_s9PzD0Q7kNvgG-5F6W&amp;edm=AOQ1c0wBAAAA&amp;...
<python><python-requests><discord><webhooks>
2024-07-30 19:37:16
1
635
Ryan Luu
78,813,291
20,591,261
Reload custom python function
<p>I'm trying to reload from a python script a custom function because i'm editing the function constantly and i dont want to reload the kernel each time i make a change on the file. I have read that i can use <code>importlib</code> .</p> <p>However, when i try to use reload i get <code>ImportError: module Classifier n...
<python><python-importlib>
2024-07-30 18:54:14
1
1,195
Simon
78,813,152
8,436,290
Ask multiple queries in parallel with Langchain Python
<p>I have managed to ask one query using langchain like this:</p> <pre><code>template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. Answer questions using the information in this docu...
<python><large-language-model><py-langchain>
2024-07-30 18:11:37
0
467
Nicolas REY
78,813,033
2,941,921
Error: to Calculate shifted delta code error for one image
<p>I am trying to find Shifted delta and running code for one image. and Im getting error on the highligted line. I have Also attached the screen shot of the error.</p> <pre><code>import numpy as np import cv2 from scipy.fftpack import dct, idct def compute_cepstrum(image): # Compute the 2D DCT (Discrete Cosine Tr...
<python><numpy>
2024-07-30 17:36:10
0
301
Qasim0787
78,813,024
5,458,723
Fast(est) way to process an expanding linear sequence in Python
<p>I have the following conditions:</p> <ul> <li>The number u(0) = 1 is the first one in u.</li> <li>For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u also.</li> <li>There are no other numbers in u.</li> <li>No duplicates should be present.</li> <li>The numbers must be in ascending sequential order</li...
<python><performance><data-structures><containers><linear-algebra>
2024-07-30 17:33:12
1
365
ep84
78,812,985
8,605,685
Ruff pandas-use-of-dot-at (PD008) - convert to numpy array for performance
<p>The <code>ruff</code> linting code <a href="https://docs.astral.sh/ruff/rules/pandas-use-of-dot-at/" rel="nofollow noreferrer"><code>pandas-use-of-dot-at (PD008)</code></a> states:</p> <blockquote> <p>If performance is an important consideration, convert the object to a NumPy array, which will provide a much greater...
<python><pandas><numpy><ruff>
2024-07-30 17:21:02
1
12,587
Salvatore
78,812,936
5,790,653
Writing json to sqlite3 but with a condition to remove a person from sqlite3 if person is not in json file
<p>I have a json file (that's dynamic and is generated daily) which is like this for yesterday:</p> <pre class="lang-json prettyprint-override"><code>[ {&quot;name&quot;: &quot;saeed1&quot;, &quot;age&quot;: 29}, {&quot;name&quot;: &quot;saeed2&quot;, &quot;age&quot;: 30}, {&quot;name&quot;: &quot;saeed3&qu...
<python><sqlite>
2024-07-30 17:08:10
1
4,175
Saeed
78,812,763
19,130,803
unable to install kaleido
<p>I am working on dash app. I have a plotly graph which I am trying to save as image. On running I got first error as</p> <pre><code>Image export using the &quot;&quot;kaleido&quot;&quot; engine requires the kaleido package, which can be installed using pip: $ pip install -U kaleido </code></pre> <p>While trying t...
<python><plotly-dash>
2024-07-30 16:13:14
0
962
winter
78,812,608
20,591,261
Use regex function on Polars
<p>I'm cleaning a column of spanish text using the following function that use <code>re</code> and <code>unicodedata</code>:</p> <pre><code>def CleanText(texto: str) -&gt; str: texto = texto.lower() texto = ''.join((c for c in unicodedata.normalize('NFD', texto) if unicodedata.category(c) != 'Mn')) texto = ...
<python><regex><python-polars>
2024-07-30 15:40:00
1
1,195
Simon
78,812,350
2,050,158
How to plot a mean line on kdeplot for each variable
<p>I would like to visualize the mean and percentiles for each variable plotted on kdeplot</p> <p>The code provided here &quot;<a href="https://stackoverflow.com/questions/63307440/how-to-plot-a-mean-line-on-a-kdeplot-between-0-and-the-y-value-of-the-mean">kdeplot showing mean and quartiles</a>&quot; does draw the mean...
<python><matplotlib><seaborn>
2024-07-30 14:36:38
2
503
Allan K
78,812,288
2,571,805
Cython dynamic array not converting to Python
<p>I'm working on:</p> <ul> <li>Ubuntu 24.04</li> <li>Python 3.12</li> <li>Cython 3.0</li> <li>cc 13.2.</li> </ul> <p>I have a C module that implements an arbitrary tree and a few constructor functions:</p> <pre class="lang-c prettyprint-override"><code>typedef unsigned char byte; typedef unsigned long ulong; // ; #re...
<python><c><malloc><cython>
2024-07-30 14:23:51
0
869
Ricardo
78,812,281
301,302
How to properly type PyMongo?
<p>I'm trying to use PyMongo in a type safe(ish) way in VS Code. I've tried following the <a href="https://pymongo.readthedocs.io/en/stable/examples/type_hints.html" rel="nofollow noreferrer">type hints</a> section in the PyMongo documentation and arrived at the following (<code>app</code> is a Flask instance):</p> <pr...
<python><mongodb><pymongo>
2024-07-30 14:22:50
1
2,958
naivedeveloper
78,812,242
12,522,881
How to group rows and sum costs where revenue is zero
<p>Im trying to group all columns (except date column) I have and keep the rows where <strong>Revenue</strong> dosent equel to zero and sum all <strong>Cost</strong> columns to.</p> <p>For example, the first three rows will be summed with the fourth row since their <strong>Revenue</strong> is zero. The three rows will ...
<python><pandas>
2024-07-30 14:16:35
2
473
Ibrahim Ayoup
78,812,183
6,061,080
Split strings in a Series, convert to array and average the values
<p>I have a Pandas Series that has these unique values:</p> <pre><code>array(['17', '19', '21', '20', '22', '23', '12', '13', '15', '24', '25', '18', '16', '14', '26', '11', '10', '12/16', '27', '10/14', '16/22', '16/21', '13/17', '14/19', '11/15', '10/15', '15/21', '13/19', '13/18', '32', '28', '1...
<python><pandas>
2024-07-30 14:05:51
4
1,107
shiv_90
78,811,831
7,057,547
xlwings keep app open beyond lifetime of pytest script
<p>I'd like to test an Excel file using xlwings and pytest. While writing tests, it would be helpful to have an option to keep the xlwings.App instance open with the test file, so that I can inspect what's going on.</p> <p>I'm using something like this:</p> <pre class="lang-py prettyprint-override"><code>import pytest ...
<python><windows><xlwings>
2024-07-30 12:48:32
1
351
squarespiral
78,811,795
27,876
Python S3 streaming, return stream from function
<p>Is it possible to return an open write stream from a function? I am getting the error:</p> <blockquote> <p>ValueError: I/O operation on closed file.</p> </blockquote> <pre><code>import boto3 import io s3 = boto3.client('s3') # Download file from S3 and upload a copy def download_s3(): response = s3.get_object...
<python><amazon-s3><stream>
2024-07-30 12:43:28
1
818
Jon Wilson
78,811,761
3,540,161
Python Scapy not detecting my npcap or winpcap installation
<p>I have a python script which imports scapy to do some network packet analysis. The first thing my script reports is &quot;WARNING: No libpcap provider available ! pcap won't be used&quot;. Without libpcap or ncap my script will not work, so I need to solve this problem.</p> <p>The minimal code to show the problem is...
<python><scapy><winpcap><npcap>
2024-07-30 12:35:39
0
7,308
Rolf
78,811,604
893,254
Numpy array `fill_value` fills matrix with same object, with same id, not independent objects
<p>Here is a short example which demonstrates how numpy array creation works with <code>fill_value</code>:</p> <pre><code>class ExampleObject(): pass my_array = numpy.full( shape=(3, 3), fill_value=ExampleObject(), ) for i in range(3): for j in range(3): print(id(my_array[i][j]) # returns same...
<python><numpy>
2024-07-30 12:06:01
1
18,579
user2138149
78,811,597
4,013,571
mypy: typing a tuple with large number of arguments
<p>I have the following requirement to type</p> <pre class="lang-py prettyprint-override"><code>n: int = 256 x: tuple[(int,) * n] = (1,) * n </code></pre> <p><code>mypy</code> however fails with <code>Type expected within [...] [misc]</code> - how can this be fixed</p> <p>Current reading:</p> <ul> <li><a href="https:/...
<python><python-typing><mypy>
2024-07-30 12:04:46
0
11,353
Alexander McFarlane
78,811,505
19,672,778
Why does order of the data matter for neural network?
<p>Recently, I discovered the really weird behaviour of my an AI model. I wanted to build AI model that would try and guess the implicit functions based on the data I gave it. For example, the equation of the flower is:</p> <p><a href="https://i.sstatic.net/1Xq8o13L.png" rel="nofollow noreferrer"><img src="https://i.ss...
<python><numpy><tensorflow>
2024-07-30 11:45:54
2
319
NikoMolecule
78,811,474
784,587
Decrypt AES-256-CBC in php
<p>I encrypt in Python this way:</p> <pre><code>from Crypto.Cipher import AES from base64 import b64decode, b64encode BLOCK_SIZE = 16 pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) unpad = lambda s: s[:-ord(s[len(s) - 1:])] class AESCipher: def __...
<python><php><encryption><aes><cbc-mode>
2024-07-30 11:38:20
2
857
Rougher
78,811,382
12,106,577
random.sample(population, X) sometimes not contained in random.sample(population, Y) when Y>X
<p><strong>EDIT</strong>: Edited original post replacing my code with an MRE from user <a href="https://stackoverflow.com/users/16759116/no-comment">@no comment</a>.</p> <p>I noticed a seemingly non-intuitive behaviour using a seeded <code>random.sample(population, k)</code> call to sample from a list of files in a dir...
<python><random><sample>
2024-07-30 11:17:01
1
399
John Karkas
78,811,118
10,658,339
How to Efficiently Handle and Display Over 1000 Plots with User Input in Jupyter Notebook with VS Code
<p>I'm running an analysis that requires plotting data and having a human (engineer) decide whether to accept the fitting based on their judgment. The dataset is large, with over 1000 plots, and user input is necessary for each plot. However, I'm encountering a problem where Jupyter Notebook stops displaying outputs af...
<python><visual-studio-code><jupyter-notebook><user-input><display>
2024-07-30 10:12:26
0
527
JCV
78,810,998
18,769,241
How to install speech recognition module for Python 2.7?
<p>I am trying to install the following module <a href="https://github.com/Uberi/speech_recognition" rel="nofollow noreferrer">https://github.com/Uberi/speech_recognition</a> from PyPi (<a href="https://pypi.org/project/SpeechRecognition/" rel="nofollow noreferrer">https://pypi.org/project/SpeechRecognition/</a>) for m...
<python><speech-recognition>
2024-07-30 09:49:04
0
571
Sam
78,810,832
1,602,160
install python package dynamically via subprocess pip but still see import error
<p>I have to dynamically install the package: <code>paho-mqtt</code> (which itself depends on <code>typing-extensions</code>) in remote machine(python 3.7) via:</p> <pre><code>import subprocess import sys try: import paho.mqtt.client as mqtt_client except ImportError: subprocess.check_call([sys.executable, &quo...
<python>
2024-07-30 09:17:58
0
734
Shawn
78,810,717
4,399,016
Extracting contents from Zipfile in Python downloaded from URL
<p>I have this <a href="https://www.statssa.gov.za/timeseriesdata/Excel/P6420%20Food%20and%20beverages%20(202405).zip" rel="nofollow noreferrer">URL</a> for downloading a Zipfile. We can download the zipfile by clicking the link.</p> <p>But this code I have does not work.</p> <pre><code>from datetime import datetime, t...
<python><python-zipfile>
2024-07-30 08:59:19
1
680
prashanth manohar
78,810,393
961,207
Finding quartile in Python given mean, std.dev
<p>Given the mean and standard deviation of a normal distribution, how in Python can I determine the quartile of a given point?</p> <p>E.g.:</p> <ul> <li>mu = 0.7</li> <li>sigma = 0.1</li> </ul> <p>Which quartile is the value 0.75 in, with Python?</p> <p>I'm after the quartile itself, not the quartile bounds - i.e. a f...
<python><statistics>
2024-07-30 07:48:58
1
571
Leon Derczynski
78,810,340
22,496,572
Allow eval access to class variables but also to a function from an imported module
<p>I want <code>eval()</code> to only have access to variables present in a class instance <code>instance</code>, but also to functions from the module <code>itertools</code>. How can I do it most elegantly?</p> <p>Without the functions from the module, I do <code>eval(expr, instance.__dict__)</code>. If I want specifi...
<python><eval>
2024-07-30 07:36:37
0
371
Sasha
78,810,300
13,840,270
Pythonic approach to avoid nested loops for string concatenation
<p>I want to find all 5-digit strings, for which</p> <ul> <li>the first three digits are in my first list,</li> <li>the second trough fourth are in my second and</li> <li>the third to fifth are in my last list:</li> </ul> <pre class="lang-py prettyprint-override"><code>l0=[&quot;123&quot;,&quot;567&quot;,&quot;451&quot...
<python>
2024-07-30 07:27:36
5
3,215
DuesserBaest
78,810,190
1,867,328
Difference in estimates of SE between R's GLM and Python's minimize method
<p>I have below dataset in <code>R</code></p> <pre><code>dat = structure(list(PurchasedProb = c(0.37212389963679, 0.572853363351896, 0.908207789994776, 0.201681931037456, 0.898389684967697, 0.944675268605351, 0.660797792486846, 0.62911404389888, 0.0617862704675645, 0.205974574899301, 0.176556752528995, 0.68702284665...
<python><r><scipy><glm>
2024-07-30 06:58:58
0
3,832
Bogaso
78,810,121
23,468,281
Python Regex to match the FIRST repetition of a digit
<p>Examples:</p> <ol> <li>For <strong>0123123123</strong>, <strong>1</strong> should be matched since the 2nd <strong>1</strong> appears before the repetition of any other digit.</li> <li>For <strong>01234554321</strong>, <strong>5</strong> should be matched since the 2nd <strong>5</strong> appears before the repetitio...
<python><regex>
2024-07-30 06:39:58
3
361
plsssineedheeeelp
78,810,016
142,605
Importing third-party classes as if they were local
<p>I'm reviewing a code and I am seeing the case when third party class</p> <pre class="lang-py prettyprint-override"><code># tables.py from sqlalchemy import Enum </code></pre> <p>is imported as it was local</p> <pre class="lang-py prettyprint-override"><code># db_update.py from .tables import Enum </code></pre> <p>...
<python>
2024-07-30 06:04:48
1
4,654
dzieciou
78,809,881
3,215,004
Why does `os.execl` interfere with `stdin` on Windows?
<p>My minimal example is null.py:</p> <pre><code>import os, sys os.execl(sys.executable, sys.executable) </code></pre> <p>I would have thought that <code>python null.py</code> would be pretty much the same as running <code>python</code>, which is the case on Ubuntu 22.04. However, on Windows 11, it seems to mess up std...
<python><windows><stdin>
2024-07-30 05:07:58
0
855
gmatht
78,809,285
4,367,371
Pandas read csv that has multiple tables
<p>I have a URL that downloads a csv file, to open it I am using the following code:</p> <pre><code> df = pd.read_csv(url) </code></pre> <p>most URLs I am using only contain a single table and they open fine, but some have the following format which causes an error:</p> <p><a href="https://i.sstatic.net/v8UpnyTo.png" r...
<python><pandas><dataframe><csv><parsing>
2024-07-29 23:02:48
1
3,671
Mustard Tiger
78,809,025
2,521,423
Adding variable indentation in front of each line of python logging output
<p>I am building logging into a python app, and I would like it to be human-readable. At the moment, the debug logs document every function that is called, with argument and return values. This means that practically, a debug log for a nested function call might look like this:</p> <pre><code>2024-07-29 16:52:26,641: D...
<python><python-logging>
2024-07-29 20:59:47
1
1,488
KBriggs
78,808,926
1,084,875
Define constraints for different JSON schema models in a list
<p>I have some JSON with a structure similar to what is shown below. The <code>threshold</code> list represents objects where the type can be <code>&quot;type&quot;: &quot;upper_limit&quot;</code> or <code>&quot;type&quot;: &quot;range&quot;</code>. Notice the <code>&quot;target&quot;</code> value should be an integer ...
<python><json><pydantic>
2024-07-29 20:24:55
2
9,246
wigging
78,808,903
18,476,381
pandas read_sql resulting in Value error: "year -10100 is out of range" caused by corrupted dates in database
<p>I am running a script to migrate data from oracle to postgres. When running the below</p> <pre><code>df = pd.read_sql( query, oracle_conn, ) </code></pre> <p>It is resulting in an error of</p> <blockquote> <p>ValueError: year -10100 is out of range</p> </blockquote> <p>For some rows accross thousands there a...
<python><sql><pandas><dataframe>
2024-07-29 20:14:23
1
609
Masterstack8080
78,808,891
808,713
PasswordInput does not react with carriage return
<p>I'm trying to avoid the need for a submit button. The below code is currently running from a remote jupyter lab. The message will be printed out only after the cursor focus is removed from the password widget. I would like carriage return to trigger the message printing. Any clues?</p> <pre><code>from panel.widgets ...
<python><panel>
2024-07-29 20:10:41
0
2,573
csta
78,808,829
8,436,290
failed_generation with Groq LLM and llama index in Python
<p>My code is the following:</p> <pre><code>from llama_parse import LlamaParse from llama_index.llms.groq import Groq from llama_parse.base import ResultType, Language from llama_index.core.node_parser import MarkdownElementNodeParser parser = LlamaParse( api_key=&quot;xxx&quot;, result_type=ResultType.MD, ...
<python><large-language-model><llama-index><groq>
2024-07-29 19:45:48
0
467
Nicolas REY
78,808,780
445,810
Subclass ctypes.c_void_p to represent a custom handler with a custom C function for constructor and destructor / free
<p>I have a somewhat exotic question.</p> <p>Imagine there is some kind of C interface with ops like (in practice I'm thinking of <a href="https://webrtc.googlesource.com/src/+/refs/heads/main/common_audio/vad/include/webrtc_vad.h" rel="nofollow noreferrer">webrtc vad API</a>):</p> <pre class="lang-cpp prettyprint-over...
<python><ctypes>
2024-07-29 19:30:46
1
1,164
Vadim Kantorov
78,808,729
595,305
Is there any way to disguise a mock object as an acceptable PyQt object in Qt method parameters?
<p>This is an MRE. You need to have <code>pytest</code> installed... and in fact <a href="https://pypi.org/project/pytest-qt/" rel="nofollow noreferrer">pytest-qt</a> won't do any harm.</p> <pre><code>import sys, pytest from PyQt5 import QtWidgets from unittest import mock class MyLineEdit(QtWidgets.QLineEdit): d...
<python><pyqt><mocking><pytest><pytest-qt>
2024-07-29 19:13:06
1
16,076
mike rodent
78,808,725
596,922
python regex to match multiple words in a line without going to the next line
<p>I'm writing a parser to parse the below output:</p> <pre><code> admin@str-s6000-on-5:~$ show interface status Ethernet4 Interface Lanes Speed MTU Alias Vlan Oper Admin Type Asym PFC --------------- ----------- ------- ----- ------------ ------ ------ ------...
<python><regex>
2024-07-29 19:12:35
5
1,865
Vijay
78,808,609
24,191,255
Excluding a label on the y-axis in Matplotlib: How?
<p>I would not like to have the first label on the y-axis on my figure which looks like this <a href="https://i.sstatic.net/AJthAFD8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJthAFD8.png" alt="Figure" /></a> now, since I don't find it very nice to have it like this.</p> <p>In my solution, I tried ...
<python><matplotlib><axis>
2024-07-29 18:39:11
1
606
Márton Horváth
78,808,552
15,307,950
How to run python subprocess with PIPE in parallel?
<p>I'm converting a bunch of SVG images to PNG using inkscape. Single threaded:</p> <pre><code> import subprocess import time import os inkscape_path = r'C:\Program Files\Inkscape\bin\inkscape.com' steps=30 filenames = [] processes = [] # t_start = time.process_time() t_start = time.time() for i in range(steps): ...
<python><subprocess>
2024-07-29 18:23:00
0
726
elechris
78,808,445
13,132,728
How to style groups of rows differently based on a column's value with Pandas Styler
<h1>What I am trying to accomplish:</h1> <p>I have the following dataframe, <code>df</code>:</p> <pre><code>data = {'person': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'a', 5: 'a', 6: 'b', 7: 'b', 8: 'b', 9: 'b', 10: 'b', 11: 'b', 12: 'c', 13: 'c', 14: 'c', 15: 'c', 16: 'c', 17: 'c'}, 'x': ...
<python><pandas><dataframe><pandas-styles>
2024-07-29 17:49:58
2
1,645
bismo
78,808,130
6,439,229
When to use event() vs. eventFilter()
<p>I'm confused about when you can use <code>event()</code> vs. <code>eventFilter()</code> to modify a widget's behaviour.</p> <p>Two examples:<br /> A Pushbutton where you can disable tooltips without changing the tooltip text:</p> <pre><code>class PButton(QPushButton): def __init__(self, *args): super()._...
<python><events><pyqt><eventfilter>
2024-07-29 16:22:06
0
1,016
mahkitah
78,808,076
3,322,533
How do you install a generated openapi client to a zipapp?
<p>So I generated an openapi client using <a href="https://github.com/OpenAPITools/openapi-generator" rel="nofollow noreferrer">openapi-generator</a>.</p> <p>And I now want to install it to my zippapp.</p> <p>There must be something wrong with my overal structure, though.</p> <p>I have an <code>app</code> folder. It co...
<python><python-3.x><pip><openapi-generator><zipapp>
2024-07-29 16:06:41
1
8,239
User1291
78,808,015
9,999,861
Django date input format seems not to be accepted
<p>I put a DateField inside a ModelForm, which seems to work fine, if I add new entries to my database. Then I added a page, where I can edit one of those entries. Of course, I am passing the date of the desired entry to the HTML, but the date format is not set as expected.</p> <pre><code># models.py class SomeModel(m...
<python><html><django><django-forms>
2024-07-29 15:46:58
1
507
Blackbriar
78,807,906
2,081,427
scrapy renew access token after some time
<p>I am using scrapy to query an api with restricted access.</p> <pre><code>def start_requests(self): self.initialize_gcs_store() url = &quot;https://api.example.com/authenticate&quot; headers = {'Content-Type': 'application/json'} headers = {'authority': 'https://apply.workable.com'} payload = { ...
<python><scrapy>
2024-07-29 15:23:23
1
2,568
DJJ
78,807,798
3,406,193
Mypy 1.10 reports error when functools.wraps() is used on a generic function
<h4>TLDR;</h4> <p>I have a decorator that:</p> <ul> <li>changes the function signature</li> <li>the wrapped function uses some generic type arguments</li> <li>Other than the signature I would like to use <code>funtools.wraps</code> to preserve the rest of the information.</li> </ul> <p>Is there any way to achieve that ...
<python><python-typing><mypy><python-decorators>
2024-07-29 14:57:14
1
4,044
mgab
78,807,787
801,924
Replace NaN by None by without raise SettingWithCopyWarning
<p>I have a data frame looking of this:</p> <pre><code> x u i rowid 0 1.0 1.0 5.0 1.0 1 2.0 2.0 4.0 2.0 2 3.0 3.0 3.0 3.0 3 4.0 4.0 2.0 NaN 4 5.0 5.0 1.0 5.0 5 6.0 4.0 0.0 6.0 6 7.0 3.0 1.0 7.0 7 8.0 2.0 2.0 NaN 8 9.0 1.0 3.0 9.0 9 1...
<python><pandas><numpy>
2024-07-29 14:54:42
1
7,711
bux
78,807,728
4,505,998
Sort by two columns where first is already sorted in pandas
<p>I have a kind of big DataFrame, and therefore it can't be sorted on O(n²). I want to sort by two columns, and <strong>one of those columns is already sorted</strong>.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'col1': [ 0, 0, 1, 2, 2, 2], 'col2': [ 'c', 'a', 'b', 'e', 'h', 'f'] }...
<python><pandas><dataframe><algorithm><sorting>
2024-07-29 14:41:02
2
813
David Davó
78,807,596
4,505,998
Dask merge ordered
<p>I have a kind of huge dataset (about 100GB) based on blockchain data. I want to merge two tables based on the <code>transactionHash</code>, which would be impossible (O(n^2)) except because these two tables are both ordered by <code>blockNumber</code>, so this can be done in O(|A|+|B|)=O(n).</p> <p>The tables would ...
<python><pandas><dask>
2024-07-29 14:10:33
0
813
David Davó
78,807,556
2,856,499
Normalising data in dat file with sections into a pandas dataframe
<p>I have a file that show an example of a data as below</p> <pre><code>CAR REPORT AREA 1 Car Honda Country America ...
<python><pandas>
2024-07-29 14:03:13
1
1,315
Adam
78,807,441
2,233,500
Problem with text rendering using CairoSVG
<p>I'm using CairoSVG to convert a SVG file into a PNG image. The position of the text seems to be off compared to the images rendered by Firefox, Safari and co. I cannot understand if the problem comes from the code, from CairoSVG or from the SVG file.</p> <p>Here is the URL of the SVG file: <a href="https://upload.wi...
<python><cairo>
2024-07-29 13:42:30
1
867
Vincent Garcia
78,807,196
4,451,315
Convert PyArrow table to pandas, but transform string to `string[pyarrow]` in pandas directly
<p>Say I have</p> <pre class="lang-py prettyprint-override"><code>import pyarrow as pa tbl = pa.table({'a': ['foo', 'bar']}) </code></pre> <p>If I do <code>tbl.to_pandas()</code>, then the dtypes of the result are <code>object</code>:</p> <pre><code>In [14]: tbl.to_pandas().dtypes Out[14]: a object dtype: object </...
<python><pyarrow>
2024-07-29 12:56:33
1
11,062
ignoring_gravity
78,807,069
625,396
How to implement in pytorch - numpy's .unique WITH(!) return_index = True?
<p>In numpy.unique there is an option <strong>return_index=True</strong> - which returns positions of unique elements (first occurrence - if several).</p> <p>Unfortunately, there is no such option in torch.unique !</p> <p><strong>Question:</strong> What are the fast and torch-style ways to get indexes of the unique el...
<python><numpy><pytorch><torch>
2024-07-29 12:26:16
1
974
Alexander Chervov
78,806,993
8,000,016
How could call a psql command from Python script
<p>I'm trying to create database table with psql command called from python scrip but I got the following error: <code>[Errno 2] No such file or directory: b'psql -d postgres -U postgres -h postgres -W -c &quot;CREATE DATABASE db_316c76d0 OWNER user_316c76d0;&quot;'</code></p> <p>The script is:</p> <pre><code>try: cr...
<python><postgresql><psql>
2024-07-29 12:09:31
1
1,264
Alberto Sanmartin Martinez
78,806,818
19,363,912
Join same name dataframe column values into list
<p>I create a dataframe with distinct column names and use <code>rename</code> to create columns with same name.</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;a_1&quot;: [&quot;x&quot;, &quot;x&quot;], &quot;a_2&quot;: [&quot;&quot;, &quot;&quot;], &quot;b_1&quot;: [&quot;&quot;, &quot;&quot...
<python><pandas><dataframe>
2024-07-29 11:28:06
1
447
aeiou
78,806,812
13,573,168
THIRD_PARTY_NOTICES.chromedriver - Exec format error - undetected_chromedriver
<p><strong>undetected_chromedriver</strong> with <strong>webdriver_manager</strong> was working well few days ago for scraping websites but out of nowhere it started throwing the error:</p> <pre><code>OSError: [Errno 8] Exec format error: '/Users/pd/.wdm/drivers/chromedriver/mac64/127.0.6533.72/chromedriver-mac-x64/TH...
<python><selenium-webdriver><web-scraping><undetected-chromedriver>
2024-07-29 11:27:10
4
4,946
Prakash Dahal
78,806,693
7,227,146
Error while finding module specification for '' (ModuleNotFoundError: __path__ attribute not found on '' while trying to find '')
<p>I have a minimal directory with the following structure:</p> <ul> <li>my_project <ul> <li>code <ul> <li>my_code.py</li> </ul> </li> <li>functions <ul> <li>module1.py</li> </ul> </li> </ul> </li> </ul> <p>The contents of each file are:</p> <pre><code>## module1.py def add_three(number): return number+3 </code></p...
<python>
2024-07-29 10:59:03
1
679
zest16
78,806,611
1,082,673
Keyringrc.cfg Permission Issues when installing packages via a python script using poetry
<p>I have an app being managed by <code>supervisor</code> running as the user <code>app_user</code>. When the script starts, it checks if there are new packages and tries to install them using the code below. It however throws the error <code>[Errno 13] Permission denied: '/root/.config/python_keyring/keyringrc.cfg'</c...
<python><python-3.x><supervisord><python-poetry>
2024-07-29 10:38:41
1
4,090
lukik
78,806,270
335,427
Create columns from grouped output
<p>I have data which looks like this</p> <pre><code>startDate endDate value sourceName 0 2024-06-03 22:26:00+02:00 2024-06-03 22:46:00+02:00 HKCategoryValueSleepAnalysisAsleepCore AppleWatch 6 2024-06-03 22:40:00+02:00 2024-06-04 07:48:00+02:00 HKCategoryValueSleepAnalysisAsleepCore Connect 1 2024-0...
<python><pandas>
2024-07-29 09:21:35
1
3,735
Chris
78,806,145
3,684,931
Is there a way to generate the computation graph of a PyTorch model from just a forward pass?
<p>Imagine a network like this:</p> <pre><code>import torch import torch.nn as nn class CoolCNN(nn.Module): def __init__(self): super(CoolCNN, self).__init__() self.initial_conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1) self.parallel_conv = nn.Conv2d(in_channels=...
<python><graph><pytorch>
2024-07-29 08:45:16
1
1,984
Sachin Hosmani
78,805,881
4,451,315
Shift a chunkedarray
<p>If I start with</p> <pre><code>import pyarrow as pa ca = pa.chunked_array([[1,3, 2], [5, 2, 1]]) </code></pre> <p>I'd like to end up with a pyarrow array with elements</p> <pre><code>[None, 1, 3, 2, 5, 2] </code></pre> <p>I don't really mind if the output is an array or a chunkedarray</p>
<python><pyarrow>
2024-07-29 07:40:00
1
11,062
ignoring_gravity
78,805,524
143,397
How to build a PyO3 extension with Yocto / OpenEmbedded?
<p>I have a Python/Rust project that uses PyO3 to build a Python extension, written in Rust.</p> <p>I have it set up with <code>maturin</code> and it works fine locally - it will build a wheel (.whl) and within that is my Python code and the Rust extension shared object, just as I'd expect.</p> <p>I need to cross-compi...
<python><rust><yocto><openembedded><pyo3>
2024-07-29 05:34:21
0
13,932
davidA
78,805,430
10,722,752
How to sort a pandas dataframe using group by
<p>I am working on a dataframe similar to below sample:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(0) np.random.seed(0) df = pd.DataFrame({'date' : np.tile(['2024-05-01', '2024-06-01'], 4), 'State' : np.repeat(['fl', 'ny', 'mi', 'nc'], 2), 'Rev' : [21000, 1...
<python><pandas>
2024-07-29 04:52:44
3
11,560
Karthik S
78,805,181
14,761,117
ValueError: Unrecognized keyword arguments passed to LSTM: {'batch_input_shape'} in Keras
<p>I'm trying to build and train a stateful LSTM model using Keras in TensorFlow, but I keep encountering a ValueError when specifying the batch_input_shape parameter.</p> <p>The error message:</p> <pre><code>ValueError: Unrecognized keyword arguments passed to LSTM: {'batch_input_shape': (1, 1, 14)} </code></pre> <p>H...
<python><keras><lstm>
2024-07-29 01:50:24
1
331
AmaniAli
78,804,934
2,697,895
How to make an Android service in Python?
<p>I want to build a simple Android app, like <a href="https://pushover.net/" rel="nofollow noreferrer">PushOver app</a>, that has a TCP server and receive text messages which it logs and then send them as push notifications. This part is already done and working fine. But I want to receive messages even if the GUI app...
<python><android><service><beeware>
2024-07-28 22:20:44
0
3,182
Marus Gradinaru
78,804,920
10,746,224
Django Admin TabularInline: How do I hide the object name of a M2M through model?
<p>How do I hide <strong><code>Unit_attribute object (3)</code></strong> from the admin display?</p> <p><a href="https://i.sstatic.net/zOahrSx5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zOahrSx5.png" alt="Django Admin" /></a></p> <p><strong>admin.py:</strong></p> <pre><code>from django.contrib impo...
<python><django><django-admin>
2024-07-28 22:13:23
1
16,425
Lord Elrond
78,804,834
208,080
Timeout parameter in subprocess does not work in chainlit app
<p>I have a script to build a Chainlit UI for my GraphRAG app running in windows. The GraphRAG query runs fine in the terminal, although it takes about 120 seconds (screenshot attached). However, when I run this Chainlit script, the timeout=300 in subprocess.run does not work as expected. Instead, I get a 'can't reach ...
<python><chainlit><graphrag>
2024-07-28 21:15:24
0
1,296
Mavershang
78,804,625
446,786
Django Models - trying to get the "best of both worlds" when it comes to copying a model vs subclassing it
<p>Let's say I have a base class (Django model) called Character that looks something like</p> <pre><code>class Character(models.Model): strength = models.blabla dex = models.blabla ... </code></pre> <p>I can set that up with its attributes and hook it up to Admin and everything is lovely.</p> <p>Then I dec...
<python><django><django-models>
2024-07-28 19:11:41
1
311
Josh
78,804,536
850,781
How to update python modules for numpy 2?
<p>On linux with pip the new numpy 2 seems to work with pandas fine:</p> <pre><code>$ python3 -c 'import numpy as np; print(np.__version__); import pandas as pd; print(pd.__version__)' 2.0.1 2.2.2 </code></pre> <p>however, on windows with miniconda I get</p> <pre><code>$ ${localappdata}/miniconda3/envs/c312/python.exe ...
<python><pandas><numpy>
2024-07-28 18:30:44
0
60,468
sds
78,804,323
525,865
bs4-approach to wikipedia-page: getting the infobox
<p>i am currently trying to apply a bs4-approach to wikipedia-page: results do not store in a df</p> <p>due to the fact that scraping on Wikipedia is a very very common technique - where we can use an appropiate approach to work with many many different jobs - i did have some issues with getting back the results - and ...
<python><pandas><beautifulsoup><wikipedia>
2024-07-28 16:54:03
1
1,223
zero
78,803,752
14,838,954
My PyTorch Model in Kaggle uses 100% CPU and 0% GPU During Training
<p>I'm trying to fine-tune a PyTorch classification model to classify plant disease images. I have properly initialized the CUDA device and sent the model, train, validation, and test data to the device. However, when training the model, it uses 100% CPU and 0% GPU. Why is this happening?</p> <pre class="lang-py pretty...
<python><deep-learning><pytorch><gpu><kaggle>
2024-07-28 12:24:12
1
485
Nirmal Sankalana
78,803,628
7,514,722
Trying pybind11 in window: undefined reference to __imp_PyGILState_Check
<p>I'm trying to get pybind11 to work in windows. I've installed pybind11 using conda-forge, then do the simplest code:</p> <pre><code>#include &quot;pybind11/pybind11.h&quot; namespace py = pybind11; </code></pre> <p>compile it with :</p> <pre><code>g++ -std=c++17 -O2 -mavx -IC:/Users/beng_/anaconda3/Lib/site-package...
<python><c++><pybind11>
2024-07-28 11:24:57
1
335
Ong Beng Seong
78,803,612
10,976,122
How can I use custom variables in Loguru in Python?
<p>I don't want the structure the Loguru gives me. I want to use a custom serialized json base structure. for eg:</p> <pre><code> { &quot;time&quot;: &quot;5:30pm&quot;, &quot;error&quot;: &quot;Type error, } </code></pre> <p>I don't want any extra params.</p> <p>From the source code I think it comes from this f...
<python><logging><fastapi><loguru>
2024-07-28 11:20:53
2
350
shaswat kumar
78,803,573
694,360
Manage packages inside a conda environment exclusively throught pip
<p>I would like to use conda as environment manager (in a Windows system) and pip as package manager.</p> <p>As suggested <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#pip-in-env" rel="nofollow noreferrer">here</a>, using conda after pip should be avoided; moreover</p...
<python><pip><conda>
2024-07-28 10:59:21
1
5,750
mmj
78,803,555
4,340,793
FastAPI dependency injection by class type
<p>I'm familiar with dependency injecting and I was trying to do something I have seen in the past in other frameworks (spring Autowired annotation).</p> <p>I have the following 2 classes :</p> <pre><code>class MyServerConfig: def __init__(self): serviceA_host = getenv(&quot;SERVICE_A_HOST&quot;) Se...
<python><dependency-injection><fastapi>
2024-07-28 10:51:15
0
4,140
JeyJ
78,803,339
7,377,543
Cannot read excel file in Pandas as required
<ol> <li>I am learning <code>stack()</code>/ <code>unstack()</code> in Pandas</li> <li>Link to the excel file is <a href="https://github.com/codebasics/py/blob/master/pandas/12_stack/stocks.xlsx" rel="nofollow noreferrer">here</a>. The data in the file looks as under:</li> </ol> <p><a href="https://i.sstatic.net/WTy3t...
<python><excel><pandas>
2024-07-28 08:51:53
0
430
Nizamuddin Shaikh
78,803,329
1,371,666
default maximized window in tkinter with red background
<p>I am using Python 3.11.9 in windows 11 OS (home edition)<br> There is a table inside a scrollable frame.<br> Here is the simplified code</p> <pre><code>import tkinter as tk class Table(tk.Frame): def __init__(self, master, header_labels:tuple, *args, **kwargs): tk.Frame.__init__(self, master, *args, *...
<python><windows><tkinter>
2024-07-28 08:45:11
0
481
user1371666
78,803,308
13,658,665
django consistently fails to load css on deployment
<p>I was deploying a simple django application to kubernetes and encountered the error of not being able to load css and js. I have tried several times to change the dockerfile,change the volume path, but I can't fix it. <a href="https://i.sstatic.net/YjJFsHdx.png" rel="nofollow noreferrer"><img src="https://i.sstatic....
<python><django><kubernetes><dockerfile><kubernetes-ingress>
2024-07-28 08:34:51
1
394
HappyKoala
78,803,220
827,927
How to efficiently check whether x appears before y in a list
<p>Given a list <code>L</code> in Python, and two elements <code>x</code> and <code>y</code> that are guaranteed to be in <code>L</code>, I wish to know whether <code>x</code> appears before <code>y</code> in <code>L</code>.</p> <p>If there is only one pair, I can simply loop over <code>L</code> until I find either <co...
<python><algorithm><performance>
2024-07-28 07:42:35
2
37,410
Erel Segal-Halevi
78,803,025
1,307,876
set widget field_value with PyMuPDF (fitz) does not work
<p>I have a simple script that should fill AcroForms inside a PDF file.</p> <pre class="lang-py prettyprint-override"><code>import fitz # PyMuPDF def fill_pdf_form(input_pdf, output_pdf, data): doc = fitz.open(input_pdf) for page_num in range(len(doc)): page = doc.load_page(page_num) for wid...
<python><pdf><pymupdf>
2024-07-28 05:37:27
0
658
bitkorn
78,802,856
1,532,338
How to parse and print API response and Error code from pymeter in python script?
<p>How to parse and print API response and Error code from pymeter in python script?</p> <p>PyMeter is python version of jmeter. (pymeter help document - <a href="https://pymeter.readthedocs.io/en/latest/api.html" rel="nofollow noreferrer">https://pymeter.readthedocs.io/en/latest/api.html</a>)</p> <p>I am trying to get...
<python><jmeter>
2024-07-28 02:43:50
1
3,846
Abhishek Kulkarni
78,802,794
5,458,723
Reversing function to obtain the lexicographic index of a given permutation
<p>I'm working on a Python3 code challenge where a message is encoded on or decoded from the shuffling order of a 52-card standard playing deck. I have already found how to encode the message, but I am having difficulty reversing the function to get a message from a given shuffling order. I have a function that finds a...
<python><algorithm><permutation><steganography><playing-cards>
2024-07-28 01:26:55
1
365
ep84
78,802,744
1,485,877
Reliably get TargetData for current process
<p>In llvmlite, an instance of <code>TargetData</code> is required to get the ABI size of an object. This makes sense given that the size of an object is dependent on the word size and alignment. If I want to immediately compile and use the code in the current process, I shouldn't need anything other that the target da...
<python><llvmlite>
2024-07-28 00:39:43
1
9,852
drhagen
78,802,587
11,106,801
Remove internal border inside a Text widget
<p>Is it possible to remove the border around between the <code>tkinter.Text</code> widget and the background colour of a tag inside it? I set both the border width and <code>highlightthickness</code> to <code>0</code> but the border is still there:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as ...
<python><tkinter><tcl><tk-toolkit>
2024-07-27 22:27:47
1
7,800
TheLizzard