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
⌀
77,982,938
1,499,402
Polars idiomatic way of aggregating n consecutive rows of a data frame
<p>I'm new to Polars, and I ended up writing this code to compute some aggregating expression over segments of <code>n</code> rows:</p> <pre><code>import polars as pl df = pl.DataFrame({&quot;a&quot;: [1, 1, 3, 8, 62, 535, 4213]}) ( df.with_columns(index=pl.int_range(pl.len(), dtype=pl.Int32)) .group_by_dynam...
<python><aggregate><python-polars><rolling-computation>
2024-02-12 16:37:11
2
4,888
Stefano M
77,982,766
5,589,640
Delete word that follows a specific word
<p>I have e-mails and transcripts in German from conversations with customers. They include personal identifiable information that I need to remove. So it is a data anonymisation task. The text would be <em>&quot;Hello Mr. Smith&quot;</em>, <em>&quot;Dear Mr Smith&quot;</em>, <em>&quot;Hello Lisa&quot;</em> etc. follow...
<python><regex>
2024-02-12 16:05:32
2
625
Simone
77,982,709
4,269,851
How to structure custom file handleing class in python?
<p>Writing my file handling class in python I came across this problem file getting closed before I can use it. Guess I can't use <code>with</code> inside class. What then is the safest way to open/close file to avoid it staying open in case my code crashes before I have chance to close the file?</p> <p>Clarification: ...
<python><file><class><with-statement>
2024-02-12 15:56:23
2
829
Roman Toasov
77,982,694
8,888,469
How to join two dataframes for a particular condition for the joining keys
<p>I have two datframes <code>df1</code> and <code>df2</code> and I want to join them and create new dataframe df3 .</p> <p>I want join work even if <code>dest</code> column of <code>df1</code> has one match in <code>dest</code> in column of <code>df2</code>.</p> <p>Join key is pair <code>org,dest</code></p> <p><strong...
<python><pandas><join>
2024-02-12 15:54:27
1
933
aeapen
77,982,614
1,961,574
django: Using dictionaries as values for models.Choices
<p>I'm trying to save a frequency to the database, which consists of an amount (e.g. 2) and a unit (e.g. months). The user must be given a choice, too. The idea is to pass this to a class that can use this info to calculate frequency (similar to, but not quite <code>timedelta</code>, however this is beyond the scope of...
<python><django>
2024-02-12 15:42:17
1
2,712
bluppfisk
77,982,303
13,086,128
Select all integer columns except a few in python-polars?
<p>Consider I have a dataframe:</p> <pre><code>import polars as pl import polars.selectors as cs df = pl.DataFrame( { 'p': [1, 2, 1, 3, 1, 2], 'x': list(range(6, 0, -1)), 'y': list(range(2, 8)), 'z': [3, 4, 5, 6, 7, None], &quot;q&quot; : list('abcdef') } ) </code></pre...
<python><python-3.x><dataframe><python-polars>
2024-02-12 14:50:01
2
30,560
Talha Tayyab
77,982,289
2,985,155
Scikit-learn Gaussian Process Regressor returns 2d vector instead of 2d Covariance matrix
<p>I'm fitting data (2d input, <strong>2d output</strong>) to a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.gaussian_process.GaussianProcessRegressor.html" rel="nofollow noreferrer">Gaussian Process from Sklearn</a> but when trying to get the covariance matrix I'm getting a 2d vector, not a matri...
<python><scikit-learn><gaussian-process><covariance-matrix>
2024-02-12 14:48:19
0
473
JackS
77,982,046
1,711,271
how to select all columns from a list in a polars dataframe
<p>I have a dataframe</p> <pre><code>import polars as pl import numpy as np df = pl.DataFrame( { &quot;nrs&quot;: [1, 2, 3, None, 5], &quot;names&quot;: [&quot;foo&quot;, &quot;ham&quot;, &quot;spam&quot;, &quot;egg&quot;, None], &quot;random&quot;: np.random.rand(5), &quot;groups&qu...
<python><select><python-polars>
2024-02-12 14:11:06
3
5,726
DeltaIV
77,981,863
11,861,874
Pandas data frame to Table in Word doc using Python
<p>I am inserting the pandas data frame as a table in a Word document using Python. I am using docx library but somehow while running a loop that creates three data frames it updates the same values in all of them, can you please let me know what's missing here?</p> <pre><code>import pandas as pd from docx import Docum...
<python><dataframe><datatable><python-docx>
2024-02-12 13:40:40
0
645
Add
77,981,774
4,396,229
ECIES Encryption for python and iOS
<p>I'm attempting to implement ECIES encryption in iOS Swift which has to be compatible with server python, but I'm encountering compatibility issues. I followed the instructions from an article for both Python and iOS, but when decrypting, it throws an error. Is there a library available that supports ECIES encryption...
<python><ios><swift><encryption-asymmetric><ecies>
2024-02-12 13:24:33
0
780
Steven
77,981,751
8,811,098
Import other class does not work in Jupyter Notebook
<p>I have a file named <strong>rentalcar.ipynb</strong> with class inside named <strong>rentalcar</strong> I am trying to import this class using other file <strong>customer.ipynb</strong>,</p> <p>I am still getting this error</p> <pre><code> --------------------------------------------------------------------------- M...
<python><jupyter-notebook><jupyter-lab>
2024-02-12 13:20:19
4
386
Nadin Martini
77,981,735
3,943,162
"agent_node() got multiple values for argument 'agent'" when extract langchain example code from notebook
<p>I'm running the example LangChain/LangGraph code for &quot;Basic Multi-agent Collaboration.&quot; I got the example from <a href="https://github.com/langchain-ai/langgraph/blob/main/examples/multi_agent/multi-agent-collaboration.ipynb/" rel="nofollow noreferrer">here</a> (Github). There is also a <a href="https://bl...
<python><jupyter-notebook><agent><py-langchain><langgraph>
2024-02-12 13:17:39
1
1,789
James
77,981,596
19,299,757
How to provide custom message in pytest-html-reporter
<p>Is there a way to provide custom message for each test when I use [pytest-html-reporter]<a href="https://pypi.org/project/pytest-html-reporter/" rel="nofollow noreferrer">https://pypi.org/project/pytest-html-reporter/</a>?</p> <p>I tried both print and logging statement for my tests but they are not shown in the rep...
<python><pytest><pytest-html><pytest-html-reporter>
2024-02-12 12:54:28
2
433
Ram
77,981,582
3,455,071
RP Zero with new system and caemra module 3 - camera libs incompatibility
<p>I am trying to refactor old camera code in my RP Zero. It looks like everything's changed in new version of the OS and old libs are no longer there or incompatible.</p> <p>In the old code I could do this to create the stream:</p> <pre><code>import cv2 from imutils.video.pivideostream import PiVideoStream import imut...
<python><raspberry-pi><camera><raspberry-pi-zero><imutils>
2024-02-12 12:52:06
0
529
smoczyna
77,981,495
5,120,843
Is this an incorrect Mann-Whitney U statistic using Apache Commons?
<p>Using the staology.com website, I did a Mann-Whitney test in both Java and in Python. Yet, the Java version appears to be incorrect or I did something wrong. The Python logic matches the website (<a href="https://www.statology.org/mann-whitney-u-test/" rel="nofollow noreferrer">https://www.statology.org/mann-whitney...
<python><java><statistics>
2024-02-12 12:38:02
1
627
Morkus
77,981,486
9,173,710
Float overflow in scipy quadrature
<p>I am trying to calculate the following function:</p> <p><a href="https://i.sstatic.net/2wHja.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2wHja.png" alt="formula" /></a></p> <p>For every point x I need to evaluate the integral numerically since it can't be solved analytically. (At least sympy and W...
<python><floating-point><integral><calculus><quad>
2024-02-12 12:36:51
2
1,215
Raphael
77,981,393
159,072
ValueError: generator already executing
<p>The following generator is throwing an exception.</p> <p>How can I resolve this issue?</p> <pre><code>import os import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split import autokeras as ak DATA_COLUMN_COUNT = 12 LABEL_COLUMN_INDEX = 2 FEATURE_START_INDE...
<python><tensorflow><neural-network><generator><auto-keras>
2024-02-12 12:17:56
1
17,446
user366312
77,981,352
567,059
Python logging filter being applied to all handlers when only added to one
<p>I am adding logging to a Python project, and I wish to log to both terminal and file. To do this I am using a <code>streamHandler</code> and a <code>fileHandler</code>.</p> <p>To make it easier to quickly differentiate between log levels, I wish to add colour to the <code>levelname</code> for the logs that are outpu...
<python><python-logging>
2024-02-12 12:11:54
1
12,277
David Gard
77,981,266
12,200,808
How to set dynamic version for tool.setuptools_scm in pyproject.toml
<p>I'm trying to test the <code>pyproject.toml</code> by building an example.</p> <p>If I deleted the line &quot;<code>[tool.setuptools_scm]</code>&quot;, the build will success, but adding that line, the build will fail with the following error.</p> <p><strong>Here is the pyproject.toml: /test/example/pyproject.toml</...
<python><ubuntu><setuptools><pyproject.toml><setuptools-scm>
2024-02-12 11:53:59
1
1,900
stackbiz
77,981,208
2,575,970
Create & Insert data with schema of Dataframe
<p>I have a csv that has 3300 attributes/columns. I cannot afford to create the columns manually in AZ SQL DB. I am looking out ways to automatically do it using Python. Came across to_sql and SQL Alchemy but does not look like it is working.</p> <blockquote> <p>Error; ArgumentError: Expected string or URL object, got ...
<python><sql-server><pandas><sqlalchemy><azure-sql-database>
2024-02-12 11:42:42
1
416
WhoamI
77,981,121
5,810,717
Using xpath and selenium to select a HTML element in Python
<p>Thanks for letting me ask my questions here. I am new to Selenium and XPath, just trying to scrape a not-so-simple website using Python.</p> <p>My questions are:</p> <ol> <li>Do you have an answer to my specific question on how to select the HTML element in question?</li> <li>Do you have any addition to the learning...
<python><selenium-webdriver><xpath><selenium-chromedriver>
2024-02-12 11:28:28
1
363
fußballball
77,980,972
1,711,271
merge groups of columns in a polars dataframe to single columns
<p>I have a polars dataframe with columns <code>a_0, a_1, a_2, b_0, b_1, b_2</code>. I want to convert it to a longer and thinner dataframe (3 x rows, but just 2 columns <code>a</code> and <code>b</code>), so that <code>a</code> contains <code>a_0[0], a_1[0], a_2[0], a_0[1], a_1[1], a_2[1],...</code> and the same for <...
<python><reshape><python-polars>
2024-02-12 11:00:30
3
5,726
DeltaIV
77,980,709
8,554,611
How do I tell PyCharm of the class variable created by a class decorator?
<p>Say, I have a decorator to make logging more straightforward:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar _T = TypeVar(&quot;_T&quot;, bound=type) def with_logger(cls: _T) -&gt; _T: from logging import getLogger cls.logger = getLogger(cls.__name__) return cls @wit...
<python><pycharm><mypy><python-decorators><python-typing>
2024-02-12 10:21:00
0
796
StSav012
77,980,617
1,762,051
Django field look up __date is not returning objects
<p>Why field lookup <code>__date</code> and <code>__month</code> are not returning any objects?</p> <pre class="lang-py prettyprint-override"><code>class MembershipPlanSubscription(TimeStampBaseModel): user = models.ForeignKey(to=User, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date =...
<python><django><django-models>
2024-02-12 10:01:57
2
10,924
Alok
77,980,601
2,563,981
Python threading basics on console application - Correct way to terminate thread/s
<p>I'm looking for the best way to handle a python console threading application with the possibility to exit at (say) Ctrl+C</p> <p>This is my code.</p> <pre><code>from threading import Thread import time import sys class MyPrint(Thread): def __init__(self): super(MyPrint, self).__init__() self....
<python><multithreading>
2024-02-12 09:59:50
0
429
Kite
77,980,560
10,117,858
Why is Merge Sort Performance LINEAR?
<p>I'm working on comparing sorting algorithms in Python. I've implemented the algorithms and a testing function that evaluates each algorithm on various input sizes, up to a very large maximum, in the hundreds of thousands. The execution times are saved for plotting later. As expected, Selection Sort exhibits a quadra...
<python><algorithm><sorting><mergesort>
2024-02-12 09:52:34
2
892
Niccolò Caselli
77,980,379
2,169,557
Is there an equivalent function to the b'' byte literal?
<p>I am working with a text file containing lines of data that include both ASCII and escaped byte data and I am trying to find a function in Python to encode the lines of text into bytes data for sending to another PC over UDP.</p> <p>The string I am trying to encode is captured OSC data and looks similar to this line...
<python><encoding><byte>
2024-02-12 09:16:47
1
1,877
Logic1
77,980,099
393,010
When can mypy infer the type of containers such as collections.Counter?
<p>Running this mypy gist (<a href="https://mypy-play.net/?mypy=latest&amp;python=3.12&amp;gist=58a8148f2c95c7a282a6f8a11ccd689a" rel="nofollow noreferrer">https://mypy-play.net/?mypy=latest&amp;python=3.12&amp;gist=58a8148f2c95c7a282a6f8a11ccd689a</a>)</p> <pre class="lang-py prettyprint-override"><code>from collectio...
<python><mypy><python-typing>
2024-02-12 08:16:35
1
5,626
Moberg
77,979,992
7,848,740
Export state_dict checkpoint from .pt model PyTorch
<p>I'm new to PyTorch and the whole model/AI programming.</p> <p>I have a library that needs a checkpoint in the form of a <em>state_dict</em> from a model to run.</p> <p>I've the <code>.pt</code> model (more preciously the <a href="https://github.com/NVIDIA/radtts" rel="nofollow noreferrer">radtts pre-trained model</a...
<python><pytorch><state-dict>
2024-02-12 07:55:47
1
1,679
NicoCaldo
77,979,686
16,896,291
Replacement for prev_execution_date as it is deprecated in airflow 2
<p>I am migrating airflow 1 pipelines on airflow 2 and stumbled across the deprecated <code>{{ prev_execution_date }}</code>.</p> <p>I am not sure what can be used instead.<br /> I found <code>prev_data_interval_start_success</code> and <code>prev_data_interval_end_success</code> but not sure which one to pick from the...
<python><airflow><jinja2><airflow-2.x>
2024-02-12 06:43:15
1
427
Hemant Sah
77,979,412
65,889
How to make the symlink behaviour of Python's os.walk deterministic across different file ssytem types
<p>I have a weird probelm with os.walk in Python 3. To illustrate let's have a directory <code>fs</code> with the following structure:</p> <pre><code>fs ├── data1.txt ├── data2.txt ├── data3.txt ├── dir │   ├── file1.txt │   ├── file2.txt │   └── file3.txt └── sym -&gt; dir </code></pre> <h5>Test 1: Directory on local ...
<python><filesystems><samba><os.walk><apfs>
2024-02-12 05:00:37
0
10,804
halloleo
77,979,354
544,982
Trouble passing AWS API Gateway query parameters to a Python AWS Lambda
<p>I have an API which I created using the AWS API Gateway and it has 2 URL String parameters so my GET call is in the following format</p> <pre><code>/endpoint?City=NYC&amp;State=NY </code></pre> <p>I am trying to capture both the City and the State URL String parameters in my Python Lambda function and when I print t...
<python><amazon-web-services><aws-lambda><aws-api-gateway>
2024-02-12 04:40:18
2
1,691
p0tta
77,979,317
4,407,597
HTTPSConnectionPool(host='',port=443) Max retries exceeded in apache and upstream prematurely closed connection while reading response header in nginx
<p>I am trying to fetch a government URL <a href="https://ahara.kar.nic.in/status2/" rel="nofollow noreferrer">https://ahara.kar.nic.in/status2/</a>, but I am getting errors like <strong>'Max retries exceeded with timed out'</strong> in Apache server and <strong>upstream prematurely closed connection while reading the ...
<python><apache><nginx><flask><python-requests>
2024-02-12 04:20:48
0
2,729
Gopala Raja Naika
77,978,953
11,618,586
Apply find_peaks() function using groupby() in a pandas dataframe
<p>I have a timeseries data that is grouped by in <code>ID</code> column.</p> <p>I tried using the following code:</p> <pre><code>def find_peaks_in_group(group): peaks, peak_properties = find_peaks(group['RFPower'], prominence=1, height=0.7) group['peaks'] = False group.loc[peaks, 'peaks'] = True group[...
<python><python-3.x><pandas><scipy>
2024-02-12 00:54:03
1
1,264
thentangler
77,978,885
9,983,652
how to install readline and ncurses using conda?
<p>I am using conda in win 10, trying to install below 2 packages and it never succeed. The error is</p> <p>PackagesNotFoundError: The following packages are not available from current channels:</p> <ul> <li>conda-forge::ncurses</li> </ul> <p>I did try different channels and it never work either.</p> <p>Thanks.</p> <pr...
<python><anaconda>
2024-02-12 00:21:04
1
4,338
roudan
77,978,720
2,933,113
SIGSEGV! error when trying to interact with Google Cloud Storage bucket w python
<p>I am writing a Google cloud function. Part of it's responsibility is to write files to a Cloud storage bucket. I believe I have bucket permissions set up and my service account, etc, but any time I try to interact with the bucket (upload files, or even bucket.exists()) I get the following error:</p> <blockquote> <p>...
<python><google-cloud-platform><google-cloud-functions><google-cloud-storage>
2024-02-11 22:52:15
1
1,456
Claytronicon
77,978,718
14,924,809
`Camelot` gives error for not having the correct arm64 architecture of Ghostscript
<p>I'm trying to use the python package <code>camelot</code> but get the following error, which I understand relates to my M1 mac I'm using:</p> <pre><code>&gt;&gt;&gt; import camelot &gt;&gt;&gt; import pandas &gt;&gt;&gt; data = camelot.read_pdf('path/to/pdf.pdf') Traceback (most recent call last): File &qu...
<python><arm64><python-camelot>
2024-02-11 22:51:16
1
510
Abigail
77,978,682
1,806,998
AWS Lambda - Database writes not reflected by subsequent read
<p>I have two lambda functions, one that inserts data into a database (create_user), and another (get_users) that reads it from a MySQL database hosted on AWS RDS.</p> <p>The database code for the create_user lambda looks like this (note the commit):</p> <pre class="lang-py prettyprint-override"><code>user = ... # get ...
<python><mysql><aws-lambda><amazon-rds><pymysql>
2024-02-11 22:36:48
1
2,243
jerney
77,978,501
11,586,490
Why isn't my instance_table.row_data object updating in Kivy MDDataTable?
<p>I'm creating a simple scorecard app but am having trouble accessing my cell values as they're updated.</p> <p>When I create the table, using the <code>create_table</code> method, I print the value of the columns through <code>column_sums</code> and all looks correct (a list of tuples with '0' in them). However, when...
<python><kivy><kivymd>
2024-02-11 21:30:24
1
351
Callum
77,978,368
893,254
How does one alter a topic configuration using incremental_alter_configs?
<p>I am trying to create a Python script to automate topic creation and configuration.</p> <p>I have managed to make the topic creation part work. I get a runtime error when trying to alter the configuration.</p> <pre><code>ValueError: expected non-empty list of ConfigEntry to alter incrementally in incremental_configs...
<python><apache-kafka><confluent-kafka-python>
2024-02-11 20:44:31
1
18,579
user2138149
77,978,226
2,386,113
What is a Contour plot (Matplotlib in Python) representing?
<p>I am confused about what my contour plot is representing. I have put the hardcoded value I obtained in my program for a <em>MWE</em> below. I have only 9 values (also plotted as scatter) but I don't understand how am I obtaining the diamond-shaped curves.</p> <pre><code>import numpy as np import matplotlib.pyplot as...
<python><matplotlib>
2024-02-11 20:00:09
1
5,777
skm
77,978,204
16,707,518
Speeding up a rolling sum calculation?
<p>I'm doing some work with a fairly large amount of (horse racing!) data for a project, calculating rolling sums of values for various different combinations of data - thus I need to streamline it as much as possible.</p> <p>Essentially I am:</p> <ul> <li>calculating the rolling calculation of a points field over time...
<python><pandas><rolling-computation>
2024-02-11 19:53:05
1
341
Richard Dixon
77,978,197
20,122,390
Should using cache between Python coroutines be blocking?
<p>I needed to use cache in a web application built in Python. Since I couldn’t directly use lru_cache in a coroutine, I built a simple decorator that would allow me to use it:</p> <pre><code>from asyncio import Lock, sleep async def acquire_lock_async(lock: Lock) -&gt; None: await lock.acquire() return ...
<python><async-await><python-asyncio>
2024-02-11 19:50:19
0
988
Diego L
77,978,139
7,981,566
Removing overlapping events from data table with intervals
<p>Given a large (&gt; 100MB) data frame of events with location and timestamps, how can I remove events synchronously occurring in all locations (i.e. putative noise) in <em>R</em>, <em>MATLAB</em> or <em>Python</em> (with reasonable performance)?</p> <p>A minimal specification of the problem in <em>R</em> would be:</...
<python><r><matlab><vectorization><intervals>
2024-02-11 19:31:21
1
1,059
NicolasBourbaki
77,978,057
4,505,998
Turn level of MultiIndex columns into a column with values (unstack columns)
<p>I have a DraFrame with a MultiIndex in the columns, and I want to turn the first level into its own column.</p> <p>Original df</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame( { ('a', 'm1'): [0,1], ('a', 'm2'): [10, 11], ('b', 'm1'): [2,3], ('b', 'm2'): [12, 13], ...
<python><pandas><dataframe>
2024-02-11 19:06:26
1
813
David Davó
77,977,838
5,905,678
Poetry project lock file and Docker container installation
<p>I have a Python project with Poetry which i would like to upload to CodeArtifact (like any other Python Repository) and then install it into a Docker container. My Python project has dependencies in the <code>pyproject.toml</code> like</p> <pre><code>[tool.poetry.dependencies] pandas = &quot;^2.1.4&quot; pytest-mock...
<python><docker><pypi><python-poetry><aws-codeartifact>
2024-02-11 18:06:46
1
1,518
Khan
77,977,794
832,560
Discord modal callback never called. The modal window gives a "Something went wrong" error, but no errors in console
<p>Spawning the model from a command:</p> <pre class="lang-py prettyprint-override"><code> @discord.app_commands.command(name=&quot;host_game_test&quot;, description=&quot;Host a new game&quot;) async def host_game_test(self, interaction: discord.Interaction): modal = HostGameModal(title=&quot;Host New G...
<python><discord><discord.py>
2024-02-11 17:55:10
1
830
Cerzi
77,977,777
893,254
How to partition a dictionary in Python?
<p>Many languages provide a standard library which provides a dictionary or binary tree map type. Many of these data structure implementations provide a function to split the data structure into a pair of data structures based on some condition.</p> <p>This is known as a partition operation. Rust calls it &quot;split o...
<python><dictionary>
2024-02-11 17:49:56
3
18,579
user2138149
77,977,601
595,305
How can I test what my `__main__` file does?
<p>I'm using pytest. NB W10.<br> I will be running my app by going <code>&gt; python src/core</code>. &quot;core&quot; is my central module, with a <code>__main__.py</code> file.</p> <p>For that reason I'm putting my &quot;tests&quot; directory in [project root]/src/core.</p> <p>I have a test file test_xxx.py. In it I ...
<python><testing><module><pytest>
2024-02-11 16:58:21
1
16,076
mike rodent
77,977,421
1,311,449
Python: configparser.InterpolationSyntaxError: '$' must be followed by '$' or '{', found: '$!'
<p>I have <code>psw: Test123$!</code> string in my configs.ini and tryin to read it with the following code will result in <code>configparser.InterpolationSyntaxError: '$' must be followed by '$' or '{', found: '$!'</code> error:</p> <pre><code>configs = configparser.RawConfigParser() configs._interpolation = configpar...
<python><special-characters><configparser>
2024-02-11 16:04:17
0
656
Mark
77,977,383
9,251,158
Recursive function fails depending on lexical scoping
<p>I want to generate variations on a name by edit distance equal or smaller than a number. I thought the simplest solution was a recursion. If I add the results of the current step after the recursion, the following code works fine; if I add them before, the recursion fails to terminate:</p> <pre class="lang-py pretty...
<python><recursion><lexical-scope>
2024-02-11 15:51:50
1
4,642
ginjaemocoes
77,977,370
10,798,503
Python Handling H264 Frames for Live Stream from Eufy Server
<p>I am currently using the <a href="https://github.com/bropat/eufy-security-ws" rel="nofollow noreferrer">Eufy Security WebSocket Server</a>, a server wrapper constructed around the eufy-security-client library, enabling access via a WebSocket interface. I have developed a python version of the client, where I attempt...
<python><opencv><video-streaming><video-processing><h.264>
2024-02-11 15:47:49
1
1,142
yarin Cohen
77,977,118
1,485,872
subprocess.Popen, communicate() and wget raises error when there is none?
<p>I have a piece of code that I use to run commend line calls from python (probably taken from SO, but seem to have missed the source on this):</p> <pre><code>import subprocess # Run cmd line def run_cmd(cmd, verbose=True, *args, **kwargs): if verbose: print(cmd) process = subprocess.Popen( cmd...
<python><subprocess>
2024-02-11 14:34:34
1
35,659
Ander Biguri
77,977,005
10,836,309
Converting a dataframe of timed tasks to timeline in Excel
<p>I have a dataframe of tasks at different resources at given times. Here is an example:</p> <pre><code>import pandas as pd data = {'product': ['Prod1', 'Prod1', 'Prod1', 'Prod2', 'Prod2'], 'resource': ['press', 'coat', 'pack', 'press', 'coat'], 'start': ['08/02/2024 10:10', '08/02/2024 13:00', '08/02/...
<python><pandas><plotly>
2024-02-11 13:58:16
1
6,594
gtomer
77,976,924
9,877,065
Assignment of a sliceable object single element
<p>It recently came to my eyes that in:</p> <pre><code>a = [1] print(a, type(a)) [b] = a print(b) b = a[0] a = [1,2] b = a[0] print(b) try : [b] = a except Exception as e: print(e) </code></pre> <p>The notation <code>[b] = a</code> could actually work.</p> <p>Why does it work, is it re...
<python>
2024-02-11 13:28:02
2
3,346
pippo1980
77,976,740
4,792,022
Efficiently comparing list of dictionaries in JSONL file with list of keys
<ul> <li>I have a jsonl file containing around 1,000,000 dictionaries</li> <li>I am interested in discionaries where the values of field_1 is a string from list_of_strings which contains around 100,000 strings.</li> </ul> <p>I can hold both in memory at the same time, and i'd like to quickly and efficiently compare the...
<python><performance><dictionary><jsonlines>
2024-02-11 12:23:04
1
544
Abijah
77,976,619
16,707,518
"window must be an integer 0 or greater" issue with '30D' style rolling calculations
<p>I've had a look and can't seem to find a solution to this issue. I'm wanting to calculate the rolling sum of the previous 30 days' worth of data at each date in the dataframe - by subgroup - for a set of data that isn't daily - it's spaced fairly irregularly. I've been attempting to use ChatGPT which is getting in a...
<python><pandas><rolling-computation>
2024-02-11 11:39:07
2
341
Richard Dixon
77,976,508
14,425,501
How to send parallel request to Google Gemini?
<p>I have 107 images and I want to extract text from them, and I am using Gemini API, and this is my code till now:</p> <pre><code># Gemini Model model = genai.GenerativeModel('gemini-pro-vision', safety_settings=safety_settings) # Code images_to_process = [os.path.join(image_dir, image_name) for image_name in os....
<python><google-gemini><google-generativeai>
2024-02-11 10:56:53
1
1,933
Adarsh Wase
77,976,453
1,616,785
whatever I do sqlalchemy wont commit to the database
<p><code>Python</code>, <code>Sqlalchemy</code>, <code>Mysql 8</code> envronment.</p> <p>I am using only raw sql select and execute commands(No ORM). I have queries across databases like <code>insert into db1.table1 select * from db2.table1</code>.</p> <pre><code>engine = create_engine(echo=True) session = sessionmaker...
<python><mysql><sqlalchemy>
2024-02-11 10:38:35
0
1,401
sjd
77,976,304
4,000,964
Abstract class from a concrete class in Python
<p>With the release of Python 3.12, <code>pathlib.Path</code> can now be subclassed. I want to create a subclass <code>CustomPath(Path)</code> for non-<code>os</code> environments (ftp, sftp, s3 storage, etc.), meaning I have to re-implemented (almost) all methods.</p> <p>I want to make sure that <code>CustomPath</code...
<python><abstract-class><pathlib>
2024-02-11 09:56:37
2
1,208
Frank Vel
77,976,298
12,387,950
Is there an efficient way to format Decimal?
<p>It is nice, easy and fast to use format-strings in python. So I never considered the performance penalty of this operation. Some time ago I switched my program from <code>float</code> data type to <code>Decimal</code> to eliminate rounding errors. Some performance degradation was expected and it is ok. But I'm surpr...
<python><performance><archlinux><f-string><python-decimal>
2024-02-11 09:53:05
2
605
StarterKit
77,976,264
1,234,434
Unable to sort a list of dictionaries by position
<p>I'm learning python and doing an online exercise.</p> <p>My current goal is to sort a list of dictionaries:</p> <pre><code>if __name__ == '__main__': arr=[] for _ in range(int(input())): name = input() score = float(input()) arr.append({name: score}) print(arr) print(...
<python>
2024-02-11 09:40:36
1
1,033
Dan
77,976,092
5,429,320
Azure Func App queue trigger throwing encoding errors when trying to read the message
<p>I have an Azure Function App that is written in python. One function adds values to my Azure Storage Account Queue. The message body is a simple string of characters for example: <code>SS3</code>.</p> <p>This function looks like:</p> <pre class="lang-py prettyprint-override"><code>def main(scheduleImportSet: func.Ti...
<python><azure><azure-functions>
2024-02-11 08:32:13
1
2,467
Ross
77,975,786
2,403,531
Python multiprocessing queues hanging without wait timers
<p>I am having trouble with queues failing to work as intended. The goal of this design is so that the <code>muncher</code> can take as little or as long as it needs, but it will always be able filled with work (input queue always has stuff, output queue always has room). I want to maximize <code>muncher</code>'s data ...
<python><multiprocessing><queue>
2024-02-11 06:07:34
1
730
user2403531
77,975,706
2,121,442
How to convert strings to bytes in a for in python
<p>I have a List of strings, but when I try to count the elements in the List which match a string, I get a byte error. Here's the code:</p> <pre><code>def countTransactions(data, lineDelim, marker): lines = data.split(lineDelim) return len([i for i in lines if marker in i]) </code></pre> <p>And here's the error I...
<python>
2024-02-11 05:30:07
1
581
Jason Michael
77,975,669
1,613,983
net::SOCKS_CONNECTION_FAILED when routing Pyppeteer request through socks proxy
<p>Here's my attempt at a minimal webscraper using pyppeteer 1.0.2 routing through a NordVPN socks proxy:</p> <pre><code>import asyncio from pyppeteer import launch import json import requests res = requests.get('https://nordvpn.com/api/server') servers = json.loads(res.content) socks_servers = [server['ip_address'] ...
<python><google-chrome><pyppeteer>
2024-02-11 05:13:52
2
23,470
quant
77,975,605
7,408,848
Saving a pandas dataframe in excel with utf-8 encoding
<p>Simply want to set the encoding of an excel workbook for saving data. All data is stored in a pandas dataframe.</p> <p>Code below:</p> <pre><code>file_name = &quot;bobs_burgers&quot; with pd.ExcelWriter(r&quot;.\Exported_data\{file_name}.xlsx&quot;.format(file_name = file_name), engine=&quot...
<python><pandas><encode>
2024-02-11 04:38:47
1
1,111
Hojo.Timberwolf
77,975,441
1,013,799
_openai_scripts.py': [Errno 2] No such file or directory
<p>Working on a python script using the OpenAI API. When I try to run the script this is my Mac terminal output:</p> <pre><code>/Library/Developer/CommandLineTools/usr/bin/python3: can't open file '/Users/me/Library/Python/3.9/lib/python/site-packages/openai/_openai_scripts.py': [Errno 2] No such file or directory </co...
<python><openai-api>
2024-02-11 03:03:27
0
3,222
Drewdavid
77,975,378
10,693,596
panel: how to obtain the name of the uploaded file?
<p>While using <code>param.Parameterized</code> way of creating a Panel application, I am not able to obtain the name of the uploaded file. The minimal code is below, I am trying to figure out the solution for the <code>update_name</code> method:</p> <pre class="lang-py prettyprint-override"><code>import panel as pn im...
<python><holoviz-panel><python-param>
2024-02-11 02:22:20
0
16,692
SultanOrazbayev
77,975,262
10,940,989
Untangle Facebook reaction encoding?
<p>I've downloaded my Facebook data in JSON format and want to perform analysis on it. It contains segments like:</p> <pre><code>{ &quot;reaction&quot;: &quot;\u00e2\u009d\u00a4&quot;, &quot;actor&quot;: &quot;...&quot; }, </code></pre> <p>The reaction here is a heart. However, if I print it in Pyth...
<python><facebook><unicode><emoji>
2024-02-11 00:56:48
2
380
Anthony Poole
77,975,111
19,299,757
Retrieve AWS secrets using boto3
<p>I want to retrieve AWS secrets using python boto3 and I came across this sample code:</p> <ul> <li><a href="https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/python/example_code/secretsmanager/get_secret_value.py" rel="nofollow noreferrer">aws-doc-sdk-examples/python/example_code/secretsmanager/get_secret_va...
<python><amazon-web-services><boto3><aws-secrets-manager>
2024-02-10 23:40:54
1
433
Ram
77,975,009
4,348,400
How do `prior` and `connect` work in `matplotlib.sankey.Sankey.add`?
<p>I have a weighted directed graph (<a href="https://networkx.org/documentation/stable/reference/classes/digraph.html" rel="nofollow noreferrer"><code>nx.DiGraph</code></a>) that I want to plot as a Sankey diagram using Matplotlib.</p> <p>I'm a bit confused about the roles of <code>prior</code> and <code>connect</code...
<python><matplotlib><plot><sankey-diagram>
2024-02-10 22:56:52
0
1,394
Galen
77,974,910
80,002
How to add custom dimensions to App Insights request telemetry in an ASGI web application?
<p>I have a python web application using Quart. Here is how I add boilerplate App Insights request telemetry to it:</p> <pre><code>... from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware f...
<python><azure-application-insights><open-telemetry>
2024-02-10 22:14:04
1
63,544
mark
77,974,845
3,787,646
How to dynamically create and set a validation model for a FastAPI endpoint based on the dependencies I'm passing?
<p>In the example below, I'd like to loose the coupling between <code>MediaController</code> and its dependencies, the <code>MediaPipelineX</code>s to enable it to work with whatever I'm passing to it. That's an important aspect of OOP and Dependency Injection.</p> <p>How do I do that? The way fastapi currently works s...
<python><oop><dependency-injection><fastapi><pydantic>
2024-02-10 21:46:56
0
863
Multisync
77,974,696
1,245,281
Is it possible to "serialize" a span such that a span could be started, and then picked up after reboot?
<p>I don't actually have any code, it's more of a conceptual &quot;how might someone do this&quot; sort of question.</p> <p>I have a python application that I am instrumenting with OpenTelemetry, the application basically does some configuration on the machine that only can be completed after a reboot. I'd like to be a...
<python><trace><open-telemetry>
2024-02-10 20:59:24
0
551
RedBullet
77,974,525
50,385
What is the right way to await cancelling an asyncio task?
<p><a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.uncancel" rel="noreferrer">The docs for cancel</a> make it sound like you should usually propagate CancelledError exceptions:</p> <blockquote> <p>Therefore, unlike Future.cancel(), Task.cancel() does not guarantee that the Task will be cancell...
<python><async-await><task><python-asyncio><cancellation>
2024-02-10 19:54:22
2
22,294
Joseph Garvin
77,974,379
8,713,442
How to find max value in list datatype column in polars dataframe
<p>I am using a Polar data frame for the first time. I am trying to match input values with data in the Postgres table. Sharing some sample code which is part of the actual code. I have a column called &quot;Score&quot; of type list[i32]. As a next step, I am trying to find the maximum value in that list. I am getting ...
<python><python-polars>
2024-02-10 18:57:44
1
464
pbh
77,974,285
515,311
Allowing a specific set of undefined values in enums
<p>Given an enum like this:</p> <pre class="lang-py prettyprint-override"><code>class Result(IntEnum): A = 0 B = 1 C = 3 </code></pre> <p>I'd like to be able to create new enum members dynamically, but only if the value is within a given range. For example, given:</p> <pre class="lang-py prettyprint-overri...
<python><python-3.x><enums>
2024-02-10 18:32:59
1
1,052
Matthew Brown
77,974,164
4,465,928
AttributeError: module 'keras.api._v2.keras' has no attribute 'models' when using tf.keras.models.Sequential() for Neural Network
<p>I'm using Jupyter Notebook and am trying to follow along this example for Siamese NN with Triplet Loss: <a href="https://github.com/13muskanp/Siamese-Network-with-Triplet-Loss/blob/master/Siamese%20Network%20with%20Triplet%20Loss.ipynb" rel="nofollow noreferrer">https://github.com/13muskanp/Siamese-Network-with-Trip...
<python><tensorflow><keras><neural-network>
2024-02-10 17:59:50
0
331
Anthony
77,974,129
13,373,677
Selenium WebDriver Fails to Locate Elements on Linux Server but works locally
<p>I'm experiencing an issue with my web scraper running on a Linux server where it fails to locate elements using Selenium WebDriver. The scraper works perfectly fine on my local machine, but when I run it on the Linux server, it throws a NoSuchElementException.</p> <p>The error message I receive is:</p> <blockquote> ...
<python><linux><selenium-webdriver><server>
2024-02-10 17:50:38
1
311
Lenart Golob
77,974,108
9,251,158
OpenTimelineIO error from exporting a Final Cut Pro file with the Kdenlive adapter
<p>Follow-up on <a href="https://stackoverflow.com/questions/77846715/monkey-patching-opentimelineio-adapter-to-import-final-cut-pro-xml">Monkey-patching OpenTimelineIO adapter to import Final Cut Pro XML</a></p> <p>I have several video projects from Final Cut Pro that I want to use in KdenLive. I found the OpenTimelin...
<python><python-3.x><xml><finalcut>
2024-02-10 17:47:09
0
4,642
ginjaemocoes
77,974,016
10,464,730
How can I stream an OpenCV video?
<p>I'm trying to make the image/video streaming from <a href="https://github.com/pornpasok/opencv-stream-video-to-web" rel="nofollow noreferrer">here</a> work on socket so I could make it send that stream to a server in the cloud. For testing, I just use <code>Live Server</code> to host the webpage and use <code>websoc...
<javascript><python><opencv><websocket><video-streaming>
2024-02-10 17:25:01
0
605
rminaj
77,973,904
5,072,010
Lambda invoke unhandled, timing out after 3 seconds?
<p>Have the following lambda function and dynamodb defined via terraform:</p> <pre><code>provider &quot;aws&quot; { region = &quot;us-east-1&quot; # Change to your desired region access_key = &quot;test&quot; # Access key for LocalStack secret_key = &quot;test&quo...
<python><aws-lambda><terraform><amazon-dynamodb><localstack>
2024-02-10 16:51:09
2
1,459
Runeaway3
77,973,757
11,329,736
Access command line values during Snakemake pipeline run
<p>Is it possible to access the values of arguments that were parsed to <code>Snakemake</code> in the command line or set in the profile yaml file?</p> <p>For example, I would like to know whether <code>--slurm</code> is <code>True</code> so that I can split certain jobs to allow for optimal parallelisation.</p>
<python><command-line><snakemake>
2024-02-10 16:07:18
1
1,095
justinian482
77,973,278
352,972
Determine which microphone source to use for Azure Cognitive Services with Python
<p>I've set up an instance of Azure Cognitive Services to listen on a microphone for a key phrase. This works fine, however I'm unable to tell it to listen to a specific microphone on my Apple Mac.</p> <p>The code I have is:</p> <pre class="lang-py prettyprint-override"><code>mic_name = self.preferences.get('mic_name',...
<python><objective-c><azure><azure-cognitive-services>
2024-02-10 13:38:57
1
452
Dan
77,973,265
14,348,996
Why does the function to close logging handlers not run when I expect?
<p>Can anyone explain why the <code>close_handlers</code> function does not run across every handler that is an instance of <code>MyHandler</code>? When I run the script below, the first <code>close_handlers</code> call in <code>thing_1</code>'s <code>finally</code> block only seems to close 1 of the 2 handlers added t...
<python><logging>
2024-02-10 13:34:50
0
1,236
henryn
77,973,238
8,398,851
How to compare 2 json files and merge in one with python
<p>Im trying to compare if a value from jsonA(deployed_devices) exists in jsonB(assigned_components) and merge them into one new json Object. The goal is to iterate over every asset_it in the deployed_devices json and check if and where the asset_id matches witch the id in assigned_components[data][rows] and generate a...
<python><json><python-3.x><comparison>
2024-02-10 13:23:36
2
323
Nico
77,973,204
10,746,224
Scraping using CSS Selectors with ::before isn't displaying text
<p>I'm trying to scrap <code>Monday, 9:30 AM</code> from <a href="https://www.ebay.com/itm/145599690533?" rel="nofollow noreferrer">this</a> ebay listing, using scrapy.</p> <p>From a scrapy shell <code>scrapy shell https://www.ebay.com/itm/145599690533?</code>:</p> <pre><code>&gt;&gt;&gt; response.css('span.ux-timer__t...
<python><css><web-scraping><scrapy><css-selectors>
2024-02-10 13:15:48
1
16,425
Lord Elrond
77,973,198
9,172,401
Solution for Django model composite foreign keys
<p>I’m working with two models in Django: Order and OrderItems. I want to establish a one-to-one relationship between them using two columns instead of the usual single column.</p> <p>I’m aware of solutions like SQL Alchemy’s ForeignKeyConstraint and the django-composite-foreignkey package, but I’d prefer not to use Fo...
<python><django><sqlalchemy>
2024-02-10 13:11:20
1
598
Marcos DaSilva
77,973,137
2,021,355
Redefine input function in Python to yield a value from a predetermined list of values each time it's called
<p>Is there a clean &quot;Pythonic&quot; way to write an input-replacement function in Python that will yield a value from a predetermined list of input values each time it's called?</p> <pre><code>raw_data = ['8', '2', '1'] c = 0 def input(): global c c += 1 return raw_data[c - 1] for _ in range(3): ...
<python><yield>
2024-02-10 12:56:11
3
1,473
Eric D
77,973,107
1,145,666
How can I read more than 4096 bytes from stdin, copy-pasted to a terminal on Linux?
<p>I have this code:</p> <pre><code>import sys binfile = &quot;data.hex&quot; print(&quot;Paste ascii encoded data.&quot;) line = sys.stdin.readline() b = bytes.fromhex(line) with open(binfile, &quot;wb&quot;) as fp: fp.write(b) </code></pre> <p>Problem is that never more than 4096 bytes are read in the <code>sy...
<python><stdin><readline>
2024-02-10 12:46:05
1
33,757
Bart Friederichs
77,972,795
22,466,650
How to set a common title for all the axes in a column of subfigures?
<p>I'm trying to set a common title for the axes of the same column.</p> <p>In the example below, we should have the ids titles only once and they should be placed at the very top of each column.</p> <p>I can't figure it out. Can you guys show me how to do that ?</p> <p><a href="https://i.sstatic.net/cXm2O.png" rel="no...
<python><matplotlib>
2024-02-10 11:17:34
3
1,085
VERBOSE
77,972,468
11,861,874
Formatting a Numbers in DataFrame
<p>Can someone please help me to format just numbers in a data frame to &quot;int&quot; and &quot;comma&quot;? I tried doing the same and got an error message mentioned below.</p> <p>Error: int() argument must be string, a bytes-like object or a number, not 'DataFrame'</p> <pre><code>import pandas as pd data1 = {'Head...
<python><pandas>
2024-02-10 09:19:26
1
645
Add
77,972,203
13,088,678
joining multiple dataframes : Reference column is ambiguous
<p>I have 3 dataframes. Joining column <code>id</code> is present exactly once in each dataframe.</p> <ul> <li><p>aggregated_df : ['id', 'country_agg', 'reference_agg', 'activities_agg', 'type_agg', 'is_batch_agg', 'is_stream_agg']</p> <ul> <li>&lt;bound method DataFrame.printSchema of DataFrame[id: string, co...
<python><apache-spark><pyspark>
2024-02-10 07:21:26
1
407
Matthew
77,971,994
10,466,809
Shorten regex to capture digits grouped by variable delimiter
<p>I have a regex that is trying to capture integer numbers like</p> <pre><code>12_456_789 </code></pre> <p>But the delimiter can by either any of <code>[\ _.,]</code> or no delimiter. My regex looks like</p> <pre><code>\d{1,3}((_\d{3})*|(\ \d{3})*|(\.\d{3})*|(,\d{3})*|(\d{3})*) </code></pre> <p>This regex works as epx...
<python><regex>
2024-02-10 05:46:11
4
1,125
Jagerber48
77,971,943
3,112,791
Blender bpy Module Ignores GPU Configuration for Rendering
<p>I'm attempting to use <code>bpy</code> (Blender) to render a scene using Python 3.10.0 on Windows. My laptop is equipped with an NVIDIA GeForce RTX 3050. Despite configuring the GPU, I consistently observe the CPU being used instead of the GPU. What am I missing?</p> <pre><code>def foo(): bpy.ops.wm.open_mainfil...
<python><rendering><blender><bpy>
2024-02-10 05:09:44
1
427
Pavel Angel Mendoza Villafane
77,971,878
10,200,497
How can I use Pandas to format individual cells conditionally in Excel?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'a': ['long', 'short', np.nan], 'b': [np.nan, 3, 2]}) </code></pre> <p>I want to style the output of <code>df.to_excel</code>. Like this:</p> <p><a href="https://i.sstatic.net/hVc8u.png" rel="nofollow noreferrer"><img src=...
<python><pandas>
2024-02-10 04:17:03
1
2,679
AmirX
77,971,802
10,292,330
Is class dict(dict) undesirable if I only want to overwrite __str__
<p>Is this approach undesirable? I want all proceeding dicts to behave this way.</p> <pre><code>import json class dict(dict): def __str__(self) -&gt; str: return json.dumps(self, indent=4) </code></pre>
<python>
2024-02-10 03:27:10
0
5,561
OysterShucker
77,971,697
899,954
How can I get my Python GStreamer app to show the webcam feed properly instead of showing garbled green video?
<p>Trying to build a very simple Python program to open the webcam on my MacBook and display that on the screen. However, I cannot get the Python version of my pipeline to display the webcam video, and I get garbled / scrolling green lines.</p> <p>Would like to understand where I went wrong and how I can fix the progr...
<python><gstreamer><python-gstreamer>
2024-02-10 02:18:18
1
783
HanSooloo
77,971,628
10,318,539
CircuitError: 'inverse() not implemented for reset.'
<p>Initially, this code was functioning correctly, but I am currently encountering an error. I am attempting to create a circuit using a unitary vector and applying inversion.</p> <pre><code>desire_vector = [0. 0.5 0. 0.5 0. 0.5 0. 0.5] qc = QuantumCircuit(qr, cr) qc.initialize(desired_vector,qr) backend = BasicAer...
<python><qiskit>
2024-02-10 01:38:37
1
485
Engr. Khuram Shahzad