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,663,428
1,447,953
Python search for modules on sys.path only, ignoring already loaded modules, for existence check purposes
<p>I am looking for a solution to the following problem. I have a package that includes some build tools (for use with SCons, though that is just incidental to the question). I want the package to be able to use these tools itself straight from source before it is installed, so I do the following in the main build file...
<python><python-importlib>
2023-12-14 22:42:46
1
2,974
Ben Farmer
77,663,325
21,612,376
Render a django template without a django app
<p>I am very new to Django. I have the following Django template, and I would like to render it to display the username variable. How can I do this without setting up an entire Django app structure?</p> <pre><code>&lt;html&gt; &lt;body&gt; hello &lt;strong&gt;{{username}}&lt;/strong&gt; your account is acti...
<python><django>
2023-12-14 22:10:45
1
833
joshbrows
77,663,249
13,376,660
Is there a way to refactor this try/except block to avoid DRY violation?
<p>This is part of a larger function using Selenium with Python for a web automation script. The website sometimes serves a popup, which results in an <code>ElementClickInterceptedException</code> but the popup isn't always served; sometimes there is no popup.</p> <p>I wrote this function to close the popup if it's ser...
<python><refactoring><repeat><dry><try-except>
2023-12-14 21:52:39
1
327
dbaser
77,663,162
10,499,034
How to install Pandas when PIP fails due to metadata generation error?
<p>I am trying to install Pandas in a standalone installation of Python 3.12 and I keep getting an error saying &quot;metadata-generation-failed.&quot; I am able to install Pandas in my Anaconda installation but I need this one to be totally separate because I am using it to connect to VB.net. I have updated PIP and ...
<python><pandas><pip>
2023-12-14 21:30:43
1
792
Jamie
77,662,999
6,083,675
Why don't API calls to /search get all matching results?
<p>I'm trying to find rows in some HuggingFace datasets which have a certain word or phrase in a specific column (e.g., &quot;output&quot;). I've written some basic Python code to do this, but I noticed an issue at the API level when trying to get a slice of the data that contains every row with one of the words from m...
<python><huggingface-datasets>
2023-12-14 20:49:42
1
6,231
Laurel
77,662,912
968,132
Pandas dataframes sorting/partitioning within multi-index
<p>I have a pandas dataframe like such:</p> <pre><code>df = pd.DataFrame({ 'class': ['Opn', 'Opn', 'MA', 'CoNo', 'Opn'], 'title': ['Title1', 'Title1', 'Title2', 'Title3', 'Title2'], 'event_count': [16, 11, 8, 7, 5] }) </code></pre> <p>How can I sort values descending within class and then within title so th...
<python><pandas>
2023-12-14 20:31:01
2
1,148
Peter
77,662,696
12,827,931
Speed up iterative algorithm in Python
<p>I'm implementing the forward recursion for Hidden Markov Model: the necessary steps (a-b) are shown here</p> <p><a href="https://i.sstatic.net/hJdzQ.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hJdzQ.jpg" alt="enter image description here" /></a></p> <p>Below is my implementation</p> <pre><code>fro...
<python><numpy>
2023-12-14 19:46:25
3
447
thesecond
77,662,322
12,708,740
Groupby merge values from one dataframe to the other
<p>I have a dataframe of &quot;words&quot;, and I would like to check which words were included, by each person in this dataframe by comparison to a word list key.</p> <p>Example data:</p> <pre><code>df = pd.DataFrame({ 'person': [1, 1, 1, 2, 3, 4, 4, 4, 4], 'word': ['apple', 'orange', 'pear', 'apple', 'grape',...
<python><pandas><dataframe>
2023-12-14 18:22:59
1
675
psychcoder
77,662,162
1,767,557
How to enable CUDA for Huggingface Trainer on Windows?
<p>I am trying to use the Trainer from the transformers library from HuggingFace in Python:</p> <pre><code>from transformers import Seq2SeqTrainingArguments from transformers import Seq2SeqTrainer # ... training_args = Seq2SeqTrainingArguments(fp16=True, # ... trainer = Seq2SeqTrainer( args=training_args, # ... <...
<python><huggingface-transformers>
2023-12-14 17:49:32
1
918
Frank im Wald
77,661,931
12,300,981
Matplotlib increase padding on cells for table when doing tight fit
<p>I like the current dimensions, fontsize, and look of my table. However, I'd like to increase the width of each cell by a little bit top/bottom (so it looks a bit prettier and less squished). But I don't quite know how to do that.</p> <pre><code>columns=['test', 'test', 'test', 'test', 'test', 'test', 'test'] rows=[...
<python><matplotlib>
2023-12-14 17:09:22
1
623
samman
77,661,574
1,473,517
why is numba 25% slower when using dicts
<p>I am interested in the performance of numba when using dicts. I did the following experiment:</p> <pre><code>from numpy.random import randint import numba as nb @nb.njit def foo_numba(a, b, c): N = 100**2 d = {} for i in range(N): d[(randint(N), randint(N), randint(N))] = (a, b, c) return d ...
<python><numba>
2023-12-14 16:14:06
1
21,513
Simd
77,661,537
4,670,852
Why does python-vlc (libvlc) drop frames in fullscreen on a Raspberry Pi 4 B?
<p>The fullscreen video is skipping frames and thus the stream was getting corrupted (some <a href="https://shopdelta.eu/h-264-image-coding-standard_l2_aid734.html" rel="nofollow noreferrer">I-frames</a> were dropped, leading to incomplete reconstruction of the video). This is with the following setup:</p> <pre><code>R...
<python><libvlc><python-vlc>
2023-12-14 16:08:11
1
406
Lupilum
77,661,453
4,670,852
Why is python-vlc playing a video in its native resolution (not fullscreen) even though I set fullscreen to True? This is on Raspberry Pi
<p>I'm running on</p> <pre><code>Raspberry Pi 4 B Python 3.11.2 python-vlc 3.0.20123 </code></pre> <p>The video opens in the left corner of the screen without the frames of a window, but not in fullscreen. I'm not using any GUI library like <code>PyQT5</code>, just the native vlc player.</p> <p>I initialize the player ...
<python><raspberry-pi><libvlc><python-vlc>
2023-12-14 15:54:38
1
406
Lupilum
77,661,426
1,514,114
Paramiko request_port_forward with and without handler
<h2>TLDR:</h2> <p>can't read data from incoming paramiko port forwarding connections when using callbacks. See this gist for a demonstration:<br /> <a href="https://gist.github.com/tatome/0d3e6479f35b25bbb31c9f94610eab6b" rel="nofollow noreferrer">https://gist.github.com/tatome/0d3e6479f35b25bbb31c9f94610eab6b</a></p> ...
<python><ssh><paramiko><ssh-tunnel>
2023-12-14 15:51:55
1
548
Johannes Bauer
77,661,424
15,416
How to annotate function attributes?
<p><a href="https://peps.python.org/pep-0232/" rel="nofollow noreferrer">PEP 232</a> defines function attributes, and <a href="https://peps.python.org/pep-0484/" rel="nofollow noreferrer">PEP 484</a> defines annotations, but I can't find how the two should be combined.</p> <p>E.g.</p> <pre><code>def foo(s:str): try: ...
<python><python-typing>
2023-12-14 15:51:46
1
181,617
MSalters
77,661,379
11,159,734
Azure Function Exit code: 137 | Please review your requirements.txt
<p>I want to publish an Azure Function with the following command using the cli/Azure Core tools:</p> <pre><code>func azure functionapp publish myFunc </code></pre> <p>However I can not even publish the function as I always get an error when installing the requirements.txt</p> <pre class="lang-bash prettyprint-override...
<python><azure><azure-functions>
2023-12-14 15:45:43
1
1,025
Daniel
77,661,276
6,484,455
Join Kafka streams in Python
<p>I need to work with Kafka streams in Python and I am analyzing the different libraries available. <a href="https://stackoverflow.com/questions/18688971/c-char-array-initialization-what-happens-if-there-are-less-characters-in-the-st">This question</a> provided some good answers and it looks like the <a href="https://...
<python><apache-kafka><faust>
2023-12-14 15:31:56
1
835
Matias B
77,661,141
13,007,467
Converting pandas groupby / apply / ewm calculation with time window to polars
<p>Due to performance consideration I would like to convert some panda based scripts to polars. I need to perform a groupby and calculate a half-life based on a datetime value. I unfortunately could not really found a cookbook for polars and relied on this <a href="https://stackoverflow.com/questions/73393235/polars-ho...
<python><dataframe><group-by><python-polars><moving-average>
2023-12-14 15:08:10
1
441
Iqigai
77,661,139
14,720,380
How do I stop the ruff linter from moving imports into an if TYPE CHECKING statement?
<p>I have a pydantic basemodel that looks something like:</p> <pre><code>from pathlib import Path from pydantic import BaseModel class Model(BaseModel): log_file: Path </code></pre> <p>And my ruff pre-commit hook is re-ordering it to:</p> <pre><code>from typing import TYPE_CHECKING from pydantic import BaseModel ...
<python><pre-commit-hook><ruff>
2023-12-14 15:08:06
2
6,623
Tom McLean
77,661,003
6,618,996
How to type hint a method that returns an instance of a class passed as parameter, with default value?
<p><em>using Python 3.11 and Mypy 1.7.</em></p> <p>I am trying to properly type hint a method that takes a class as parameter, with a default value, and returns an instance of that class. The class passed as parameter must be a subclass of a specific base class. How should I do that? I tried to use a <a href="https://m...
<python><generics><mypy>
2023-12-14 14:49:59
1
6,129
Guillaume
77,660,998
3,121,975
Dagster executable missing from container
<p>I've been trying to create a container to run in Dagster cloud on an ECS-hybrid deployment model. I'm able to actually push the container to Dagster but I continually get this error:</p> <pre><code>dagster_cloud.workspace.ecs.client.EcsServiceError: ECS service failed because task arn:aws:ecs:ap-northeast-1:*****:ta...
<python><amazon-web-services><docker><dagster>
2023-12-14 14:49:30
2
8,192
Woody1193
77,660,996
10,749,925
How can I create a Sagemaker endpoint for this notebook?
<p>I have created a VectorDB (FAISS) and input PDF's into it. Then i'm using the Langchain wrappper for AWS Bedrock to call it. I know Kowledge Bases exist now, but at least in the SageMaker notebook, i have a bit more control. The model works perfectly in SageMaker Notebook, when i ask a question, it returns the answe...
<python><machine-learning><aws-lambda><aws-api-gateway><amazon-sagemaker>
2023-12-14 14:49:20
1
463
chai86
77,660,943
20,920,790
How to check that i is 0 in io.BytesIO().seek(i)?
<p>I make lineplot to send for sending to Telegram. First sending is ok.</p> <p>Second time I get error: BadRequest: File must be non-empty</p> <p>How to check what i = 0 (position of cursor) in seek(i)?</p> <pre><code>sns.lineplot(x=x, y=y); plt.title('test plot'); plot_object = io.BytesIO() plt.savefig(plot_object) ...
<python><io><telegram>
2023-12-14 14:43:11
1
402
John Doe
77,660,933
2,144,877
python mathplotlib 3d scatter plot with colorbar ',' marker problem
<p>I've been playing with ray tracing. I managed to get the plot to have the correct shape and size by using:</p> <p>ax.set_box_aspect((np.ptp(xs), np.ptp(ys), np.ptp(zs))).</p> <p>and to have a 4d colorbar plot.</p> <p>My current problem is with the marker. Using '.' gives dots as expected</p> <p>(click images to zo...
<python><matplotlib><3d><scatter-plot>
2023-12-14 14:41:19
0
459
Don Mclachlan
77,660,887
11,501,976
Multi-region image segmentation based on pixel intensities
<p>I am attempting to segment a grayscale image into three regions based on its pixel intensities. Due to illumination and specks, this task turns out to be more challenging than I expected...</p> <p>Here is the <strong>original image</strong>:</p> <p><a href="https://i.sstatic.net/UnUDt.png" rel="nofollow noreferrer">...
<python><image-processing><image-segmentation><scikit-image>
2023-12-14 14:34:09
1
378
JS S
77,660,539
10,576,322
Dynamically change used database table while django app is running?
<p>I want to create a service that has a page to configure a data base table (columns and types) and that allows to CRUD lines in it via the page.</p> <p>The content of that table should then be used for comparison with payload of rest api call.</p> <p>I am quite new to django and don't know if that approach is possibl...
<python><django>
2023-12-14 13:31:01
0
426
FordPrefect
77,660,498
6,331,353
Homebrew installed python on mac returns weird response including "line 1: //: is a directory" & "line 7: syntax error near unexpected token `('"
<p>When I run <code>python3</code> I get the following</p> <pre><code> % python3 /opt/homebrew/bin/python3: line 1: //: is a directory /opt/homebrew/bin/python3: line 3: //: is a directory /opt/homebrew/bin/python3: line 4: //: is a directory /opt/homebrew/bin/python3: line 5: //: is a directory /opt/homebrew/bin/pytho...
<python><python-3.x><homebrew>
2023-12-14 13:25:34
1
2,335
Sam
77,660,453
20,803,947
kombu.exceptions.OperationalError: [Errno 111] Connection refused (flask, docker-compose)
<p>i'm having problems with my flask app</p> <p>having the premises:</p> <p>Python, Flask, Celerey, MongoDB, RabbitMQ.</p> <p>When I make a request to the API, I get the following return:</p> <p>kombu.exceptions.OperationalError: [Errno 111] Connection refused</p> <p>and this only happens when I run docker-compose up, ...
<python><flask><docker-compose><rabbitmq><celery>
2023-12-14 13:20:58
1
309
Louis
77,660,187
20,920,790
Why telegram bot not sending the message?
<p>Why bot not sending message? My code:</p> <pre><code>import telegram import requests bot_token = 'token***' my_bot = telegram.Bot(token=bot_token) def get_chat_id(bot_token): request = requests.post(f'https://api.telegram.org/bot{bot_token}/getUpdates') result = request.json()['result'][0]['message']['cha...
<python><telegram><telegram-bot><python-telegram-bot>
2023-12-14 12:33:49
1
402
John Doe
77,660,084
1,538,049
Unable to locate package sqlite3 in Dockerfile
<p>I am pretty new to building containers with Docker, I commonly use conda environments for my day to day work, however this time I needed to work with a computation server that only allows running docker containers. I want to build an image that will allow me to run my Pytorch code. What I prepared is like the follow...
<python><linux><docker><sqlite>
2023-12-14 12:16:26
1
3,679
Ufuk Can Bicici
77,660,071
386,641
Unable to select _ts from Cosmos db in databricks
<p>unable to select _ts from cosmos db from python script written in databricks.</p> <pre><code>read_config = { &quot;spark.cosmos.accountEndpoint&quot;: url, &quot;spark.cosmos.accountKey&quot;: key, &quot;spark.cosmos.database&quot;: database, &quot;spark.cosmos.container&quot;: container, &quot;s...
<python><databricks><azure-cosmosdb><azure-databricks>
2023-12-14 12:14:51
1
303
DeepVeen
77,659,976
9,851,915
Convert .msg file to .eml file in Python
<p>I'm writing a wrapper API to send some email reports to a third-party SaaS which parse them and get some information about them. My users have to report with <code>.eml</code> or <code>.msg</code> file (I am required to accept both formats). I just found out my SaaS provider does not deal with <code>.msg</code> file...
<python><python-3.x><email><msg><eml>
2023-12-14 11:56:23
0
319
giacom0c
77,659,718
5,525,704
What is the proper way to install Python 3.10 or higher on Docker development environments
<p>I use the <code>docker/dev-environments-default:stable-1</code> as a base image for development environments. However, the OS version (Debian Bullseye) only supports Python versions up to 3.9 via apt, so I can only install newer versions from source.</p> <p>Are there any other official base images for Docker develop...
<python><docker>
2023-12-14 11:14:25
1
1,167
Alexander Ershov
77,659,569
16,545,894
Reviews button is not clicking on google map
<p>I am trying to click Google Maps Company's <code>Reviews</code> button and after that extract 10 reviews description with selenium python.</p> <p><strong>An example link is given below:</strong></p> <blockquote> <p><a href="https://www.google.com/maps/place/PakDeZon+B.V./@52.7092108,4.9585823,17z/data=!3m1!4b1!4m6!3...
<python><google-maps><selenium-webdriver><web-scraping>
2023-12-14 10:48:30
2
1,118
Nayem Jaman Tusher
77,659,552
10,347,145
Google Generative AI API error: "User location is not supported for the API use."
<p>I'm trying to use the Google Generative AI <code>gemini-pro</code> model with the following Python code using the <a href="https://ai.google.dev/api/python/google/generativeai" rel="nofollow noreferrer">Google Generative AI Python SDK</a>:</p> <pre><code>import google.generativeai as genai import os genai.configure...
<python><google-generativeai><google-gemini>
2023-12-14 10:45:25
6
23,669
Rok Benko
77,659,458
2,724,299
Check if any element of list a comes from list b
<p>I've a fixed list of strings, <code>pets = ['rabbit','parrot','dog','cat','hamster']</code> and I need to match another string <code>basket = ['apple','dog','shirt']</code>. This <code>basket</code> will be varying.</p> <p>Typically <code>pets</code> will have 300 element string while <code>basket</code> will have 5...
<python><list>
2023-12-14 10:30:47
1
738
Frash
77,659,393
8,531,215
subtracting a numpy array by a list is slow
<p>Given a numpy array of shape <code>4000x4000x3</code>, which is an image with 3 channels, subtract each channel by some values. I can do it as following:</p> <p><strong>Implementation 1</strong></p> <pre><code>values = [0.43, 0.44, 0.45] image -= values </code></pre> <p>Or,</p> <p><strong>Implementation 2</strong></...
<python><numpy>
2023-12-14 10:21:19
1
2,373
TaQuangTu
77,659,281
7,191,911
Why does subprocess.run fail to run notepad in Win11 due to missing "package identity", when os.system succeeds?
<p>On Windows 10 with admin-installed Anaconda distribution, I had no problem using subprocess.run to open Notepad. However, when I now try to run the same command on Windows 11 from a user-installed Miniforge python environment, it fails with the following <code>package identity</code> error:</p> <pre class="lang-py p...
<python><python-3.x><subprocess><windows-11><os.system>
2023-12-14 10:07:14
0
331
Diomedea
77,659,240
6,450,267
uwsgi + flask-socketio in multi-processes
<p>I am trying to build a websocket server step by step. But I meet crucial problem when I try to use eventlet or gevent.</p> <h2>There are my codes for the server:</h2> <h4>[uwsgi.ini]</h4> <pre><code>[uwsgi] chdir = /home/user/websocket module=websocket:app callable=app processes=4 socket=/home/user/websocket/uwsgi....
<python><websocket><uwsgi><flask-socketio>
2023-12-14 10:00:09
1
340
Soonmyun Jang
77,659,211
14,487,032
Vscode jupyter intellisense not showing doc for tensorflow keras
<p>Vscode jupyter autocompletes, but doesn't show doc for <code>keras</code> fields</p> <pre><code>import tensorflow as tf from tensorflow import keras; import numpy as np import matplotlib.pyplot as plt %matplotlib inline </code></pre> <p>Even if I press <kbd>ctrl+shift+ space</kbd>, no doc shows to describe the funct...
<python>
2023-12-14 09:55:27
1
16,236
Abraham
77,659,069
98,967
How to understand and debug memory usage with JAX?
<p>I am new to JAX and trying to learn use it for running some code on a GPU. In my example I want to search for regular grids in a point cloud (for indexing X-ray diffraction data).</p> <p>With <code>test_mats[4_000_000,3,3]</code> the memory usage seems to be 15 MB. But with <code>test_mats[5_000_000,3,3]</code> I ge...
<python><jax>
2023-12-14 09:33:15
1
889
Jon
77,658,886
401,226
python requests sslL Client hello uses TLS V1 and server refuses connection, and I don't know why it uses v1
<p>Context: This is python 3.11.6 based on this docker image: python:3.11.6-slim-bullseye</p> <p>Ultimately this is used for a zeep connection but the problem is the SSL connection is not established.</p> <p>It is an up to date openssl library</p> <pre><code>print(ssl.OPENSSL_VERSION) PyDev console: starting. OpenSSL 1...
<python><python-requests><openssl><tls1.2>
2023-12-14 09:01:32
1
7,351
Tim Richardson
77,658,489
7,839,727
How to run only new Unit Test within AzureDevops pipeline
<p>Let's assume I have a simple Python app which has a few modules and each module has a set of tests. I've configured my Azure DevOps pipeline so that all tests are performed for each pull request to pass our quality gate.</p> <p>Is it possible to configure my Azure DevOps pipeline to run tests only from Pull Request?...
<python><azure-devops><azure-pipelines>
2023-12-14 07:45:44
2
500
SerSergious
77,658,330
14,348,930
custom tkinter progress bar not working for "indeterminate" mode
<p>I'm trying to create a YouTube video downloader GUI using <code>yt-dlp</code> and <code>custom-tkinter</code> library.</p> <p>I successfully implemented progressbar using <code>CTkProgressBar()</code> inside a <code>CtkFrame</code> for &quot;determinate&quot; mode which will show progress of the filesize downloaded....
<python><tkinter><progress-bar><customtkinter><yt-dlp>
2023-12-14 07:10:24
1
321
rangarajan
77,658,301
2,824,791
Python imports fail when invoked by nf-core process
<p>I created a nf-core project using nf-core create. I am trying to invoke python scripts using nf-core processes. This technique worked in my nextflow project as I was able to avoid having to write code in a process. Most of the imports are failing.</p> <pre><code>import sys --&gt; works import pymongo --&gt; fails fr...
<python><python-3.x><nextflow><nf-core>
2023-12-14 07:03:36
0
5,096
jlo-gmail
77,658,292
13,950,559
How to inspect the exact bytes sent by scrapy?
<p>I'm crawling a website which seems to be detecting crawlers based on nuances like header item order, since a naive translation from a successful <code>curl</code> request into scrapy got rejected with 403 Forbidden, but then just by changing <code>dict</code> to <code>OrderedDict</code> it got accepted with 200 OK. ...
<python><web-scraping><scrapy>
2023-12-14 07:01:24
1
488
Sylvain Hubert
77,658,135
3,416,774
What is the PageElement type?
<p>In this code, I have asserted that the <code>event</code> object must be an instance of the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#bs4.Tag" rel="nofollow noreferrer" title="Beautiful Soup Documentation — Beautiful Soup 4.12.0 documentation"><code>Tag</code></a> class:</p> <pre class="lang-py...
<python><beautifulsoup>
2023-12-14 06:23:14
1
3,394
Ooker
77,657,891
19,048,408
In Polars, how can you add row numbers within windows?
<p>How can I add row numbers within windows in a DataFrame?</p> <p>This example depicts what I want (in the <code>counter</code> column):</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pl.DataFrame([{'groupings': 'a', 'target_count_over_windows': 1}, {'groupings': 'a', 'target_count_over_windows'...
<python><dataframe><window-functions><python-polars>
2023-12-14 05:12:23
1
468
HumpbackWhale194
77,657,807
1,115,716
replacing characters dynamically
<p>I have a series of strings I need to alter based on some criteria, and I'm trying to build a list of words to replace in the string like so:</p> <pre><code>test = &quot;CAPTAIN AMERICA TO SUPERMAN&quot; delimeters = ['AND', 'TO', 'THEN'] delimited_speaker_string = &quot;&quot; for delimeter in delimeters: delim...
<python><python-3.x>
2023-12-14 04:36:26
1
1,842
easythrees
77,657,592
23,512,643
R: Equivalent of Python "add_volume()" function?
<p>I am working with the R programming language.</p> <p>I found this tutorial/website over here that shows how to fill the volume under the surface in Python/Plotly (<a href="https://community.plotly.com/t/fill-volume-under-the-surface/64944/2" rel="nofollow noreferrer">https://community.plotly.com/t/fill-volume-under-...
<python><r><plotly>
2023-12-14 03:05:52
2
6,799
stats_noob
77,657,555
1,837,400
Python TypedDict 'a' or 'b' but not both in inherited TypedDict's
<p>I have some data coming in that could look like</p> <pre><code>{&quot;cloud_url&quot;: &quot;https://example.com/file.txt&quot;, &quot;filetype&quot;: &quot;txt&quot;} </code></pre> <p>or it could look like</p> <pre><code>{&quot;local_filepath&quot;: &quot;./file.csv&quot;, &quot;filetype&quot;: &quot;csv&quot;, &qu...
<python><python-typing><python-3.10><typeddict>
2023-12-14 02:53:52
2
462
codythecoder
77,657,335
4,451,521
matplotlib plot and its mpld3 version have different markers sizes
<p>I have this minimum reproducible code</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import mpld3 # Create a DataFrame with columns id, X, and Y # num_points = 100 # t = np.linspace(0, 4 * np.pi, num_points) # data = {'id': range(1, num_points + 1), 'X': 10 * np.cos(t), 'Y': 5...
<python><matplotlib><mpld3>
2023-12-14 01:21:35
0
10,576
KansaiRobot
77,657,210
1,049,903
Conditionally apply CSS class to wtforms element in Python flask
<p>I want to apply an additional <strong>is-invalid</strong> CSS class to a wtforms element only if there is an error present in the form.</p> <p>I've landed on the following code to achieve this and it works:</p> <pre><code>{% if form.email.errors %} {{ form.email(placeholder=&quot;Email&quot;, class=&quot;form-contro...
<python><flask><flask-wtforms><wtforms>
2023-12-14 00:26:09
2
6,024
Dean Wild
77,657,001
10,431,629
Creating a ratio between variables in a Stacked dataframe grouped by some Columns
<p>I have a df as follows:</p> <pre><code>df_in G1 G2 TPE QC A S1 td 2 A S1 ts 4 A S2 td 6 A S2 ts 3 B S1 td 20 B S1 ts 40 ...
<python><pandas><group-by><multiple-columns><group-concat>
2023-12-13 23:08:17
3
884
Stan
77,656,906
1,872,565
Selenium Check alert present or not in robotramework
<p>How to check an alert box exits in robotframework?</p> <pre><code>Alert accept Alert dismiss Alert cancel Handle alert </code></pre> <p>In my application sometimes alert will be there sometimes not? How to handle such situation?</p>
<python><robotframework>
2023-12-13 22:37:53
1
947
Learner
77,656,892
5,111,234
OpenMDAO Dymos Simulate Method Calls Setup Multiple Times
<p>I currently have an <code>ExplicitComponent</code> that takes as an input altitude and computes atmospheric properties at that altitude. The compute function itself uses another Python library to do this. When the library calculates the atmospheric properties, it loads in a large data file to do it. As such, I have ...
<python><openmdao>
2023-12-13 22:34:55
1
679
Jehan Dastoor
77,656,542
1,186,991
Changing the format of a screenshot in Jupyter Notebooks
<p>I can display screenshots in my notebook by just using the snipping tool and then pasting them in.</p> <pre><code>![image-3.png](attachment:image-3.png) </code></pre> <p>but if i want to format it, i keep getting broken links. Ive tried the following and not sure what is wrong with it:</p> <pre><code>&lt;p&gt; &lt;i...
<python><jupyter-notebook>
2023-12-13 21:08:24
1
3,631
Hans Rudel
77,656,496
16,545,894
Scrape Company opening amd closing time on Google map
<p>I am trying to get Google Maps Company's opening and closing times with selenium python.</p> <p><strong>An example link is given bellow :</strong></p> <blockquote> <p><a href="https://www.google.com/maps/place/Solar+Project+Development+%26+Engineering+Ltd./@23.7988032,90.3525855,17z/data=!3m1!4b1!4m6!3m5!1s0x3755c18...
<python><selenium-webdriver><web-scraping><data-mining>
2023-12-13 20:56:43
1
1,118
Nayem Jaman Tusher
77,656,478
1,332,811
Inline images are showing up as attachments in Gmail inbox
<p>I am sending emails in Python with CID inline images. The inline images work fine: they show up embedded in the email and the email itself does not appear to have attachments.</p> <p>However, in the Gmail inbox view, it shows the inline image as an attachment:</p> <p><a href="https://i.sstatic.net/qnbCA.png" rel="no...
<python><email><email-attachments><mime>
2023-12-13 20:53:03
1
667
leros
77,656,400
3,825,495
reference module from outer folder
<p>I have a module that I'm developing called &quot;py_lopa&quot;. typically, while developing it, I'll write a small script in the super-folder one layer up from &quot;py_lopa&quot; and run it from there. however, this higher folder is getting cluttered with small files.</p> <p>I'd like to somehow move the scripts t...
<python><module>
2023-12-13 20:33:57
1
616
Michael James
77,656,247
102,221
ogg audio file is not played by pygame
<p>I have the next version of pygame package: pygame <code>2.5.0</code> (SDL <code>2.28.0</code>) in python <code>3.10.8</code>.</p> <p>.ogg file generated by telegram client and uploaded to server is successfully played by VLS application but next python code</p> <pre><code>import pygame audio_file_path = r'&lt;OGG P...
<python><pygame><sdl>
2023-12-13 19:54:09
1
1,113
BaruchLi
77,656,160
2,157,783
Pytorch, random number generators and devices
<p>I always put on top of my Pytorch's notebooks a cell like this:</p> <pre><code>device = ( &quot;cuda&quot; if torch.cuda.is_available() else &quot;mps&quot; if torch.backends.mps.is_available() else &quot;cpu&quot; ) torch.set_default_device(device) </code></pre> <p>In this convenient way, I can ...
<python><pytorch><gpu>
2023-12-13 19:35:47
1
680
MadHatter
77,656,117
1,473,517
when can you use numpy arrays as dict values in numba?
<p>I am confused by the type rules for numba dicts. Here is an MWE that works:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import numba as nb @nb.njit def foo(a, b, c): d = {} d[(1,2,3)] = a return d a = np.array([1, 2]) b = np.array([3, 4]) ...
<python><numba>
2023-12-13 19:28:42
1
21,513
Simd
77,656,084
13,400,029
Python: Regular expression to match alpha-numeric characters not working on LeetCode compiler
<p>my code is not working using this solution.</p> <p><a href="https://i.sstatic.net/BAhbA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BAhbA.png" alt="enter image description here" /></a></p> <p>Leetcode question: 125. Valid Palindrome Easy 8.6K 8.1K Companies A phrase is a palindrome if, after conve...
<python><python-3.x>
2023-12-13 19:20:54
1
619
Delicia Fernandes
77,656,015
11,192,275
Problem using the `geom_col` in plotnine with Linux (Ubuntu 22.04.3 LTS) and Windows
<p>When I try to run the following reproducible example using <code>plotnine</code> I get an error:</p> <pre><code>import pandas as pd from plotnine import ( ggplot, aes, geom_col ) from plotnine.data import mtcars df = (mtcars. loc[:, [&quot;name&quot;, &quot;disp&quot;]]. drop_duplicates(subset=&quot;n...
<python><plotnine>
2023-12-13 19:05:29
1
456
luifrancgom
77,655,929
1,711,088
Selenium. Python. Chrome. How to get current (active/focused) tab?
<p>Ubuntu + Python3 + Selenium + Chromium</p> <p>I'm using selenium in semi-automated tests. Some work doing user, and some work are automated by python. And i have a problem. I want to know which tab active right now? User can change tabs - and script should work with active tab only. I find lot of answers how to open...
<python><selenium-webdriver><tabs><chromium>
2023-12-13 18:49:31
0
976
Massimo
77,655,862
6,168,639
Pytest paramaterized fixture not returning yielded object, only returning tuple?
<p>I'm working to setup a fixture that will open a headless (or headed) instance of a web browser for some end to end testing. I am using Django with pytest and pytest-django.</p> <p>I'd like to be able to paramaterize the test class with the browsers I'd like to use and whether or not they are headless in a fashion li...
<python><testing><pytest><pytest-django>
2023-12-13 18:37:12
1
722
Hanny
77,655,841
2,961,550
Strip whitespace of field for peewee Model
<p>In <code>peewee</code> I have a model where I want to <code>strip</code> the white space of some fields when an instance is created. Is it possible to do this?</p> <p>e.g.</p> <pre><code>import peewee as pw class Person(pw.Model): email = pw.CharField() name = pw.CharField() mom = Person(email=&quot; mothe...
<python><peewee>
2023-12-13 18:31:47
1
1,417
bicarlsen
77,655,593
3,941,671
Access Thread args in Thread.run()
<p>I have a question based on an example from this <a href="https://superfastpython.com/thread-producer-consumer-pattern-in-python/#Shared_Buffer" rel="nofollow noreferrer">guide</a> (see code below):</p> <p>In this example, when the thread is created a callback function and the <code>queue</code> are given as argument...
<python><multithreading>
2023-12-13 17:43:25
1
471
paul_schaefer
77,655,474
12,106,577
Python multiprocessing Manager process not exiting after successfully stopping parent processes
<p>I'm wrote the following demo script to replicate the multiprocessing handling logic from a more complex case (from now on the original code), however the key parts should be there.</p> <p>The original code running with python 3.10.12 had a memory leak when sometimes stopped by CTRL+C, as seen with <code>htop</code> ...
<python><multiprocessing><keyboardinterrupt>
2023-12-13 17:22:54
1
399
John Karkas
77,655,459
12,214,934
Scipy Multinomial Probability Mass Function is almost always 0.0
<p>To calculate the probability for categorical features, I was told to use the Multinoulli distribution, which is supposedly a special case of the multinomial distribution, where the number of trials is 1.</p> <p>I was given some probabilities for 10 different categories:</p> <pre><code>p = [0.14285714 0.11428571 0.14...
<python><scipy><multinomial>
2023-12-13 17:19:56
1
722
Kajice
77,655,440
1,264,211
Can you protect a python variable with exec()?
<p>This is kind of a hacky Python question.</p> <p>Consider the following Python code:</p> <pre class="lang-py prettyprint-override"><code>def controlled_exec(code): x = 0 def increment_x(): nonlocal x x += 1 globals = {&quot;__builtins__&quot;: {}} # remove every global (including all python builtins) ...
<python>
2023-12-13 17:16:41
1
335
Bix
77,655,360
7,563,454
Direction vector: Correctly scale sin(radians(x)) + cos(radians(z)) with y axis
<p>I have an issue with the directional transform math for a voxel raytracer I'm working on in Python. X axis is left-right, Y axis is up-down, Z axis is forward-backward: I calculate view direction from a camera angle stored in degrees, direction being the virtual arrow the point of view points toward: Z rotation tran...
<python><python-3.x><math><vector><3d>
2023-12-13 17:03:39
1
1,161
MirceaKitsune
77,655,334
5,931,672
Autocompletion for my python module using click
<p>I created a python module I install. It uses a Bash CLI commands such as <code>my-module init</code> or <code>my-module delete</code>.</p> <p>The structure is like:</p> <pre><code>my-module/ |--- setup.py |--- my_module | |--- __main__.py | |--- delete.py | |--- init.py </code></pre> <p><code>setup.py</code...
<python><autocomplete>
2023-12-13 16:57:55
2
4,192
J Agustin Barrachina
77,655,312
3,139,771
Pyinstaller unable to find module when frozen
<p>This is what I have:</p> <pre><code>├── demo │ ├── mypkg │ │ └── __main__.py │ │ └── api.py │ │ └── startserver.py │ └── readme.md </code></pre> <p>api.py has =&gt;</p> <pre><code>import hug @hug.get('/ping') def ping(): return {&quot;response&quot;: &quot;pong&quot;} </code></pre> <p>startserver...
<python><pyinstaller><hug>
2023-12-13 16:54:55
2
357
Impostor Syndrome
77,655,287
2,154,374
python mmap write with packed value
<p>On Linux setup, I am trying to write device file using python's <code>mmap</code>.</p> <p>Following is the code snippet:</p> <pre><code>import struct, os, mmap, sys def write(addr, size, data): filename = &quot;&lt;pci_device_file&gt;/resource0&quot;; # page size of this setup (typically 4k) ...
<python><mmap>
2023-12-13 16:52:09
1
309
boomerang
77,655,249
1,138,192
Dynamodb batch delete based on sort key pattern
<p>I have a DynamoDB table with the following structure:</p> <pre><code>sk | pk ---------------|----- 1#2023-12-01 | abv 1#2023-12-02 | abv 1#2023-12-03 | abv 1#2023-12-04 | abv 1#2023-12-05 | abv 2#2023-12-01 | abv 2#2023-12-02 | abv 2#2023-12-03 | abv 2#2023-12-04 | abv 2#2023-...
<python><amazon-web-services><amazon-dynamodb><boto3>
2023-12-13 16:45:14
2
38,823
A l w a y s S u n n y
77,655,206
6,357,916
Algorithm to obtain indices of list where list element resets to near zero
<p>I have list of increasing and decreasing float values:</p> <p><a href="https://i.sstatic.net/Vzbev.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Vzbev.png" alt="enter image description here" /></a></p> <p>As you can see in the image, the values may increase or decrease and may suddenly reset to near...
<python><list><algorithm><sorting><indexing>
2023-12-13 16:38:25
2
3,029
MsA
77,655,131
6,907,488
parsing string with special characters (subprocess.run stdout)
<p>I am grabbing output of CLI call (for context GithubAPI)</p> <p>command:</p> <pre><code>import subprocess j = subprocess.run(&quot;gh api /orgs/{__org__}/teams&quot;, shell=True, stdout=subprocess.PIPE, text=True) </code></pre> <p>the <code>j.stdout</code> object is a type <code>str</code> with the API response.</...
<python><regex><subprocess><gh-api><ansi.sys>
2023-12-13 16:27:20
1
671
dozyaustin
77,655,047
1,942,868
Insert the row to the Queryset manually
<p>I have objects and filter, which get the <code>label</code> <code>value</code> pair from database.</p> <pre><code> results = (m.Drawing.objects. annotate(label=F('update_user__name'),value=F('update_user')). values('label','value'). annotate(dcount=Count('update_user__name')). order_by()) ...
<python><django>
2023-12-13 16:13:32
1
12,599
whitebear
77,655,001
11,052,072
Cleanest way to structure unit tests in Python
<p>I usually structure my projects in this way:</p> <pre><code>root src __init__,py main.py utils.py xyz.py tests __init__.py test_main.py test_utils.py test_xyz.py README.md LICENSE Other stuff... </code></pre> <p>In the tests I import the functions I need to test with imports...
<python><python-unittest>
2023-12-13 16:06:51
1
553
Liutprand
77,654,887
599,265
How can I reasonably support basic SSLv3 connections in a user-facing package for modern Python?
<p>I have a Python package for controlling a piece of lab equipment that has a server listening on a network connection. In response to changes to California law, the machine has recently been updated to use SSL connections rather than plain text. Unfortunately, despite being updated in the last few years, it only su...
<python><ssl>
2023-12-13 15:50:23
0
10,008
cge
77,654,869
1,103,752
plumbum fails to connect via jump host, but raw command succeeds
<p>I'm trying to SSH into <code>final_machine</code> via the jump host <code>portal_machine</code>. Both remote machines are Linux, local is Windows. When I run the following command in a cmd, I can successfully connect</p> <pre><code>ssh {username}@{final_machine} -oProxyCommand=&quot;ssh -W {final_machine}:22 {userna...
<python><ssh><plumbum><jumphost>
2023-12-13 15:48:17
1
5,737
ACarter
77,654,642
2,474,876
Pandas data frame splitting by cycles
<p>I have a pandas data frame for the stops &amp; scheduled times of a single transit route throughout a given day. I would like to split this into multiple frames each corresponding to individual trips made by a given bus (based only on the <code>stop</code> cycles &amp; not when the <code>scheduled</code> periodicity...
<python><pandas>
2023-12-13 15:12:00
1
417
eliangius
77,654,547
7,802,354
How to avoid printing unnecessary UWSGI error messages in the log file
<p>My Flask app is generating thousands of</p> <blockquote> <p>'OSError: write error'</p> </blockquote> <p>messages in my log file (my log file is defined in the .ini file; logger = '/temp/my_app.log). Most of them happen due to users disconnecting from the server or cancelling a request. I only need my error handling ...
<python><nginx><flask><uwsgi>
2023-12-13 15:00:09
1
755
brainoverflow
77,654,458
14,321,038
Define __getitem__() wthin class constructor
<p>Python allows assigning function definitions to class members directly like,</p> <pre class="lang-py prettyprint-override"><code>class A: def __init__(self): self.test = lambda x: print(x) a = A() a.test(10) # prints 10 </code></pre> <p>However for <code>__getitem__(self, idx)</code> it's not that simple. Say...
<python><constructor>
2023-12-13 14:49:26
1
427
Orwellian Mentat
77,654,317
13,877,952
Pandas : mean/median precedent rows having the same ID
<p>I have the following ordered Dataframe</p> <pre><code>Index ID Amount 1 A 10 2 A 15 3 A 17 4 A 12 5 A 10 6 B 20 7 B 15 ... </code></pre> <p>What I want is to add a column indicating <strong>the median of all the precedent Amounts for the same IDs</strong> in the dat...
<python><pandas><dataframe>
2023-12-13 14:28:05
1
564
Adept
77,654,253
7,425,726
error in keras TimeDistributed layer after updating to keras 3.0.0
<p>I use the keras TimeDistributed layer in an LSTM architecture just like the following example taken from <a href="https://machinelearningmastery.com/timedistributed-layer-for-long-short-term-memory-networks-in-python/" rel="nofollow noreferrer">https://machinelearningmastery.com/timedistributed-layer-for-long-short-...
<python><tensorflow><keras>
2023-12-13 14:17:10
0
1,734
pieterbons
77,653,807
16,525,263
get a missing value for a column in one dataframe from another dataframe
<p>I have a dataframe 'persons' as below</p> <pre><code>name age serial_no mail John 25 100483 john@abc.com Sam 49 448900 sam@abc.com Will 63 will@abc.com Robert 20 299011 Hill 78 hill@abc.com </code></pre> <p>I have another dataframe 'people' as below</p> <pr...
<python><apache-spark><pyspark><apache-spark-sql>
2023-12-13 13:04:24
2
434
user175025
77,653,793
4,417,769
influxdb-client-python in multiprocessing: TypeError("cannot pickle '_thread.lock' object")
<p>I'm running a multiprocessing.Pool and am downloading data via the influxdb-client-python.</p> <p>The code boils down to:</p> <pre class="lang-py prettyprint-override"><code>def do_stuff(): InfluxDBClient( url=os.environ[&quot;INFLUX_HOST&quot;], token=os.environ[&quot;INFLUX_TOKEN&quot;], ...
<python><influxdb>
2023-12-13 13:02:20
1
1,228
sezanzeb
77,653,680
1,782,792
Correct use of buffer protocol for dynamic array
<p>I have a dynamic array type in C++ that I would like to expose through the <a href="https://docs.python.org/3/c-api/buffer.html" rel="nofollow noreferrer">buffer protocol</a>. The type is already exposed as a sequence in Python, but I want to build NumPy arrays with the C++ array data, and I am hoping that a buffer ...
<python><c++><python-c-api>
2023-12-13 12:43:44
1
59,921
javidcf
77,653,679
15,299,206
How to log the insert update and delete in pandas
<p>my csv is below</p> <pre><code>Date,ProductID,Price,Quantity 2023-01-01,1001,10,1 2023-01-02,1001,10,1 2023-01-02,1011,10,6 </code></pre> <p>My output_data.csv below</p> <pre><code>ProductID,TotalSales 1001,20 1011,60 </code></pre> <p>if I am adding csv row and updating also deleting the input csv the output_data.cs...
<python><pandas>
2023-12-13 12:43:39
1
488
sim
77,653,619
11,748,924
AttributeError: DataFrameResampler object has no attribute interpolate in cuDF
<p>With similiar syntax, here is original of pandas dataframe function to resample and interpolate:</p> <pre><code>def resample_and_interpolate(df, datetime_column): # Convert datetime column to datetime format df[datetime_column] = pd.to_datetime(df[datetime_column]) df = df.set_index(datetime_column) # Resam...
<python><pandas><dataframe><cudf>
2023-12-13 12:33:55
1
1,252
Muhammad Ikhwan Perwira
77,653,496
2,913,290
Python MySQL Cursor being blocked by read-only priviledges
<p>I've been using the Python MySQL Database MySQL connection (mysql-connector=2.2.9 and mysql=0.0.3) for almost a year and it worked as a charm.</p> <p>However, our WRITE permissions were removed from a core database. So far, it should not be a problem, because we only fetch data from that database and write to other ...
<python><mysql><mysql-python><mysql-connector>
2023-12-13 12:12:24
0
906
Daniel Vilas-Boas
77,653,406
901,188
getting inside column data change data frame to panda
<p>i am using Databricks with pyspark and i have data in data frame which i am converting in Panda, which change data sequence of array type inside of my column. same issue if i do <code>dataframe.collect()</code>.</p> <p>code snipped</p> <pre><code> result_df = prule_val.groupBy(&quot;CUSTOMER_CODE&quot;).agg( ...
<python><pyspark>
2023-12-13 11:56:14
0
757
Dilip
77,653,244
2,815,264
How to run RedisInsight V2 and a Redis Cluster on Docker localhost using user-defined bridge?
<p>We've noticed many peers are struggling with the RedisInsight V2 setup and a dockerized Redis Cluster on Windows. We are running Windows 11 and the latest Docker Desktop with WLS2 activated. Since macvlan, ipvlan and host network types are not available on Windows (development machines), we are somewhat limited.</p>...
<python><redis><redis-cluster><redis-py><redisinsights>
2023-12-13 11:32:52
0
2,068
feder
77,653,127
241,605
How can you suppress logging for a block of code in structlog?
<p>I am writing a test of an error condition, checking that it occurs and is handled. I don't want the test output to be spammed with error messages for errors that have been deliberately provoked and handled. Structlog is being used for all the logging.</p> <p>How can I temporarily suppress all log output for a block ...
<python><structlog>
2023-12-13 11:13:59
1
20,791
Matthew Strawbridge
77,653,116
10,979,307
Why BeautifulSoup gives me more tags than available?
<p>I'm extracting the audios of a bunch of words from <a href="https://www.oxfordlearnersdictionaries.com/" rel="nofollow noreferrer">Oxford Learner's Dictionaries</a> using <code>BeautifulSoup</code> in Python. Here's the code:</p> <pre class="lang-py prettyprint-override"><code>#!/bin/python3 import sys import reque...
<python><web-scraping><beautifulsoup>
2023-12-13 11:12:46
1
761
Amirreza A.
77,653,080
6,307,685
Simplifying expression with SymPy by specifying ranges
<p>I would like to simplify an expression with cases/branches by specifying the range of my <code>Idx</code> object. Consider the following example:</p> <pre class="lang-py prettyprint-override"><code>import sympy as sym i = sym.Idx(&quot;i&quot;) j = sym.Idx(&quot;j&quot;) N = sym.Symbol(&quot;N&quot;, integer=True) ...
<python><sympy><symbolic-math>
2023-12-13 11:07:45
1
761
soap
77,653,042
8,160,318
Default project credentials in GCP Cloud Functions not implicit anymore?
<p>I have a Google Cloud Function that uses GCP client libraries like the python <a href="https://cloud.google.com/python/docs/reference/storage/latest" rel="nofollow noreferrer"><code>google-cloud-storage</code> (v2.1.0)</a>:</p> <pre class="lang-py prettyprint-override"><code>from google.cloud.storage import Client ...
<python><google-cloud-platform><google-cloud-functions><google-cloud-storage>
2023-12-13 11:02:53
1
16,993
Jozef - Spatialized.io