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,503,020
2,587,422
Python projects depending on one another in VSCode
<p>I have a workspace in VSCode with some Python projects which depend on one another. I'd like to test changes on some projects at the same time. Is it possible to configure VSCode (maybe with a plugin) in order to do so?</p>
<python><visual-studio-code>
2023-11-17 16:00:41
1
315
Luigi D.
77,502,964
17,194,313
How do I leverage naming conventions in a Python codebase to avoid repetitive code without `eval`/`exec`?
<p>I have a number of DataFrames in Python:</p> <pre class="lang-py prettyprint-override"><code>[df1, df2, fd3, df4, ...] </code></pre> <p>And a large number of functions that act on them</p> <pre class="lang-py prettyprint-override"><code>[clean_df1, clean_df2, clean_df2, ...] </code></pre> <pre class="lang-py prettyp...
<python><dataframe><python-polars>
2023-11-17 15:51:47
4
3,075
MYK
77,502,783
1,094,836
Formatted xticklabels on pandas plot show as 1971
<p>I've imported data from an Excel file and I plot it with Matplotlib. If I use only default settings I get accurate results with correct tick labels, even if not formatted the way I want.</p> <pre><code>df.plot() </code></pre> <p><a href="https://i.sstatic.net/PsRCm.png" rel="nofollow noreferrer"><img src="https://i....
<python><pandas><matplotlib><datetime><xticks>
2023-11-17 15:23:41
0
487
Michael Stern
77,502,645
3,102,968
Running a Jupyter Notebook Fails with a 500 Error
<p>I'm trying to run a simple Jupyter notebook on my local machine and I strangely run into some errors.</p> <pre><code>$ python --version Python 3.11.5 </code></pre> <p>I just run the following command:</p> <pre><code>$jupyter notebook </code></pre> <p>and when I select the available notebooks, I get a 500 Error and i...
<python><jupyter-notebook>
2023-11-17 15:05:36
2
15,565
joesan
77,502,352
8,359,217
FastAPI passing params in get request via TestClient
<p>I'm currently working with FastAPI's TestClient and came across an unexpected behavior that I'd like some clarification on.</p> <p>Working Example:</p> <pre class="lang-py prettyprint-override"><code>from fastapi.testclient import TestClient from fastapi import status def my_func(client: TestClient) -&gt; None: ...
<python><pytest><fastapi>
2023-11-17 14:20:49
0
303
Matheus Schaly
77,502,176
12,493,753
ModuleError with pyranges when reading .pkl file in Jupyter Notebook
<p>I need to read a .pkl file in JupyterLab. The code I have is:</p> <pre><code>import dill # Loading scplus_obj scplus_obj = dill.load(open('/path-to-my-file/scplus_obj.pkl', 'rb')) </code></pre> <p>The error get is :</p> <pre><code>--------------------------------------------------------------------------- ModuleNo...
<python><pickle><jupyter-lab><dill>
2023-11-17 13:53:32
1
446
Arnoneel Sinha
77,502,027
4,433,386
Infer return type annotation from other function's annotation
<p>I have a function with a complex return type annotation:</p> <pre class="lang-py prettyprint-override"><code>from typing import (Union, List) # The -&gt; Union[…] is actually longer than this example: def parse(what: str) -&gt; Union[None, int, bool, float, complex, List[int]]: # do stuff and return the object as...
<python><python-typing>
2023-11-17 13:27:37
3
36,888
Marcus Müller
77,501,948
6,654,730
Creating a stamp with pypdf does not work for simple PDF file, works for others
<p>I am following the <code>pypdf</code> documentation here: <a href="https://pypdf.readthedocs.io/en/latest/user/add-watermark.html#watermark-overlay" rel="nofollow noreferrer">https://pypdf.readthedocs.io/en/latest/user/add-watermark.html#watermark-overlay</a></p> <p>I want to overlay one PDF over another (or overlay...
<python><python-3.x><pdf><pypdf>
2023-11-17 13:14:53
2
7,670
M3RS
77,501,936
1,761,587
Can async generators run concurrently?
<p>I'm trying to understand async generators and its practical use-case better. So, I wrote this code</p> <pre><code>import asyncio async def download(urls): for url in urls: print(f&quot;Downloading page at {url} started&quot;) await asyncio.sleep(2) # simulating a page download print(f&qu...
<python><asynchronous><async-await><generator><coroutine>
2023-11-17 13:13:00
0
332
knightcool
77,501,713
13,635,877
Looking up the value associated with the previous date of same ticker
<p>I have a reproducible example that only has 4 rows, but I am using this for a 12m row dataset.</p> <p>Is there an easier way to achieve what the following code does? As you can see there are a lot of steps.</p> <pre><code>import pandas as pd df = pd.DataFrame([['1/1/2023','ABC',0.01],['1/1/2023','XYZ',0.09],['1/7/2...
<python><pandas><dataframe><merge>
2023-11-17 12:39:07
1
452
lara_toff
77,501,687
6,703,592
dataframe merge un-crossed blocks
<p>I want to merge some un-crossed blocks. For example</p> <pre><code>import pandas as pd df = pd.DataFrame() df_11 = pd.DataFrame([[1,1], [1,1]], index=['1', '2'], columns=['col1', 'col2']) df_12 = pd.DataFrame([[2,2], [2,2]], index=['1', '2'], columns=['col3', 'col4']) df_21 = pd.DataFrame([[3,3], [3,3]], index=['3'...
<python><pandas><dataframe>
2023-11-17 12:33:03
3
1,136
user6703592
77,501,565
1,761,587
Python generator missing a value during iteration
<p>Hello while using generators in my code, I noticed this strange behaviour where after breaking out from the loop, the <code>next()</code> call on a generator skips one value. Example code:</p> <pre><code>from itertools import cycle def endless(): yield from cycle((9,8,7,6)) total=0 e = endless() for i in e: ...
<python><loops><for-loop><iterator><generator>
2023-11-17 12:12:49
1
332
knightcool
77,501,353
726,730
pyqt5 font-size and dimensions missmatch between QtDesigner (preview mode) and production
<p><a href="https://i.sstatic.net/icrtm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/icrtm.png" alt="enter image description here" /></a></p> <p><a href="https://i.sstatic.net/KjPhV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KjPhV.png" alt="enter image description here" /></a></p> ...
<python><pyqt5><size><font-size><qt-designer>
2023-11-17 11:35:21
1
2,427
Chris P
77,501,303
2,587,422
Python SimpleQueue not fair
<p>The Python standard library provides two implementations for the thread-safe <code>SimpleQueue</code>:</p> <ol> <li>A <a href="https://github.com/python/cpython/blob/main/Modules/_queuemodule.c#L28-L35" rel="nofollow noreferrer">pure C implementation</a></li> <li>A fallback <a href="https://github.com/python/cpython...
<python><queue><cython><python-multithreading>
2023-11-17 11:27:23
0
315
Luigi D.
77,501,140
2,132,157
How can I plot a 2D image and align its projection to the axes keeping the plots dimension small compared to the image?
<p>I am struggling finding a way to keep the projection of the image completely aligned to the image (as in the figure below) but at the same time reducing their dimension so that the image take most of the figure space.</p> <pre class="lang-py prettyprint-override"><code> import matplotlib.pyplot as plt import...
<python><matplotlib><matplotlib-gridspec>
2023-11-17 10:59:42
1
22,734
G M
77,501,093
4,131,583
Pandas - compute the sum of numerical characters of every string in a dataframe
<p>I have a dataframe with a column &quot;dname&quot;. It contains many rows of 2LD domain names. i.e.</p> <pre><code>123ask example92 what3ver ... </code></pre> <p>I want to find the number of digits for every string in every row.</p> <pre><code>6 11 3 ... </code></pre> <p>So, to create a new column in the dataframe w...
<python><pandas><dataframe>
2023-11-17 10:53:25
3
923
gevaraweb
77,500,954
859,227
Iterate over dataframe columns by index and step 2
<p>For a dataframe like this</p> <pre><code> M1_x M1_y M2_x M2_y 0 2 0.861626 2 0.980591 1 4 0.685437 4 0.647706 2 8 0.495346 8 0.303102 3 16 0.327949 16 0.133477 </code></pre> <p>I would like to plot two...
<python><dataframe>
2023-11-17 10:33:09
2
25,175
mahmood
77,500,939
2,929,914
Python Polars ComputeError when reading pickle file
<p>When I try to execute the snippet below:</p> <pre><code>import pickle f = open('my_file_path.pkl', 'rb') loaded_obj = pickle.load(f) f.close() </code></pre> <p>I'm getting the following error:</p> <pre><code>ComputeError: out-of-spec: Unable to get root as message: {err:?} </code></pre> <p>At first I thought that t...
<python><python-polars>
2023-11-17 10:30:50
0
705
Danilo Setton
77,500,656
14,823,310
Is it safe to store supabase session access token in streamlit session state?
<p>I am using supabase authentication system for my streamlit app which is a multipage app. One page is the login and another page display the data of the logged in user.</p> <p>To retrieve the user in the page with data I have to store in session-state the token of the logged in user.</p> <p>In my login.py I Have:</p>...
<python><token><browser-cache><streamlit><supabase>
2023-11-17 09:45:35
0
591
pacdev
77,500,616
15,948,240
Product between MultiIndex and a list
<p>I have a MultiIndex object with 2 levels:</p> <pre><code>import pandas as pd mux = pd.MultiIndex.from_tuples([(1,1), (2,3)]) &gt;&gt;&gt; MultiIndex([(1, 1), (2, 3)], ) </code></pre> <p>I want to multiply it by a list <code>l=[4,5]</code>, I tried</p> <pre><code>pd.MultiIndex.from_product([mux...
<python><pandas><multi-index><cartesian-product>
2023-11-17 09:38:17
3
1,075
endive1783
77,500,442
12,242,085
How to add cross validation to Optuna function to tune hyperparameters for LSTM?
<p>I have code to tune hyperparameters in LSTM. How can I:</p> <ol> <li>add cross validation based on 5 folds on training dataset</li> <li>print avg <code>AUC</code> from each iteration from training dataset divided on 5 folds</li> <li>print <code>AUC</code> from test dataset (of course do not divide test dataset on fo...
<python><machine-learning><lstm><cross-validation><optuna>
2023-11-17 09:10:24
0
2,350
dingaro
77,500,330
13,798,993
Python retrieving data from its memory address
<p>I currently have a very large dataset (~15 GB) which should be used by multiple python scripts at the same time.</p> <p>Loading single elements of the dataset takes too long, so the whole dataset has to be in memory.</p> <p>My current best approach would be to have a python process which has all the elements loaded,...
<python><python-3.x><memory>
2023-11-17 08:50:01
1
689
Quasi
77,500,265
4,494,781
How to typephint a return value to an IntEnum
<p>I want to annotate a function to indicate that it can only return values from an <code>IntEnum</code></p> <pre><code>from enum import IntEnum import random class GoodIntegers(IntEnum): THE_ANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING = 42 DEADBEEF = 0xdeadbeef LEET = 1337 def f() -&gt; GoodInteg...
<python><mypy><python-typing>
2023-11-17 08:35:35
0
1,105
PiRK
77,500,211
16,027,663
Can't Upgrade to Python 3.12 on Windows 8.1 - No "Upgrade Now" Option
<p>I am running Python 3.7.4 currently and need to upgrade to 3.12 on my Windows 8.1 PC.</p> <p>When I run the installer I don't get an &quot;Upgrade Now&quot; option as the various guides I have read suggest:</p> <p><a href="https://i.sstatic.net/XM0ik.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XM0...
<python>
2023-11-17 08:24:57
0
541
Andy
77,500,127
12,104,604
How to pass string data between processes using Python's multiprocessing and shared memory with Array('c', fixed_length)
<p>I looked at <a href="https://stackoverflow.com/q/21290960/12104604">past questions</a> about sharing Python string data using multiprocessing and shared memory, but it seems unresolved.</p> <p>I know that I can share numbers and arrays between processes with <a href="https://qiita.com/t_okkan/items/4127a87177ed2b2db...
<python><multiprocessing>
2023-11-17 08:08:05
1
683
taichi
77,500,119
3,732,793
unittest example from the docs not working for dynamic list
<p>From the <a href="https://docs.python.org/3/library/unittest.html#organizing-test-code" rel="nofollow noreferrer">documentation</a> this example</p> <pre><code>import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): s...
<python><python-unittest>
2023-11-17 08:07:08
1
1,990
user3732793
77,499,757
5,308,802
SQLAlchemy: return ORM objects from subquery
<p>I need to join several tables, then return distinct rows by some rule based on partitions of model C.id (let's use <code>row_number()==1</code> for simplicity). As it's a window function, it cannot be directly used in <code>where</code>, so requires an outer query to filter. And it works, but it turns that moving mo...
<python><sqlalchemy><orm><window-functions>
2023-11-17 06:44:01
1
1,228
AivanF.
77,499,506
4,277,485
python pandas replace any string value in all the numeric column with constant
<p>As a part of data cleaning, Dataset have 100+ column and want to check if any numeric/float columns have string values and replace all of them with constant numeric value.</p> <p>Data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">data1</th> <th style="text-al...
<python><python-3.x><pandas><dataframe><replace>
2023-11-17 05:26:33
1
438
Kavya shree
77,499,424
3,382,426
Why can I convert an RGB image to a 17 color palette, but no fewer? (Python Pillow version 10.1.0)
<p>The image used doesn't seem to matter. Here's an RGB image:<br /> <a href="https://i.sstatic.net/xLAKX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xLAKX.png" alt="blue/black gradient" /></a></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import PIL from PIL import Image im...
<python><python-imaging-library><color-palette>
2023-11-17 04:55:19
0
772
user3382426
77,499,326
13,430,381
How to cast array data from object to float64 after reading an Excel file with Pandas/NumPy?
<p>I am trying to import a number of Excel files in a for loop and cast a column from the file as an array of type <code>float64</code>, to be used later in an lmfit function. To do so, I read the Excel files (iterated by an index), put data from one column into a list, and then cast the list as an array. Shown below:<...
<python><arrays><pandas><numpy><lmfit>
2023-11-17 04:16:24
1
526
ttoshiro
77,499,302
832,230
Calculate Bollinger Z-score using Pandas
<p>Given a series, I want to calculate its Bollinger Z-score (not the Bollinger band) using Pandas. There exists a prior <a href="https://stackoverflow.com/q/74283043/">question</a> which discusses how to calculate the band, but not the z-score.</p> <p>Given a variable <code>series</code> of type <code>pandas.Series</c...
<python><pandas><technical-indicator>
2023-11-17 04:08:37
1
64,534
Asclepius
77,499,188
2,604,247
What is a Plain Text Translation of this SQL Query?
<p>My SQL knowledge is really basic, and need some help in <em>translating</em> this rather long query (running in a python script querying some AWS athena database, with some f-strings embedded) to plain English or flow chart. I understand concepts of SELECT * WHERE, JOINS etc., but this seems really advanced, renamin...
<python><sql><mysql><query-optimization>
2023-11-17 03:26:12
2
1,720
Della
77,499,112
2,446,374
query github commits from a certain date using pygithub
<p>have the following code:</p> <pre class="lang-py prettyprint-override"><code>from github import Github ... g = github(token) query = f'org:{org_name} author:{username} since=2021-10-19T00:00:00Z' commits = g.search_commits(query, sort='author-date', order='desc') </code></pre> <p>If I have the &quot;since&quot; para...
<python><github><pygithub>
2023-11-17 02:51:31
1
3,724
Darren Oakey
77,498,968
14,503,336
FastAPI CORS, wildcard in allow origins not working
<p>Simplified versions of my code, using two approaches.</p> <pre><code>from fastapi import FastAPI middleware = [ Middleware( CORSMiddleware, allow_origins=[&quot;*&quot;], allow_credentials=False, allow_methods=[&quot;*&quot;], allow_headers=[&quot;*&quot;], ) ] app =...
<python><next.js><cors><fastapi><middleware>
2023-11-17 01:59:17
1
599
Anonyo Noor
77,498,924
179,234
Trying pip download with platform manylinux1_x86_64 still gives error for windows
<p>I have a web server (debian) that is not connected to the internet and would like to run my code in it. I have the code running in my local machine (windows) and also have it running on a dev server that has internet access to it (debian)</p> <p>To do that I want to</p> <ul> <li>download all needed pip libraries in ...
<python><pip>
2023-11-17 01:38:34
0
1,417
Sarah
77,498,920
3,140,750
Python Type Narrowing with TypeGuard: Narrowing Return type that is a TypeVar
<p>Consider the following case:</p> <pre><code>from typing import TypeVar from typing_extensions import TypeGuard _T = TypeVar('_T', str, int) def is_str(val: _T) -&gt; TypeGuard[str]: return isinstance(val, str) def is_int(val: _T) -&gt; TypeGuard[int]: return isinstance(val, int) def process_str_int(data:...
<python><python-typing><typeguards><pyright>
2023-11-17 01:37:52
1
409
Atimaharjun
77,498,859
7,077,532
Python Dataframe: For Each Row Pick One Value from Five Different Columns And Place In New Column Based on if Value is in List
<p>Let's say I'm starting with the following input table below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>id</th> <th>val1</th> <th>val2</th> <th>val3</th> <th>val4</th> <th>val5</th> <th>val_final</th> </tr> </thead> <tbody> <tr> <td>2023-08-29</td> <td>B3241</td> <td>4...
<python><dataframe><list><filter><isin>
2023-11-17 01:09:43
1
5,244
PineNuts0
77,498,677
1,227,778
How to update Django url (to include data/param) after POST
<p>I have a search form (place names) on my home page with an auto-complete dropdown on the search input field. When the user presses enter after selecting an item in the search box the form does a post. When the results return I still have the same url (<a href="https://mywebsite.com" rel="nofollow noreferrer">https...
<python><django>
2023-11-17 00:01:50
1
495
The Huff
77,498,663
858,675
get sharepoint file programatically (I know the url from a web browser)
<p>I use sharepoint from a web browser.</p> <p>I visualize a file (xls file) that has following url</p> <p><a href="https://mysite.sharepoint.com/:x:/r/_layouts/15/Doc.aspx?sourcedoc=%7Bxxxxxx-xxxxx-xxxx%7D&amp;file=filename.xlsx&amp;action=default&amp;mobileredirect=true" rel="nofollow noreferrer">https://mysite.share...
<python><sharepoint><microsoft365>
2023-11-16 23:57:49
0
5,660
gelonida
77,498,534
10,973,108
Selenium + Cloudflare - trouble to access page
<p>I'm stucked to access this website - https://...</p> <p>The cloudflare is blocking the selenium driver.</p> <p>Currently i'm using <a href="https://github.com/seleniumbase/SeleniumBase" rel="nofollow noreferrer">https://github.com/seleniumbase/SeleniumBase</a> that suports undetected driver, but not works.</p> <p>I'...
<python><selenium-webdriver><selenium-chromedriver><cloudflare><seleniumbase>
2023-11-16 23:19:37
0
348
Daniel Bailo
77,498,449
11,141,816
Why V+1 in Embedding layer(`Embedding(V+1,D)(i)`) where V the vocabulary size?
<p>Suppose</p> <pre><code>from tensorflow.keras.preprocessing.text import Tokenizer tokenizer = Tokenizer() ... V = len(tokenizer.word_index) </code></pre> <p>where <code>V</code> was the vocabulary size.</p> <p>I was told that the embedding layer</p> <pre><code>x = Embedding(V+1,D)(i) </code></pre> <p>where <code>D</c...
<python><tensorflow><shapes><word-embedding>
2023-11-16 22:52:46
1
593
ShoutOutAndCalculate
77,498,423
1,175,788
How do I download non-dataframe data from a Databricks notebook?
<p>I'm trying to download a schema of a dataframe, or essentially the output of <code>df.printSchema()</code> but the schema is too big that it's getting truncated in the output. This is in a production environment too, so I can't temporarily store the output onto the Hive metastore. Any way to fully print or save the ...
<python><databricks>
2023-11-16 22:44:56
1
3,011
simplycoding
77,498,397
9,687,785
How to set size of total memory for sparkling water cluster in Databricks
<p>I am working in Databricks with Sparkling Water 3.40.0.4; I have a total driver memory of 512 GB and six workers with 64 GB each. When I call</p> <pre><code>hc = H2OContext.getOrCreate() </code></pre> <p>the internal H2O cluster is created across six workers, but the total cluster memory size is roughly 60 GB. I can...
<python><apache-spark><databricks><h2o><sparkling-water>
2023-11-16 22:38:15
0
683
omoshiroiii
77,498,172
18,237,126
Tkinter displaying an image on fullscreen
<p>I am trying to set a background image for a menu. However, the image comes with some white padding that I can't quite remove.</p> <p>The image works fine and it is being every element i place on the screen.</p> <p>I am looking for a way to remove this padding. Or, in other words, for the image to fit the whole scree...
<python><image><tkinter><fullscreen>
2023-11-16 21:37:45
1
314
António Rebelo
77,498,034
215,120
Weird pyspark behavior when filtering on booleans
<p>We have some existing code that used to work in Spark 3.1, and now is not working in Spark 3.3. It is really trivial code, so its blowing my mind why the filter isn't working:</p> <pre><code>widgets_df = widgets_df.filter(F.col(&quot;_id&quot;).isin(*widget_ids)) </code></pre> <p>For some reason, even if there are r...
<python><apache-spark><pyspark><apache-spark-sql><aws-glue>
2023-11-16 21:02:30
0
18,431
rouble
77,498,009
13,033,188
Python Read from csv1 and reference csv2 to write to csv3
<p>I have two csv files, csv1 is the working file that changes, csv2 is static and used as a reference set.</p> <p>csv1 - input.csv</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Owner</th> <th>Status</th> <th>Date</th> <th>Group</th> </tr> </thead> <tbody> <tr>...
<python><csv><reference>
2023-11-16 20:56:43
1
413
Happy.Hartman
77,497,945
19,694,624
Pending bot reply from a slash command pycord
<p>I have a bot, and I want to type the command <code>/chat</code> and then have the bot create a thread and respond to the command there. I did that successfully, but the problem is that the message &quot;bot is thinking&quot; keeps pending even after bot completed everything I asked.</p> <p>So I was wondering, how ca...
<python><python-3.x><discord><discord.py><pycord>
2023-11-16 20:43:57
2
303
syrok
77,497,941
5,527,646
How to remove string items from a list
<p>Suppose I have a list of string items like this:</p> <pre><code>myList = ['CLIPPOLY', 'ExternalCrosswalk','CrossReference', 'SourceCitation', 'Status', 'Waterbody', 'N_1_EDesc', 'N_1_ETopo', 'N_1_JDesc', 'N_1_JTopo', 'N_1_Props', 'Line'] </code></pre> <p>I want to remove any item that has 'N_1' from my list. Simple ...
<python><list>
2023-11-16 20:43:30
1
1,933
gwydion93
77,497,663
4,329,348
ROS 2 how have a callback and main code in same node / fille?
<p>I want to have a single file / node that will subscribe to a topic, while it will also let the node to run as a main code synchronously. The problem is that I can seem to find the proper way to have async and sync code in ROS2. I would like when the node is killed to send zero velocities to the robot to stop moving....
<python><ros><ros2>
2023-11-16 19:48:27
1
1,219
Phrixus
77,497,639
10,589,070
Python Filtering OData Entity by Parent - Requests Library
<p>I have an OData API I'm trying to query using the Python Requests library. I'm trying to filter a table based on the parent table for an incremental data pull. The children tables don't use a <code>last_update_date</code>, but I can get this date from the parent as the parent's <code>last_updated_date</code> chan...
<python><python-requests><filtering><odata>
2023-11-16 19:45:47
1
446
krewsayder
77,497,448
893,254
Python project structure - no module named 'lib'
<p>I have never worked on or built myself a properly structure Python codebase before. I aim to do that today.</p> <p>Here's the structure I have attempted to implement:</p> <pre><code>My-Fancy-Project-Name /src /bin /binary1/main.py /binary2/my_binary.py /binary3 my_scripy.py au...
<python>
2023-11-16 19:07:38
1
18,579
user2138149
77,497,397
897,224
How to autogenerate Pydantic field value and not allow the field to be set in initializer or attribute setter
<p>I want to autogenerate an ID field for my Pydantic model and I don't want to allow callers to provide their own ID value. I've tried a variety of approaches using the <code>Field</code> function, but the ID field is still optional in the initializer.</p> <pre class="lang-py prettyprint-override"><code>class MyModel(...
<python><pydantic>
2023-11-16 18:57:32
2
2,840
Brian
77,497,391
826,235
Pandas to_csv write json objects with no spaces
<p>I have a dataframe object with some columns of type dict, containing some nested json objects. When I use to_csv to write the dataframe to a csv file, everything works, however the json objects have spaces for formatting in them, like:</p> <p><code>{'field': 'value', 'field2': 'value2'}</code></p> <p>I want to write...
<python><json><pandas><csv>
2023-11-16 18:56:59
1
1,377
yogi
77,497,299
2,492,274
fastapi Error: AssertionError: Status code 204 must not have a response body
<p>I have this code using FastAPI:</p> <pre><code>@router.put( &quot;/api/v1/me/language&quot;, tags=[&quot;users&quot;], responses={ 400: {&quot;model&quot;: BadRequest}, 401: {&quot;model&quot;: Unauthorized}, 403: {&quot;model&quot;: Forbidden}, 404: {&quot;model&quot;: No...
<python><fastapi>
2023-11-16 18:41:34
1
607
Stoecki
77,497,219
1,188,943
Stale element exception handling is not working in Selenium
<p>The following code cannot handle the Stale element exception error:</p> <pre><code> website_accessable = False try: driver.get(addressToVerify) website_accessable = True except WebDriverException as e: if 'net::ERR_SSL_PROTOCOL_ERROR' in str(e): ...
<python><selenium-webdriver>
2023-11-16 18:27:13
0
1,035
Mahdi
77,496,981
7,243,493
update dictionary in nested array of dictionaries
<p>I want to update the list2 based on the values in the opti array, in a way so that it check if the nested array has a dict with the key 'RSI_15' and then update the dict with the key &quot;val&quot; in the same array, and so on for all the arrays in the opti array.</p> <p>right now my output is this</p> <pre><code>[...
<python><arrays><dictionary>
2023-11-16 17:44:14
3
568
Soma Juice
77,496,918
9,443,671
Import PyAudio not working on M3 Pro Mac OS Sonoma (Could not import the PyAudio C module 'pyaudio._portaudio'.)
<p>So I'm running into this error which many other people seem to run into on previous macbook such as the M1... I've tried everything they suggest to fix it, which is to brew install portaudio from <code>--HEAD</code> and to install from source, but I always seem to run into problems with the C library one way or the ...
<python><pyaudio><portaudio>
2023-11-16 17:34:00
1
687
skidjoe
77,496,754
464,277
Using reindex with value_counts in pandas groupby
<p>I'd like to use value_counts with groupby, and keep all labels in the original dataframe. In the example below for, instance,</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'month': [1, 1, 1, 1, 1, 1, 2, 2, 2], 'day': [1, 1, 1, 2, 2, 2, 1, 1, 1], 'value': [1, 2, 3, 4, 5, 6, 1, 1,...
<python><pandas><group-by>
2023-11-16 17:04:21
3
10,181
zzzbbx
77,496,693
386,861
Switching between venvs in VSCode
<p>I'm working through a tutorial in running python in VSCode and am struggling to switch to run numpy. <a href="https://code.visualstudio.com/docs/python/python-tutorial" rel="nofollow noreferrer">https://code.visualstudio.com/docs/python/python-tutorial</a></p> <pre><code>import numpy as np msg = &quot;Roll a dice&q...
<python><numpy><visual-studio-code>
2023-11-16 16:56:28
1
7,882
elksie5000
77,496,677
6,599,648
Python forward a gmail message using Google API
<p>I'm trying to forward a message using Google's API client. In order to do that, I am reading the message, modifying it and would then like to send it, but I run into a problem where the message that I download has the wrong type and I don't know how to encode it. Here is my code:</p> <pre class="lang-py prettyprint-...
<python><gmail-api><urlencode>
2023-11-16 16:54:11
1
613
Muriel
77,496,615
2,383,070
How to label items in a string column by conditional regex in Polars
<p>In Polars, I'm working with a DataFrame with messy string data in a column. In this example, the column can contain a phone number, email address, state, zip code, etc. (my real data actually has a hundred or more different &quot;patterns&quot; stored in this column that is a million rows long.)</p> <pre class="lang...
<python><regex><dataframe><python-polars>
2023-11-16 16:45:38
2
3,511
blaylockbk
77,496,602
9,923,776
Django 4.2 , GenericIPAddress and CIDR
<p>Im updating a project from:</p> <pre><code>Python 3.9 + Postgres 13 + Django 4.0.6 + psycopg2 </code></pre> <p>TO</p> <pre><code>Python 3.11 + Postgresql 15 + Django 4.2 + psycopg3 </code></pre> <p>I have a big problem with GenericIPFields. It seems that it doesn't support cidr anymore.</p> <p>When I try to save an ...
<python><django>
2023-11-16 16:44:18
1
656
EviSvil
77,496,541
2,304,735
How to read double values from CSV file and add them to the same column in pandas?
<p>The following data is in a CSV file:</p> <pre><code>SBUX, Starbucks, YHOO, Yahoo, ABK, Ambac Financial, V, Visa, MA, Mastercard, MCD, McDonald's, MCK, McKesson, MDT, Metronic, MRK, Merk&amp;Co, MAR, Marriott International, MKTX, MarketAxess, LRCX, LAM Research, LOW, Lowe's </code></pre> <p>I want to add each row of ...
<python><python-3.x><pandas><dataframe><csv>
2023-11-16 16:34:18
1
515
Mahmoud Abdel-Rahman
77,496,454
3,763,302
Is there a more efficient way to Apply by Row, then by Column?
<p>My dataset contains 5 measurements taken daily, over a 700 day timespan. I wish to be able to group these values by the day of the week, and then apply the <code>trim_mean</code> function from <code>scipy.stats</code> to the each of the 5 measurements, using <code>1/stddev</code> as the <code>proportiontocut</code> ...
<python><pandas><numpy><group-by>
2023-11-16 16:21:14
1
1,232
Ted
77,496,267
3,102,121
I cannot step into the imported function from the Python module using the PyCharm debugger
<p>I have my main Python script that uses the function 'hello_world' from my imported module 'module1.py</p> <p><a href="https://i.sstatic.net/EYItj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EYItj.png" alt="enter image description here" /></a></p> <p>However, if I use the PyCharm Debugger I cannot ...
<python><function><debugging><module><pycharm>
2023-11-16 15:56:25
1
406
jorge
77,496,183
11,016,395
Adding hatches for certain rows and columns in clustermap
<p>I have used seaborn.clustermap() to plot clustermap as shown below</p> <pre><code>labels = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;, &quot;f&quot;, &quot;g&quot;, &quot;h&quot;, &quot;i&quot;, &quot;j&quot;, &quot;k&quot;, &quot;l&quot;, &quot;m&quot;, &quot;n&quot;, &quot;o&quot;, ...
<python><matplotlib><seaborn><heatmap><clustermap>
2023-11-16 15:44:40
1
483
crx91
77,495,949
3,979,160
LibOpenShot problem with Python bindings, 'openshot' has no attribute 'GetVersion'
<p>I'm trying to compile LibOpenShot for Windows, using this guide: <a href="https://github.com/OpenShot/libopenshot/wiki/Windows-Build-Instructions" rel="nofollow noreferrer">https://github.com/OpenShot/libopenshot/wiki/Windows-Build-Instructions</a></p> <p>All goes well. Had to manually download zmq.hpp and place it ...
<python><windows><openshot>
2023-11-16 15:08:40
0
523
Hasse
77,495,913
9,182,743
groupby.rolling slower than with for loop
<p>I want to perfomr a groupby rolling mean on a large dataset.</p> <p>With large df, doign groupby.rolling seems to be slower than using for loop:</p> <p>This</p> <pre class="lang-py prettyprint-override"><code>grouped['value'].rolling(window=window_size, min_periods=0).mean().reset_index(level=0, drop=True) </code></...
<python><pandas><group-by>
2023-11-16 15:02:53
2
1,168
Leo
77,495,903
214,296
How to create socket to send and receive UDP packets
<p>How may I create a socket that can both send and receive UDP packets?</p> <p>My application requires that sockets are bound to the physical network interface because it's a multicast system with multiple interfaces connecting to redundant, duplicate networks on the target device. It is necessary that my script be a...
<python><sockets><udp><python-3.6><multicast>
2023-11-16 15:01:31
0
14,392
Jim Fell
77,495,844
9,806,500
directory of jsons to df with pathlib
<p>I've got a set of jsons in a directory that I'm trying to loop through and read to Pandas df with <code>pathlib.Path('my_jsons_dir').iterdir()</code></p> <p>The case for a single file works great</p> <pre><code>json_path = pathlib.Path('my_json_path') dict_single = json.loads(json_path.read_bytes()) df_single = pd.D...
<python><json><pandas>
2023-11-16 14:51:42
1
635
M. Wood
77,495,593
4,177,781
Polars how to bin a datetime type column
<p>I am trying to bin a date column. I was able to do that fairly easy using Pandas library. But I am getting the following error with Polars:</p> <pre class="lang-python prettyprint-override"><code>Traceback (most recent call last): File &quot;\workspace\polars.py&quot;, line 4, in &lt;module&gt; pl.col(&quot;ts...
<python><datetime><python-polars>
2023-11-16 14:20:25
4
352
arman
77,495,574
13,489,398
Video tag autoplay pauses when user navigates away from page
<p>I got a video tag that looks like this</p> <pre><code>&lt;video muted controls autoPlay src={videoSrc} width=&quot;640px&quot; height=&quot;480px&quot; onEnded={handleOnEnded} ref={videoRef} /&gt; </code></pre> <p>streaming in video from a websock...
<python><reactjs><typescript><video>
2023-11-16 14:16:42
0
341
ZooPanda
77,495,512
3,551,700
Add file creation and modification date to metadata with DirectoryLoader
<p>I am working with the LangChain library and am interested in whether it is possible to load file creation and/or modification dates together with file content with DirectoryLoader and add that information to the documents' metadata. Is it possible? How to do that?</p> <p>Currently, I load only docx files, but I woul...
<python><langchain><py-langchain>
2023-11-16 14:07:30
1
1,526
Primoz
77,495,492
8,869,570
How to set a list of new columns values to 0.0 in a dataframe?
<p>Suppose I have a list of columns</p> <pre><code>cols = ['col1', 'col2', 'col3'] </code></pre> <p>and a dataframe</p> <pre><code>df = pd.DataFrame() </code></pre> <p>I want to add these <code>cols</code> to <code>df</code> and set them to <code>0.0</code>.</p> <pre><code>for col in cols: df[col] = 0.0 </code></pre>...
<python><pandas><dataframe>
2023-11-16 14:03:25
1
2,328
24n8
77,495,422
2,748,523
get a websocket message to test it
<p>I am quite new to testing web-sockets with pyhton I need to tests an existing code that I cannot change.The code is using websocket-client===0.57.0 a quite old version. It's possible that I am missing out on a simple fix</p> <p>Here is the init function for the class :</p> <pre><code>class Client(): def __init__...
<python><websocket><pytest>
2023-11-16 13:54:19
1
1,220
Ziwdigforbugs
77,495,343
3,979,160
Compiling LibOpenShot -> cannot find zmq.hpp [Win/msys64]
<p>I'm trying to compile LibOpenShot for Windows, using this guide: <a href="https://github.com/OpenShot/libopenshot/wiki/Windows-Build-Instructions" rel="nofollow noreferrer">https://github.com/OpenShot/libopenshot/wiki/Windows-Build-Instructions</a></p> <p>All goes well untill I enter the cmake command for building l...
<python><c><windows><development-environment><openshot>
2023-11-16 13:45:11
1
523
Hasse
77,495,245
2,756,412
SALABIM how to minimize memory requirements
<p>I am using the <a href="https://www.salabim.org/" rel="nofollow noreferrer">Salabim package</a> in python to simulate some queueing theory. Salabim <a href="https://www.salabim.org/manual/" rel="nofollow noreferrer">(documentation)</a> is based on <a href="https://simpy.readthedocs.io/en/latest/" rel="nofollow noref...
<python><memory><simulation><simpy>
2023-11-16 13:31:01
2
906
Floris Padt
77,495,105
6,840,039
Pandas: count unique users using rolling window
<p>I have dataframe with time and user_id</p> <pre><code> time user_id 2023-02-20 00:00:20 5008662006351712 2023-02-20 00:01:25 5008662006474892 2023-02-20 00:04:28 5008662006889403 2023-02-20 00:05:33 5008662006351712 2023-02-20 00:07:36 5008662004944382 2023-02-20 00:08:37 500866200676041...
<python><pandas>
2023-11-16 13:13:15
2
4,492
Petr Petrov
77,494,978
5,736,091
How to plot columns with a value and x-y positions as a color grid in subplots
<p>In R I would do the following to make a grid of facets with a raster-plot in each facet:</p> <pre><code># R Code DF &lt;- data.frame(expand.grid(seq(0, 7), seq(0, 7), seq(0, 5))) names(DF) &lt;- c(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;) DF$I &lt;- runif(nrow(DF), 0, 1) # x y z I # 1: 0 0 0 0.70...
<python><pandas><matplotlib><seaborn><heatmap>
2023-11-16 12:55:47
1
1,357
Phann
77,494,964
12,016,688
Why list comprehensions create a function internally?
<p>This is disassembly of a list comprehension in <a href="/questions/tagged/python-3.10" class="post-tag" title="show questions tagged &#39;python-3.10&#39;" aria-label="show questions tagged &#39;python-3.10&#39;" rel="tag" aria-labelledby="tag-python-3.10-tooltip-container">python-3.10</a>:</p> <pre class="lang-py p...
<python><python-3.x><list-comprehension><cpython><python-internals>
2023-11-16 12:53:19
3
2,470
Amir reza Riahi
77,494,963
1,333,515
How do I access the camera/transform parameters in cv2.Stitcher?
<p>I am trying to stitch together a bunch of microscope images, but I need to keep track of the physical location of each image. Before stitching, I know the coordinates of each individual image, but after stitching the Python method only returns the stitched image and some status flag.</p> <p>How do I obtain the (affi...
<python><opencv><computer-vision><image-stitching><opencv-stitching>
2023-11-16 12:53:18
1
501
Jan M.
77,494,961
17,220,672
mpy gives keeps raising error because of Protocol
<p>Im using pytest framework with mypy and when writing fixtures I created Protocols to mimic return types. (I could not import it directly because of env instantiation)</p> <p>This example greatly simplifies my troubles:</p> <pre><code> from typing_extensions import Protocol class LoadServiceType(Protocol): z: in...
<python><protocols><mypy>
2023-11-16 12:52:45
1
419
mehekek
77,494,902
6,283,849
How to retrieve user's username after authenticating in Gradio
<p>I have a gradio app with a custom login function. I was successful in doing authentication, but then I would like to retrieve and keep the user's username during the session. What would be the solution?</p> <pre class="lang-py prettyprint-override"><code>import gradio as gr def login(email, password): &quot;&qu...
<python><authentication><gradio>
2023-11-16 12:43:37
1
6,421
Alexis.Rolland
77,494,877
13,066,054
How to add condition in pandas named aggregates
<pre><code> director_master_id company_master_id designation date_cessation appointment_original_date some_col director_name appt_chng_desig_date t_designation t_dir_category 0 2601721 2465280 Director NaT 2020-08-21 0000000 ...
<python><pandas><dataframe>
2023-11-16 12:38:51
2
351
naga satish
77,494,813
18,793,790
How do I install packages and a virtual maching on a server that does not have internet using pipenv?
<p>I have a python script that I am trying to put on a server that does not have internet access. I am using pipenv to create a virtual environment. Nornally how I do the scripts on servers with internet access it I copy the script, pipfile and pipfile.lock into a directory on the server. Then I make a empty .venv fold...
<python><python-3.x><pipenv>
2023-11-16 12:30:35
1
346
Avi4nFLu
77,494,746
9,974,205
How can I move datetime to the closest five minutes?
<p>I am working with a dataframe in pandas. In this dataframe there is a column which type is datetime. It represents the moment in which a product is sold, other columns indicate the price, the type, amount sold, amount remaining...</p> <p>To do an analysis, I want more datetime columns to check how many products are ...
<python><pandas><dataframe><datetime><ceil>
2023-11-16 12:20:31
1
503
slow_learner
77,494,696
499,699
PyTorch For Loop Optimisations and Speedup techniques
<p>This is a problem I've now encountered three times in the past year.</p> <p>I appreciate that in certain scenarios, a vectorized solution will be better and considerably faster.</p> <p>However IMHO, there is a trade off between discovering a vectorizing solution and using what is essentially a for loop (or double fo...
<python><for-loop><pytorch>
2023-11-16 12:12:57
3
14,954
Ælex
77,494,647
12,069,922
CUDA Runtime Error during Spacy Transformers NER Model Training
<p>I am currently training a custom NER model (having 90k data records), using Spacy Transformers (en_core_web_trf) and I'm encountering an issue where the training process is taking an unusually long time and eventually gets killed, throwing a CUDA runtime error.</p> <p>Here's a brief overview of my setup:</p> <pre><c...
<python><gpu><spacy><huggingface-transformers>
2023-11-16 12:05:30
1
399
iamhimanshu0
77,494,552
5,199,660
Azure Data Factory, Batch Service, Python: Unable to append blob with csv chunks
<p>Azure Data Facory pipeline runs a Custom activity with Batch Service as a linked service, which holds Python code in it. The transformation was built for running locally, and I want to make it work on Azure, saving blobs (csv files) into Azure Storage (Az Data Lake).</p> <p>The transformation runs on chunks, and per...
<python><azure><azure-data-factory><azure-storage><azure-batch>
2023-11-16 11:49:17
1
656
Eve
77,494,543
5,841,406
seleniumbase (undetected Chrome driver): how to set request header?
<p>I am using seleniumbase with Driver(uc=True), which works well for my specific scraping use case (and appears to be the only driver that consistently remains undetected for me).</p> <p>It is fine for everything that doesn't need specific header settings.</p> <p>For one particular type of scrape I need to set the Req...
<python><selenium-webdriver><http-headers><seleniumbase>
2023-11-16 11:48:38
2
1,165
MandyShaw
77,494,525
8,233,873
Altair: Apply condition to axis label color based on label membership in a list
<p>I have a scheduling plot where the Y axis is categorical (each Y-entry corresponds to a piece of equipment and the x axis displays time).</p> <p>I have a list of equipment that contains scheduling clashes. For each equipment item in the list of equipment with clashes, I want to highlight the equipment name in red on...
<python><pandas><streamlit><altair>
2023-11-16 11:45:55
2
313
multipitch
77,494,518
149,900
Emulate openssl s_client verify facility in Python
<p>I want to do something similar to this:</p> <pre><code>openssl s_client -verify_return_error -quiet -strict -verifyCAfile CA_file.crt server.name:4443 </code></pre> <p>The Certificate installed on <code>server.name</code> is a partial chain containing (in order): Server's cert, and the Intermediate1 cert.</p> <p>Run...
<python><openssl><pyopenssl>
2023-11-16 11:44:10
0
6,951
pepoluan
77,494,287
12,769,783
Is the name of the second parameter to __deepcopy__ required to be memo?
<p>Is it required to name the second argument of the <code>__deepcopy__</code> function <code>memo</code>, in case <code>__deepcopy__</code> is called with <code>memo</code> as a keyword argument?</p> <p>If I simply want to exclude instances from deep copies, would:</p> <pre class="lang-py prettyprint-override"><code>o...
<python><deep-copy>
2023-11-16 11:04:00
0
1,596
mutableVoid
77,494,052
6,399,645
How to interrupt python script that is running a bash command?
<p>I'm running a python script, which is running a bash command <code>cmd</code> via</p> <pre class="lang-py prettyprint-override"><code>try: subprocess.run(['/bin/bash', '-ic', cmd]) except as e: print(&quot;Error:&quot;, e) </code></pre> <p>I run this python script from a bash terminal. When I press <code>cnt...
<python><linux><bash>
2023-11-16 10:30:26
1
434
user56834
77,493,818
4,451,315
Decorator which changes ints to strings with correct type hints
<p>I have written a decorator which changes the types of some arguments passed to a decorated function.</p> <p>For example, any argument which was <code>int</code> should become <code>str</code>:</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable def decorator(func: Callable) -&gt; Callabl...
<python><mypy><python-typing>
2023-11-16 09:57:06
1
11,062
ignoring_gravity
77,493,762
14,661,648
Flask Sock (Websocket) route runs one last time before disconnect
<p>In <code>flask-sock</code> which is for regular websockets, If I run a <code>while</code> loop in a route function, and at the end use a <code>time.sleep(15)</code>, if I disconnect during the <code>time.sleep</code> the loop will run for one last time before disconnecting.</p> <p>I tried to use try except with a bo...
<python><flask><websocket>
2023-11-16 09:47:59
1
1,067
Jiehfeng
77,493,727
18,091,040
Create and get pseudonym of a transaction of credential issue using Hyperledger Indy
<p>I am trying to dive deep in <a href="https://github.com/hyperledger/indy-sdk/blob/main/docs/how-tos/issue-credential/README.md" rel="nofollow noreferrer">this example</a> of Hyperledger Indy about how to issue a credential. Basically, an &quot;author 1&quot; creates a schema definition and stores it in the ledger. T...
<python><blockchain><hyperledger><hyperledger-indy>
2023-11-16 09:41:30
1
640
brenodacosta
77,493,697
1,019,455
py.typed does not be included when use pyproject.toml
<p>I am publishing my package with <code>mypy</code> supported. Unfortunately, I can't bundle <code>py.typed</code> which is blank file to py package. Here is my directory structure from my <a href="https://github.com/elcolie/AGA8-python" rel="nofollow noreferrer">repository</a>.</p> <p>I have followed the <a href="htt...
<python><build><mypy>
2023-11-16 09:36:58
1
9,623
joe
77,493,608
19,198,552
How can I move a tkinter canvas-window by the mouse-pointer?
<p>I have a tkinter Canvas where some objects are placed and can be moved by the mouse pointer. One of these objects is a text, which is not implemented as canvas-text-item but as a text-widget in a canvas-window-item, as I want to implement syntax highlighting for the text. I know how to implement the move-feature for...
<python><tkinter><tkinter-canvas>
2023-11-16 09:25:25
2
729
Matthias Schweikart
77,493,498
9,940,188
Why does a Python system package try to import a local module?
<p>I just ran into a weird problem: a system package (smtplib) tries to import a local package / module. I wrote a script named &quot;email.py&quot; that imports smtplib, which in turn seems to try to import email.utils not from the system email package but from my script. The problem goes away if I rename the script t...
<python>
2023-11-16 09:08:54
1
679
musbur