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
76,185,737
11,277,108
"OSError: [Errno 48] Address already in use" when checking IP address in a loop
<p>I'm using the <a href="https://pypi.org/project/WhatIsMyIP/" rel="nofollow noreferrer"><code>whatismyip</code></a> package to check my IP address before I call an IP sensitive API. The code runs in a loop and I'm finding after a few iterations I get the following error:</p> <pre><code>OSError: [Errno 48] Address alr...
<python><sockets>
2023-05-05 20:28:16
1
1,121
Jossy
76,185,575
6,534,818
Transformers: How to override subclass
<p>I need to override a subclass but I am not sure how to do it:</p> <pre><code>RuntimeError: Passing `optimizers` is not allowed if Fairscale, Deepspeed or PyTorch FSDP is enabled. You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method. </code></pre> <p>Here is a limited example making...
<python><huggingface-transformers>
2023-05-05 19:59:31
0
1,859
John Stud
76,185,570
1,814,881
Efficiently performing elementwise operation using coordinates on scipy sparse array
<p>I'm trying to figure out how to efficiently do the following operation on a scipy sparse array (csc format):</p> <p>Elementwise pseudocode:</p> <pre><code>try: r = M[i,j] / (V[i] + V[j]) if r.isfinite(): M[i,j] = r else: # Leave at old value pass # e.g. 1e200/1e-200 -&gt; inf exce...
<python><scipy><sparse-matrix>
2023-05-05 19:58:21
1
1,459
TLW
76,185,423
3,507,584
Applying pandas styler to format dataframe header in latex
<p>I am trying to get the <code>latex</code> file for the following table/dataframe:</p> <pre><code>df = pd.DataFrame(np.random.rand(10,2)*5, index=pd.date_range(start=&quot;2021-01-01&quot;, periods=10), columns=[&quot;Tokyo&quot;, &quot;Beijing&quot;]) df.index.nam...
<python><pandas><pandas-styles>
2023-05-05 19:36:35
3
3,689
User981636
76,185,248
512,480
Invalid exception in PIL image library?
<p>I'm using the version of PIL from the begin &quot;pillow&quot; package:</p> <pre><code>from PIL import Image </code></pre> <p>When running on Linux (but nowhere else) I sometimes get these very strange errors:</p> <pre><code>Exception ignored in: &lt;function Image.__del__ at 0x7efefc7adf80&gt; Traceback (most recen...
<python><exception><python-imaging-library>
2023-05-05 19:07:56
1
1,624
Joymaker
76,185,208
13,653,794
How to structure golang api that uses function from python file
<p>I am writing an api that will be sending messages over websockets.</p> <p>I have a python monitoring function that is used to monitor and format the data which will be sent over the websocket. If this monitoring function was written in golang, I'd run the function on a separate goroutine and each time new data was f...
<python><go><ctypes>
2023-05-05 19:00:07
1
374
Fergus Johnson
76,184,947
2,687,317
How to plot binned datetimes from pd.cut
<p>SO I have data like this:</p> <pre><code>LFrame Date_Time DoW run_time az el distance pass_ID SV_ID Direction PFD_Jy 0 3114360965 2023-03-29 17:25:20 Wednesday 62720.0 349.254117 12.199639 2.171043e+06 2023_03_29_154 154 SB 8.505332 1 3114360977 2023-03-29 17:25:21 Wednesday 62721.0 ...
<python><pandas><matplotlib>
2023-05-05 18:15:09
2
533
earnric
76,184,853
659,503
Python3 won't run - no module name encodings
<p>When I try to run a python command I get a warning about missing module 'encodings'. So I set the PYTHONHOME variable as described in other SO answers, but it still can't find 'encodings'</p> <pre><code>[root@fedora ~]# python help Python path configuration: PYTHONHOME = '/usr/lib64/python3.9/venv/bin/python' P...
<python><installation>
2023-05-05 18:00:56
1
4,736
TSG
76,184,843
1,888,440
RuntimeError: await wasn't used with future when using twisted, pytest_twisted plugin, and asyncio reactor
<p>I'm running into the <code>RuntimeError: await wasn't used with future</code> in a simple pytest. I have the <code>pytest_twisted</code> plugin enabled with the argument <code>--reactor asyncio</code>. I can see that twisted is using asyncio and all my twisted tests run fine. However, this code gives me the above er...
<python><python-asyncio><twisted>
2023-05-05 18:00:27
2
4,994
robert_difalco
76,184,613
475,710
Dynamically add test methods to python unittest in setup method
<p>I wish to add dynamic tests to a python unittest class during setup. Is there any way to get this working?</p> <p>I know that this works <a href="https://stackoverflow.com/questions/32899/how-do-you-generate-dynamic-parameterized-unit-tests-in-python">based on the answers on this page</a>:</p> <pre><code>def generat...
<python><dynamic><python-unittest>
2023-05-05 17:22:32
1
1,011
Sennin
76,184,540
791,793
Get all documents from ChromaDb using Python and langchain
<p>I'm using langchain to process a whole bunch of documents which are in an Mongo database.</p> <p>I can load all documents fine into the chromadb vector storage using langchain. Nothing fancy being done here. This is my code:</p> <pre class="lang-python prettyprint-override"><code>from langchain.embeddings.openai imp...
<python><langchain><py-langchain><chromadb>
2023-05-05 17:09:44
5
721
user791793
76,184,438
1,443,702
Capture flask request when entering and leaving the application
<p>I'm struggling a bit with writing decorators to capture and modify requests within my flask application once the requests enters the application context and leaves the application context.</p> <p>My function in a flask application looks like below. I want the control of requests at two points to add custom headers a...
<python><flask><python-requests><request><distributed-tracing>
2023-05-05 16:55:39
6
4,726
xan
76,184,432
2,601,293
Add type hints to a python package similar to how TypeScript can use a .d.ts file
<p>I'm using a library that is a little old and doesn't have Python type hints.</p> <p>Since this isn't my library, I can't simply just type hints in. With TypeScript, there is a concept of using a <strong>.d.ts</strong> file that goes along side the <strong>.js</strong> file. This provides typing information without ...
<python><typescript><type-hinting>
2023-05-05 16:54:38
1
3,876
J'e
76,184,257
1,914,781
annotate on subplot with add_annotation
<p>The top subplot works fine but the bottom one the arrow start/end style not the same as top subplot!</p> <pre><code>import re import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots def plot_line(df,pngname): fontsize = 10 title = &quot;demo&quot; xlabel = &q...
<python><plotly><scatter-plot>
2023-05-05 16:29:09
1
9,011
lucky1928
76,184,252
3,667,089
How to avoid creating a newline when using if-else in f-string expression
<p>Please see the below minimal example,</p> <pre><code>printbbb = True print(f&quot;&quot;&quot;AAA {'''BBB''' if printbbb else ''} CCC&quot;&quot;&quot;) </code></pre> <p>This prints</p> <pre><code>AAA BBB CCC </code></pre> <p>as desired, however, if I set <code>printbbb</code> to <code>False</code>, it prints</p> <p...
<python><python-3.x><f-string>
2023-05-05 16:28:44
2
3,388
user3667089
76,184,234
5,437,090
pandas dataframe map using lambda function with multiple input arguments | AttributeError: 'DataFrame' object has no attribute 'map'
<p><strong>Given</strong>:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(data={'user_ip': [&quot;u1&quot;, &quot;u2&quot;, &quot;u3&quot;, &quot;u4&quot;, &quot;u5&quot;], 'a': [1, np.nan, 8, 2, 0], 'b': [2, 5, 1, np.nan, 0], ...
<python><pandas><error-handling>
2023-05-05 16:26:42
1
1,621
farid
76,184,100
3,358,927
How to send at-commands to tcp port and retrieve response
<p>I am writing Python code to receive information from tcp port 20001. According to the documentation , there are some AT-commands that can be called. One of them is <code>+OK</code>. Also, the AT command end bit must be <code>0x0D</code></p> <p><a href="https://i.sstatic.net/I8Mzs.png" rel="nofollow noreferrer"><img ...
<python><sockets><tcp><byte>
2023-05-05 16:08:44
1
5,049
ddd
76,183,984
2,475,612
python mypy: sorting a list on nullable key - where items with null fields are removed
<p>I am on a project using mypy 1.2.0. I am linting the following code:</p> <pre class="lang-py prettyprint-override"><code>from datetime import date, timedelta from pydantic import BaseModel class ScheduleItem(BaseModel): start_date: Optional[date] = None items = [ ScheduleItem(start_date=None), Sched...
<python><mypy>
2023-05-05 15:54:25
2
1,614
i_trope
76,183,964
226,081
pip install with target directory but skip already installed system packages
<p>The <code>pip install --target</code> lets you install Python packages into a specific directory which can then be added to the PYTHONPATH (basically creating something similar to a virtualenv but without the Python interpreter and libs).</p> <p>However, I have a use-case where I'd like to install packages into the ...
<python><pip><virtualenv><python-packaging><python-venv>
2023-05-05 15:52:41
0
10,861
Joe Jasinski
76,183,891
14,775,478
Is saving keras models with tf >=2.12.0 not backward compatible?
<p>I am struggling with keras' way of saving models in <code>v2.12.0</code>. It does not seem to be backward compatible. Am I getting something wrong, or must we refactor code to migrate to <code>v2.12.0</code>?</p> <p>Here is our old way of saving models (<code>v2.7.0</code>): Pass valid <code>.h5</code> file (!) path...
<python><tensorflow><keras>
2023-05-05 15:43:32
2
1,690
KingOtto
76,183,853
1,825,360
Pandas dataframe to Html ValueError: Styles supplied as string must follow CSS rule formats
<p>I'm trying to write a Pandas data frame to HTML format (Pandas 1.5.3) and getting the following error. The code however runs fine in PD version 0.25.1.</p> <p>This is a small dataframe which I uploaded in <a href="https://pastebin.com/MGnwCvMk" rel="nofollow noreferrer">pastebin</a></p> <pre class="lang-py prettypri...
<python><pandas><valueerror>
2023-05-05 15:38:23
1
469
The August
76,183,798
1,821,692
What the purpose of creating Python class inherited from `abc.ABC` but without `abstractmethod`?
<p>I've read TorchServe's default handlers' sources and found that the <a href="https://github.com/pytorch/serve/blob/86d440041b663961c71a6262fe648111d85b27d8/ts/torch_handler/base_handler.py#L62" rel="nofollow noreferrer"><code>BaseHandler</code></a> is inherited from <code>abc.ABC</code> and doesn't have any abstract...
<python><abc><abstract-methods><torchserve>
2023-05-05 15:29:57
1
3,047
feeeper
76,183,675
13,039,962
differences between markers of scatter and mlines legend
<p>With this code i'm plotting values of a map:</p> <pre><code>conditions = [(maxcwd1['CWD'] == 0), (maxcwd1['CWD'] &gt; 0) &amp; (maxcwd1['CWD'] &lt; 3), (maxcwd1['CWD'] &gt;= 3) &amp; (maxcwd1['CWD'] &lt; 5), (maxcwd1['CWD'] &gt;= 5) &amp; (maxcwd1['CWD'] &lt; 7), (maxcwd1['CWD'] &gt;= 7) &amp; (maxcw...
<python><pandas><matplotlib>
2023-05-05 15:16:57
0
523
Javier
76,183,636
12,292,254
Default value for nested dataclasses
<p>I got the following dataclasses in Python:</p> <pre><code>@dataclass class B(baseClass): d: float e: int @dataclass class A(baseClass): b: B c: str </code></pre> <p>I have this configured so that the baseClass allows to get the variables of each class from a config.json file. This file contains the follo...
<python><nested><python-dataclasses>
2023-05-05 15:11:58
1
460
Steven01123581321
76,183,587
2,664,910
Can you monitor multiple urlpatterns with Django's runserver autoreload
<p>In the project I'm working on, I'd like to have it run 2 apps on one runserver for development purposes (standalone in production), to utilize amongs others autoreload options.</p> <p>What I'd like to do is have wsgi application, and asgi application by implementing Django channels next to it. For that, I feel like ...
<python><django><django-rest-framework><django-channels>
2023-05-05 15:05:32
0
429
800c25d6-cd74-11ed-afa1-0242ac
76,183,504
127,320
Long creation time with conda env create -f environment.yml
<p>I have the following <code>environment.yml</code> file. It is taking 1.5 hours to create this environment. How to improve (or debug) the creation time?</p> <pre><code>name: test_syn_spark_3_3_1 channels: - defaults - conda-forge dependencies: - python=3.10 - pandas=1.5 - pip=23.0 - pyarrow=11.0.0 - pys...
<python><anaconda><conda><miniconda>
2023-05-05 14:55:13
1
80,467
Aravind Yarram
76,183,497
2,664,910
How to setup urlpatterns for ASGI Django Channels http type protocol?
<p>I am pretty sure I am missing something from the documentation, but I am unable to find a definitive answer anywhere.</p> <p>I have a Django application, and what I'd like to do is use Django Channels for websocket purposes, however I am also interested in async http that Django Channels can provide for me.</p> <p>L...
<python><django><django-channels><asgi>
2023-05-05 14:54:06
1
429
800c25d6-cd74-11ed-afa1-0242ac
76,183,463
507,770
Cannot Set Figure DPI
<p>I am trying to set the figure DPI. The docs say that it <em>should</em> default to 100, but it is defaulting to 200. I am trying to force it to 200 in 2 different ways. No dice.</p> <p>Here is my python script in its entirety.</p> <pre><code>import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 100 fig = plt....
<python><matplotlib>
2023-05-05 14:50:48
0
18,592
bbrame
76,183,446
1,833,326
Duplicates even there are no duplicates
<p>I have a data frame as a result of multiple joins. When I check, it tells me that I have a duplicate, even though that is impossible from my perspective. Here is an abstract example:</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, IntegerType, StringType imp...
<python><apache-spark><pyspark><apache-spark-sql><databricks>
2023-05-05 14:48:49
1
1,018
Lazloo Xp
76,183,438
20,212,187
Sklearn pipeline with LDA and KNN
<p>I try to use <code>LinearDiscriminantAnalysis</code> (LDA) class from sklearn as preprocessing part of my modeling to reduce the dimensionality of my data, and after applied a KNN classifier. I know that a good pratice is to use pipeline to bring together preprocessing and modeling part.</p> <p>I also use the method...
<python><scikit-learn><pipeline><knn>
2023-05-05 14:47:38
1
543
Adrien Riaux
76,183,422
1,114,105
How to share a string using Python 3's multiprocessing.Value?
<p>I am trying to share a string between two processes using Value, but it does not work.</p> <pre><code>from multiprocessing import Value, Process import time import ctypes def say_hi(v): with v.get_lock(): print(f&quot;Saying hi with {v.value=:}&quot;) v.value = &quot;borat&quot; if __name__ == &...
<python><python-multiprocessing><ctypes>
2023-05-05 14:45:56
2
1,189
user1114
76,183,393
17,353,489
How to view-cast / reinterpret-cast in pythran / numpy?
<p>I'm trying to do <code>numpy</code> view-casting (which I believe in <code>C/C++</code> land would be called reinterpret-casting) in pythran:</p> <p>The following silly made-up example takes an array of unsigned 8-byte integers, reinterprets them as twice as many unsigned 4-byte integers, slices off the first and la...
<python><numpy><reinterpret-cast><pythran>
2023-05-05 14:41:41
1
533
Albert.Lang
76,183,337
5,016,028
Select features by correlation with label in pandas dataframe
<p>I have a dataframe of the form:</p> <pre><code>df = pd.DataFrame({ 'A' : [1,2,3], 'B' : [4,5,6], 'label' : [1.0, 0.0, 1.0] }) </code></pre> <p>And I first select only the features that have a correlation above a threshold to the <code>'label'</code> column.</p...
<python><python-3.x><pandas><dataframe><list>
2023-05-05 14:35:47
2
4,373
Qubix
76,183,316
7,985,055
How does one serialize a firefox profile in selenium?
<p>All,</p> <p>I am trying to setup a firefox profile to run some selenium tests in a docker container selenium standalone firefox.(<a href="https://hub.docker.com/r/selenium/standalone-firefox/" rel="nofollow noreferrer">https://hub.docker.com/r/selenium/standalone-firefox/</a>) . However, I am not able to integrate t...
<python><selenium-webdriver><firefox>
2023-05-05 14:33:51
2
525
Mr. E
76,183,278
9,885,747
How to locally develop EventHub Triggered Functions in Python (programming model v2)?
<p>I would like to learn to develop Azure Functions locally using Visual Studio Code. While there are <a href="https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators" rel="nofollow noreferrer">numerous examples</a> and <a href="https://www.youtube.com/...
<python><azure><azure-functions><event-handling><emulation>
2023-05-05 14:29:48
4
1,685
DataBach
76,182,959
1,509,372
Full outer join in Django ORM
<p>I have a set of models like this:</p> <pre class="lang-py prettyprint-override"><code>class Expense(models.Model): debitors = models.ManyToManyField(Person, through='Debitor') total_amount = models.DecimalField(max_digits=5, decimal_places=2) class Debitor(models.Model): class Meta: unique_toget...
<python><django><orm>
2023-05-05 13:55:20
3
758
Compizfox
76,182,881
12,193,952
How to operate a Kubernetes cluster on Digitalocean from Python?
<h2>the question</h2> <p>I am running a Kubernetes cluster in Digitalocean and I want to connect to it from certain Python app, in order to retrieve information about running services. I am able to setup the connection from my local (where <code>kubeconfig</code> created using <code>doctl</code> is present), however ho...
<python><kubernetes><digital-ocean><kubeconfig>
2023-05-05 13:45:58
1
873
FN_
76,182,735
3,182,021
Why this gradient descent algorithm does not works for all values of sinus function?
<p>I have this gradient descent code that compute well for boolean functions but not for sinus. I do not know what is the problem with it? I tried to change activation function of hidden layer or output layer from sigmoid to hyperbolic tangent but it still does not compute the good values for some values of sinus.</p> ...
<python><deep-learning><gradient-descent>
2023-05-05 13:28:44
1
419
Damien Mattei
76,182,705
10,232,932
Use virtual enviorment from a git repository in visual studio code
<p>I created a virtual enviornment (venv) called <em><strong>.MF39</strong></em> on my local machine in windows and pushed this into a git repository, lets call the repository: &quot;mastermind&quot;.</p> <p>When I now go on a different machine and run the commands in the terminal of visual studio code:</p> <pre><code>...
<python><git><visual-studio-code>
2023-05-05 13:25:51
2
6,338
PV8
76,182,623
4,172,765
Upload file using Python-requests
<p>I have a problem when writing REST API to upload files by Python. This is the REST API on Postman. It worked.<br /> <a href="https://i.sstatic.net/c2IKF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c2IKF.png" alt="enter image description here" /></a></p> <p>But when I write the python code, it show...
<python><python-requests>
2023-05-05 13:15:50
1
917
ThanhLam112358
76,182,588
15,632,586
What should I do to save files in the right directory in Flask?
<p>I am creating a website in Flask, in which ideally after pasting my report and adding the report name, the website would save the newly generated report in <code>static/{report_name}/new_file.txt</code> and a Graphviz file (in <code>static/{report_name}/graph.gv</code>).</p> <p>Here is my current js and HTML code th...
<javascript><python><flask>
2023-05-05 13:11:03
0
451
Hoang Cuong Nguyen
76,182,587
1,436,800
Error installing Syft 0.2.5 in Colab: subprocess exited with error
<p>I am trying to install Syft version 0.2.5 on Google Colab using the command !pip install syft==0.2.5. However, I am running into an error while installing the scipy dependency. The error message indicates that the subprocess to install the build dependencies did not run successfully, with exit code 1. I am encounter...
<python><scipy><google-colaboratory><pysyft>
2023-05-05 13:11:01
0
315
Waleed Farrukh
76,182,394
14,271,847
How to build a JWT RS256 Algorithm using Python?
<p>How to fix the error &quot;JWT method 'encode' does not exist&quot; when trying to mount a base64 for the assertion parameter of an API?</p> <p>I'm trying to create a base64 to use as an &quot;assertion&quot; parameter in an API call, but I'm getting an error saying that the &quot;encode&quot; method of the JWT does...
<python><encoding><jwt><rs256>
2023-05-05 12:50:52
1
429
sysOut
76,182,290
16,367,397
I installed the module, but still writes ModuleNotFoundError
<p>I installed Python using brew I put the package like this pip install moderngl, as you can see in the screenshot it is there, but it still gives an error that it is not installed <a href="https://i.sstatic.net/ain5J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ain5J.png" alt="enter image descriptio...
<python><pip>
2023-05-05 12:38:30
1
348
steind.VY
76,182,348
1,581,090
How to create a small python code to get a list of participants of a teams call?
<p>Using python, and having an azure applicationID/ objectID/ tenantID / clientID and clientSecret I want to access a &quot;teams&quot; meeting using e.g. <code>requests</code> to get the list of participants of an ongoing teams meeting. There seems to be a lot of confusion between existing and non-exsting modules like...
<python><azure><microsoft-teams>
2023-05-05 12:38:17
2
45,023
Alex
76,182,193
4,045,275
How to create a list or array of days falling on the 15th of each month
<h2>What I am trying to do</h2> <p>I am trying to create a list or array of dates all falling on a specific day of the month, and then changing the first item. E.g. something like:</p> <pre><code>20-Jan-2023,15-Feb-2023,15-Mar-2023, etc. </code></pre> <p>I am sure this is documented somewhere, but I find the quality of...
<python><pandas><date><datetime>
2023-05-05 12:28:21
1
9,100
Pythonista anonymous
76,182,022
9,827,719
Docker install WeasyPrint on Google Cloud Run for Python gives "Unable to locate package python-lxml"
<p>I am trying to install WeasyPrint on Google Cloud Run using Dockerfile. This gives error <code>Unable to locate package python-lxml</code>. What can I do to install Weasyprint?</p> <p><strong>Dockerfile</strong></p> <pre><code># Specify Python FROM python:latest ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ...
<python><docker><weasyprint>
2023-05-05 12:05:27
0
1,400
Europa
76,181,779
1,308,967
Cache Django REST Framework HTTP Streaming Response?
<p>I am trying to cache Django REST Framework HTTP streaming responses.</p> <p>My thinking is a Response sub-class can write the chunks into a temporary file as it streams, and on closing after streaming the final chunk, run a callable that copies the file into cache.</p> <pre class="lang-py prettyprint-override"><code...
<python><django><caching><httpresponse>
2023-05-05 11:38:08
1
6,522
Chris
76,181,776
13,040,314
how to disable pep8 in pycharm for a code block
<p>I want to disable pep8 for a block of code for example, a an array which has long text, I do not want it to complain about line too long. How can I disable the pep8 inspection only for that array?</p>
<python><pycharm><pep8><pep>
2023-05-05 11:37:45
0
325
StaticName
76,181,711
5,016,028
Remove all dataframe columns that have a sum lower than given value
<p>I have a dataframe <code>df</code> where some columns have very small elements. I want to remove these columns based on the sum of the elements. If the sum is below 1.0, then I want to drop the column. Now I am trying this:</p> <pre><code>df = df.loc[:, (df.sum() &lt; 1.0).any(axis=0)] </code></pre> <p>But it does t...
<python><pandas><dataframe>
2023-05-05 11:30:50
2
4,373
Qubix
76,181,453
3,561,433
Hyperparameter tuning for Custom Gym Env in Stable Baselines3 using RL Zoo
<p>I have created a Gym environment and am able to train it via PPO from Stable Baselines3. However, I am not getting desired results. The agent seems to be stuck at the local optimum rather than the global one. However, even reaching this stage required a lot of computing and I am unsure if I have proper parameter set...
<python><reinforcement-learning><openai-gym><hyperparameters><stable-baselines>
2023-05-05 10:57:33
1
522
Manish
76,181,450
572,575
Metplotlib show error The number of FixedLocator locations, usually from a call to set_ticks, does not match the number of labels
<p>I want to plot graph and show the label in Matplotlib. I have some class to plot in same axis.</p> <pre><code> import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap x = [1,1, # plot 2 value at X1 2,2,2,2, # plot 4 value at X2 3,3,3,3,3, 4,4,4,4...
<python><matplotlib>
2023-05-05 10:57:09
0
1,049
user572575
76,181,426
241,605
Custom rendering of nested field in django-tables2
<p>I have a table defined like this, where I want to apply custom rendering for a field:</p> <pre><code>import django_tables2 as tables class SetTable(tables.Table): class Meta: model = Set fields = ( &quot;series.title&quot;, ) def render_series_title(self, value): ...
<python><django><django-tables2>
2023-05-05 10:53:20
1
20,791
Matthew Strawbridge
76,181,408
5,672,673
Error concatenating layers in the generator in a GAN
<p>I am making a GAN (in deep learning) in tensor flow Keras. The generator is a UNET architecture: we downsample the image input into smaller and deeper matrix, then we upsample to restore the size. Here is the code for the generator:</p> <pre><code>OUTPUT_CHANNELS = 3 def downsample(filters,size,apply_batchnorm = Tru...
<python><tensorflow><keras><deep-learning><generative-adversarial-network>
2023-05-05 10:51:20
0
1,177
Linh Chi Nguyen
76,181,266
10,685,529
Type hints with Python ^3.10 and Pylance for VSCode
<p>I try to follow the new features for type hinting that came with Python 3.10. I use VSCode with the pylance extension.</p> <p>For instance I have a methos like this in a class:</p> <pre class="lang-py prettyprint-override"><code>def execute( self, query: str, return_type: str | None = None ) -&gt; pd.Dat...
<python><python-typing><pylance>
2023-05-05 10:34:26
1
1,353
Lewi Uberg
76,181,251
12,466,687
How to apply value_counts() to multiple columns in polars python?
<p>I am trying to apply <code>value_counts()</code> to multiple columns, but getting an error.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.from_repr(&quot;&quot;&quot; ┌──────────────┬─────────────┐ │ sub-category ┆ category │ │ --- ┆ --- │ │ str ┆ str ...
<python><dataframe><apply><python-polars><unpivot>
2023-05-05 10:31:34
4
2,357
ViSa
76,181,200
14,548,431
Python send e-mail async with trio
<p>I want to send e-mails in an asynchronous way by using the package trio. I found the package aiosmtplib, but this is only for asyncio.</p> <p>Is there any package which I can use for it, or has anyone an idea of how to implement this with trio?</p> <p>Update: I found this package <a href="https://pypi.org/project/ma...
<python><email><asynchronous><smtp><python-trio>
2023-05-05 10:24:01
0
653
Phil997
76,181,169
3,729,714
Python - filedialog.askdirectory won't recognize initialdir of local drive
<p>I'm trying to get the second filedialog call in my script to open to my local C drive, but it will only open the first call's initialdir, which is a UNC path. (Both are stored in different variables).</p> <p>1: Is the following syntax correct, and is there anything I need to do to force the code to use the second ...
<python><python-3.x>
2023-05-05 10:20:49
0
1,735
JM1
76,180,846
1,401,202
Send notification from cron action in Odoo 16
<p>I have a recurring CRON action in my app. When fired it updates some records in the database. I want to inform the creator of the record that it has been updated by the CRON task. I've tried many variations of the code below but no message is sent. There is no error thrown.</p> <pre><code>def _send_discuss_message(s...
<python><odoo><odoo-16>
2023-05-05 09:40:12
1
8,078
kpg
76,180,798
11,758,843
Jenkins Job Failing for urllib3: ValueError: Timeout value connect was <object object at 0x7efe5adb9aa0>, but it must be an int, float or None
<p>As of May 4, 2023, at 16:00, I started seeing one of our Jenkins job failing with the following error:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__....
<python><jenkins><python-requests><jenkins-pipeline><urllib3>
2023-05-05 09:35:31
2
5,920
Abdullah Khawer
76,180,541
14,949,601
In Python multiprocesssing, why the `qsize()` of a queue is not 0, but `get_nowait()` produce empty item?
<p>I write a python program where I use <code>multiprocessing</code> lib to communicate between parent process and child process.</p> <p><a href="https://i.sstatic.net/oxMJ9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oxMJ9.png" alt="enter image description here" /></a></p> <p>In this code and the ru...
<python><multiprocessing><queue>
2023-05-05 09:05:49
0
329
dongrixinyu
76,180,497
353,337
Read XML prolog
<p>I have an XML file</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;?foo class=&quot;abc&quot;?&gt; &lt;document&gt; ... &lt;/document&gt; </code></pre> <p>frpm which I'd like to read the <code>foo</code> prolog using Python.</p> <pre class="l...
<python><xml>
2023-05-05 09:00:08
2
59,565
Nico Schlömer
76,180,141
11,696,358
Select the maximum number of rows so that the sum of the columns is balanced
<p>Suppose I have a table with the following columns and much more rows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Id</th> <th>n_positive_class1</th> <th>n_positive_class2</th> <th>n_positive_class3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>0</td> <td>10</td> <td>4000</td> </tr>...
<python><pandas><numpy><imbalanced-data>
2023-05-05 08:16:59
0
478
user11696358
76,180,106
5,404,765
How to store name value pair in Django db?
<p>I want to create a student record data base using django db. The class will look something like below</p> <pre><code>class StudentRecord(models.Model): studentname = models.CharField() #marks = ['Science':98, 'Maths':99, 'Computer'::95] </code></pre> <p>I want to add 'marks' field, which is like a dictiona...
<python><django><web-applications>
2023-05-05 08:11:45
3
311
Darshan Bhat
76,179,953
11,082,866
Pycairo error while deploying django app on AWS
<p>My app is deployed on AWS ElasticBeanStalk was working fine up until one hour ago and now it is giving 502 Bad gateway error. When I tried to redeploy the application it gives me the following error</p> <pre><code>2023/05/05 07:41:44.917340 [ERROR] An error occurred during execution of command [self-startup] - [Inst...
<python><django><amazon-elastic-beanstalk>
2023-05-05 07:52:21
1
2,506
Rahul Sharma
76,179,643
13,957,731
Pymysql reset cursor like mysql.connector
<p>I have a piece of code which I migrate driver from mysql.connector to pymysql. On mysql.connector there have cursor.reset(free=True), is there pymysql have functionality like that?</p>
<python><mysql><pymysql>
2023-05-05 07:12:31
0
325
GurbaniX
76,179,430
1,976,597
Perform some action when a Python module is imported
<p>I want to run a function only if a particular package has been imported, or is later imported.</p> <p>In pseudo code, this is what I want to do:</p> <pre class="lang-py prettyprint-override"><code> if 'some_package' in sys.modules: # The easy part do_things_with_some_package() else: # The pseudo code somehow_r...
<python>
2023-05-05 06:40:49
3
4,914
David Gilbertson
76,179,376
14,094,546
Which statistics test should I use to check difference in frequency between 2 populations?
<p>I have two population and I want to known if their difference is significant or no (since the population B is the result of a subset of population A after some filtering criteria). Which test should I use (since I have only 2 numbers). I am confused trying to find the correct approach (and implement it in Python). T...
<python><statistics><chi-squared><t-test><population>
2023-05-05 06:31:32
0
520
Chiara
76,179,314
1,668,622
How to correctly assign elements of recursively typed collections?
<p>According to <a href="https://github.com/python/mypy/issues/731" rel="nofollow noreferrer">https://github.com/python/mypy/issues/731</a> recursive type definition should be possible and enabled by default. And for me it's working somehow.</p> <p>However I didn't manage to successfully assign a value from a recursive...
<python><python-3.x><mypy><recursive-type>
2023-05-05 06:21:44
1
9,958
frans
76,179,056
2,566,283
A package import works when running script directly but not when that script is imported by another
<p>I have this situation:</p> <pre><code>main_script.py tools/ __init__.py a.py b.py </code></pre> <p>In <code>a.py</code> I have the following</p> <pre><code>import argparse from b import b_func def main(): parser = argparse.ArgumentParser() parser.add_argument('a') args = parser.parse_args() ...
<python><python-3.x><import>
2023-05-05 05:25:06
2
2,724
teepee
76,178,810
16,527,596
How to call the methods of 3 other classes into another class in python
<p>So for now i have build 3 classes</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcol color_dict = mcol.TABLEAU_COLORS def lin2db(x): return 10*np.log10(x) def db2lin(x): return 10**(x/10) class ADC(): fs_step = 2.75625e3 def __init__(self,n_bit):...
<python><oop>
2023-05-05 04:11:27
1
385
Severjan Lici
76,178,795
8,391,698
How to test if a sequence contains a new line characters within a certain window length in Python
<p>I have this list in Python:</p> <pre><code>my_list = [&quot;KKAWTMYGNLSKKDQNRYNA\nDAT&quot;, # false &quot;EEQLLNEPD\nKIVIIPACVIDELEENKKLKGLEEILKKVRRA&quot;, #true &quot;NNCLQKYKEAEEYYEESIFILKTVN&quot;, # false &quot;EEQLLNEPD\nKIVIIPACV\nIDELEENKKLKGLEEILKKVRRA&quot;, #true ...
<python><python-3.x><string>
2023-05-05 04:08:18
3
5,189
littleworth
76,178,774
15,584,917
Python group by and keep rows with greatest absolute value?
<p>I have a very large dataframe. I would like to group by <code>col1</code> and <code>col4</code> and keep rows which have the greatest absolute value in <code>col5</code>.</p> <p>However I would like the final table to also include <code>col2</code> and <code>col3</code> (but I do not want to group by these columns w...
<python><pandas>
2023-05-05 04:00:23
1
339
1288Meow
76,178,706
6,751,456
django serializer dictfield vs jsonfield
<p>I have a column <code>custom_property</code> of type <code>jsonb</code> in postgres.</p> <p>I need to validate a payload for this column.</p> <pre><code>payload: { &quot;description&quot;: &quot;test description3&quot;, &quot;custom_property&quot;: { &quot;access&quot;: &quot;Yes&quot; } } </cod...
<python><json><django><dictionary><django-serializer>
2023-05-05 03:39:51
1
4,161
Azima
76,178,525
14,365,042
How to combine multiple rows (with two column values are different) into one row in Pandas
<p>I have a big survey data (over 50K rows) as:</p> <pre><code>df1 = pd.DataFrame(list(zip(['0001', '0001', '0002', '0003', '0004', '0004'], ['a', 'b', 'a', 'b', 'a', 'b'], ['USA', 'USA', 'USA', 'USA', 'USA', 'USA'], ['Jan', 'Jan', 'Jan',...
<python><pandas>
2023-05-05 02:44:18
0
305
Joe
76,178,000
10,387,506
Assemble random sales table with Python
<p>I have attempted to assemble a randomized sales table with mock data.</p> <ul> <li>I have a customer table with 50,000 entries.</li> <li>I have a product table with 550,000 entries.</li> <li>I produced a series with store codes. Ideally I'd like 5 stores.</li> <li>I also created a date/time series spanning 2 years.<...
<python><pandas><numpy>
2023-05-04 23:39:06
1
333
Dolunaykiz
76,177,904
5,725,780
How do I validate all files in a torrent using libtorrent offline in python?
<p>Given a torrent file, I would like to use libtorrent to validate that I have all the files, essentially what a <em>force recheck</em> would do in a bittorrent client, and I want to do it off-line and without involving some other client.</p> <p>I've only found how to recalculate the hash for all pieces but I'm not qu...
<python><bittorrent><libtorrent>
2023-05-04 23:07:17
1
721
pipe
76,177,732
6,286,900
How to test API with pytest
<p>I have the following <a href="https://github.com/sasadangelo/races/blob/main/app/races_api.py" rel="nofollow noreferrer">CRUD Flask application</a> where I have my CRUD api defined <a href="https://github.com/sasadangelo/races/blob/main/app/races_api.py" rel="nofollow noreferrer">in this file</a> for the Race object...
<python><flask><pytest>
2023-05-04 22:21:13
0
1,179
Salvatore D'angelo
76,177,622
4,885,544
Executing celery task through a listener on a RabbitMQ queue
<p>I am trying to run a script for a messaging consumer that listens to a rabbitMQ instance and executes a celery job based on that message value. I am receiving issues with circular dependencies and cannot figure what exactly is the issue and how to fix it. Below are my file examples:</p> <p>celery.py import os from c...
<python><django><rabbitmq><celery><pika>
2023-05-04 22:00:42
1
486
sclem72
76,177,601
3,159,428
pandas group by date in pandas 2.0
<p>i have this dataframe</p> <pre class="lang-none prettyprint-override"><code>date in_count out_count 2013-01-03, 1.00000, 0.00000 2013-03-04, 1.00000, 0.00000 2013-04-08, 1.00000, 0.00000 2013-04-22, 1.00000, 0.00000 2013-05-06, 0.00000, 1.00000 </code></pre> <p>the idea is to grouping by week...
<python><pandas><dataframe>
2023-05-04 21:56:32
2
486
Fermin Pitol
76,177,509
7,988,497
Python Packaging with Pytest
<p>I have a tree like this</p> <pre><code>src __init__.py my_app __init__.py db.py config.py tests __init__.py test_db.py </code></pre> <p>In <code>db.py</code> I've got an import like this</p> <pre><code>from config import my_func </code></pre> <p>This works fine when I run db.py by itself (pytho...
<python><python-3.x>
2023-05-04 21:36:04
1
1,336
MichaelD
76,177,506
2,562,058
Is it possible to display images in IPython (or Jupyter) console?
<p>I have just discovered that there are tools that allow embedding images into terminals, like <a href="https://linuxhint.com/display-image-linux-terminal/" rel="nofollow noreferrer">these ones</a>.</p> <p>I am wondering if there is a <code>IPython</code> (or, more generally <code>jupyter console</code>) builtin funct...
<python><jupyter><ipython><jupyter-console>
2023-05-04 21:35:54
1
1,866
Barzi2001
76,177,432
4,538,768
Reduction of queries in ManyToMany field with prefetch_related
<p>I want to reduce further the number of queries. I used prefetch_related decreasing the number of queries. I was wondering if it is possible to reduce to one query. Please let me show the code involved:</p> <p>I have a view with prefetch_related:</p> <pre><code>class BenefitList(generics.ListAPIView): serializer_...
<python><django><django-models><django-views>
2023-05-04 21:20:11
1
1,787
JarochoEngineer
76,177,406
1,711,271
Compute m columns from 2m columns without a for loop
<p>I have a dataframe where some columns are name-paired (for each column ending with <code>_x</code> there is a corresponding column ending with <code>_y</code>) and others are not. For example:</p> <pre><code>import pandas as pd import numpy as np colnames = [ 'foo', 'bar', 'baz', 'a_x', 'b_x', 'c_x', 'a...
<python><pandas><apply><calculated-columns>
2023-05-04 21:15:42
3
5,726
DeltaIV
76,177,382
1,224,437
Fine grained resource management in an async function?
<p>Using <code>@asyncio.coroutine</code> one can write a fine-grained resource manager for acquiring and releasing a shared resource (say a <code>Lock</code> or a global variable or database connection):</p> <pre class="lang-py prettyprint-override"><code>@asyncio.coroutine def resource_context(func: Callable[..., Awai...
<python><asynchronous><async-await><python-asyncio>
2023-05-04 21:10:38
1
517
fritzo
76,177,372
2,377,957
Generating Accessible PDFs in Python
<p>I am attempting to generate automated reports which are Accessible (508 Compliant). I read that <code>reportlab</code> is capable of generating pdf which are accessible. I have yet to see any examples of this being true. However, there is a paid option. I have been experimenting extensively with various packages inc...
<python><pdf><accessibility>
2023-05-04 21:08:27
3
4,105
Francis Smart
76,177,370
14,293,020
How to reproject xarray dataset memory efficiently with chunks and dask?
<p><strong>Context:</strong> I have a netcdf file that I want to reproject. It is a costly operation, and I am learning how to use <code>dask</code> and <code>zarr</code> to do it efficiently without crashing my RAM.</p> <p><strong>Code presentation:</strong> <code>ds</code> is a 3D <code>xarray</code> dataset (dimensi...
<python><dask><python-xarray><chunks><zarr>
2023-05-04 21:08:21
1
721
Nihilum
76,177,366
12,064,467
Dot product between NumPy arrays
<p>I have a Pandas Series object called X, which has dimension (100,). Each element of X is mapped to a NumPy ndarray of floating point numbers, with shape (10, 10). I also have another Pandas Series object called Y, which also has dimension (100,). Each element of Y is mapped to a Pandas DataFrame; each DataFrame cont...
<python><pandas><numpy>
2023-05-04 21:07:42
1
522
DataScienceNovice
76,177,151
2,312,835
Argmax over vectors in numpy
<p>I am trying to write as clean and efficient an expression as possible in order to solve the following problem. I have a set <code>[[v11,...,v1n],...,[vm1,...,vmn]]</code> of vectors (stored as an <code>(m,n,a)</code> array) and a second set <code>[b1,...,bk]</code> (again, as a <code>(k,a)</code> array). What I want...
<python><numpy><linear-algebra>
2023-05-04 20:26:39
1
330
Daniel Robert-Nicoud
76,177,087
5,090,680
SimpleITK: Rigidly transform image according to 4x4 matrix defined in numpy
<p>I have an image that I have read using <code>sitk.ReadImage</code> and a 4x4 numpy array representing a rigid transform I would like to apply on the image. For the life of me, I cannot seem to figure out how to cast the numpy array to a transform object that is accepted by sitk when trying to perform <code>sitk.Resa...
<python><numpy><itk><simpleitk>
2023-05-04 20:17:20
0
368
brohan322
76,177,042
12,064,467
Pandas Correlation Matrices?
<p>I have a large DataFrame; the values of all columns are floating point numbers, and the indices are of type DatetimeIndex. For example, here is the first part of my DataFrame:</p> <pre><code> col0 col1 col2 col3 col4 ... 2035-10-30 1.0 1.0 1.0 1.0 1.0 ... 2035-10-31 1.0 1.0 1.0 1.0 1.0 ... 203...
<python><pandas><dataframe><data-science>
2023-05-04 20:10:00
1
522
DataScienceNovice
76,176,965
4,027,688
Include py.typed file in wheel produced with nuitka
<p>I'm trying to build a wheel for a pyproject.toml based project using nuitka as described <a href="https://nuitka.net/doc/user-manual.html#use-case-5-setuptools-wheels" rel="nofollow noreferrer">here</a>. I'd like to include a <code>py.typed</code> file in the final wheel. My repo structure looks like this</p> <pre><...
<python><setuptools><python-packaging><nuitka>
2023-05-04 19:58:42
1
3,175
bphi
76,176,610
3,709,062
Second test with pytest-postgresql still using schema from first test
<p>I am trying to perform some tests using <strong>pytest-postgresql</strong> but it seems I do not fully grasp how the engine generated from the fixture works. The code below is the minimal example I could write to reproduce the error I am getting. There are 2 tests named for tokyo and london and each is meant to use ...
<python><sqlalchemy><pytest>
2023-05-04 19:04:36
2
1,176
GStav
76,176,587
2,281,318
PyLance in strict mode: additional typing hints for external libraries
<p>The code [Python 3.11, Visual Studio Code, Pylance strict mode]</p> <pre class="lang-py prettyprint-override"><code>from typing import List, Tuple import networkx as nx graph = nx.MultiDiGraph() # .add_edge(source node, sink node, edge type) graph.add_edge(&quot;node1&quot;, &quot;node2&quot;, (0, 0)) graph.add_e...
<python><python-typing><pyright>
2023-05-04 19:01:20
1
966
Antoine
76,176,534
1,246,260
Longer Responses with LlamaIndex?
<p>I currently have LlamaIndex functioning off some private data just fine, however, it only outputs about 1000 characters worth. How do I extend the output until its completion? I know I can bump the tokens a bit, but I'm looking at potentially pages worth.</p> <pre><code>llm_predictor = LLMPredictor(llm=OpenAI(temper...
<python><openai-api><llama-index>
2023-05-04 18:56:12
2
613
Jon
76,176,477
10,286,813
Python, Regex everything before a sequence
<p>I have a data frame column which contains the following strings. I want to parse everything to the left of the 4 or 5 digit number into a separate column</p> <pre><code>column name 0 129 4,029.16 08-31-13 8043 304.12 02-28-13 00T773466 1 19 179.00 03-31-12 T0707440 7794 2,898.56 01-31-13 00T757276 2 ...
<python><regex><dataframe>
2023-05-04 18:50:15
4
1,049
Nev1111
76,176,439
2,883,245
Why is my streamlit app's second radio disappearing when I change the default answer?
<p>I am designing an small annotation interface which will present users with a series of examples. An example will be presented to a user, they will make a mutually exclusive selection using a radio button, then more information will be presented in a second button where they can make a new selection with the same opt...
<python><streamlit>
2023-05-04 18:43:37
1
17,125
erip
76,176,245
489,088
How to get the indexes of a sort operation instead of a sorted array using numpy?
<p>I have a 3D array like so:</p> <pre><code>arr = [[[20, 5, 10], ...], ...] </code></pre> <p>if I do</p> <pre><code>print(arr.argsort()) </code></pre> <p>I get the indexes that would sort the array on that last axis:</p> <pre><code>[[[1, 2, 0], ...], ...] </code></pre> <p>But what I want is for each position the index...
<python><arrays><numpy><numpy-ndarray>
2023-05-04 18:15:50
1
6,306
Edy Bourne
76,176,222
1,874,170
Overriding __new__ to pre-process arguments and create a subclass
<p>I've got a base class, <code>_BaseWidget</code>, which is not instantiated. It's got many <code>abstractmethod</code>s to be filled in by sub-classes like <code>AppleWidget</code> and <code>PearWidget</code> which are actually instantiated and used.</p> <p>However, <strong>for convenience</strong>, I'd like to make ...
<python><class><constructor><subclass>
2023-05-04 18:11:26
0
1,117
JamesTheAwesomeDude
76,176,132
11,155,419
Regex to extract part of URL that can be in the middle or end
<p>So I have a URL that could be in the following three formats:</p> <pre class="lang-none prettyprint-override"><code>https://www.example.com/d/abcd-1234/edit https://www.example.com/d/abcd-1234/ https://www.example.com/d/abcd-1234 </code></pre> <p>I would like to extract only the <code>abcd-1234</code> bit from the a...
<python><python-3.x><regex>
2023-05-04 17:59:20
3
843
Tokyo