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,137,153
1,171,746
How to install pip into a tmp directory?
<p>How to install pip into a tmp directory?</p> <p>I want to install pip into a tmp directory, install a few packages to a custom directory, then remove the tmp directory.</p> <p>I am creating an extension for LibreOffice that automatically installs <code>pip</code> via <code>get-pip.py</code> if it is not installed an...
<python><pip><libreoffice>
2023-09-19 18:38:29
2
327
Amour Spirit
77,137,092
12,935,622
How to show all x-tick labels with seaborn.objects
<p>How do I make it so that it shows all x ticks from 0 to 9?</p> <pre><code> bin diff 1 4 -0.032748 3 9 0.106409 13 7 0.057214 17 3 0.157840 19 0 -0.086567 ... ... ... 1941 0 0.014386 1945 4 0.049601 1947 9 0.059406 1957 1 0.045282 1959 6 -0.033853 </code>...
<python><seaborn><xticks><seaborn-objects>
2023-09-19 18:28:23
1
1,191
guckmalmensch
77,137,062
518,012
Python / Azure Event Hubs
<p>I'm putting together a very basic Python script which suppose to send a sample JSON data to Azure Event Hubs. Here is my script:</p> <pre><code>import asyncio from azure.eventhub.aio import EventHubProducerClient async def send_json_message(connection_string, event_hub_name, json_message): &quot;&quot;&quot;Sends...
<python><azure-eventhub>
2023-09-19 18:22:59
1
15,684
Eugene Goldberg
77,136,999
2,634,153
Clean way to pass different parameters in Python
<p>I would like to write a wrapper function around <code>requests.post()</code> which implements retries in case when the call raises an exception. Somethingl like</p> <pre><code>def http_post(endpoint, headers=headers, payload=payload): ... try: response = requests.post(endpoint, headers=headers, data=...
<python><python-3.x>
2023-09-19 18:12:53
0
617
PassoGiau
77,136,916
9,873,381
How do I fix this image shape error when feeding image to ResNet50?
<p>I would like to use a camera attached to a Raspberry Pi 4 to stream video and detect objects simultaneously. I have been able to take photos and record videos using this apparatus.</p> <p>However, when I try to run a ResNet50 classifier on top of the stream, I am facing a shape inconsistency error.</p> <p>I request ...
<python><tensorflow><keras><resnet><image-classification>
2023-09-19 17:59:24
1
672
Skywalker
77,136,876
13,395,230
Ending Numpy Calculation Early
<p>Given two large arrays,</p> <pre><code>A = np.random.randint(10,size=(10000,2)) B = np.random.randint(10,size=(10000,2)) </code></pre> <p>I would like to determine if any of the vectors have a cross product of zero. We could do</p> <pre><code>C = np.cross(A[:,None,:],B[None,:,:]) </code></pre> <p>and then check if C...
<python><arrays><numpy><optimization>
2023-09-19 17:53:47
2
3,328
Bobby Ocean
77,136,866
10,122,160
AWS Apprunner Failing Health Check when pytorch is involved. But container works well on local
<p>I have been experimenting with AWS app runner. I found a basic tutorial code that uses flask. Here is the code :</p> <pre><code>from flask import render_template from flask import Flask app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/app') def blog(): re...
<python><deployment><pytorch><aws-app-runner>
2023-09-19 17:52:37
1
308
Enes Kuz
77,136,761
850,781
Python logger produces output without handlers
<p>Every now and then, while running under Jupyter and after interrupting the kernel, I start getting duplicate output on my logger: <code>stdout.info(&quot;foo&quot;)</code> prints:</p> <pre><code>2023-09-19 13:19:19 INFO 17892/MainThread/324310998 foo INFO:stdout:foo </code></pre> <p>I still have just one handler in ...
<python><logging><python-logging>
2023-09-19 17:34:04
1
60,468
sds
77,136,759
942,317
ModuleNotFoundError: No module named 'piplite'
<p>I'm trying to run a Jupiter file, please note I'm new to python.</p> <p>following is first code block which fails within Jupiter, I'm using it with Vscode.</p> <pre class="lang-py prettyprint-override"><code> # Dependency needed to install file # If running the notebook on your machine, else leave it commented #!p...
<python>
2023-09-19 17:33:56
1
10,317
STEEL
77,136,744
1,499,575
Does doxygen support python argument type hints?
<p>Given the function predicate below, doxygen seems to truncate after <code>test_point_count</code> is there any configuration option in the Doxyfile which can rectify this? Unfortunately, I am stuck with doxygen version 1.8.5 and I don't see much that references python compatibility.</p> <pre class="lang-py prettypr...
<python><doxygen><python-typing>
2023-09-19 17:31:49
0
1,152
mreff555
77,136,421
11,053,343
Restricted Python in Zope - Unauthorized Error
<p>I have a python script in the Zope (5.8.3) ZMI. When I was running Zope 5.5.1 this worked perfectly but since I upgraded to 5.8.3 and thus updated all the accompanying python modules, I am now getting the error:</p> <p>Unauthorized: Cannot access verify in this context</p> <p>verify is part of the cryptography libra...
<python><security><zope><python-cryptography><ed25519>
2023-09-19 16:35:17
0
1,515
kittonian
77,136,391
5,547,553
How to read columns of a hive partitioned parquet file in python?
<br> Generally you read the schema of a parquet file like: <pre><code>import pyarrow.parquet as pq sch = pq.read_schema(path+filename, memory_map=True) </code></pre> <p>But this does not work for hive partitioned files.<br> Tried adding the</p> <pre><code>partitioning='hive' </code></pre> <p>option, but it is not imple...
<python><parquet>
2023-09-19 16:31:45
2
1,174
lmocsi
77,136,363
6,599,648
Python threading Flask - do I need to close my thread using x.join()?
<p>I have some code in Python Flask which does the following:</p> <ol> <li>get user input</li> <li>calculates (0.3s)</li> <li>writes to DB (3s)</li> <li>return view to user</li> </ol> <p>Currently the user has to wait 3.3s for the view to return to them, so I'd like to return the view to the user while I write to the D...
<python><flask><python-multithreading>
2023-09-19 16:28:38
1
613
Muriel
77,136,355
409,568
How to work with someone else's Jupyter Notebook and virtualenv?
<p>I'm new to Jupyter Notebooks and I must be missing something that is entirely obvious to everyone else so apologies for the stupid question.</p> <p>I have been given a Jupyter Notebook (in Python) that imports a few third-party modules that seem to be installed in the environment of the person who created it, ie it ...
<python><jupyter-notebook>
2023-09-19 16:27:41
1
730
tospo
77,136,231
2,023,111
How to fix ChromeDriver SessionNotCreatedException in Google Colab?
<p>I was asked to use a python web scraping script that was created in Google Colab, but I'm getting the following error:</p> <blockquote> <p>SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 90 Current browser version is 117.0.5938.88 with binary path /...
<python><selenium-webdriver><selenium-chromedriver><google-colaboratory>
2023-09-19 16:07:24
1
319
Jonathan Cakes
77,135,971
12,300,981
Why aren't the dimensions of my x-axis and y-axis the same?
<p>So I'm attempting to generate a 4x4 where the bottom left is a perfect square.</p> <pre><code>fig=plt.figure() ax=np.empty((2,2,),dtype=object) ax[1][0]=fig.add_subplot(2,2,3) ax[0][0]=fig.add_subplot(2,2,1,sharex=ax[1][0]) ax[1][1]=fig.add_subplot(2,2,4,sharey=ax[1][0]) ax[0][1]=fig.add_subplot(2,2,2,sharex=ax[1][1...
<python><matplotlib>
2023-09-19 15:30:56
1
623
samman
77,135,954
7,397,195
SQLAlchemy: Declarative Many to Many map for Parent with two primary keys
<p>I'm trying to declare a many to many relationship using SQLAlchemy where my parent RowHeader can create Child Economists via a relationship table. I keep running into errors around multiple join paths, lack of declared Foreign Keys. I also have situations where the creation of children violates primary key constr...
<python><sqlite><sqlalchemy>
2023-09-19 15:28:55
1
454
leeprevost
77,135,931
2,112,406
Capture stdout from C++ function on python side in pytest (pybind11)?
<p>In C++, I have a class, and one of its methods (constructor, in this MRE) is supposed to print out something:</p> <pre><code>class Ex { std::string name; std::string content; public: Ex(std::string content_, std::string name_){ name = name_; content = content_; std::cout &lt;&lt;...
<python><c++><pytest><pybind11>
2023-09-19 15:27:00
0
3,203
sodiumnitrate
77,135,860
9,571,463
How to handle aiohttp.client_exceptions.ClientOSError: [Errno 1] [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:2624)
<p>I occasionally run into a TLSV1 error (might be because I am on a VPN) when making HTTP calls via <code>aiohttp</code>. I have read a bit about the error in this SO question <a href="https://stackoverflow.com/questions/44316292/ssl-sslerror-tlsv1-alert-protocol-version">here</a>.</p> <p>but as noted in the comments,...
<python><tls1.2><aiohttp>
2023-09-19 15:16:19
0
1,767
Coldchain9
77,135,853
12,845,199
Extract date from weirdly formatted datetime using Polars
<pre><code>import polars as pl df = pl.DataFrame(['2023-08-01T06:13:24.448409', '2023-08-01T07:29:34.491027']) print(df.with_columns(pl.col('column_0').str.strptime(pl.Date,'%Y-%m-%d'))) </code></pre> <p>So I have the following mass of code, and for some ungodly reason I cant for the death of me extract the date from...
<python><dataframe><datetime><python-polars>
2023-09-19 15:15:32
2
1,628
INGl0R1AM0R1
77,135,788
165,260
ValueError: Shapes (None, 28) and (None, 28, 10) are incompatible
<p>I am trying to train model using keras sequential model and my code is below:</p> <pre><code>from tensorflow.keras import Input from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Example input and output sequences input_sequence = [&quot;Mad...
<python><machine-learning><keras><sequential>
2023-09-19 15:08:05
1
8,124
Madhup Singh Yadav
77,135,749
5,150,025
I need to extract the config block as Python dict
<p>I have a dataform project and I need to extract the config block of .sqlx files and parse it as Python dictionary.</p> <p>I am trying using RegEx.</p> <p>RegEx: <code>config\s*{[^}]*}</code></p> <pre class="lang-py prettyprint-override"><code>import re config_pattern = r'config\s*{[^}]*}' config_match = re.search(c...
<python><regex><dataform>
2023-09-19 15:03:10
1
1,123
Marcelo Gazzola
77,135,623
1,014,217
_nanquantile_dispatcher() got an unexpected keyword argument 'method'
<p>I have a pandaas dataframe with about 6k rows, with a timestamp column which is hourly and a value which is a float.</p> <p>I am using DARTS for prediction and plotting</p> <pre><code>import pandas as pd from darts import TimeSeries df = dfTienen_final.toPandas() df_no_duplicates = df.drop_duplicates(subset=['belgiu...
<python><pandas><matplotlib><time-series><u8darts>
2023-09-19 14:48:46
0
34,314
Luis Valencia
77,135,614
3,936,496
Plot graph with area of two data set and get probability
<p>I am trying to plot a path of rotating rod ends as it moves forward in space. I made a vector that rotates around the centre with certain rotational speed and then move the vector to the place next place with certain translational speed. I made the whole function work with time-steps (for loop as time-step), so I ca...
<python><plot><plotly><fill>
2023-09-19 14:47:12
2
401
pinq-
77,135,307
991,045
How to add custom parameter to pip create environment in VS code?
<p>I inherited a python project which needs some dependencies from a non-default repo. I want to add a custom parameter (address of the repo) to the .venv creation action in VSCode.</p> <p>The project uses pip. Adding <code>-f https://address.of.repo/stable.html</code> to the <code>pip install ...</code> command succes...
<python><visual-studio-code><pip>
2023-09-19 14:09:52
0
470
iDPWF1
77,135,303
1,852,526
Pandas insert a blank row after each row in Excel
<p>New to Pandas firstly. I am using the following code to write to an Excel file using Pandas. Please see the line <code>worksheet.write(0, col_num, value, header_format)</code>. Question is, how can I insert a blank row after each row. For instance I want something like</p> <pre><code>Col1 Col2 Col3 Col4 (This is t...
<python><pandas><excel>
2023-09-19 14:09:35
1
1,774
nikhil
77,135,294
11,252,662
Filtering data from Spark dataframe based on datatype
<p>I am extracting data from DynamoDB based on date filter using Pyspark Glue job.</p> <p><strong>updated</strong> column here is in <strong>epoch</strong> format and is of long data type in DynamoDB.</p> <p><strong>updated</strong> column also has some bad data that are of <strong>struct</strong> data type. I would li...
<python><pyspark><aws-glue>
2023-09-19 14:08:17
1
397
vvazza
77,135,230
16,659,468
How to fix errors when installing modules in a Docker image?
<p>I encountered an issue while making a docker file wherein the message: &quot;ERROR: failed to solve: process &quot;/bin/sh -c pip install streamlit&quot; did not complete successfully: exit code: 1&quot; popped up, and I can't figure out why I'm struggling to install the streamlit module into my image via the file. ...
<python><pip><dockerfile><streamlit>
2023-09-19 14:00:00
1
685
Saksham Paliwal
77,134,818
2,881,345
Get differences between 2 dataframes
<p>In Python, I need to get differences between 2 dataframes having a different number of columns and rows.</p> <p>A column &quot;Pk&quot; is present in both dataframes. The schemas are not known in advance.</p> <p>The output should be a new dataframe containing <strong>only</strong> the rows and columns having diferen...
<python><dataframe><pyspark>
2023-09-19 13:05:33
2
3,437
bjnr
77,134,706
7,437,143
"Event loop is closed! Is Playwright already stopped?"
<h2>Context</h2> <p>After initialisation of a playwright browser object in function <code>initialise_playwright_browsercontroller</code>, I try to use its <code>Page</code> object in another function. However, that yields get error:</p> <blockquote> <p>&quot;Event loop is closed! Is Playwright already stopped?&quot;</p...
<python><playwright><playwright-python>
2023-09-19 12:50:37
3
2,887
a.t.
77,134,697
7,231,968
Redmail: Python sending email too slow
<p>I was first using smtplib to send email but then shifted to redmail because it was more concise. (smptlib also took time sending email)</p> <p>this is how I am doing it</p> <pre><code>from redmail import outlook outlook.username = 'XXXXXXX' outlook.password = 'XXXXXX' def send_email(subject, body, to_email): try...
<python><smtp>
2023-09-19 12:49:54
0
323
SunAns
77,134,663
12,468,387
Selenium deletes chrome profiles
<p>Selenium deletes chrome profiles. It happens ~1 in 30 times</p> <p>My code:</p> <pre><code>from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import os, sys, time, json, glob from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys impo...
<python><python-3.x><google-chrome><selenium-webdriver>
2023-09-19 12:44:06
2
449
Denzel
77,134,662
19,238,204
How to Draw 3D Synthesis of Fourier Series
<p>I saw this by using Tikz: <a href="https://tikz.net/fourier_series/" rel="nofollow noreferrer">https://tikz.net/fourier_series/</a></p> <p>I want to create this 3D synthesis of Fourier Series: <a href="https://i.sstatic.net/mCWZL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mCWZL.png" alt="1" /></a...
<python><numpy><matplotlib><fft><matplotlib-3d>
2023-09-19 12:43:46
1
435
Freya the Goddess
77,134,624
7,167,564
How do I access the data in Google Cloud Function written in Python passed via JS FormData from frontend?
<p>I have a ReactJS Frontend, where I am sending a data along with POST request's body payload in the <code>FormData</code> structure, but I am unable to access the data in my Google Cloud Function written Python using <code>request</code> parameter`. Below is my frontend code:</p> <pre><code>handleUpload = async (file...
<python><reactjs><python-3.x><google-cloud-functions><form-data>
2023-09-19 12:37:36
1
311
Khubaib Khawar
77,134,615
1,714,692
How to scale axes independently in pyvista?
<p>Suppose I have <code>x</code>, <code>y</code>, <code>z</code> and <code>x2</code>, <code>y2</code>, <code>z2</code> arrays. I am plotting them as 2 different 3d splines in pyvista.</p> <pre><code>import numpy as np import pyvista as pv network = pv.MultiBlock() points_1 = np.column_stack((x, y, z)) spline_1 = pv.S...
<python><3d><scale><pyvista>
2023-09-19 12:36:13
1
9,606
roschach
77,134,587
15,921,143
CORS issue when making GET requests to Django server behind Caddy reverse proxy
<p>I'm encountering a CORS (Cross-Origin Resource Sharing) issue when making GET requests to my Django server, which is hosted behind a Caddy reverse proxy. Here's the situation:</p> <ol> <li>I have a Django server running, serving an API.</li> <li>The Django server is behind a Caddy reverse proxy.</li> <li>I'm trying ...
<javascript><python><django><cors><caddy>
2023-09-19 12:31:34
0
303
Indrajeet Haldar
77,134,575
1,652,219
How to handle query batches in SQLAlchemy?
<p>I am currently experimenting with creating and executing stored procedures from Python using SQLAlchemy, and I keep running into this error: &quot;X must be the first statement in a query batch&quot;. From reading up on the topic, these &quot;query batches&quot; should be separated by &quot;GO&quot;, but &quot;GO&qu...
<python><sql><sqlalchemy>
2023-09-19 12:29:52
1
3,944
Esben Eickhardt
77,134,573
2,424,587
ConversationalRetrievalChain with ConversationBufferMemory "TypeError: tuple indices must be integers or slices, not str"
<p>When I run langchain's ConversationalRetrievalChain with ConversationBufferMemory I get an error:</p> <blockquote> <p>&quot;TypeError: tuple indices must be integers or slices, not str&quot;</p> </blockquote> <p>The problem is in: langchain/chains/conversational_retrieval/base.py:25) This line: <code>human = &quot;H...
<python><langchain>
2023-09-19 12:29:29
1
9,166
Hanan Shteingart
77,134,535
8,040,117
Migrate PostgresDsn.build from pydentic v1 to pydantic v2
<p>I have simple Config class from FastAPI tutorial. But it seems like it uses old pydantic version. I run my code with pydantic v2 version and get a several errors. I fix almost all of them, but the last one I cannot fix yet. This is part of code which does not work:</p> <pre><code>from pydantic import AnyHttpUrl, Htt...
<python><sqlalchemy><fastapi><pydantic>
2023-09-19 12:24:36
5
2,265
Vladyslav
77,134,476
5,868,293
Select rows that come after a condition, under a condition in pandas
<p>I have a dataframe that looks like this:</p> <pre><code>import pandas as pd pd.DataFrame({'id': [1,1,1,1,2,2,2,2], 'time': [1,2,3,4,1,2,5,6], 'is': [0,1,0,0,0,1,0,0]}) id time is 0 1 1 0 1 1 2 1 2 1 3 0 3 1 4 0 4 2 1 0 5 2 2 1 6 2 5 0 7 2 ...
<python><pandas>
2023-09-19 12:15:10
2
4,512
quant
77,134,430
10,589,923
Using the same variable between different Python Runs
<p>I have a script like this</p> <pre><code>for epoch in range(num_epochs): for bag in range(num_bags): feats = pd.read_csv(f&quot;feats_{bag}.csv&quot;) ... # some logic </code></pre> <p>As you can see, it repetitively reads data from a set of files. Each <code>&quot;feats_{bag}.csv&quot;</code> fi...
<python><redis><multiprocessing><shared-memory><mmap>
2023-09-19 12:08:30
2
444
Danial
77,134,285
10,533,225
Make a distinct dataframe based on a column with prioritization condition
<p>I want to make a distinct dataframe that if they have the same <code>product_number</code>, there is a prioritization about the <code>product_name</code>.</p> <p>Here is the prioritization: <strong>Product A &gt; B &gt; C</strong></p> <p>In this table, you can see that there are same <code>product_number</code> with...
<python><pyspark>
2023-09-19 11:46:05
1
583
Tenserflu
77,134,254
8,324,480
Specify dependencies in pyproject.toml with install URL or with index-url
<p>I like to have my package installable with <code>pip install ...</code> and to use the <code>pyproject.toml</code> standard.</p> <p>I can specify dependencies to install from git, with:</p> <pre><code>dependencies = [ 'numpy&gt;=1.21', 'psychopy @ git+https://github.com/psychopy/psychopy', ] </code></pre> <p...
<python><dependencies><packaging><pyproject.toml>
2023-09-19 11:42:38
3
5,826
Mathieu
77,134,246
1,062,967
stop spark dataframe distributing to cluster - it needs to stay on driver
<p>we have a workload that computes on spark cluster workers (cpu intensive). The results are pulled back to the driver which has a large memory allocation to collect the results via RDD .collect() Results are then further processed resulting in a pandas dataframe (pre-existing package logic, can't change).</p> <p>That...
<python><pyspark><apache-spark-sql><databricks><rdd>
2023-09-19 11:41:43
1
440
DaManJ
77,134,205
8,444,568
Measure CPU usage of a process and all it's subprocesses
<p>I'm creating a new process <code>A</code> using <code>multiprocessing.Process</code>, and <code>A</code> may fork/spawn new processes <code>B,C,D...</code>, B/C/D can also fork/spawn new processes <code>E,F,G...</code></p> <p>Now I want to measure the overall cpu usage of process <code>A</code> and all it's children...
<python><python-multiprocessing>
2023-09-19 11:36:20
2
893
konchy
77,134,004
10,952,047
change color clusters umap python
<p>sorry I'm totally new in python but I need to use it for some analysis. I usually use R. However, I need to change colours in my umap plot:</p> <pre><code>import scanpy as sc import anndata from scipy import io from scipy.sparse import coo_matrix, csr_matrix import numpy as np import os import pandas as pd &gt;&gt;...
<python><scanpy>
2023-09-19 11:08:19
0
417
jonny jeep
77,133,997
6,546,694
Python runtime for the code significantly different depending upon where the recursion function is placed
<p>I am trying to solve a <a href="https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/" rel="nofollow noreferrer">leetcode problem</a>. My solution gives markedly different results depending upon the kind of construction I have of the code. The only way to explain this is by giving y...
<python><class><oop><recursion><caching>
2023-09-19 11:06:39
0
5,871
figs_and_nuts
77,133,860
3,801,449
Wheel dependencies - No matching distribution found
<p>I wanted to distribute my software via PyPi. My <code>pyproject.toml</code> configuration file looks like this:</p> <pre><code>[build-system] requires = [&quot;hatchling&quot;] build-backend = &quot;hatchling.build&quot; [project] name = &quot;saoovqe&quot; version = &quot;0.1.6&quot; authors = [ ... ] description ...
<python><pip><python-wheel>
2023-09-19 10:43:37
0
3,007
Eenoku
77,133,712
534,238
VS Code Python Debug uses virtual files rather than actual source code
<h1>Configurations</h1> <ul> <li>Python plugin (used to be called Pylance)</li> <li>Standard VS Code debugger</li> <li>PDM / <code>pyproject.toml</code> package format</li> <li>installing package locally</li> </ul> <p>I can provide other config details if needed, but I think they are irrelevant.</p> <h1>Issue</h1> <p>I...
<python><visual-studio-code><debugging>
2023-09-19 10:20:54
1
3,558
Mike Williamson
77,133,672
7,483,509
Solving environment conflict with brew and libgio-2.0.0.dylib
<p>I am running a python gstreamer app on mac but I get a library conflict. Here is the app:</p> <pre class="lang-py prettyprint-override"><code>import gi gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') from gi.repository import Gtk, Gst, Gdk Gst.init(None) Gtk.init(None) class VideoPlayer: def ...
<python><gtk><homebrew><gstreamer><glib>
2023-09-19 10:15:20
0
1,109
Nick Skywalker
77,133,666
2,071,807
Should Django enumeration types like TextChoices be compared with `is` or `==`?
<p>The <a href="https://docs.djangoproject.com/en/4.2/ref/models/fields/#enumeration-types" rel="nofollow noreferrer">Django Enumeration Types documention</a> says that fields like <code>models.TextChoices</code></p> <blockquote> <p>... work similar to enum from Python’s standard library, but with some modifications.</...
<python><django>
2023-09-19 10:14:27
2
79,775
LondonRob
77,133,489
99,989
In Python, why doesn't dataclasses.asdict work with fields of type dictionary?
<p>Why doesn't dataclasses.asdict work with dictionary values (not keys)?</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import asdict, dataclass, field @dataclass(order=True, frozen=True, eq=True) class Path: p: tuple[str, ...] = field(default=()) @dataclass class C: p: dict[Path, int...
<python><python-dataclasses>
2023-09-19 09:49:38
1
33,551
Neil G
77,133,470
9,067,016
Split text by sentences
<p>I run into a problem to find a comfort method to split text by the list of predefined sentences. Sentences can include any special characters and whatever absolutely custom.</p> <p>Example:</p> <pre><code>text = &quot;My name. is A. His name is B. Her name is C. That's why...&quot; delims = [&quot;My name. is&quot;,...
<python><regex><python-re><sentence>
2023-09-19 09:48:03
2
609
Vova
77,133,408
6,243,129
How to use patch for a variable in PyTest
<p>I have below Python code:</p> <pre><code>#datamanager.py import os BASE_DIR = '' #SOME_VALUE data_list = '' #SOME_VALUE loaded_data = dict.fromkeys(data_list) def update_data(): for key, current_model in loaded_data.items(): mod_dir = os.path.join(BASE_DIR, key) if not os.path.exists(mod_d...
<python><pytest><patch><pytest-mock>
2023-09-19 09:41:44
1
7,576
S Andrew
77,133,098
464,538
List bucket files in S3 files permission denied. But upload works
<p>I'm making a simple script in Python to upload and list the files in a S3 bucket, the problem is that I can upload the files, but I receive a <code>Permission Denied</code> error when I try to list the files.</p> <p>This is the policy:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;Version&quot;: ...
<python><python-3.x><boto3>
2023-09-19 08:57:38
1
1,584
Klian
77,133,095
3,337,089
Customize state_dict() and load_state_dict() pytorch
<p>I have a nested set of classes (each of type <code>torch.nn.module</code>). I need to do some preprocessing before saving the weights of one of the nested classes. Is it possible to override the <code>state_dict()</code> function so that I can insert the preprocessing in my custom implementation?</p> <p>Sample code:...
<python><pytorch><save><customization>
2023-09-19 08:57:08
1
7,307
Nagabhushan S N
77,133,078
7,483,509
No URI handler implemented for \"gst-pipeline\"." - using PyQt 5.15
<p>I am writing a simple video player with gstreamer and PyQt 5.15.8.</p> <p>The code is a slightly modified version from <a href="https://coderslegacy.com/python/pyqt5-video-player-with-qmediaplayer/" rel="nofollow noreferrer">this website</a> where I replaced:</p> <pre class="lang-py prettyprint-override"><code> d...
<python><macos><pyqt5><gstreamer>
2023-09-19 08:55:28
0
1,109
Nick Skywalker
77,132,977
353,337
`PyRun_String` equivalent in Python stable ABI?
<p>I have a C++ Python library that I'd like to translate to use the <a href="https://docs.python.org/3/c-api/stable.html" rel="nofollow noreferrer">stable ABI</a>. It currently uses <a href="https://docs.python.org/3.12/c-api/veryhigh.html#c.PyRun_String" rel="nofollow noreferrer"><code>PyRun_String</code></a></p> <pr...
<python><c>
2023-09-19 08:42:19
1
59,565
Nico Schlömer
77,132,964
11,355,926
Converting string to list with dictionaries
<p>I have a big string in the following format (100K+ lines):</p> <pre><code>----------- Phone Information ----------- #TotalPhones, #TotalRegistered, #RegisteredSCCP, #RegisteredSIP, #UnRegistered, #Rejected, #PartiallyRegistered, StateId, #ExpUnreg 202, 202, 178, 24, 0, 0, 0, 842,0 DeviceName, Descr, Ipaddr, Ipv6ad...
<python><string><dictionary>
2023-09-19 08:41:12
5
3,060
Cow
77,132,940
449,193
Eclipse PyDev Debugger: Unable to load existing shared libraries - ImportError: libffi.so.7 / libssl.so.1.1
<p>When running pydev debugger on eclipse, it errors out about missing shared libraries namely libffi and libssl, although both are installed</p> <pre><code>&gt;locate libffi.so.7 /usr/lib/x86_64-linux-gnu/libffi.so.7 </code></pre> <pre><code>&quot;/home/user1/.var/app/org.eclipse.Java/eclipse/plugins/org.python.pydev...
<python><eclipse><pydev>
2023-09-19 08:38:19
1
8,794
omars
77,132,571
4,994,781
With pytest under Windows, create an unreadable file for unit testing
<p>I'm using <code>pytest</code> under Windows and one of the thing I have to test is behaviour when a file cannot be read and the operation raises <code>PermissionError</code>.</p> <p>In my unit test I cannot use <code>chmod()</code> because under Windows it cannot be used to remove read permission.</p> <p>I understan...
<python><windows><unit-testing><pytest>
2023-09-19 07:43:38
0
580
Raúl Núñez de Arenas Coronado
77,132,556
14,460,824
How to fill a set of columns values with values of another set of columns?
<p>I have a <code>dataframe</code> with two column sections <code>Pn</code> and <code>En</code>:</p> <pre><code>df_original = pd.DataFrame({ 'P1':['','',1,''], 'P2':[4,2,'',3], 'P3':[48,20,10,''], 'P4':['',320,160,264], 'E1':['','',1,3], 'E2':[4,2,10,264], 'E3':[48,20,'',528], 'E4':['','...
<python><pandas><dataframe><merge>
2023-09-19 07:41:29
2
25,336
HedgeHog
77,132,536
3,833,632
How to show selenium browser in VNC after creating it over SSH with a virtual display
<p>I created a selenium browser over SSH using like so</p> <pre><code>from pyvirtualdisplay import Display display = Display(visible=0, size=(1920, 1920)) display.start() driver = webdriver.Chrome() </code></pre> <p>I then logged into the machine with VNC. And my goal is to move the chrome window created there onto my ...
<python><selenium-webdriver><vnc>
2023-09-19 07:38:25
1
715
CalebK
77,132,367
3,336,423
What is the difference between `asyncio.open_connection` and `socket.socket.accept()`
<p>I'm trying to connect to a server. Our client-side script opens the connection using:</p> <pre><code>reader, writer = await asyncio.open_connection(HOST, PORT) </code></pre> <p>We wanted to integrate this with legacy code that opens a connection using:</p> <pre><code>with socket.socket(socket.AF_INET,socket.SOCK_STR...
<python><sockets><python-asyncio>
2023-09-19 07:10:31
1
21,904
jpo38
77,132,221
1,014,217
adding new features to pyspark dataframe takes 8 hours and doesnt finish
<p>The following function adds some features to a dataframe which is about 6k rows only. However after 8 hours running it didnt finish, what am I doing wrong?</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.window import Window from pyspark.sql import functions as F def add_rain_features(df, lag_h...
<python><pandas><pyspark>
2023-09-19 06:45:10
0
34,314
Luis Valencia
77,131,972
487,554
Unable to run a simple Airflow DAG with BashOperator calling Python scripts
<p>I installed Airflow, both through Apache and Astronomer and wrote a really simple DAG with two tasks, each of which are BashOperators that call a Python script. The first Python script, in turn, reads a file and writes out a file, while the second one reads the file created by the previous Python script, reads anoth...
<python><airflow><directed-acyclic-graphs><astronomer>
2023-09-19 05:48:15
3
2,837
CodingInCircles
77,131,968
839,733
Sorted set searching and ordering
<p>Python Sorted Containers package contains <a href="https://grantjenks.com/docs/sortedcontainers/sortedset.html" rel="nofollow noreferrer">SortedSet</a>, that can be initialized as follows:</p> <pre><code>__init__(iterable=None, key=None) </code></pre> <blockquote> <p>key: Function used to extract comparison key from...
<python><sorting><hash><set><sortedcontainers>
2023-09-19 05:47:12
2
25,239
Abhijit Sarkar
77,131,897
1,181,065
SimPy Concurrency
<p>I have a network simulation with SimPy. A packet is sent from the generator class (includes yield for 1.5s) to the Slot class (includes another yield for 1.5s) then to the wire class and then to the destination. I need to detect collisions coming from different Slots to the wire class and they share the same timesta...
<python><simpy>
2023-09-19 05:23:24
1
539
Hanna
77,131,869
14,842,800
What does Depends() do in FastAPI?
<p>I'm trying to understand dependency injection in FastAPI. Why is Depends() needed in the following example from the docs? What does Depends() do?</p> <pre><code>from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit...
<python><dependency-injection><fastapi>
2023-09-19 05:16:07
1
321
Sam Archer
77,131,617
21,305,238
Using attrs decorators in PyCharm
<p>I have the following <em>attrs</em> class:</p> <pre class="lang-py prettyprint-override"><code>from attrs import define, field @define class Foo: bar: int = field() @bar.validator def check(self, attribute, value): ... </code></pre> <p>It works normally at runtime, as expected:</p> <pre><co...
<python><pycharm><python-typing><python-attrs>
2023-09-19 03:50:47
0
12,143
InSync
77,131,295
270,043
Data type error while reading Parquet files in pyspark
<p>I have converted a bunch of CSV files into parquet files, and while trying to load 5 rows of the parquet files into another Pyspark dataframe, I got an error.</p> <p>How I converted my CSV files into Parquet files:</p> <pre><code>df = spark.read.options(delimiter='|', inferSchema=True).csv(csv_folder, header=True) d...
<python><pyspark><types><parquet>
2023-09-19 02:04:11
0
15,187
Rayne
77,131,261
11,141,816
High dimension convex hull library in python
<p>I tried to compute some high dimension convex hull in python. The computation had to be precise and &quot;QJ&quot; in Qhull was not quite an acceptable option.</p> <p>I found <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html" rel="nofollow noreferrer"><code>scipy.spatial.Con...
<python><scipy><qhull>
2023-09-19 01:53:25
0
593
ShoutOutAndCalculate
77,131,079
17,588,005
Why openCV's implementation of Blob Detection is different from skimage?
<p>For a long time, I thought that OpenCV implementation of <code>SimpleBlobDetector</code> is the approach mentioned in <a href="https://en.wikipedia.org/wiki/Blob_detection" rel="nofollow noreferrer">Wikipedia</a>, in which a stack of images with different blurring parameters is created and then a search for maximal ...
<python><opencv><scikit-image>
2023-09-19 00:45:20
0
328
Odeaxcsh
77,131,060
493,553
Pylance (VS Code type checking) mistakes the count() infinite iterator as finite
<p>I'm relatively new to Pylance (VS Code's static type checker, based on Pyright) and just stumbled upon this type checking error with the <code>count()</code> infinite iterator. I have some code I've been playing with, which I reduced to the following basic version which reproduces the problem:</p> <pre class="lang-p...
<python><python-typing><pyright>
2023-09-19 00:38:17
1
2,772
yoniLavi
77,130,821
5,278,205
cannot install python packages in rstudio project environment
<p>I primarily use rstudio for running python scripts. I'm interested in trying out rstudio's github integration. Unfortunately, I cannot get python libraries installed. <code>!pip install pandas</code> for example returns the error <code>sh: pip: command not found</code>. When i try installing from terminal I get that...
<python><r><github><rstudio>
2023-09-18 23:09:29
0
5,213
Cyrus Mohammadian
77,130,662
2,350,986
When using Flask-Login and Peewee as the ORM, is there a need to create the login attributes on the database?
<p>The <a href="https://flask-login.readthedocs.io/en/latest/#your-user-class" rel="nofollow noreferrer">Flask-Login documentation states</a> that you should create some attributes for your User model to handle some aspects of the authentication and session handling process, which is fair.</p> <p>However, when adding t...
<python><flask><peewee><flask-login>
2023-09-18 22:12:04
1
504
Renato Oliveira
77,130,576
1,512,250
AttributeError: 'Depends' object has no attribute 'query'
<p>I'm new to this.</p> <p>Here is my generator function to retrieve database object:</p> <pre><code>def get_db_session(): db = SessionLocal() try: yield db finally: db.close() </code></pre> <p>Then I have a method to get a user from my database:</p> <pre><code>def get_user_from_db(email: st...
<python><dependency-injection><sqlalchemy><fastapi>
2023-09-18 21:50:12
2
3,149
Rikki Tikki Tavi
77,130,313
12,821,675
Two Layer Nested Serializers - Django Rest Framework
<p>Say I have models with grandparent-parent-child relations like so:</p> <p><strong>models.py</strong></p> <pre class="lang-py prettyprint-override"><code>class Unit(...): number = models.CharField(...) class Listing(...): unit = models.ForeignKey('Unit', related_name=&quot;listings&quot;, ...) number_of_...
<python><django><django-rest-framework>
2023-09-18 20:51:09
1
3,537
Daniel
77,130,229
616,728
psycopg3 inserting dict into JSONB field
<p>I have a table with a <code>JSONB</code> field and would like to insert into it using a named dict like so:</p> <pre><code>sql = &quot;INSERT INTO tbl (id, json_fld) VALUES (%(id)s, %(json_fld)s)&quot; conn.execute(sql, {'id':1, 'json_fld': {'a':1,'b':false, 'c': 'yes'}}); </code></pre> <p>I tried the answers in <a ...
<python><postgresql><jsonb><psycopg3>
2023-09-18 20:32:55
2
2,748
Frank Conry
77,130,085
2,307,570
Does Python always use UTF-8 when reading from or writing to a file? (Open function with only file and mode args.)
<p>I have the impression, that reading from and writing to a file always uses UTF-8.<br> I tried to find a counter-example by using a different encoding for the script, but did not find one.</p> <p>My example uses the Yen-Symbol, whose encoding in UTF-8 is <code>C2 A5</code>.<br> <code>'¥'.encode('utf-8') == b'\xc2\xa5...
<python><utf-8><character-encoding>
2023-09-18 19:59:34
1
1,209
Watchduck
77,130,056
14,566,295
Converting a list to pandas dataframe where list contains dictionary
<p>I wanted to convert a <code>list</code> to <code>pandas</code> dataframe, where the first element of the <code>list</code> is a <code>dictionary</code>.</p> <p>I have below code</p> <pre><code>import pandas as pd import numpy as np pd.DataFrame([{'aa' : 10}, np.nan]) </code></pre> <p>However this fails with below me...
<python><pandas><dataframe><list><dictionary>
2023-09-18 19:53:40
2
1,679
Brian Smith
77,129,892
210,867
Poetry config and publish are broken for me
<p>I'm on a new Ubuntu 22.04 desktop. I've installed Poetry. (Initially v1.5.1, but when I ran into this problem, I upgraded to v1.6.1 to see if it fixed anything - it didn't.)</p> <p>The problem is whenever I try to use <code>poetry config pypi-token.pypi &quot;MYTOKEN&quot;</code> to store my PyPI token, it says no...
<python><pypi><python-poetry>
2023-09-18 19:24:15
1
8,548
odigity
77,129,876
11,064,604
Pip install failing in Windows
<p>I cannot install python packages locally on my work windows machine. Inside powershell I have tried</p> <pre><code>py -m pip install pandas </code></pre> <p>only to get the following errors:</p> <blockquote> <p>WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection ...
<python>
2023-09-18 19:20:53
2
353
Ottpocket
77,129,870
8,587,712
how to check if element of list contains one of the elements of another list
<p>I have a list of strings <code>['asdf', 'qwer', 'zxcv']</code> and I need to return a list containing the elements of this list which contain any of the strings in <code>['a', 'g', 'y']</code>. I have attempted this with the following list comprehension</p> <pre><code>lst = ['asdf', 'qwer', 'zxcv'] target_strings = ...
<python><string><list><list-comprehension>
2023-09-18 19:19:26
3
313
Nikko Cleri
77,129,839
7,422,392
Django and Django-CMS Static and Media URLs: https://https://
<p>In Django the following <code>settings</code> are configured:</p> <pre><code>MEDIA_URL=&quot;https://abcdefg.cloudfront.net/media/&quot; STATIC_URL=&quot;https://abcdefg.cloudfront.net/static/&quot; </code></pre> <p>In web browsers the URL for the static files is correct. The URL for media files however is incorrect...
<python><django><django-cms>
2023-09-18 19:13:35
1
1,006
sitWolf
77,129,754
13,764,814
How to configure debug environment for vscode
<p>I am struggling to debug my project.</p> <p>The directory structure is as follows:</p> <p>Root Dir</p> <ul> <li>ModuleA <ul> <li>Submodule1</li> <li>Submodule2</li> </ul> </li> <li>ModuleB <ul> <li>Submodule3</li> <li>Submodule4</li> </ul> </li> </ul> <p>When debugging a python script within Submodule3 (e.g. <code>p...
<python><visual-studio-code><path><vscode-debugger>
2023-09-18 18:54:57
1
311
Austin Hallett
77,129,672
2,112,406
Allowing deepcopy for a C++ object that has vector of pointers to another object in pybind11
<p>I have two classes defined in C++:</p> <pre><code>class Pet { public: Pet(std::string &amp;name) : name(name) {} void set_name(std::string &amp;name_) { name = name_;} std::string &amp;get_name () { return name; } private: std::string name; }; class Zoo { public: Zoo() {} void set_pets(std::...
<python><c++><oop><pybind11>
2023-09-18 18:36:17
0
3,203
sodiumnitrate
77,129,544
529,286
Can't build a non-stacked bar plot progressively, starting from a DataFrame
<p>I'm trying to build a bar plot with Pandas, matplotlib and Jupyter, where I'd like to place multiple series about the same index values one after another, without stacking. I've tried this:</p> <pre class="lang-py prettyprint-override"><code> d = { &quot;shop&quot;: [ &quot;London&quot;, &quot;Berlin&quot;, &quot...
<python><pandas><matplotlib>
2023-09-18 18:16:01
1
3,104
zakmck
77,129,493
2,107,488
retrieve secrets from Azure Key vault in azure databricks WITHOUT secret scope
<p>I know, I can use secret scope in Azure Databricks and easly retrieve secrets/keys from Azure KeyVault.</p> <p>But</p> <p>I would like to try another way -&gt; via a service principal.The service principal has permission to get/list secrets from my azure key vault.</p> <p>My steps:</p> <ol> <li>I create a cluster in...
<python><azure><azure-databricks><azure-keyvault><azure-service-principal>
2023-09-18 18:08:59
1
3,087
Kaja
77,129,441
6,068,731
Spotify API - Cannot get recently played songs
<blockquote> <p>I want to get my recently played songs using Python.</p> </blockquote> <p>I created an APP on the Spotify Developers website. I have the Client ID and the Client Secret. I managed to use these to use the <code>search</code> function to find the <code>artist_id</code> of an artist, and grab their top tra...
<python><spotify><spotipy>
2023-09-18 17:59:59
0
728
Physics_Student
77,129,052
1,061,095
How to schedule a custom Task object within an async block?
<p>I've developed the following prototype, towards a callbacks-based approach to using asyncio with HTTP (<a href="https://www.python-httpx.org/async/" rel="nofollow noreferrer">HTTPX</a>).</p> <p>My idea with this prototype was to produce a generic &quot;task chain&quot; structure for Python asyncio. This introduces a...
<python><http><python-asyncio>
2023-09-18 16:54:12
0
486
Sean Champ
77,129,015
993,812
Move data within dataframe conditionally
<p>I've got some data with two &quot;measurement series&quot;. What I'd like to do is essentially copy and paste the values from columns C&amp;D of Series A where type equals 0 to columns A&amp;B of Series B where the first occurrence of the Name and Day columns are equal to those found in Series A and the values of co...
<python><pandas>
2023-09-18 16:48:18
2
555
John
77,128,939
1,991,502
Can I make a QStandardItem editable from one view but not the other?
<p>Consider the snippet below that creates two item models and views for a single item:</p> <pre><code>item = QStandardItem(&quot;my item&quot;) item_model_1 = QStandardItemModel() item_model_1.appendRow(item) item_model_2 = QStandardItemModel() item_model_2.appendRow(item) view_1 = QTreeView() view_1.setModel(item_...
<python><pyqt><pyside>
2023-09-18 16:34:48
1
749
DJames
77,128,850
9,582,176
How to set typehint for default type
<p>I'm trying to set correct typehint for default type in this situation</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar class Foo: pass class FooBar(Foo): pass T = ... def baz(type_: type[T] = Foo) -&gt; T: return type_() </code></pre> <p>Already tried to use</p> <pr...
<python><mypy><python-typing><type-variables>
2023-09-18 16:21:54
1
659
Oleg
77,128,728
10,093,190
How can I detect strikethrough text from .docx tables?
<p>I'm using python-docx to parse some tables to dictionaries. However, some of those tables contain strikethrough text. This text needs to be excluded.</p> <p>I have already found <a href="https://stackoverflow.com/questions/27904470/checking-for-particular-style-using-python-docx/27910938#27910938">how to detect stri...
<python><docx><python-docx>
2023-09-18 16:01:36
1
501
Opifex
77,128,576
5,299,750
Why are not all the Conv2D weights of my tflite model in Int8 after conversion with dynamic range quantization?
<p>I have a Keras model and follow the <a href="https://www.tensorflow.org/lite/performance/post_training_quant" rel="nofollow noreferrer">Post-training dynamic range quantization guide</a> to convert it to a tflite model. Upon inspection with <a href="https://netron.app/" rel="nofollow noreferrer">Netron</a>, however,...
<python><tensorflow><quantization><dtype>
2023-09-18 15:38:32
1
954
Christian Steinmeyer
77,128,486
3,833,632
Can the parent process find out the PID of a daemon process created via a double fork
<p>I have some python code that forks twice to create a daemon. I know code like this is not at all uncommon so I was surprised I couldn't find people mentioning how you get the PID of your grandchild process here. I am willing to explore all options. Even if necessary using the filesystem. I just want to do it in the ...
<python><fork>
2023-09-18 15:27:45
0
715
CalebK
77,128,442
1,517,108
Appending a series of 2d numpy array to create a 3d numpy array
<p>I thought this was an easy problem, but I have been struggling with it.</p> <p>I have a dataframe with 4 columns (Open, High, Low, Close).</p> <p>I need to iteratively select</p> <ul> <li>for 100 times</li> <li>a batch of 75 rows</li> <li>each having 4 columns. Such that the final shape is (100,75,4)</li> </ul> <p>I...
<python><pandas><numpy-ndarray>
2023-09-18 15:21:24
1
2,425
user1517108
77,128,370
17,034,564
Sorting dataframe cells based on extracted value?
<p>I have a dataframe which looks as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Column_1</th> <th>Column_2</th> <th>Column_3</th> <th>Column_4</th> </tr> </thead> <tbody> <tr> <td>'0 0 1 apple'</td> <td>'0 0 2 banana'</td> <td>'7 5 6 orange'</td> <td>'4 2 9 mango'</td> </tr> <...
<python><pandas><loops>
2023-09-18 15:10:57
2
678
corvusMidnight
77,128,337
14,039,739
How to accommodate None types when comparing dates in SQL Alchemy Query?
<p>My query:</p> <pre><code>abandoned_days = 10 abandoned_date = datetime.now() - timedelta(days=abandoned_days) abandoned_requests = db.query(models.DocumentRequest)\ .filter( models.DocumentRequest.case_id.in_([case[&quot;id&quot;] for case in cases]), models.DocumentRequest.status == 'requested'...
<python><sqlalchemy>
2023-09-18 15:07:57
1
561
personwholikestocode