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
75,202,407
11,015,558
Creating a date range in python-polars with the last days of the months?
<p>How do I create a date range in Polars (Python API) with only the last days of the months?</p> <p>This is the code I have:</p> <pre><code>pl.date_range(datetime(2022,5,5), datetime(2022,8,10), &quot;1mo&quot;, name=&quot;dtrange&quot;) </code></pre> <p>The result is: <code>'2022-05-05', '2022-06-05', '2022-07-05', '...
<python><datetime><date-range><python-polars>
2023-01-22 17:20:02
3
1,994
Luca
75,202,296
6,076,861
Read mutliple parquet files to pandas with select columns where select columns exist
<p>When running the below i hit an error due to some of the files missing the required columns</p> <pre class="lang-py prettyprint-override"><code> li = [] for filename in parquet_filtered_list: df = pd.read_parquet(filename, columns = list_key_cols_aggregates ) li...
<python><pandas><pyarrow>
2023-01-22 17:04:24
1
2,045
mapping dom
75,202,174
4,451,315
Which directive to use to parse Z in time string?
<p>If I use <code>fromisoformat</code> (in Python3.11), then <code>Z</code> is parsed as <code>UTC</code>:</p> <pre class="lang-py prettyprint-override"><code>In [15]: dt.datetime.fromisoformat('2020-01-01T03:04:05Z') Out[15]: datetime.datetime(2020, 1, 1, 3, 4, 5, tzinfo=datetime.timezone.utc) </code></pre> <p>But how...
<python><datetime><utc><iso8601>
2023-01-22 16:46:06
1
11,062
ignoring_gravity
75,202,027
2,447,609
Rclone+Python - Retain the file permissions during the backup to the S3 bucket
<p>I'm using the rclone with python. I want to persist the file permissions during the file transfer and then retain back during the restore. What is the best way to implement this?</p> <p>I don't see the &quot;rclone mount&quot; is the best solution for our transfer. Please suggest me...</p>
<python><rclone>
2023-01-22 16:24:46
1
365
suresh goud
75,201,985
12,350,966
pandas groupby with value_counts(normalize=True) return dataframe instead of series?
<p>Not the data I am using, but best reproducible example I can think of:</p> <pre><code> test = pd.util.testing.makeMixedDataFrame() grouped = test.groupby(['C', 'B'])['A'].value_counts(normalize=True) </code></pre> <p>give a series:</p> <pre><code>C B A foo1 0.0 0.0 1.0 foo2 1.0 1.0 1.0 foo3...
<python><pandas>
2023-01-22 16:20:14
0
740
curious
75,201,928
1,714,385
ImportError: cannot import name '_log_class_usage' from 'torchtext.utils'
<p>I recently updated pytorch and torchtext from anaconda, in order to run <a href="https://pytorch.org/tutorials/beginner/torchtext_translation_tutorial.html" rel="nofollow noreferrer">this tutorial</a> from the torchtext website, but it seems that my installation of torchtext has been broken. Everytime that I try <co...
<python><pytorch><torchtext>
2023-01-22 16:12:41
1
4,417
Ferdinando Randisi
75,201,847
3,507,584
Plotly make marker overlay add_trace
<p>I have the following Scatterternary plot below. Whenever I <code>add_trace</code>, the marker remains under it (so you cannot even hover it). How can I make the marker circle above the red area? [In implementation, I will have several areas and the marker may move around]</p> <p>I tried adding <code>fig.update_terna...
<python><scatter-plot><plotly>
2023-01-22 16:00:54
1
3,689
User981636
75,201,806
7,168,098
change indentation in VS code for python functions
<p>I am using VS code to write python code.</p> <p>When writing functions I get: <a href="https://i.sstatic.net/pcZQU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pcZQU.png" alt="enter image description here" /></a></p> <p>What I would like to have when I hit return after every variable of the method ...
<python><visual-studio-code>
2023-01-22 15:55:26
3
3,553
JFerro
75,201,798
2,881,414
Separating elements from a list in Python depending on a condition
<p>I have a list of elements and want to <strong>separate</strong> the elements of the list by a certain condition.</p> <p>A simple example is a list of numbers and i want to separate the odd from the even ones. For that could use the <code>filter</code> builtin like so:</p> <pre class="lang-py prettyprint-override"><c...
<python><functional-programming>
2023-01-22 15:53:56
4
17,530
Bastian Venthur
75,201,698
16,698,040
urlencode without quote python
<p>I wish to use Python's <code>urllib.parse.urlencode()</code> method to convert a dict to URL-like params, however, I do not want any quoting of characters, just the <code>?&lt;...&gt;=&lt;...&gt;&amp;&lt;...&gt;=&lt;...&gt;</code> logic.</p> <p>Is that possible?</p>
<python><url>
2023-01-22 15:39:51
1
475
Stack Overflow
75,201,645
11,405,004
How to count the number of unique values per group over the last n days
<p>I have the pandas dataframe below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>groupId</th> <th>date</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2023-01-01</td> <td>A</td> </tr> <tr> <td>1</td> <td>2023-01-05</td> <td>B</td> </tr> <tr> <td>1</td> <td>2023-01-17</td...
<python><pandas><dataframe>
2023-01-22 15:32:38
2
386
confused_pandas
75,201,622
817,630
What are the correct mypy hints for this generic classmethod?
<p>I have a series of classes that looks like this</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod from typing import TypeVar T = TypeVar(&quot;T&quot;, bound=&quot;A&quot;) U = TypeVar(&quot;U&quot;, bound=&quot;ThirdPartyClass&quot;) class ThirdPartyClass: &quot;&quot;&qu...
<python><generics><types><mypy>
2023-01-22 15:30:03
0
5,912
Kris Harper
75,201,521
13,943,207
Panel is overlapping and has a wrong ratio in mplfinance plot
<p>I'm trying to plot a subplot but there are two problems. <br> #1 The <code>panel_ratio</code> setting <code>(6,1)</code> is unnoticed. <br> #2 The y axis of the top panel juts down and overlaps the y axis of the bottom panel, so that the bars are trimmed in the top panel</p> <p>What is wrong with the code?</p> <pre>...
<python><matplotlib><mplfinance>
2023-01-22 15:13:38
1
552
stanvooz
75,201,514
1,417,053
Sending Pickled Objects Using Pickle5's Out-of-Band Buffers Over the Network
<p>I've been using PyArrow to do my Serialization/Deserialization of custom made objects and have been searching for ways to use Pickle's new <code>protocol 5</code> to replace PyArrow as discussed <a href="https://github.com/apache/arrow/issues/11239" rel="nofollow noreferrer">here</a>.</p> <p>I want to send the seria...
<python><serialization><deserialization><pickle><zeromq>
2023-01-22 15:12:39
1
2,620
Cypher
75,201,456
3,817,518
Python Dynamic Programming Problem - ( 2 dimension recursion stuck in infinite loop )
<p>In the book &quot;A Practical Guide to Quantitative Finance Interview&quot;, there is a question called Dynamic Card Game, 5.3 Dynamic Programming)</p> <p>The solution according to the book is basically the following:</p> <p><code>E[f(b,r)] = max(b−r,(b/(b+r))∗E[f(b−1,r)]+(r/(b+r))∗E[f(b,r−1)])</code></p> <p>with th...
<python><recursion><dynamic-programming><infinite-recursion>
2023-01-22 15:04:00
3
1,986
nyan314sn
75,201,404
7,446,003
How to make sequential signup pages with Django allauth?
<p>I currently have a single page signup form implemented with allauth</p> <pre><code>from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(_('Professional email address'), unique=True) username = models.CharField(_(&quot;User Name&quot;), blank=False, max...
<python><django>
2023-01-22 14:57:03
0
422
RobMcC
75,201,226
7,575,552
Replacing a Keras layer in a pretrained model with another layer
<p>I am using Keras with Tensorflow version 2.7 as backend. I am referring to the stackoverflow post at <a href="https://stackoverflow.com/questions/45306433/removing-then-inserting-a-new-middle-layer-in-a-keras-model/45309508#45309508">Removing then Inserting a New Middle Layer in a Keras Model</a>. I aim to instanti...
<python><tensorflow><keras>
2023-01-22 14:29:37
2
1,189
shiva
75,201,174
4,576,519
How to create a recurrent connection between two Dense layers in Keras?
<p>Before starting, there is a <a href="https://stackoverflow.com/questions/63899389/how-to-create-a-recurrent-connection-between-2-layers-in-tensorflow-keras">very similar question</a>, but it was asked 2 years ago and I would like to do this <em>without</em> creating a custom class. Essentially, I have the simple fee...
<python><tensorflow><keras><recurrence>
2023-01-22 14:23:19
0
6,829
Thomas Wagenaar
75,201,041
2,748,513
How to print matching json element value from nested json string
<p>my_json file has list of nested dicts, I need to print only the username if <code>type==Developer-Verified and it's value==1</code>, I managed to print just the approvals list, unable to to go further.</p> <pre><code>$ cat myjson_file | python3.6 -c &quot;import sys, json; approvals=json.load(sys.stdin)['currentPatc...
<python><python-3.6>
2023-01-22 14:04:37
1
3,221
rodee
75,201,003
3,672,883
How can I reference var from section into another section in pyproject.toml?
<p>Hello I am building a pyproject object and I have the following two sections</p> <pre><code>[tool.poetry] version = &quot;0.1.0&quot; [tool.commitizen] version = &quot;0.1.0&quot; </code></pre> <p>As you can see poetry uses the version in its section and commitizen in its section, the question is how to can I set o...
<python><python-poetry><pyproject.toml><commitizen>
2023-01-22 13:59:15
2
5,342
Tlaloc-ES
75,200,983
4,432,671
NumPy: how implement Mathematica's MixedRadix in NumPy?
<p>Mathematica has a built-in function <a href="https://reference.wolfram.com/language/ref/MixedRadix.html" rel="nofollow noreferrer">MixedRadix</a> which maps an integer to a list of digits in a mixed radix numerical system.</p> <p>Here's my Python version of the same:</p> <pre><code>def mixed_radix(num, bases): d...
<python><numpy><wolfram-mathematica>
2023-01-22 13:56:05
1
3,737
xpqz
75,200,875
1,436,800
How to write permissions in a viewset with conditional statements in DRF?
<p>I have a viewset written in DRF:</p> <pre><code>class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = models.MyClass.objects.all() def get_serializer_class(self): permission = self.request.user.permission if permission=='owner' or permission=='admin': ret...
<python><django><django-rest-framework><django-views><django-permissions>
2023-01-22 13:40:20
1
315
Waleed Farrukh
75,200,874
14,952,975
how to display a text in a more readable format in python?
<p>I'm very new to python</p> <p>and I have <strong>diff</strong> text like this</p> <pre class="lang-xml prettyprint-override"><code> &lt;revision&gt; - &lt;count&gt;22&lt;/count&gt; + &lt;count&gt;33&lt;/count&gt; &lt;/revision&gt; </code></pre> <p>this is config file changes</p> <p>everywhere that you <st...
<python>
2023-01-22 13:40:17
1
1,658
morteza mortezaie
75,200,764
19,694,624
Can't run Chrome in headless mode using Selenium
<p>So here's my code first:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options import time from fake_useragent import UserAgent import random ua = UserAgent() options = Options() chrome_options = webdriver.ChromeOptions() chr...
<python><selenium><automation><screen-scraping><google-chrome-headless>
2023-01-22 13:22:17
1
303
syrok
75,200,651
11,564,487
VS Code IntelliSense inside R magic
<p>Suppose that one is using an <code>ipyn</code> notebook, with <code>R</code> magic cells. Can <code>IntelliSense</code> work for the <code>R</code> code inside the R magic cells?</p> <p>I have extensively searched the web but found nothing so far.</p>
<python><r><visual-studio-code>
2023-01-22 13:05:11
1
27,045
PaulS
75,200,579
9,406,165
How to create an abstract subclass of SQLAlchemy's Table(Base) class
<p>I am using SQLAlchemy to create tables in my project. I have a requirement where all these tables should have some specific attributes and functions. I want to create a structure such that all tables inherit from an abstract class which includes these attributes and functions.</p> <p>Here's an example of what I want...
<python><sqlalchemy>
2023-01-22 12:52:36
1
507
CodingTil
75,200,487
16,169,533
Stripe payment do something when payment is successfull Django
<p>I have an app about posting an advertises and by default i made an expiration date for</p> <p>every advertise (30 days) now i wanna use stripe to extend the expiration date.</p> <p>what i have so far is the checkout but i want when the payment i success i update the database.</p> <p>my checkout view :</p> <pre><code...
<python><django><django-rest-framework><stripe-payments>
2023-01-22 12:41:37
1
424
Yussef Raouf Abdelmisih
75,200,316
14,282,714
ModuleNotFoundError: No module named 'nbformat'
<p>I would like to run python in a <code>Quarto</code> document. I followed the <a href="https://quarto.org/docs/computations/python.html" rel="nofollow noreferrer">docs</a> about installing and using python in Quarto, but the error stays. Here is some reproducible code:</p> <pre><code>--- title: &quot;matplotlib demo&...
<python><jupyter><quarto>
2023-01-22 12:14:29
1
42,724
Quinten
75,200,206
19,776,016
How to return 1 in numpy array with one row using .shape?
<p>For the arrays with only one row <code>x_data.shape</code> return <code>(4,) </code>or<code> (5,)</code> is it possible to modify it to return <code>(4,1)</code>? Sometimes when I pass one dimension matrix to my function it runs into an error because <code>m = x_data.shape[1]</code> is not defined.</p>
<python><numpy>
2023-01-22 11:58:15
2
339
Gaff
75,200,179
16,154,762
Extracting values from a special string type dataframe column
<p>I have a string-type pandas dataframe column:</p> <pre><code>{&quot;min&quot;:[0,1,0.1,0,0,0], &quot;max&quot;:[0,1,0.4,0,0,0]} </code></pre> <p>df:</p> <pre><code>ID min_max_config 1 {&quot;min&quot;:[0,1,0.1,0,0,0], &quot;max&quot;:[0,1,0.4,0,0,0]} 2 {&quot;min&quot;:[0,1,0.1,0,0,0], &qu...
<python><pandas><dataframe>
2023-01-22 11:54:31
1
439
genz_on_code
75,200,177
7,084,115
Python MQTT - Understanding the Scenario
<p>I have the following requirements to implement.</p> <p>The application should offer simple REST API interface taking inputs for add operation and returning calculation result. The application should offer Mqtt interface</p> <ol> <li><p>Subscribe for topic e.g. calculator/add and accept payload e.g. {“number1”:10, “n...
<python><mqtt><fastapi>
2023-01-22 11:54:28
0
4,101
Jananath Banuka
75,199,880
5,929,910
How to handle mainloop and serve_forever socket server together in if __name__ == '__main__'
<p>I am using Tkinter which has a QRcode generate button. I want to create a QRcode based on the provided URL and if I click the QRcode generate button then it will generate a QRcode and the URL will be active forever. The code I tried so far.</p> <pre><code>generate_button = tk.Button(my_w,font=22,text='Generate QR co...
<python><sockets><tkinter>
2023-01-22 11:03:34
0
3,137
mhhabib
75,199,703
16,589,029
Django Rest Framework fail on setting a new context to the serializer
<p>Django time:</p> <p>I am facing an issue with providing a context to the serializer:</p> <pre class="lang-py prettyprint-override"><code>class CommentSerializer(serializers.ModelSerializer): likes = CustomUserSerializer(many=True,source='likes.all') class Meta: fields = 'likes', model...
<python><django><django-rest-framework>
2023-01-22 10:31:46
1
766
Ghazi
75,199,675
4,858,867
Use remove() function to delete elements containg specific substring from list
<p>I was trying to delete some elements which contain specific substring of a list. For this reason, I tried to use the <a href="https://docs.python.org/3.9/library/array.html?highlight=remove#array.array.remove" rel="nofollow noreferrer">remove()</a> to solve my problem.</p> <p>However, remove() did not solve my probl...
<python><arrays>
2023-01-22 10:26:57
1
383
Kai-Chun Lin
75,199,603
5,091,507
Simplify scientific notation/offset in matplotlib axis
<p>I am trying to draw a plot with large data using matplotlib. matplotlib simplifies the numbers on the y-axis which is expected. However, there are too many useless leading zeros that I can not find a way to remove.</p> <p>Here's a reproducible example:</p> <pre><code>import matplotlib.pyplot as plt y = [i for i in r...
<python><matplotlib><scientific-notation>
2023-01-22 10:12:18
1
1,047
A.A.
75,199,354
302,378
Serve string containing HTML as webpage
<p>This code serves a webpage (using micropython on a microcontroller). I don't think the use of <a href="https://github.com/miguelgrinberg/microdot/blob/main/src/microdot.py" rel="nofollow noreferrer">microdot.py</a> (a Flask-like library) is important for the question, but I apologize this it not reproducible without...
<python><webserver><micropython>
2023-01-22 09:24:28
1
2,601
Alex Holcombe
75,199,166
4,865,723
pandas.cut() with NA values causing "boolean value of NA is ambiguous"
<p>I would like to understand why this code does raise an <code>TypeError</code>.</p> <pre><code>import pandas pandas.cut(x=[1, 2, pandas.NA, 4, 5, 6, 7], bins=3) </code></pre> <p>The full error</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/h...
<python><pandas>
2023-01-22 08:49:56
2
12,450
buhtz
75,199,032
1,335,492
Use static object in LibreOffce python script?
<p>I've got a LibreOffice python script that uses serial IO. On my systems, opening a serial port is a very slow process (around 1 second), so I'd like to keep the serial port open, and just send stuff as required.</p> <p>But LibreOffice python apparently reloads the python framework every time a call is made. Unlike m...
<python><libreoffice>
2023-01-22 08:19:58
1
2,697
david
75,199,021
17,696,880
How to accumulate the modifications made on a string in each one of the iterations of a for loop?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;Acá festejaremos mi cumpleaños. Yo ya sabía que los naipes estaban abajo de su manga.&quot; #example 1 list_all_adverbs_of_place = [&quot;aquí&quot;, &quot;aqui&quot;, &quot;acá&quot; , &quot;aca&quot;, &quot;abajo&quot;, &quot;bajo&quot;, &...
<python><python-3.x><string><loops><for-loop>
2023-01-22 08:18:23
1
875
Matt095
75,198,932
16,610,577
How to call an async function from the main thread without waiting for the function to finish (utilizing aioconsole)?
<p><strong>I'm trying to call an async function containing an await function from the main thread without halting computation in the main thread.</strong></p> <p>I've looked into similar questions employing a variety of solutions two of which I have demonstrated below, however, none of which seem to work with my curren...
<python><asynchronous><async-await><python-asyncio>
2023-01-22 07:54:51
2
342
Leon
75,198,911
7,624,196
Usage of nested protocol (member of protocol is also a protocol)
<p>Consider a Python protocol attribute which is also annotated with a protocol. I found in that case, both mypy and Pyright report an error even when my custom datatype follows the nested protocol. For example in the code below <code>Outer</code> follows the <code>HasHasA</code> protocol in that it has <code>hasa: Has...
<python><mypy><python-typing><pyright>
2023-01-22 07:51:58
1
1,623
HiroIshida
75,198,634
13,194,245
How to add a root inside of main root of XML in Pyton
<p>I have the following xml which i have export using the following:</p> <pre><code>df.to_xml('test.xml', index=False, row_name='instance', root_name='file') </code></pre> <p>which produces an xml file like:</p> <pre><code>&lt;file&gt; &lt;instance&gt; &lt;ID&gt;1&lt;/ID&gt; &lt;name&gt;John&lt;/name&gt; ...
<python><xml>
2023-01-22 06:41:51
3
1,812
SOK
75,198,404
18,125,194
Determine the duration of an event
<p>I have a dataframe with a list of events, a column for an indicator for a criterion, and a column for a timestamp.</p> <p>For each event, if the indicator is true, I want to see if the event lasted more than one period, and for how long.</p> <p>In terms of an expected output, I have provided an example below. For th...
<python><pandas><datetime>
2023-01-22 05:39:12
1
395
Rebecca James
75,198,369
14,154,784
django_bootstrap5 not formatting anything
<p>I'm trying to get basic bootstrap formatting working in a django app, and installed <a href="https://github.com/zostera/django-bootstrap5" rel="nofollow noreferrer">django_bootstrap5</a> to do so. No formatting, however, is getting applied to any of the pages.</p> <p>Here's the various pages:</p> <p>base.html:</p> <...
<python><django><django-bootstrap3><django-bootstrap4><django-bootstrap5>
2023-01-22 05:27:32
1
2,725
BLimitless
75,198,338
9,532,692
Using pass in the if else statement of python List Comprehension
<p>I am trying to get a grasp of list comprehension and ran into a problem that throws a syntax error.</p> <p>Here I'm trying to get a list of odd number:</p> <pre><code>ll = [] for each in l: if each%2 == 1: ll.append(each) else: pass ll &gt;&gt;&gt; [1, 3, 5] </code></pre> <p>Using list compre...
<python><list-comprehension>
2023-01-22 05:20:42
1
724
user9532692
75,198,319
8,422,170
AttributeError: tensorflow has no attribute io
<p>I am trying to train a seq2seq model using simpletransformers library. While using the Seq2Seq model, I am constantly getting this error</p> <pre><code>import tensorflow as tf from simpletransformers.seq2seq import Seq2SeqModel, Seq2SeqArgs import logging model_args = { &quot;reprocess_input_data&quot;: True, &quo...
<python><python-3.x><tensorflow><attributeerror><simpletransformers>
2023-01-22 05:16:42
0
1,939
Mehul Gupta
75,198,237
13,307,245
Stream a .zst compressed file line by line
<p>I am trying to sift through a big database that is compressed in a .zst. I am aware that I can simply just decompress it and then work on the resulting file, but that uses up a lot of space on my ssd and takes 2+ hours so I would like to avoid that if possible.</p> <p>Often when I work with large files I would strea...
<python><python-3.x><archive><zstd>
2023-01-22 04:50:30
1
579
SimonUnderwood
75,198,235
726,773
Why does the key received by `__getitem__` become `0`?
<p>I was implementing a <code>__getitem__</code> method for a class and found that <code>obj[key]</code> worked as expected, but <code>key in obj</code> always transformed <code>key</code> into <code>0</code>:</p> <pre class="lang-py prettyprint-override"><code>class Mapper: def __getitem__(self, key): print(f'Re...
<python>
2023-01-22 04:50:01
1
631
Nick S
75,198,183
14,673,832
Unexpected output in nested list comprehension in Python
<p>I have a nested list comprehension, when I print the output, it gives me generator object, I was expecting a tuple.</p> <pre><code>vector = [[1,2],[2,3],[3,4]] res = (x for y in vector for x in y if x%2 == 0) print(res) </code></pre> <p>I thought since I have small bracket for res assignment, I thought the result w...
<python><list><list-comprehension><generator>
2023-01-22 04:33:36
1
1,074
Reactoo
75,197,726
597,858
Download pdfs and join them using python
<p>I have a list, named links_to_announcement, of urls for different pdfs.</p> <p>How do I download them and join them together? My code generated a corrupt pdf which doesn't open in pdf reader at all.</p> <pre><code>with open('joined_pdfs.pdf', 'wb') as f: for l in links_to_announcement: response = request...
<python>
2023-01-22 01:45:12
1
10,020
KawaiKx
75,197,685
1,070,480
Why can't I pass the default_factory argument in collections.defaultdict as a keyword argument?
<p>If I first do</p> <pre class="lang-python prettyprint-override"><code>from collections import defaultdict </code></pre> <p>then doing</p> <pre class="lang-python prettyprint-override"><code>defaultdict(lambda: &quot;Default value&quot;)[7] </code></pre> <p>yields <code>'Default value'</code>. However, instead doing<...
<python><default-value><keyword-argument><defaultdict>
2023-01-22 01:21:40
0
3,998
HelloGoodbye
75,197,614
15,239,717
How can I get Total Deposit of Customers
<p>I am working on a Django project with 2 Models; Customer and Deposit and I want to display a list of Customers with their names, deposited dated, account number, and Total Deposited within the year so how do I do it the right way. See what I have tried but Couldn't get the Customers' name in my Django Templates.</p>...
<python><django>
2023-01-22 00:55:03
1
323
apollos
75,197,608
597,858
Extracting links in a sequence from a table in a webpage using Selenium in Python
<p>I want to extract links of pdfs from this <a href="https://www.bseindia.com/stock-share-price/sanghi-industries-ltd/sanghiind/526521/corp-announcements/" rel="nofollow noreferrer">page</a> using Selenium in python</p> <p>I managed to extract the entire table that contains the rows and the links to the pdfs.</p> <pre...
<python><selenium>
2023-01-22 00:52:11
1
10,020
KawaiKx
75,197,222
20,959,773
Get outer-HTML of element on click
<p>Im making a project for finding xpath, and i need the fastest and easiest way for the user to actually select in a webpage the element he wants the xpath to be found. Selection ideally needs to be made with just a click, which needs to return the value of outerHTML of that element,so I can take it and process agains...
<javascript><python><html><selenium><xpath>
2023-01-21 23:07:59
1
347
RifloSnake
75,197,211
16,319,191
Import multiple sas files in Python and then row bind
<p>I have over 20 SAS (sas7bdat) files all with same columns I want to read in Python. I need an iterative process to read all the files and rbind into one big df. This is what I have so far, but it throws an error saying no objects to concatenate.</p> <pre><code>import pyreadstat import glob import os path = r'C:\\Us...
<python><dataframe><sas><rbind>
2023-01-21 23:05:44
1
392
AAA
75,196,668
13,285,779
What has to be an input shape for a CNN using MFCC?
<p>I am doing some classification on audio data using MFCC. I have extracted MFCCs from a few audio samples and I would like to pass them to a CNN, however I have hard time understanding what <code>input_shape</code> parameter I should provide to my model for training and classifications.</p> <p>The training set <code>...
<python><tensorflow><keras><conv-neural-network><mfcc>
2023-01-21 21:24:26
0
1,359
CuriousPan
75,196,539
13,441,462
Pyzbar does not recognize CODE-128 barcode
<p>I am trying to read text encoded in barcode - I am using <code>pyzbar</code> like this:</p> <pre><code>from pyzbar import pyzbar import cv2 img = cv2.imread(&quot;example/path&quot;) barcodes = pyzbar.decode(img, symbols=[pyzbar.ZBarSymbol.CODE128]) print(barcodes) </code></pre> <p>It normally works, but in the la...
<python><opencv><image-processing><barcode><zbar>
2023-01-21 21:01:24
1
409
Foreen
75,196,513
17,311,709
Django Form unexpected keyword argument
<p>i have a form which contains a choiceField and i need to populate it from a view, so i'm trying to use the kwargs inside the init function like this :</p> <pre class="lang-py prettyprint-override"><code>class SelectionFournisseur(forms.Form): def __init__(self,*args, **kwargs): super(SelectionFournisseur...
<python><django>
2023-01-21 20:57:39
1
635
Rafik Bouloudene
75,196,453
4,974,431
Regex : split on '.' but not in substrings like "J.K. Rowling"
<p>I am looking for names of books and authors in a bunch of texts, like:</p> <pre><code>my_text = &quot;&quot;&quot; My favorites books of all time are: Harry potter by J. K. Rowling, Dune (first book) by Frank Herbert; and Le Petit Prince by Antoine de Saint Exupery (I read it many times). That's it by th...
<python><regex>
2023-01-21 20:47:37
1
1,624
Vincent
75,196,422
9,855,588
pytest parameterization indirectly when using unittest framework
<p>I'm using the python unittest and pytest frameworks together. I ran into a case where I have a fixture that generates signed header tokens, which I'm trying to mock locally. So I want to create a fixture that I can pass a payload to when the test runs. It doesn't seem like I can do it with pytest and unittest togeth...
<python><python-3.x><pytest><python-unittest>
2023-01-21 20:41:58
1
3,221
dataviews
75,196,263
10,380,766
Calculating a rolling weighted sum without a for loop in python/numpy
<p>I recently asked the question: <a href="https://stackoverflow.com/questions/75192220/numpy-convolve-method-has-slight-variance-between-equivalent-for-loop-method-for">NumPy convolve method has slight variance between equivalent for loop method for Volume Weighted Average Price</a></p> <p>Trying to use <code>np.convo...
<python><numpy>
2023-01-21 20:14:52
1
1,020
Hofbr
75,196,143
15,461,255
Seaborn error with kde plot: The following variable cannot be assigned with wide-form data `hue`
<p>I have a pandas dataframe <code>df</code> with two columns (<code>type</code> and <code>IR</code>) as this one:</p> <pre><code> type IR 0 a 0.1 1 b 0.3 2 b 0.2 3 c 0.8 4 c 0.5 ... </code></pre> <p>I want to plot three distributions (one for each <code>type</code>) with t...
<python><pandas><seaborn><kernel-density>
2023-01-21 19:57:09
1
350
Palinuro
75,196,023
1,483,288
Pandas, merge multiple dummy variables into one column by name
<p>I have a datafile with one VALUE column and multiple dummy variables representing TYPES. I have copied a short example below. I need the average of each type (which I can get) with a column with the named type (which I don't seem to be able to get). Pointers would be welcome.</p> <pre><code>import pandas as pd data ...
<python><pandas><dataframe><aggregate><dummy-variable>
2023-01-21 19:35:46
3
773
ccc31807
75,196,015
3,837,788
TypeError raised even if the variable seems to be of the right type
<p>Considering the following code portion:</p> <pre><code>txt = 'Some text, dude!' with open('to_load', mode='wb') as f: raw = txt.encode('ascii') print(raw, file=f) </code></pre> <p>Could anybody please explain why a <code>TypeError: a bytes-like object is required, not 'str'</code> exception is raised inside <c...
<python><python-3.x><string><file><binary>
2023-01-21 19:34:19
0
566
rudicangiotti
75,195,927
6,367,971
Using glob recursion to get sub directories and files containing CSVs
<p>I am trying to concat multiple CSVs that live in subfolders of my parent directory.</p> <pre><code>/ParentDirectory │ │ ├───SubFolder 1 │ test1.csv │ ├───SubFolder 2 │ test2.csv │ ├───SubFolder 3 │ test3.csv │ test4.csv │ ├───SubFolder 4 │ test5.csv </code></pre> <p>When I do</p> <pr...
<python><pandas><glob>
2023-01-21 19:17:44
2
978
user53526356
75,195,914
8,059,615
Python GRPC 13 Internal Error when trying to yield response
<p>When I print the response, everything seems to be correct, and the type is also correct.</p> <pre><code>Assertion: True Response type: &lt;class 'scrape_pb2.ScrapeResponse'&gt; </code></pre> <p>But on postman I get &quot;13 INTERNAL&quot; With no additional information:</p> <p><a href="https://i.sstatic.net/ZSgKA.pn...
<python><grpc><grpc-python>
2023-01-21 19:14:20
1
405
Yousef
75,195,748
1,436,800
AttributeError Exception: Serializer has no attribute request in DRF
<p>I have written following code in serializer where I am validating data:</p> <pre><code>class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = &quot;__all__&quot; def validate(self, data): role = data[&quot;role&quot;] roles = models.Role....
<python><django><django-rest-framework><django-views><django-serializer>
2023-01-21 18:46:38
1
315
Waleed Farrukh
75,195,738
9,102,437
How to update a python library without restarting ipynb kernel?
<p>Unfortunately, there is no better way to do this, so please don't ask why I can't do it the normal way, it is too long to explain :). The issue is that one of the packages demands numpy&lt;=1.21, but the one installed is 1.23.4 . In the notebook I run <code>!pip install numpy==1.21</code> which solves the issue, BUT...
<python><python-3.x><linux><numpy><sys>
2023-01-21 18:45:27
4
772
user9102437
75,195,622
18,023,322
Download video with yt-dlp using format id
<p>How can I download a specific format without using options like &quot;best video&quot;, using the format ID... example: 139, see the <a href="https://i.sstatic.net/7MlOf.jpg" rel="noreferrer">picture</a></p> <pre class="lang-none prettyprint-override"><code>❯ yt-dlp --list-formats https://www.youtube.com/watch?v=BaW...
<python><yt-dlp>
2023-01-21 18:26:44
2
605
LegzDev
75,195,481
149,818
Z3 optimize by index not a value
<p>With greate respect to the answer of @alias there: (<a href="https://stackoverflow.com/a/69655123/149818">Find minimum sum</a>) I would like to solve similar puzzle. Having 4 agents and 4 type of works. Each agent does work on some price (see <code>initial</code> matrix in the code). I need find the optimal allocati...
<python><dynamic-programming><z3><z3py>
2023-01-21 18:04:27
1
23,762
Dewfy
75,195,469
16,567,918
Django multi-language does not load the custom-translated files when changing the user language but only works when LANGUAGE_CODE explicitly set
<p>when I change the language of the user by URL or calling <code>translation.activate(lang_code)</code> only the default texts are translated and the custom translation that I created not loading, but if I change the <code>LANGUAGE_CODE</code> to the target language in the settings file the translation shows without a...
<python><python-3.x><django><internationalization><django-i18n>
2023-01-21 18:02:27
1
445
Nova
75,195,325
10,694,247
How to monitor AWS Fsx ONTAP Filesystem Usage using lambda function and cloudwatch metrics
<p>I am first time trying to work on the <code>aws lambda</code> function to get the monitoring for <code>FSxN</code> IE <code>FSx</code> for ONTAP Storage in AWS.</p> <p>Here I want to get the <code>StorageCapacity</code> and <code>StorageTier</code> in order to achieve total <code>filesystemUsed</code> percentage for...
<python><amazon-web-services><aws-lambda>
2023-01-21 17:40:56
1
488
user2023
75,195,218
3,259,222
Inherit as required only some fields from parent pandera SchemaModel
<p>I have Input and Output pandera SchemaModels and the Output inherits the Input which accurately represents that all attributes of the Input schema are in the scope of the Output schema.</p> <p>What I want to avoid is inheriting all attributes as required (non-Optional) as they are rightly coming from the Input schem...
<python><pydantic><pandera>
2023-01-21 17:23:32
2
431
Konstantin
75,195,149
15,229,310
python display type of raised exception
<p>I define my own exception</p> <pre><code>class MyException(Exception): pass </code></pre> <p>somewhere deep in project folder structure, i.e. project\subfolder_1\subfolder_2\etc...\exceptions.py and then use it <code>from project.subproject.subfolder_1.subfolder_2.\etc ... .exceptions import MyException as MyExc...
<python>
2023-01-21 17:13:58
1
349
stam
75,195,111
6,952,996
How to keep track of data structures for class instances in Python
<p>I am using VSCode to write Python code.<br /> I have a lot of different structures for data that is sent and received from other functions and stored in variables.<br /> I tend to resort to put an example of the structure of the variable as a comment in the code, to help with quickly providing information when writi...
<python><visual-studio-code>
2023-01-21 17:07:43
0
937
Johnathan
75,195,106
14,584,978
Write python polars lazy_frame to csv gzip archive after collect()
<p>What is the best way to write a gzip archive csv in python polars?</p> <p>This is my current implementation:</p> <pre><code>import polars as pl import gzip # create a dataframe df = pl.DataFrame({ &quot;foo&quot;: [1, 2, 3, 4, 5], &quot;bar&quot;: [6, 7, 8, 9, 10], &quot;ham&quot;: [&quot;a&quot;, &quot...
<python><gzip><lazy-evaluation><python-polars>
2023-01-21 17:06:33
2
374
Isaacnfairplay
75,195,030
6,792,327
Gemini API: Supplied value is not a valid DateTime
<p>I am attempting to call an endpoint provided by the <a href="https://docs.gemini.com/rest-api/#fx-rate" rel="nofollow noreferrer">Gemini REST API to extract FX rates</a>, but it kept throwing this error message:</p> <blockquote> <p>{'result': 'error', 'reason': 'Bad Request', 'message': &quot;Supplied value '1495127...
<python>
2023-01-21 16:55:00
1
2,947
Koh
75,194,890
1,096,777
Why are PIL and its Image module capitalized?
<p><a href="https://peps.python.org/pep-0008/#package-and-module-names" rel="nofollow noreferrer">PEP8 standard is for modules to be lower-case</a></p> <p>PIL being a top-level module in all caps isn't so bad, but to <a href="https://pillow.readthedocs.io/en/stable/reference/Image.html" rel="nofollow noreferrer">name a...
<python><python-imaging-library><pep8>
2023-01-21 16:36:08
1
2,556
mavix
75,194,852
7,091,646
count of sublists containing item for all items
<p>I'm looking for a more efficient/pythonic way of doing this.</p> <pre><code>l = [[0,0],[1,0],[4,5,1],[2,3,5],[0,4]] set_l = set([i for sl in l for i in sl]) sublists_containing_item_count = [sum([1 for x in l if i in x]) for i in set_l] count_dict = dict(zip(set_l,sublists_containing_item_count)) count_dict {0:...
<python><counter>
2023-01-21 16:30:50
6
1,399
Eric
75,194,840
4,321,525
How to loop over all elements of different sorted lists in sorted order?
<p>I have several sorted lists. How can I loop over all elements in sorted order efficiently and elegantly? In my real-life problem, those lists contain elements that are directly comparable and sortable but are different and require different treatment.</p> <p>I prefer to retain my lists, which is why I copy them manu...
<python><list><algorithm><loops>
2023-01-21 16:29:30
3
405
Andreas Schuldei
75,194,729
4,688,705
Is this a multi-threading race condition problem?
<p>In a python3 tkinter project, I am trying to read a continuous stream of data from a serial port (just an arduino sending a milli second value over USB).</p> <p>The code which reads serial data runs in a separate thread so as to disconnect it from the GUI loop.</p> <p>I need to be able to connect and disconnect from...
<python><python-multithreading><pyserial>
2023-01-21 16:12:17
0
529
Søren ONeill
75,194,622
922,588
Is there a problem with Pipes in Python multiprocessing on macOS?
<p>I'm encountering some strange behavior with <code>Pipe</code> in Python multiprocessing on my Mac (Intel, Monterey). I've tried the following code in 3.7 and 3.11 and in both cases, not all the tasks are executed.</p> <pre><code>def _mp_job(nth, child): print(&quot;Nth is&quot;, nth) if __name__ == &quot;__main...
<python><python-multiprocessing>
2023-01-21 15:57:44
0
415
Sam Bayer
75,194,618
15,229,310
Python exception - add custom message as very last line
<p>any exception causing code, e.g.</p> <pre><code> l= [1,2,3] index = 4 l[index] </code></pre> <p>produce standard exception output to console</p> <p><em>trace</em></p> <p><em>IndexError: list index out of range</em></p> <p><em>Process finished with exit code 1</em></p> <p>I'd like to add custom message a...
<python>
2023-01-21 15:57:26
0
349
stam
75,194,469
2,255,491
Django namespacing still produces collision
<p>I have two apps using same names in my django project. After configuring namespacing, I still get collision. For example when I visit <code>localhost:8000/nt/</code>, I get template from the other app. (localhost:8000/se/ points to the right template).</p> <p>I must have missed something. Here is the code:</p> <p><e...
<python><django><django-urls>
2023-01-21 15:32:30
1
11,222
David Dahan
75,194,431
19,130,803
Dash dcc.upload component for large file
<p>I am developing a dash application. In that I have file upload feature. The file size is big enough minimum is some about 100MB to support that I have set <code>max_size=-1</code> (no file size limit). Below is code:</p> <pre><code>dcc.Upload( id=&quot;upload_dataset&quot;, children=html.Div( [ &quot;Drag an...
<python><plotly-dash>
2023-01-21 15:25:57
1
962
winter
75,194,186
4,764,604
Password unregistered when saving a new user in a Django with a custom user model
<p>When I try to register a user, adapting what I learnt from <a href="https://youtu.be/Ae7nc1EGv-A?t=2029" rel="nofollow noreferrer">Building a Custom User Model with Extended Fields youtube tutorial</a>, I can't login afterwards despite providing the same password. However I can log in for any I created through the c...
<python><python-3.x><django><authentication><model-view-controller>
2023-01-21 14:48:27
0
3,396
Revolucion for Monica
75,194,160
166,442
Flask route doesn't capture parts containing urlencoded slash
<p>I have defined a Flask route as follows:</p> <pre><code>@app.route('/upload/from_url/&lt;url:string&gt;') def upload_from_url(url: str) -&gt; str: return {'url': url} </code></pre> <p>I also tried the route with <code>&lt;url&gt;</code> only. In any case, the route doesn't match if it contains a URL encoded slas...
<python><flask>
2023-01-21 14:43:59
1
6,244
knipknap
75,194,130
14,098,258
how to make a scrollable legend in bokeh
<p>I make <code>bokeh</code> line plots from <code>pandas DataFrames</code> with many columns. I have already managed to hide individual lines by clicking on the corresponding legend entry. However, the legend is too big and does not fit in the graph. I have tried placing the legend outside of the graph, still does not...
<python><pandas><dataframe><plot><bokeh>
2023-01-21 14:40:34
0
383
Andre
75,194,122
15,877,202
How can I recreate a class object for testing, tried debugging and printing relevant items but can't get it?
<p>I have the following class:</p> <pre><code>class MessageContext: def __init__(self, raw_packet, packet_header, message_header, message_index): self.raw_packet = raw_packet self.pkthdr = packet_header self.msghdr = message_header self.msgidx = message_index self.msg_seqno ...
<python><class>
2023-01-21 14:39:07
0
566
Patrick_Chong
75,194,035
8,761,554
Logistic Regression in seaborn does not show the line
<p>I have a simple dataframe with continous and categorical column:</p> <pre><code> Unemployment Rate AcceptsCash E020 0.058080 0 E021 0.049818 0 E022 ...
<python><numpy><seaborn><lmplot>
2023-01-21 14:26:34
0
341
Sam333
75,194,030
7,267,480
loading number of CSVs to one dataset for neural network training for signal transformation y1(x) -> y2(x)
<p>I am trying to build a neural network for signal transformation: <code>y1(x) - &gt; y2(x)</code> using TensorFlow and Keras as main instruments.</p> <p><strong>I want to prepare a training dataset from files which are stored separately and my question for now is how to do it efficient way?</strong></p> <p><strong>DA...
<python><tensorflow><neural-network>
2023-01-21 14:25:57
0
496
twistfire
75,193,965
17,124,619
RandomForestClassifer throwing estimator error
<p>I am attempting to build a stacking classifier using multiple combinations of available models, however, when I have a RandomForestClassifier the loop throws an error. Here is what I have attempted:</p> <blockquote> <p>'RandomForestClassifier' object has no attribute 'estimators_'. Did you mean: 'estimator_'?</p> </...
<python><machine-learning><scikit-learn>
2023-01-21 14:13:35
0
309
Emil11
75,193,847
2,929,914
Can I use python's mouse library with Spyder 5.2.2 @ Anaconda 2.3.1
<p>I'm trying to learn how to control the mouse with Python learning from:</p> <p><a href="https://www.thepythoncode.com/article/control-mouse-python" rel="nofollow noreferrer">How to Control your Mouse in Python</a></p> <p>My IDE is Spyder (version 5.2.2) and I'm running it from Anaconda (version 2.3.1).</p> <p>When I...
<python><anaconda><spyder>
2023-01-21 13:54:24
1
705
Danilo Setton
75,193,665
2,179,795
Correcting pandas index "duplicate" behavior
<p>I am trying to create a new dataframe using the structure of an existing index (the source of this is a excel file, so the empty spaces are important) and some new data. Typically I would create the index and assign it data values by constructing a new pd.DataFrame() object.</p> <p>However, I am encountering odd beh...
<python><pandas>
2023-01-21 13:23:03
2
1,247
Merv Merzoug
75,193,628
9,493,965
Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f81fe558fa0>": "Post.author" must be a "UserData" instance
<p>I'm trying to write simple tests for some endpoints but the second one keeps failing. Here's the test.py</p> <pre><code>from rest_framework.test import APITestCase, APIRequestFactory, APIClient from rest_framework import status from django.urls import reverse from .views import PostViewSet from django.contrib.auth i...
<python><django><django-rest-framework>
2023-01-21 13:17:44
0
425
Raskolnikov
75,193,298
6,463,651
Jupyter Notebook kernel dies when i import model from Huggingface
<p>Here is the code where I am loading a huggingface pre trained model , but my kernel dies. The model size in the description page is only 458 MB size. Why is it failing?</p> <pre><code>from transformers import TextClassificationPipeline, AutoModelForSequenceClassification, AutoTokenizer model_name = &quot;ElKulako/cr...
<python><jupyter-notebook><nlp><huggingface-transformers>
2023-01-21 12:27:00
0
603
Shubh
75,193,297
1,512,250
Create the same ids for the same names in different dataframes in pandas
<p>I have a dataset with unique names. Another dataset contains several rows with the same names as in the first dataset.</p> <p>I want to create a column with unique ids in the first dataset and another column in the second dataset with the same ids corresponding to all the same names in the first dataset.</p> <p>For ...
<python><pandas>
2023-01-21 12:26:35
1
3,149
Rikki Tikki Tavi
75,192,900
2,651,073
How to get max of counts for groupby (most frequent items)
<p>I have a dataframe. I want to group by rows on some columns and then form a count column and then get the max of counts and create a column for it and attach it to dataframe.</p> <p>I tried:</p> <pre><code> df[&quot;max_pred&quot;] = df.groupby(['fid','prefix','pred_text1'], sort=Fal...
<python><pandas><dataframe><group-by><max>
2023-01-21 11:16:43
2
9,816
Ahmad
75,192,895
6,478,085
Replacing sub-string occurrences with elements of a given list
<p>Suppose I have a string that has the same sub-string repeated multiple times and I want to replace each occurrence with a different element from a list.</p> <p>For example, consider this scenario:</p> <pre class="lang-py prettyprint-override"><code>pattern = &quot;_____&quot; # repeated pattern s = &quot;a(_____), b...
<python><regex><python-re>
2023-01-21 11:15:11
3
2,662
damianodamiano
75,192,471
20,920,790
Can't run Python visual element in Power BI
<p>I'm trying to create a hist plot in Power BI.<br /> I got installed ANaconda, MS Vusial Code.<br /> Screenshots with my settings:<br /> <img src="https://i.sstatic.net/dziR6.png" alt="Power BI setting" /> <img src="https://i.sstatic.net/KqHDI.png" alt="Python home folder" /><br /> I'm trying make hist with simple ta...
<python><powerbi>
2023-01-21 09:55:56
1
402
John Doe