QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
79,084,529
8,947,266
Streamlit Javascript integration
<p>I can't get any js function in streamlit (python) to work, the return value is always 0, no matter how I tried to write it. For instance</p> <pre><code>anonymous = st_javascript(&quot;&quot;&quot; (() =&gt; { return 2; })() &quot;&quot;&quot;) st.write(f&quot;JavaScript returned: {anonymous}&quot;) ...
<javascript><python><streamlit>
2024-10-14 01:58:22
1
304
Romero Azzalini
79,084,460
13,634,560
pandas, determine if set value already exists in dataframe
<p>I am checking to see if a tuple of unordered values is already in another list. I am new to Python, and so have not used sets much, but am a heavy pandas user and so was thrilled to find <a href="https://stackoverflow.com/questions/66279365/how-to-check-if-a-slice-of-a-tuple-in-a-set-of-tuples-is-in-another-set-of-t...
<python><pandas><dataframe><set>
2024-10-14 00:46:41
1
341
plotmaster473
79,084,176
12,011,020
Polars read_json fails to parse date type schema
<p>I want to read in a polars dataframe from a json string containing dates in the standard iso-format &quot;yyyy-mm-dd&quot;. When I try to read the string in and set the dtype of the date column witheither <code>schema</code> or <code>schema_override</code> this results in only NULL values.</p> <h2>MRE</h2> <pre clas...
<python><json><dataframe><python-polars>
2024-10-13 21:25:18
2
491
SysRIP
79,084,149
7,077,159
How to iteratively run a Python script on the contents of a CSV file
<p>I have a Python program that takes a url as a runtime argument. I want to modify this by creating a 'wrapper' to process a CSV file containing a list of urls as the input instead of a single url. The script should be executed once for each row in the CSV file.</p> <p>Here is my simple script 'myscript.py':</p> <pre>...
<python><csv>
2024-10-13 21:09:21
3
333
Packwood
79,084,135
1,285,061
Python regex inconsistent match for the same expression for using `search` and `findall`
<p>Why does <code>re</code> have inconsistent match for the same expression for using <code>search</code> and <code>findall</code>.</p> <pre><code>import re msg = 'data from 192.168.10.255 and 10.10.10.10' ipregex_d = re.compile('((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]...
<python><python-3.x><regex>
2024-10-13 21:02:11
1
3,201
Majoris
79,083,774
3,825,948
How to use DTMF input in Twilio to call Python function
<p>I have Twilio working with a Python IVR app using a bi-directional websocket connection. DTMF messages from Twilio are used to detect user digit input while the websocket connection is alive. This is working well. However, when I receive and recognize DTMF input, for example the number 1 was pressed, I want to call ...
<python><websocket><twilio><dtmf>
2024-10-13 17:41:18
0
937
Foobar
79,083,667
6,312,511
How do I change a column of single-value Python tuples into integers?
<p>As part of a class assignment, I have received a dataframe which has a data value associated with a single-value tuple:</p> <pre><code>d = {'value': [0.827278, 0.586009, 0.832050, 0.576557, 0.943456], 'userId': [(75,), (106,), (686,), (815,), (1040,)]} df = pd.DataFrame(data=d) </code></pre> <p>I need to deploy <c...
<python><pandas>
2024-10-13 16:53:37
2
1,447
mmyoung77
79,083,492
922,130
How to include a directory with compiled binaries in a Python wheel using pyproject.toml?
<p>I want to create a Python wheel that contains a single Python module (<code>script.py</code>) and a directory of compiled C++ binaries. Below is my project structure:</p> <pre class="lang-bash prettyprint-override"><code>root/ β”‚ β”œβ”€β”€ bin/ β”‚ β”œβ”€β”€ binary1 β”‚ β”œβ”€β”€ binary2 β”‚ β”œβ”€β”€ binary3 β”‚ └── binary4 β”œβ”€β”€ script.py β”œ...
<python><setuptools><python-packaging><python-wheel>
2024-10-13 15:21:23
1
909
sherlock85
79,083,302
307,050
Slice list of 2D points for plotting with matplotlib
<p>I've got a list of two-dimensional points represented in a <code>numpy</code> style array:</p> <pre><code>lines = np.array([ [[1,1], [2,3]], # line 1 (x,y) -&gt; (x,y) [[-1,1], [-2,2]], # line 2 (x,y) -&gt; (x,y) [[1,-1], [2,-7]] # line 3 (x,y) -&gt; (x,y) ]) </code></pre> <p>I'd like to plot th...
<python><numpy><matplotlib><numpy-slicing>
2024-10-13 13:57:23
1
1,347
mefiX
79,083,280
3,286,489
When "pip install github", it errors with "aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found"
<p>When I <code>pip install github</code>, I have the following error</p> <pre><code>Collecting github Using cached github-1.2.7-py3-none-any.whl.metadata (1.7 kB) Collecting aiohttp==3.8.1 (from github) Using cached aiohttp-3.8.1.tar.gz (7.3 MB) Installing build dependencies ... done Getting requirements to bu...
<python><python-3.x><github>
2024-10-13 13:47:25
0
61,245
Elye
79,082,898
4,432,498
Wait in a method until some methods finished in another threads
<p>I need to implement the waiting in a method until some other methods in different threads are finished.</p> <p>This is my implementation (not working as expected):</p> <pre><code>import queue from concurrent.futures import ThreadPoolExecutor import threading import time import logging logging.basicConfig( level...
<python><multithreading><concurrency>
2024-10-13 10:18:10
1
550
Anton
79,082,892
15,869,059
Fusion-like timeline in Python
<p>In Autodesk Fusion, the timeline shows individual operations on a 3D model:</p> <p><a href="https://i.sstatic.net/c6V5BngY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c6V5BngY.png" alt="a timeline containing operations on a 3D model" /></a></p> <p>Each operation can be added, removed or modified a...
<python><jupyter-notebook><3d>
2024-10-13 10:16:08
1
431
glibg10b
79,082,779
8,275,142
gmodels::fit.contrast equivalent in Python
<p>I would like to test for synergy between 2 drugs given to animals, and I measured the tumor growth at different time-points in 15 animals in each group.</p> <p>I use the statistical test for Bliss independence synergy, which is a modified t-statistic derived from the principles of linear models and the properties of...
<python><r><statistics><statsmodels><patsy>
2024-10-13 09:01:10
1
852
SΓ©bastien Wieckowski
79,082,403
3,847,651
Why a Python-based Windows service can't be started
<p>I want to develop a Windows service using Python. As a try, I copied code from <a href="https://thepythoncorner.com/posts/2018-08-01-how-to-create-a-windows-service-in-python/" rel="nofollow noreferrer">this page</a>. Then I compiled it to the EXE file with <a href="https://pyinstaller.org/en/stable/" rel="nofollow ...
<python><windows><service>
2024-10-13 04:30:39
0
1,553
Wason
79,082,174
565,635
If I install two distribution packages that provide the same import package, which one is imported?
<p>As a quick reminder, a <a href="https://packaging.python.org/en/latest/glossary/#term-Distribution-Package" rel="nofollow noreferrer"><em>distribution package</em></a> is what you install through <code>pip</code>. Each distribution package can contain (multiple) <a href="https://packaging.python.org/en/latest/glossa...
<python><pip><python-import><python-packaging>
2024-10-13 00:10:50
0
119,106
orlp
79,082,153
14,579,156
Google Classroom API Assign Coursework To Students
<p>I'm trying to create a script that will assign students by ID to coursework. The code appears to be working, but I'm getting a 500 response from the server. Any idea what I'm doing wrong? I've tried different student ids and they all give the same result?</p> <pre><code>assign_coursework_to_students(service, course_...
<python><google-classroom>
2024-10-12 23:48:15
0
370
ShadowGunn
79,082,075
2,675,349
How to efficiently process messages from Rabbit MQ?
<p>I have an architecture-related question about implementing a Python API/Microservices that need to process 30 million incoming requests.</p> <p>I am planning to to use RabbitMQ or Amazon SQS.</p> <p>Question: Question: Will the callback mechanism be able to handle the message volume efficiently, or do you have any b...
<python><asynchronous><rabbitmq><microservices><event-driven>
2024-10-12 22:44:35
0
1,027
Ullan
79,081,999
8,397,886
VS Code terminal is inconsistent with normal terminal MacOS ARM
<p>Below I have attached two images. One from my VS Code terminal and the other one from my normal terminal. The difference is important because I keep getting dependency issues due to the packages being compiled for x86_64 instead of Arm64 which is what it should be.</p> <p>What is the discrepancy due to and how can I...
<python><visual-studio-code><terminal><arm64><python-venv>
2024-10-12 21:44:52
1
2,577
Ludo
79,081,924
189,878
With spaCy, how can I get all lemmas from a string?
<p>I have a pandas data frame with a column of text values (documents). I want to apply lemmatization on these values with the spaCy library using the pandas <code>apply</code> function. I've defined my <code>to_lemma</code> function to iterate through the words in the document and concatenate the corresponding lemma...
<python><pandas><nlp><spacy><lemmatization>
2024-10-12 21:03:21
2
2,346
Patrick
79,081,900
1,790,839
Get context from previous airflow task
<p>I have the following DAG:</p> <blockquote> <p>task_a &gt;&gt; task_b &gt;&gt; task_c</p> </blockquote> <p>I would like to be able:</p> <ul> <li>to somehow access inside task_c some parameters (environment variables to be precise) passed to task_b (which is a KubernetesOperator)</li> <li>without changing task_b (so n...
<python><airflow>
2024-10-12 20:44:10
0
450
kofi_kari_kari
79,081,887
8,190,068
Adjusting Checkbox and Label alignment in a GridLayout
<p>I am relatively new to Kivy, and I'm having problems adjusting checkboxes and their associated labels within a GridLayout. With reference to the image below...</p> <p><a href="https://i.sstatic.net/Cbdh6b8r.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Cbdh6b8r.png" alt="Import Dialog with Grid Layo...
<python><kivy-language><grid-layout>
2024-10-12 20:38:05
1
424
Todd Hoatson
79,081,885
1,492,229
Unable to install Torch using pip
<p>I using Windows</p> <p>I installed Python 3.13</p> <p>I am trying to <code>pip install torch</code></p> <p>However, when attempting to do so, I encounter this error.</p> <pre><code>F:\Kit&gt;pip install torch ERROR: Could not find a version that satisfies the requirement torch (from versions: none) ERROR: No matchin...
<python><pytorch><pip>
2024-10-12 20:37:14
2
8,150
asmgx
79,081,866
2,287,458
Polars Pivot treats null values as 0 when summing
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl pl.DataFrame({ 'label': ['AA', 'CC', 'BB', 'AA', 'CC'], 'account': ['EU', 'US', 'US', 'EU', 'EU'], 'qty': [1.5, 43.2, None, None, 18.9]})\ .pivot('account', index='label', aggregate_function='sum') </code>...
<python><dataframe><null><pivot-table><python-polars>
2024-10-12 20:29:48
1
3,591
Phil-ZXX
79,081,859
7,886,968
How do I ensure that my Python script and its child processes handle Ctrl-C properly?
<p>System:</p> <ol> <li><p>A Raspberry Pi-4 running Buster using Python 3.7 with an Adafruit 128x32 2.23&quot; OLED Bonnet connected to the GPIO pins.Β  Ref: <a href="https://learn.adafruit.com/adafruit-2-23-monochrome-oled-bonnet" rel="nofollow noreferrer">https://learn.adafruit.com/adafruit-2-23-monochrome-oled-bonnet...
<python><linux><signals><raspberry-pi4>
2024-10-12 20:26:12
2
643
Jim JR Harris
79,081,361
174,365
Echo y from within python
<p>I'm trying to import and use a module originally made as a standalone script. Preferably without altering it, to keep tool commonality with the authors. One function I'm using prompts for a y/n response, to which I want to always answer &quot;y&quot;:</p> <pre><code>input(&quot;\nContinue? (y/n): &quot;).lower() </c...
<python>
2024-10-12 15:54:52
2
2,613
Emilio M Bumachar
79,081,039
561,243
Failing to serialize a dataclass generated with make_dataclass with pickle
<p>In my code, I am generating classes run-time using the make_dataclass function.</p> <p>The problem is that such dataclasses cannot be serialized with pickle as shown in the code snippet here below.</p> <p>It is important to know that for my application those dataclass instances <strong>must</strong> be pickable beca...
<python><multiprocessing><pickle><python-dataclasses>
2024-10-12 12:54:30
1
367
toto
79,080,790
10,200,497
How to get the largest streak of negative numbers by sum?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [-3, -1, -2, -5, 10, -3, -13, -3, -2, 1, -200, -100], } ) </code></pre> <p>Expected output:</p> <pre><code> a 10 -200 11 -100 </code></pre> <p>Logic:</p> <p>I want to return the largest streak of negative numbers in ...
<python><pandas><dataframe>
2024-10-12 10:19:35
1
2,679
AmirX
79,080,448
22,466,650
How to truly compare two dataframes based on a key column?
<p>My inputs are two dataframes:</p> <pre><code>import pandas as pd df_having = pd.DataFrame({'ID': ['ID_01', 'ID_01', 'ID_01', 'ID_01', 'ID_02', 'ID_03', 'ID_03', 'ID_05', 'ID_06', 'ID_06'], 'NAME': ['A', 'A', 'A', 'A', 'E', 'B', 'B', 'E', 'A', 'A'], 'TYPE': ['A', 'A', 'B', 'A', 'C', 'A', 'B', 'F', 'A', 'A'], 'CATEGO...
<python><pandas><dataframe>
2024-10-12 07:50:55
0
1,085
VERBOSE
79,080,145
2,816,062
Convert Django JSON field to Text in subquery
<p>I have two models <code>Assignment</code> and <code>Application</code>. <code>Assignment</code> has <code>meta</code> field which has <code>uuid</code> data that is used to match <code>uuid</code> field on <code>Application</code>. My goal is to join assignee information when I query applications.</p> <p>I have some...
<python><django>
2024-10-12 03:46:27
0
2,868
Andrew Zheng
79,079,917
5,508,532
Filter polars DataFrame where values starts with any string in a list
<p>I have a DataFrame with a few million rows, e.g.:</p> <pre><code>df = pl.DataFrame({ 'col1': ['12345', '12', '54467899', '5433523353','0024355'] }) </code></pre> <p>And a list of a couple hundred prefixes such as:</p> <pre><code>prefixes = ['123', '544', '55443345'] </code></pre> <p>Is there an efficient way to ...
<python><regex><dataframe><python-polars>
2024-10-11 23:19:59
3
1,938
binary01
79,079,634
2,402,098
Exclude objects with a related date range
<p>Using these (simplified of course) models:</p> <pre><code>class Person(models.Model): name = models.CharField() class InactivePeriod(models.Model) person = models.ForeignKeyField(Person) start_date = models.DateField() end_date = models.DateField() class Template(models.Model): day = models.Cha...
<python><django><postgresql><cron>
2024-10-11 20:21:27
1
342
DrS
79,079,460
1,485,877
How to type annotate the splat/spread function
<p>Consider the common <code>splat</code> function, also known as <code>spread</code>, which takes a function of <code>n</code> arguments and wraps it in a function of one <code>n</code>-element tuple argument:</p> <pre class="lang-py prettyprint-override"><code>def splat(f: Callable[???, A]) -&gt; Callable[[???], A]: ...
<python><python-typing>
2024-10-11 19:03:10
1
9,852
drhagen
79,079,448
9,707,202
In python xarray, how do I create and subset lazy variables without loading the whole dataarray?
<p>I am trying to create a python function that opens a remote dataset (in a opendap server) using xarray and automatically creates new variables lazily. A use case would be to calculate magnitude and direction when u and v components are available, e.g.:</p> <pre><code>import xarray as xr import dask import dask.array...
<python><dask><python-xarray><opendap><thredds>
2024-10-11 18:56:26
1
436
Marcelo Andrioni
79,079,425
7,124,155
How to emulate Python nested or "sub" attributes
<p>How can I track a sub-attribute that applies to some attributes but not others? It seems such a thing does not exist, but please confirm.</p> <p>I read some similar questions <a href="https://stackoverflow.com/questions/17914737/can-python-objects-have-nested-properties">here</a> and <a href="https://stackoverflow.c...
<python><python-3.x><class><attributes>
2024-10-11 18:47:34
1
1,329
Chuck
79,079,387
23,260,297
Applying styles to different columns in table
<p>I am getting an error when trying to apply a color to specific columns when creating a table with reportlab.</p> <p>Here is my entire script for a reproducible example (you will need to put an output path on line 109):</p> <pre><code>import pandas as pd from datetime import datetime from reportlab.platypus import Fr...
<python><pandas><reportlab>
2024-10-11 18:34:16
1
2,185
iBeMeltin
79,079,203
11,638,153
How to combine multiple docx files into a single in python
<p>I combined multiple text files into a single text file using simple code:</p> <pre><code>with open(&quot;Combined_file.txt&quot;, 'w') as f1: for indx1, fil1 in enumerate(files_to_combine): with open(files_to_combine[indx1], 'r') as f2: for line1 in f2: f1.write(line1) ...
<python><python-3.x><ms-word><python-docx>
2024-10-11 17:22:45
1
441
ewr3243
79,079,170
3,785,010
PyQt6 failure in Python 3.13.0 - ModuleNotFoundError: No module named PyQt6.sip
<p>The following simple example fails at line 2, the import, when run with Python 3.13.0 and PyQt6 6.7.1 in October of 2024:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt6.QtWidgets import QApplication, QWidget app = QApplication(sys.argv) w = QWidget() w.resize(250, 200) w.setWindowTitle('...
<python><python-3.x><pyqt6><python-3.13>
2024-10-11 17:10:45
1
1,109
IntelligenceGuidedByExperience
79,079,142
1,016,784
Intermittently losing ContextVar when passing from parent to child thread
<p>I have a subclass of <code>Thread</code> that I use across my project. In this class, I pass in the ContextVar manually. However, at times (once or twice a day), I notice that the ContextVar in the child thread is not set (reverted to a default value).</p> <pre class="lang-py prettyprint-override"><code>class MyThre...
<python><python-3.x><multithreading><python-multithreading><python-contextvars>
2024-10-11 17:01:35
1
1,240
Kyuubi
79,078,996
4,048,657
How to optimize a single index in a PyTorch tensor?
<p>I have code like this optimizing an (N,3) tensor.</p> <pre class="lang-py prettyprint-override"><code>deform_verts = torch.full(verts_shape, 0.0, device=device, requires_grad=True) optimizer = torch.optim.SGD([deform_verts], lr=5e-2, momentum=0.9) </code></pre> <p>However, what I really want is to optimize a single ...
<python><pytorch>
2024-10-11 16:07:32
0
1,239
Cedric Martens
79,078,922
3,398,536
PKS12 pfx certificate doens't load in python playwright
<p>I'm using playwright python and the usage of PKS12 certificates seems not be working properly.</p> <p>We try to follow the <a href="https://playwright.dev/python/docs/release-notes#version-146" rel="nofollow noreferrer">playwright documentation</a> and this example from <a href="https://stackoverflow.com/a/78943350/...
<python><playwright><playwright-python>
2024-10-11 15:46:43
2
341
Iron Banker Of Braavos
79,078,889
19,502,111
What is the difference between Dropout(1.0) and stop_gradient?
<p>Consider these two architectures:</p> <pre><code>prev_layer -&gt; dropout 1.0 -&gt; next_layer (output layer) prev_layer -&gt; stop_gradient -&gt; next_layer (output layer) </code></pre> <p>As gradients flow from the output layer to the input, both must produce the same behavior where <code>prev_layer</code> weights...
<python><arrays><numpy><tensorflow><keras>
2024-10-11 15:36:08
1
353
Citra Dewi
79,078,880
13,031,996
Vectorised linear interpolation where x, xp and yp are all 2D
<p>I have a similar issue to <a href="https://stackoverflow.com/questions/49713617/linear-interpolation-of-two-2d-arrays?noredirect=1&amp;lq=1">Linear interpolation of two 2D arrays</a>.</p> <p>But in my case x, xp and yp are all 2 dimensional. For instance:</p> <pre><code>import numpy as np x = np.array([[2, 3], [1, ...
<python><numpy>
2024-10-11 15:32:13
2
957
Stefan
79,078,872
3,196,122
How to create schema with fixed values using pydantic
<p>I have a json that looks like the following, exported from pandas Dataframe:</p> <p><code>{&quot;columns&quot;: [&quot;x&quot;, &quot;y&quot;, &quot;z&quot;], &quot;data&quot;: [[0, 0, 0.5], [1, 1, null]]}</code></p> <p>This, I want to send to a FastAPI and validate using pydantic.</p> <ol> <li>How can I enforce tha...
<python><pandas><fastapi><pydantic>
2024-10-11 15:29:59
2
483
KrawallKurt
79,078,823
9,274,940
LangGraph Error - Invalid Tool Calls when using AzureChatOpenAI
<p>I'm following the LangGraph <a href="https://academy.langchain.com/courses/take/intro-to-langgraph/lessons/58239232-lesson-6-agent" rel="nofollow noreferrer">tutorial</a> (from LangGraph) and I'm getting an error when switching from &quot;ChatOpenAI&quot; to &quot;AzureChatOpenAI&quot;. This is the code example from...
<python><langchain><langgraph>
2024-10-11 15:14:09
0
551
Tonino Fernandez
79,078,703
23,260,297
Order columns in dataframe before converting to report lab
<p>I am creating a pdf report using report lab based on multiple pandas dataframes.</p> <p>The tables that are displayed in the pdf need to have to columns in a specific order.</p> <p>here is a sample dataframe:</p> <pre><code>df = pd.DataFrame({ 'Counterparty': ['foo', 'fizz', 'fizz', 'fizz','fizz', 'foo'], ...
<python><pandas><reportlab>
2024-10-11 14:45:12
2
2,185
iBeMeltin
79,078,700
19,648,465
Error when deploying Django/DRF backend on Google Cloud: No matching distribution found for Django==5.0.4
<p>I am trying to deploy my Django backend (using Django Rest Framework) on a Google Cloud VM instance. However, when I run <code>pip install -r requirements.txt</code>, I encounter the following error:</p> <pre><code>Collecting asgiref==3.8.1 Using cached asgiref-3.8.1-py3-none-any.whl (23 kB) Collecting attrs==23.2...
<python><django><linux><ubuntu><google-cloud-platform>
2024-10-11 14:44:55
1
705
coder
79,078,340
14,720,215
How to check type of Ellipsis
<p>I have really specific case, when I need to check types by <code>isinstance</code> in python. And in really rare cases I want to check that value is <code>Ellipsis</code>. For example lets get dict:</p> <pre class="lang-py prettyprint-override"><code>customer_ids_map = { &quot;1&quot;: &quot;aaa&quot;, &quot...
<python><python-3.x>
2024-10-11 12:59:06
1
1,338
Kirill Ilichev
79,078,329
8,467,078
Python typing specific substring type
<p>Is it possible to define a Type in Python that only allows strings starting (or ending) with a specific substring? Such that at runtime, it's still allow to pass any string, but a static type checker will only allow the specific substring.</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>special_s...
<python><python-typing>
2024-10-11 12:55:58
1
345
VY_CMa
79,078,313
8,261,345
Docker is downgrading SSL for MySQL connection
<h3>The server</h3> <p>I have a MySQL server v8.4 running in Google Cloud with <code>skip-name-resolve</code>. It requires SSL connections, but without trusted client certificates.</p> <p>I have a user configured on the server to connect from any IP: <code>'myuser'@'%'</code>.</p> <p>I have verified the user can connec...
<python><ssl><libmysqlclient>
2024-10-11 12:51:58
1
694
Student
79,078,306
12,466,687
Unable to install python-poppler on Windows for pdftotext
<p>I am trying to install poppler on Windows for Python as I want to use pdftotext.</p> <p>I have referred to several SO posts like:</p> <ul> <li><a href="https://stackoverflow.com/questions/52336495/cannot-install-pdftotext-on-windows-because-of-poppler">cannot install pdftotext on windows because of poppler</a></li> ...
<python><pdftotext><poppler>
2024-10-11 12:50:28
1
2,357
ViSa
79,078,287
8,040,369
Groupby a df column based on other column and add a default value to everylist
<p>I have an df which has 2 columns lets say Region and Country.</p> <pre><code>Region Country ================================ AMER US AMER CANADA APJ INDIA APJ CHINA </code></pre> <p>I have grouped the unique Country list for each Region using the code and o/p like below:</p> <pre><code...
<python><python-3.x><pandas>
2024-10-11 12:44:45
1
787
SM079
79,078,271
313,768
Why is lstsq such a poor fit for this case?
<p>I am attempting to produce a plane of best fit through a locus of points in an RGB colour space. These points are:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; colours array([[ 0, 0, 0], [255, 255, 255], [120, 136, 97], [135, 129, 86], [ 93, 67, 31], [2...
<python><numpy><linear-regression><linear-algebra>
2024-10-11 12:40:49
0
16,660
Reinderien
79,078,236
3,753,826
Capturing Matplotlib coordinates with mouse clicks using ipywidgets in Jupyter Notebook
<h1>Short question</h1> <p>I want to capture coordinates by clicking different locations with a mouse on a Matplotlib figure inside a Jupyter Notebook. I want to use <code>ipywidgets</code> <strong>without</strong> using any Matplotlib magic command (like <code>%matplotlib ipympl</code>) to switch the backend and <stro...
<python><numpy><matplotlib><jupyter-notebook><ipywidgets>
2024-10-11 12:34:11
2
17,652
divenex
79,078,033
4,262,344
yield from with a Generator class
<p>Due to needing a self reference inside the generator I have Generator classes instead of generator functions. But I also want to use &quot;yield from&quot; like:</p> <pre><code>def gen1(): yield &quot;foo&quot; def gen2(): t = gen1() yield from t yield &quot;bla&quot; for i in gen2(): print(i) ...
<python><generator>
2024-10-11 11:31:03
1
12,446
Goswin von Brederlow
79,077,951
21,185,825
Class is in another directory - returns 0 tests
<p>I want to create different classes for my tests. But when I run my test unit, it does not run the test in my test class. The <code>setUp</code> function is never reached and zero tests are made.</p> <pre class="lang-none prettyprint-override"><code>python -m unittest discover -s src -p &quot;tests.py&quot; Ran 0 te...
<python><python-unittest>
2024-10-11 11:09:30
2
511
pf12345678910
79,077,824
3,961,495
How to plot bar graphs with pandas using cut function and interval when NaNs are involved?
<p>I'm wrestling with the following:</p> <p>I have a dataframe with 2 columns of float values that may include NaNs.</p> <p>For example:</p> <pre><code>In [5]: df = pd.DataFrame({'vals1': [10,20,25,15,np.nan, 2], 'vals2': [5, 11, 12, np.nan, np.nan, np.nan]}) In [6]: df Out[6]: vals1 vals2 0 10.0 5.0 1 20....
<python><pandas><matplotlib><nan><binning>
2024-10-11 10:29:46
1
3,127
Ytsen de Boer
79,077,781
4,245,090
How can I to use Python with Selenium to run automatically a website (chrome) in the background when I want to press a button and download?
<p>I would like to create an automated program in python with the help of selenium that opens a website, navigates to a section where I press a button and downloads the data. If the program is not running in the background, it works fine (then I don't use the <code>chrome_options.add_argument(&quot;--headless=old&quot;...
<python><selenium-webdriver><button><background>
2024-10-11 10:16:09
1
627
Sevi
79,077,734
5,269,892
Pandas missing value representation in aggregated dataframe
<p>When applying an aggregation to a grouped pandas DataFrame, the aggregated output appears to contains different values for aggregated all-missing-value-columns, depending on the type of the dataframe column. Below is a minimal example, containing one non-missing-value (an integer, a string and a tuple), one <code>Na...
<python><pandas><aggregate><nan><nonetype>
2024-10-11 10:01:31
1
1,314
silence_of_the_lambdas
79,077,664
2,086,511
Weird subprocess.Popen pipe issue
<p>I am coding a Turkish AI assistant. In order to chat with the language model, I load the language model into the AI. The voice questions I ask are converted to text and entered as input, and the output is read aloud. Unfortunately, the above code snippet does not work as I want. Normally, I need to be able to send i...
<python><shell><command-line><subprocess><pipe>
2024-10-11 09:41:37
1
328
kenn
79,077,528
451,878
Use JWT token with FactoryBoy's tests and FastAPI
<p>I've some problems to find examples to use FactoryBoy (with FastAPI) with JWT token.</p> <p>My integration fastapi+jwt is working. But, testing... I'm confused.</p> <p>Here's my code :</p> <pre><code>def fake_oauth2_token(): client_token = TestClient(app) response = client_token.post( &quot;api/auth...
<python><fastapi><factory-boy>
2024-10-11 09:01:36
1
1,481
James
79,077,213
2,300,597
Anaconda3 - downgrade python version to 3.11.8 in the current (base) environment
<p>Windows 11 OS</p> <p>I installed a clean Anaconda3 platform just 3 days ago. It came with Python 3.12.4. But it seems some things (PySpark related) just don't work with python 3.12.4.</p> <p>For example, I am getting a similar error like this one here, when I try running some PySpark examples.</p> <p><a href="https:...
<python><anaconda><conda><anaconda3>
2024-10-11 07:38:18
0
39,631
peter.petrov
79,077,054
2,156,537
Creating many hard links to a single file gradually slows down hard link creation
<p>I've written a backup script in Python that uses hard links to create full backups while saving a lot of space. When a new backup is made, the most recent backup is compared to the source files. If a source file has not changed (as determined by the file size and the modification time) since the last backup, a hard ...
<python><windows><backup><ntfs><hardlink>
2024-10-11 06:40:19
0
617
Mark H
79,076,840
17,889,492
matplotlib path patch outside axes
<p>I want to create a tab for a plot. I have a <code>PathPatch</code> object that I would like to place just above the top spine (i.e. outside the plotting area). Secondly I would like a method that dynamically adjusts the width of the path in accordance with the width of the text.</p> <pre><code>import matplotlib.pypl...
<python><matplotlib>
2024-10-11 04:51:43
2
526
R Walser
79,076,445
4,377,521
It appears that Dramatiq with asyncio operates with just a single worker
<p>I am trying to run several jobs in parallel.<br> When I define actor as a sync function it uses different workers.<br> But when functions is <code>async</code> it uses only one thread(worker).<br></p> <p>I generally understand difference between asynchronous parallelism and <code>multithreading</code>/<code>multipro...
<python><dramatiq>
2024-10-10 23:43:55
1
2,938
sashaaero
79,076,434
15,848,470
How to create a sequence of floats in Polars of type List[f64]
<p>I have a polars List[f64], column &quot;a&quot;. I want to create a new List[f64], column &quot;b&quot;, which is a sequence from the min to the max of that row's list in column a, in intervals of 0.5, inclusive. So for a row with a column &quot;a&quot; list of <code>[0.0, 3.0, 2.0, 6.0, 2.0]</code>, the value in co...
<python><dataframe><python-polars>
2024-10-10 23:35:59
2
684
GBPU
79,076,277
5,978,560
Find truncated strings for provided word in python
<p>I am attempting to do a string comparison that checks for common truncated words in the string while doing a word by word comparison.</p> <p>Does a python library exist for finding variations of truncated words in the english language?</p> <pre><code>if &quot;inc&quot; in truncated_stings_for(&quot;Incorporated&quot...
<python>
2024-10-10 22:00:32
0
526
brw59
79,076,276
14,256,643
Python scrapy playwright getting error ValueError: Page.evaluate: The future belongs to a different loop
<p>here is full error logs</p> <pre><code>line 514, in wrap_api_call raise rewrite_error(error, f&quot;{parsed_st['apiName']}: {error}&quot;) from None ValueError: Page.evaluate: The future belongs to a different loop than the one specified as the loop argument </code></pre> <p>I am trying to click on submit button...
<python><python-3.x><web-scraping><scrapy>
2024-10-10 22:00:11
1
1,647
boyenec
79,076,160
3,127,764
Which Emojis are supported by the Zendesk API? (It looks like a SUBSET of the ones the web UI supports!)
<p>I use <a href="https://developer.zendesk.com/api-reference/ticketing/tickets/ticket_comments/" rel="nofollow noreferrer">Zendesk (&quot;ZD&quot;) developer API to update tickets with comments</a>. I frequently put markdown into ticket comments (using the &quot;body&quot; item and not the &quot;html_body&quot; item w...
<python><emoji><zendesk-api>
2024-10-10 21:07:51
1
6,307
HaPsantran
79,075,956
219,153
How to improve random access of a video frame with Python?
<p>I'm using <code>pims</code> library (<a href="https://github.com/soft-matter/pims" rel="nofollow noreferrer">https://github.com/soft-matter/pims</a>) to access frames from .MOV file with over 25K frames, 3840 Γ— 2160, H.264 (High Profile), 60fps.</p> <pre><code>import pims from time import perf_counter video = pims....
<python><ffmpeg><video-capture>
2024-10-10 19:51:10
1
8,585
Paul Jurczak
79,075,821
8,734,075
Finding the difference in rows of a table, and returning only the columns where values are different
<p>I'm working on analyzing some data. I have a way of doing this in excel, but it's slow and too much manual work. I'd like to find a more effective way to find what I'm looking for.</p> <p>Here's the scenario: I have a DB table (multiple, but let's just focus on a single one for now) that has many rows and many colum...
<python><sql><pandas><database><postgresql>
2024-10-10 19:05:57
3
374
MKUltra
79,075,777
4,048,657
How can I run backward() on individual image pixels without causing an error of trying to backward through the graph a second time?
<p>I have this code</p> <pre class="lang-py prettyprint-override"><code>... vertex_id = 275 deform_verts.retain_grad() # input predicted_silhouette.retain_grad() # output impact_img = torch.zeros_like(predicted_silhouette, requires_grad=False) for i in range(image_size): for j in range(image_size): pixel = pr...
<python><pytorch>
2024-10-10 18:53:43
1
1,239
Cedric Martens
79,075,630
12,005,060
Vercel Deployment Not Creating Tables in PostgreSQL with FastAPI/SQLModel
<p>I'm deploying a FastAPI app with SQLModel on Vercel. The environment variable <code>DATABASE_URL</code> is set correctly in Vercel, and the app is able to connect to the PostgreSQL database hosted on Supabase.</p> <p>However, the problem is that during deployment, tables are not being created in the database. Despit...
<python><postgresql><sqlalchemy><fastapi><sqlmodel>
2024-10-10 17:58:36
0
325
Mubashar Hussain
79,075,564
6,141,238
What is the best way to fit a quadratic polynomial to p-dimensional data and compute its gradient and Hessian matrix?
<p>I have been trying to use the scikit-learn library to solve this problem. Roughly:</p> <pre><code>from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression # Make or load an n x p data matrix X and n x 1 array y of the corresponding # function values. poly = Polynomial...
<python><scikit-learn><linear-regression><polynomials><hessian-matrix>
2024-10-10 17:32:12
3
427
SapereAude
79,075,522
952,161
How to efficiently import many modules while providing a "one module index"
<p>I have a project with the current structure:</p> <pre><code>β”œβ”€β”€ program.py └── interfaces β”œβ”€β”€ domain1.py β”œβ”€β”€ domain2.py └── index.py </code></pre> <p>with <em>interfaces/index.py</em>:</p> <pre><code>from . import domain1 from . import domain2 </code></pre> <p><em>interfaces/domain1.py</em>:</p> <pre><co...
<python><import>
2024-10-10 17:19:36
1
433
Fabrice E.
79,075,509
1,275,942
Remove packages that do not exist anymore and can be edited in Pip
<p>I install a local package in editable mode.</p> <p><code>pip install -e ~/subdir/test_example</code></p> <p>Then, I switch branches to a branch where <code>subdir/test_example/pyproject.toml</code> does not exist yet.</p> <p><code>git switch master</code></p> <p>Now Pip is in a broken state:</p> <pre><code>$ pip fre...
<python><pip><python-packaging>
2024-10-10 17:14:10
0
899
Kaia
79,075,233
9,878,263
Launch a subset of docker compose services (containers). Use a script?
<p>How to start only some containers from the list of services present in a docker-compose.yml file?</p> <p>MS Visual Studio supports it, see <a href="https://learn.microsoft.com/en-us/visualstudio/containers/launch-profiles?view=vs-2022" rel="nofollow noreferrer">here</a>.</p> <p>This question has already been asked: ...
<python><powershell><docker-compose>
2024-10-10 15:53:27
0
1,591
Mathieu CAROFF
79,075,095
10,518,698
How to get site id of One Drive for Business with MS Graph API
<p>I'm struggling to get site id for my one drive link with MS Graph API.</p> <p>This is my one drive link - <code>https://sharedspace-my.sharepoint.com/:f:/r/personal/naruto/Documents/Shared%20Folders/hinata?csf=1&amp;web=1&amp;e=M3GWjd</code></p> <p>and I took the host and site url from the above link.</p> <pre><code...
<python><azure><microsoft-graph-api><onedrive>
2024-10-10 15:12:01
1
513
JSVJ
79,074,576
72,813
Different PyInstaller behaviour when signing app using QWebEngineView
<p>I have an app using a QWebEngineView widget, and when I create a distribution package with PyInstaller, I get a different behaviour if I sign the app or not. I created a small reproducible example (<em>tester.py</em>):</p> <pre><code>import time import sys from PySide6.QtCore import QUrl from PySide6.QtWebEngineWidg...
<python><pyinstaller><pyside6><qwebengineview>
2024-10-10 13:14:36
1
448
nicolaum
79,073,992
4,636,579
How to implement a preprocessor for code in python
<p>I have some code an want to scan i line by line. The problem is that in code, statements are build up over several lines, like</p> <pre><code>def UART(ONE): ONE = UUUU001 + 4 print(ONE) </code></pre> <p>I would like to have a tool which would scan the code and prepare it f...
<python><abstract-syntax-tree>
2024-10-10 10:36:59
0
681
Coliban
79,073,763
11,814,996
facebook/m2m100_418M model - how to translate longer sequences of text
<p>I have this extracted the following text from Wikipedia's Wiki (<a href="https://en.wikipedia.org/wiki/Wiki" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Wiki</a>),</p> <pre><code>A wiki is a form of hypertext publication on the internet which is collaboratively edited and managed by its audience directly...
<python><facebook><nlp><huggingface-transformers><machine-translation>
2024-10-10 09:45:20
0
3,172
Naveen Reddy Marthala
79,073,468
9,974,205
How to handle repeated events in a time range intersection calculation in Pandas?
<p>I am working on a Python script using Pandas to analyze event data. My goal is to calculate the intersection of active events.</p> <p>My code works fine if the same event doesn't happen twice. However, if it happens twice, my code returns empty dataframes.</p> <p>Here it is the defective code:</p> <pre><code>import ...
<python><pandas><dataframe><data-analysis><intersection>
2024-10-10 08:41:16
1
503
slow_learner
79,073,176
4,505,998
Speeding up Dataset.__getitems__
<p>I have a model with a <code>forward</code> function that receives optional parameters, like this:</p> <pre class="lang-py prettyprint-override"><code>class MyModel(nn.Module): ... def forward(self, interactions: torch.Tensor, user_features: Optional[torch.Tensor] = None): &quot;&quot;&quot; Where _N_ ...
<python><pytorch><pytorch-dataloader>
2024-10-10 07:23:08
1
813
David DavΓ³
79,073,159
9,542,989
MS Teams Bot Cannot Respond on Web Chat
<p>I have created a bot via MS Teams. I registered the bot in MS Bot Framework portal and then created an app that is connected to this bot on Teams.</p> <p>I am able to chat with my bot and it responds without an issue. However, it does not work when I try to use the web chat option that is provided to test the bot in...
<python><botframework><microsoft-teams>
2024-10-10 07:14:08
0
2,115
Minura Punchihewa
79,073,040
6,455,731
How to type partial application?
<p>How to type partial application (preferably with 3.12 syntax)? With the following simple implementation:</p> <pre class="lang-py prettyprint-override"><code>class simple_partial: def __init__(self, f: Callable, *args, **kwargs) -&gt; None: self.f = f self.args = args self.kwargs = kwargs ...
<python><python-typing>
2024-10-10 06:45:43
1
964
lupl
79,072,552
1,230,724
Cumulative sum with overrides on condition
<p>I'm trying to calculate the balance (the level) of an inventory over time and have incoming and outgoing quantities as input (and a category for each type of inventory). Usually I would calculate <code>incoming - outgoing</code> and carry over to the next period (cumulative sum), but in this case an added difficulty...
<python><pandas><dataframe><cumulative-sum>
2024-10-10 02:25:48
1
8,252
orange
79,072,308
2,595,216
Build Python C extension with cibuildwheel
<p>I try build/compile wheels for <code>lupa</code> under windows. I got one working job in github-action <a href="https://github.com/emcek/pyi/actions/runs/11264308367" rel="nofollow noreferrer">github-action</a> 'manual' for Python 3.6.</p> <p>I needed replace original <code>setup.py</code> to be able build <code>lua...
<python><visual-studio><github-actions><lupa>
2024-10-09 23:15:33
1
553
emcek
79,072,229
8,414,875
django-haystack elasticsearch spanish special chars (accents)
<p>I'm using Django-haystack 3.3.0 over Django 4.x, and use Elasticsearch 7.17.24 as backend.</p> <p>I'm dealing with texts in Spanish, so for example I'm index the text:</p> <pre><code>El corazΓ³n del mar </code></pre> <p>And when I'm trying to search:</p> <pre><code>corazon </code></pre> <p>I got <code>0</code> result...
<python><django><elasticsearch><django-haystack>
2024-10-09 22:22:29
1
347
juanbits
79,072,098
275,088
Solving Leetcode's "1813. Sentence Similarity III" using regexes
<p>I'm trying to solve this <a href="https://leetcode.com/problems/sentence-similarity-iii/description/" rel="nofollow noreferrer">problem</a> from Leetcode using regexes (just for fun):</p> <blockquote> <p>You are given two strings <code>sentence1</code> and <code>sentence2</code>, each representing a sentence compose...
<python><regex>
2024-10-09 21:18:59
2
16,548
planetp
79,071,911
1,492,613
in python how can I annotate the type of Literal type?
<p>I basically want to have a argument that accept the literal object as input</p> <pre class="lang-py prettyprint-override"><code>from typing import Literal, TypeVar, get_args MyLiteral=Literal[&quot;a&quot;, &quot;b&quot;] def func1( cls_literal # how to annotate here? ): print(get_args(cls_literal)) ...
<python><python-typing>
2024-10-09 20:10:54
2
8,402
Wang
79,071,739
20,591,261
Optimizing Variable Combinations to Maximize a Classification
<p>I am working with a dataset where users interact via an app or a website, and I need to determine the optimal combination of variables <code>(x1, x2, ... xn)</code> that will maximize the number of users classified as &quot;APP Lovers.&quot; According to the business rule, a user is considered an &quot;APP Lover&quo...
<python><optimization><python-polars>
2024-10-09 19:10:51
3
1,195
Simon
79,071,274
6,458,245
What is wrong with this NumPy linear algebra matrix rank calculator?
<p>Consider:</p> <pre><code>import numpy as np from numpy.linalg import matrix_rank for i in range(1, 70): y = np.linspace(0,i, i+1) y = 2 ** y x = np.ones(i+1) matrix = np.stack([x,y]) print(matrix_rank(matrix)) </code></pre> <p>After 48, I see the rank shifting from 2 to 1. How do I fix this?</p>
<python><numpy><linear-algebra>
2024-10-09 16:45:57
1
2,356
JobHunter69
79,071,043
17,580,381
Shared memory sizing for a numpy array
<p>In the example seen on <a href="https://superfastpython.com/numpy-array-sharedmemory/" rel="nofollow noreferrer">superfastpython.com</a>, the size of a shared memory segment to be used to support a 1-dimensional numpy array is calculated as the number of elements multiplied by the data type size.</p> <p>We know that...
<python><arrays><numpy><shared-memory>
2024-10-09 15:38:56
1
28,997
Ramrab
79,071,022
2,881,888
I am not able to create a python module that correctly supports type checking
<p>I have created a python module MyModule that is entirely written with typing support (for a matter of maintenance).</p> <p>But when I write a script that uses MyModule, let's say MyScript.py:</p> <pre><code>from MyModule import MyClass, MyOtherClass if __name__ == &quot;__main__&quot;: a = MyClass(1, 2) a =...
<python>
2024-10-09 15:33:43
2
1,401
Louis Caron
79,070,976
11,266,889
request from Django to djangorestframework from the same Docker Container timeouts
<p>I have 2 containers with docker compose:</p> <pre><code>services: web: container_name: web build: context: . dockerfile: Dockerfile command: bash -c &quot;python manage.py makemigrations &amp;&amp; python manage.py migrate &amp;&amp; python manage.py collectstatic --no-in...
<python><django><docker><django-rest-framework>
2024-10-09 15:21:17
0
305
pipikej
79,070,891
6,480,757
Vectorize the operation of finding the lowest value of a column in dataframe groups defined by another column
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame( data = [ [0,0], [1,0], [2,2], [3,3], [4,3], [5,3], [6,4], [7,4], ], columns = ['day_count', 'level'] ) </code></pre> <p>I am wondering if there is a vectorizable way to calculate ...
<python><pandas><group-by><vectorization>
2024-10-09 14:57:58
0
544
Mike
79,070,591
5,181,947
Saving styled pandas dataframe as image throws ValueError
<p>I have python code like so:</p> <pre><code>import dataframe_image as dfi def color_negative_red(val): color = f'rgba(255, 50, 50, {min(1, val / 350)})' return f'background-color: {color}' styled_df = df.style.applymap(color_negative_red, subset=pd.IndexSlice[:, pd.IndexSlice['Active (bps)', :]]) dfi.export(...
<python><pandas>
2024-10-09 13:48:43
1
1,924
Ankur
79,070,422
7,550,314
Poetry - ModuleNotFoundError: No module named jwt
<p>Added PyJWT pkg to the project but getting error that the module is not found. I added the pkg using the poetry add command from a private repository.</p> <pre><code>from jwt import decode, get_unverified_header alg = get_unverified_header(token)[&quot;alg&quot;] decoded_token = decode(token, algorithms=[alg], optio...
<python><python-poetry><pyjwt>
2024-10-09 13:16:19
1
415
Faisal
79,070,395
352,290
How to avoid duplicate words within an array
<p>How to avoid duplicate words within an array. In the following scenario</p> <p><code>First scenario:</code> I want all 3 players to be present in the output including <code>Phil</code>. <code>Phil</code> is a subset of <code>Phillies</code> so it should not be removd from the output.</p> <p><code>Second scenario:</c...
<python>
2024-10-09 13:10:49
1
1,360
user352290
79,070,211
7,971,750
Local package isn't recognized even with __init__.py
<h2>Original question</h2> <p>Current project setup is</p> <pre><code>project/ β”œβ”€ ams/ β”‚ β”œβ”€ __init__.py β”‚ β”œβ”€ common/ β”‚ β”‚ β”œβ”€ dataclasses.py β”‚ β”‚ β”œβ”€ __init__.py β”œβ”€ entry_point/ β”‚ β”œβ”€ bar_api/ β”‚ β”‚ β”œβ”€ swagger/ β”‚ β”‚ β”‚ β”œβ”€ main.yaml β”‚ β”‚ β”œβ”€ __init__.py β”‚ β”œβ”€ run.py β”‚ β”œβ”€ __init__.py </code></pre> <p>with <code>run.p...
<python><pip><python-3.8>
2024-10-09 12:25:15
1
322
bqback
79,069,996
964,491
Feedparser errors during SSl read operation when accessing NASDAQ RSS Feeds
<p>By utliizing Python 3.12, Feedparser 6.0.11, ca-certificates installed</p> <p>When attempting to read this RSS feed: <a href="https://www.nasdaq.com/feed/rssoutbound?category=Financial+Advisors" rel="nofollow noreferrer">https://www.nasdaq.com/feed/rssoutbound?category=Financial+Advisors</a>. Feedparser library retu...
<python><python-3.x><ssl><feedparser>
2024-10-09 11:27:37
1
2,563
Dan