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
74,916,782
3,624,549
Python argparse - make arguments required or optional based on another argument
<p>How can a program accept/validate a set of parameters, depending on a previous parameter/option?</p> <p>e.g:</p> <pre><code>params: &lt;action1&gt; -p &lt;path&gt; -name &lt;name&gt; -t &lt;type&gt; &lt;action2&gt; -v &lt;value&gt; -name &lt;name&gt; &lt;action3&gt; -p &lt;path&gt; -t &lt;ty...
<python><argparse>
2022-12-26 01:44:36
1
2,420
Alg_D
74,916,729
4,159,193
Install matplotlib for Python with MSYS MinGW 64
<p>I want to install matplotlib for Python using MSYS MinGW x64. The command</p> <pre><code>$ pacman -S mingw-w64-x86_64-python-matplotlib </code></pre> <p>had failed previously. Then I made some changes, and now I want to try the above command again, but I only get these error messages:</p> <pre><code>$ pacman -S ming...
<python><matplotlib><msys2><pacman-package-manager>
2022-12-26 01:26:15
1
546
flori10
74,916,557
10,626,286
Error decode/deserialize Avro with Python from Kafka
<p>Hello all i have debezium which listen to changes on postgres and put events on kafka topic everything works great except i have issues decoding payloads i have tried both methods but no luck</p> <p><a href="https://i.sstatic.net/FIj5O.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FIj5O.png" alt="en...
<python><apache-kafka><kafka-consumer-api>
2022-12-26 00:24:42
2
750
Soumil Nitin Shah
74,916,479
14,293,274
replicate numpy style array initialisation in c++
<p>I'm trying to replicate basic NumPy functionalities in C++ (for practice).</p> <p>I'm stuck replicating the following initialization: here's how it looks in python/NumPy:</p> <pre><code>x = np.array([[1], [2]]) </code></pre> <p>which evaluates to:</p> <pre><code>array([[1], [2]]) </code></pre> <p>In my C++ co...
<python><c++><arrays><numpy><initialization>
2022-12-25 23:54:58
0
594
koegl
74,916,461
16,319,191
How to drop rows (or subset other rows) based on values in lists in pandas? Create mutually exclusive subsets of dfs
<p>How to drop rows which have at least 1 element from both the lists? Looking for something iterative over more than 100 columns. Minimal example with 3 columns is:</p> <pre><code>list1 = [&quot;abc1&quot;, &quot;def&quot;] list2 = [&quot;ghi&quot;, &quot;ghj&quot;] df = pd.DataFrame({&quot;index&quot;: [0,1,2,3,4,5,6...
<python><pandas><subset><drop>
2022-12-25 23:49:26
1
392
AAA
74,916,343
3,520,363
python script removes file extension
<p>I have some video files</p> <pre><code>A Single Man (2009).avi Accident (2009).mkv Adventureland (2009).mp4 </code></pre> <p>I use a python script that rename in this way</p> <pre><code>A Single Man (2009) [Drama] Accident (2009) [Thriller] Adventureland (2009) [Comedy] </code></pre> <p>What is the problem ? Script ...
<python>
2022-12-25 23:12:46
0
380
user3520363
74,916,307
9,135,359
How to cleanup ‘orphaned’ text in poorly written html using Python?
<p>Let me explain: I scrapped html off a poorly written website and wish to clean up the code by encapsulating each line within a <code>&lt;div&gt;</code> tag, keep the existing <code>bold</code>, <code>italic</code> and other formatting information, keep the <code>images</code> and <code>links</code>. I will then form...
<python><html><beautifulsoup>
2022-12-25 23:01:58
1
844
Code Monkey
74,916,234
4,828,720
Using Python Social Auth with Flask-Login
<p><a href="https://python-social-auth.readthedocs.io/en/latest/configuration/flask.html" rel="nofollow noreferrer">https://python-social-auth.readthedocs.io/en/latest/configuration/flask.html</a> says &quot;The application works quite well with Flask-Login&quot; however it does not specify what exactly is needed to be...
<python><flask><python-social-auth>
2022-12-25 22:40:48
0
1,190
bugmenot123
74,916,211
14,427,714
How to iterate divs in selenium python
<p>I want to iterate this html div</p> <pre><code>&lt;div class=&quot;ag-center-cols-container&quot; ref=&quot;eCenterContainer&quot; role=&quot;rowgroup&quot; unselectable=&quot;on&quot; style=&quot;width: 1550px; height: 118.4px;&quot;&gt;&lt;div role=&quot;row&quot; row-index=&quot;0&quot; aria-rowindex=&quot;4&quot...
<python><selenium><web-scraping><automation>
2022-12-25 22:33:54
1
549
Sakib ovi
74,916,074
152,113
How to inject arguments from a custom decorator to a command in discord.py?
<p>I'm working on a bot which keeps track of various text-based games in different channels. Commands used outside the channel in which the relevant game is running should do nothing of course, and neither should they activate is the game is not running (for example, when a new game is starting soon). Therefore, almost...
<python><discord.py><python-decorators>
2022-12-25 21:55:20
2
2,511
Kasper
74,915,831
1,970,440
VsCode notebook can't see pandas module
<p>In VsCode I have activated .venv environment in which I can see pandas module confirmed with <code>pip show pandas</code> command and I still see error: <code>ModuleNotFoundError: No module named 'pandas'</code></p> <p>(.venv) C:\PythonWs\testVsCodeNotebook&gt;python --version Python 3.10.8</p> <p>How I can resolve ...
<python><pandas><visual-studio-code><pip>
2022-12-25 20:53:05
1
663
AlexeiP
74,915,752
18,360,265
How to resolve TypeError: 'Request' object is not callable Error in Flask?
<p>I am trying to learn Flask. and here I am facing an issue.</p> <p>I have created a route ( <code>/register</code> ) in my Flask app. and I am trying to trigger this using Postman.</p> <p>But I am getting this Error:</p> <pre><code>TypeError: 'ImmutableMultiDict' object is not callable </code></pre> <p>Here is my cod...
<python><flask>
2022-12-25 20:31:28
1
409
Ashutosh Yadav
74,915,654
2,474,581
Tkinter Treeview shows only first 3 columns
<p>On startup of the program; Tkinter Treeview shows only the first 3 columns of 5. When you alter with the mousepointer in the heading the width of a random column by a small amount(few pixels), all columns comes in sight after releasing the mouse button.</p> <p>update: option <code>displaycolumns=&quot;#all&quot;</co...
<python><tkinter>
2022-12-25 20:10:48
1
1,346
Kustekjé Meklootn
74,915,592
11,280,068
Browser console shows CORS error regardless of the type of error that happens on the server side of a fastapi app
<p>I have fastapi app that is running on the same server as a react app.</p> <p>I make a simple, async request to the route, but regardless of the type of error that happens on the server (syntaxerror, valueerror, etc...), the browser console shows a CORS error</p> <p>I am 100% positive it is not a cors error</p> <p>Ho...
<javascript><python><python-3.x><rest><fastapi>
2022-12-25 19:56:44
0
1,194
NFeruch - FreePalestine
74,915,576
18,059,131
How to get the peak of an audio file in python?
<p>How could I get the dB value of the peak of a wav file (for example, the peak of some wav file could be -6db, aka its loudest point is -6db) using python?</p>
<python><audio><pydub>
2022-12-25 19:52:04
1
318
prodohsamuel
74,915,347
1,840,471
pip3 using a different Python version than pyenv has activated
<p>I've installed pyenv to activate Python 3.9, and that appears to have worked:</p> <pre class="lang-bash prettyprint-override"><code>maxghenis@MacBook-Air-3 policyengine-canada % pyenv versions system * 3.9.16 (set by /Users/maxghenis/.pyenv/version) maxghenis@MacBook-Air-3 policyengine-canada % python -V Py...
<python><pip><virtual-environment>
2022-12-25 18:59:09
0
15,993
Max Ghenis
74,915,335
15,359,178
Append Data in HDF5 file
<p>I want to append new date to my already created HDF5 file but I don't how to append more data to it, I don't know the actual syntax for appending</p> <p>I have created an HDF5 file to save my data in HDF format as</p> <pre class="lang-py prettyprint-override"><code>with h5py.File(save_path+'PIC200829_256x256x256x3_f...
<python><pandas><hdf5><hdf>
2022-12-25 18:57:09
1
451
Saran Zeb
74,915,324
8,262,214
How do I split a string with backward slashes in from the backward slashes substring using split() of python?
<p>I have a string which looks similar to <code>123456 \\RE1NUM=987</code> and I have been trying to split it <code>\\RE1NUM=</code>.</p> <p>I have tried <code>.split(&quot;\\RE1NUM=&quot;)</code> and it gives <code>['123456 \\', '987']</code>. I believe backward slashes are being interpreted as escape characte...
<python><python-3.x>
2022-12-25 18:54:18
3
512
Zircoz
74,915,281
5,407,797
Type error when accessing Django request.POST
<p>I'm attempting to build an XML document out of <code>request.POST</code> data in a Django app:</p> <pre><code>ElementTree.Element(&quot;occasion&quot;, text=request.POST[&quot;occasion&quot;]) </code></pre> <p>PyCharm is giving me an error on the <code>text</code> parameter saying <code>Expected type 'str', got 'Typ...
<python><django><pycharm><typeerror>
2022-12-25 18:47:21
1
1,239
AAM111
74,915,260
694,360
Pillow conversion from RGB to indexed P mode
<p>I have an <code>RGB</code> image with only 25 colors,</p> <p><a href="https://i.sstatic.net/ws8lc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ws8lc.png" alt="enter image description here" /></a></p> <p>and I want to convert it to <code>P</code> mode to make it indexed (saving space, as far as I un...
<python><python-imaging-library>
2022-12-25 18:44:20
2
5,750
mmj
74,915,246
525,913
Create new conda environment with latest python AND all the packages that I've added in an existing environment
<p>I want to create new conda environment with latest python (want 3.10 or later) AND the appropriate versions of all the packages (like matplotlib and pandas) that I've added in an existing environment (it's NOT the base environment). I don't recall what all of these packages are. Is there a way to do this without bre...
<python><anaconda><conda>
2022-12-25 18:41:07
1
2,347
ViennaMike
74,915,118
4,531,757
How I find drug_code sequence for each pateint in their treatment?
<p>Experts, Even though every patient comes to the hospital for the treatment of the same disease, his/her sequence of treatment is slightly different based on their current conditions. Example: Few patients may need more pre-care/pre-medicines than other patients. Here our objective is how to collect all sequences of ...
<python><pandas><numpy>
2022-12-25 18:16:28
1
601
Murali
74,915,029
2,878,298
Iterate through each column and find the max length
<p>I want to get the maximum length from each column from a pyspark dataframe.</p> <p>Following is the sample dataframe:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.sql.types import StructType,StructField, StringType, IntegerType data2 = [(&quot;James&quot;,&quot;&quot;,&quot;Smith&quot;,&quot;366...
<python><apache-spark><pyspark><apache-spark-sql>
2022-12-25 18:01:33
1
1,268
venus
74,914,830
1,873,689
Error working with COM object from Python throw clr reference - class not registred
<p>Trying to make an App for Solidworks. First tried to use win32com or comtypes to get access to the COM object of solidworks. Made some progress, but couldnt get it working well. Found a way to work with clr and interop dlls. More progress, but now got stuck on this error:</p> <pre><code>System.Runtime.InteropService...
<python><com><registry><win32com><solidworks>
2022-12-25 17:25:10
0
1,301
aleXela
74,914,765
12,242,085
How to correctly change format of date where day and month is changes in position in Data Frame in Python Pandas?
<p>I have DataFrame in Pandas like below:</p> <p>data type of COL1 is &quot;object&quot;</p> <pre><code>COL1 ------ 1-05-2019 22-04-2019 5-06-2019 </code></pre> <p>And I need to have this column as data type &quot;object&quot; and in format dd-mm-yyyy for example 01-05-2019.</p> <p>When I use code like follow: <code>...
<python><pandas><dataframe><date><strftime>
2022-12-25 17:13:59
1
2,350
dingaro
74,914,731
913,098
Python boto3, list contents of specific dir in bucket, limit depth
<p>This is the same as <a href="https://stackoverflow.com/questions/27292145/python-boto-list-contents-of-specific-dir-in-bucket">this question</a>, but I also want to limit the depth returned.</p> <p>Currently, all answers return all the objects after the specified prefix. I want to see just what's in the current hier...
<python><amazon-s3><boto3>
2022-12-25 17:08:16
3
28,697
Gulzar
74,914,720
5,050,577
Python versions are not changing despite activating virtual environment in WSL2
<p><strong>Background:</strong></p> <p>In WSL2 (ubuntu 20.04) I created a python virtual environment inside a directory. Using the command <code>python3 -m venv venv</code> my system's python version was set to python3.11 (after downloading) via <code>sudo update-alternatives --config python3</code> and then choosing t...
<python><python-3.x><virtualenv><windows-subsystem-for-linux>
2022-12-25 17:05:45
2
3,229
DanT29
74,914,696
7,773,898
issue while writing into postgresql database in glue job
<p>Hey I am trying to write data into postgresql db from glue job but getting below error <code>IllegalArgumentException: Option 'dbtable' can not be empty.</code></p> <p>Below is my code which seems to be correct</p> <p>How I read from s3</p> <pre><code>glueContext.create_dynamic_frame.from_options( format...
<python><amazon-web-services><apache-spark><aws-glue>
2022-12-25 17:01:11
0
383
ALTAF HUSSAIN
74,914,655
10,563,068
How to Re-initialise the dataframe to integer and decimal from float for multiple columns in pandas?
<p>I am trying to convert the dataframe to integer and decimal based on the columns. However, I want to do it without specifying the column names as there are many columns. For now, I have converted a float to integer but when I use this code, it also converts the columns with decimal into integer. Below is my code:</p...
<python><pandas><dataframe>
2022-12-25 16:54:29
1
453
Sriram
74,914,592
5,704,664
Merge data with timestamp without overriding old data
<p>I have data <code>A</code> that looks like this:</p> <pre><code>timestamp,some_value 389434893,abc 348973493,dac 128197291,fgd </code></pre> <p>I have other data <code>B</code> that is the newer version of <code>A</code> (with more data):</p> <pre><code>timestamp,some_value 389434893,wwwwwwe # timestamp DID NOT CHAN...
<python><pandas>
2022-12-25 16:44:32
1
2,018
comonadd
74,914,576
558,639
seeking yet another numpy stacking function
<p>Just this:</p> <pre><code>&gt;&gt;&gt; a1 array([[0], [1], [2], [3], [4]]) &gt;&gt;&gt; b2 array([[100, 101], [102, 103], [104, 105], [106, 107], [108, 109]]) </code></pre> <p>I want to stack t...
<python><numpy><numpy-ndarray>
2022-12-25 16:41:45
2
35,607
fearless_fool
74,914,461
475,982
Spacy add_alias, TypeError
<p><strong>MWE</strong></p> <pre><code>from spacy.kb import KnowledgeBase import spacy #kb.add_entity already called. nlp = spacy.blank(&quot;en&quot;) kb = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=96) name = &quot;test&quot; qid = 1 # type(qid) =&gt; int kb.add_alias(alias=name.lower(), entities=[qid], p...
<python><cython><spacy><spacy-3>
2022-12-25 16:14:45
1
3,163
mac389
74,914,333
10,563,068
Re-initialise the dataframe did not work in pandas
<p>I am new to pandas and I am trying to re-initialise the dataframe using the pd.DataFrame constructor with dtype=object. This is because the column from excel is reading it as float instead of integer. When I try to change it to object, the data seems the same. It still showing as float. The datatype have changed to ...
<python><pandas><dataframe>
2022-12-25 15:51:27
1
453
Sriram
74,914,319
5,133,524
How to type only the first positional parameter of a Protocol method and let the others be untyped?
<h1>Problem</h1> <p>How to only type the first positional parameter of a Protocol method and let the others be untyped?</p> <p>Example, having a protocol named <code>MyProtocol</code> that has a method named <code>my_method</code> that requires only the first positional parameter to be an int, while letting the rest be...
<python><type-hinting><mypy><python-3.9><duck-typing>
2022-12-25 15:48:46
3
523
giuliano-macedo
74,914,230
17,889,840
How to import Transformers with Tensorflow
<p>After installing Transformers using</p> <pre><code>pip install Transformers </code></pre> <p>I get version 4.25.1 , but when I try to import Transformer by</p> <pre><code>from tensorflow.keras.layers import Transformer # or from tensorflow.keras.layers.experimental import Transformer </code></pre> <p>I get this err...
<python><tensorflow><keras><transformer-model>
2022-12-25 15:30:53
1
472
A_B_Y
74,914,150
2,602,550
Why objects in flask-sqlalchemy still show up as valid?
<p>After setting up two tables with the following code</p> <pre class="lang-py prettyprint-override"><code>class User(db.Model): id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) email = db.Column(db.String(100), unique=True) password = db.Column(Password) name = db.Column(db.Stri...
<python><sqlalchemy><flask-sqlalchemy>
2022-12-25 15:16:32
0
355
chronos
74,913,940
12,242,085
How to convert specific format of date to useful and readable format of date in Python Pandas?
<p>I have DataFrame in Pandas like below:</p> <p>DATA TYPES:</p> <ul> <li><p>ID - numeric</p> </li> <li><p>HOLIDAY - object</p> </li> <li><p>YEAR - object</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>HOLIDAY</th> <th>YEAR</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>1 st...
<python><pandas><string><date>
2022-12-25 14:38:45
2
2,350
dingaro
74,913,886
11,981,718
How to change the plot x axis in time series in graph objects plotly
<p>I want them to go from 0 to 24 h to export those images and create a gif. <a href="https://i.sstatic.net/qALO4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qALO4.png" alt="enter image description here" /></a></p>
<python><pandas><plotly>
2022-12-25 14:30:11
0
412
tincan
74,913,853
12,226,377
Removing different string patterns from Pandas column
<p>I have the following column which consists of email subject headers:</p> <pre><code>Subject EXT || Transport enquiry EXT || RE: EXTERNAL: RE: 0001 || Copy of enquiry EXT || FW: Model - Jan SV: [EXTERNAL] Calculations </code></pre> <p>What I want to achieve is:</p> <pre><code>Subject Transport enquiry 0001 || Copy of...
<python><pandas><regex>
2022-12-25 14:24:17
2
807
Django0602
74,913,841
4,215,840
Python Object inheritance
<pre class="lang-py prettyprint-override"><code>class Phone: def install(): ... class InstagramApp(Phone): ... def install_app(phone: &quot;Phone&quot;, app_name): phone.install(app_name) app = InstagramApp() install_app(app, 'instagram') # &lt;--- is that OK ? </code></pre> <p><code>install_app</c...
<python><object><inheritance>
2022-12-25 14:22:11
4
451
Sion C
74,913,448
12,242,085
How to read table from url as DataFrame and modify format of data in one column in Python Pandas?
<p>I have a link to the website with table like the follow: <a href="https://www.timeanddate.com/holidays/kenya/2022" rel="nofollow noreferrer">https://www.timeanddate.com/holidays/kenya/2022</a></p> <p>How can I:</p> <ol> <li>read this table as DataFrame in Jupyter Notebook in Python ?</li> <li>Convert column &quot;Da...
<python><pandas><date><web-scraping><beautifulsoup>
2022-12-25 13:03:48
2
2,350
dingaro
74,913,369
2,153,383
how can I get the access token needed for ms graph
<p>when registering an app in azure to access mail using ms graph the callback URL is optional, when I try this code it doesn't seem to get the correct token because I get an error 400 when using the token to access office 365. But if I copy the token from the ms graph developer page and use that token it works.</p> <p...
<python><microsoft-graph-api>
2022-12-25 12:46:36
2
2,471
MTplus
74,913,169
5,783,753
How can I make pdf2image work with PDFs that have paths containing Chinese characters?
<p>Following <a href="https://stackoverflow.com/questions/46184239/extract-a-page-from-a-pdf-as-a-jpeg">this question</a>, I tried to run the following code to convert PDF with a path that contains Chinese characters to images:</p> <pre><code>from pdf2image import convert_from_path images = convert_from_path('path with...
<python><image><pdf>
2022-12-25 12:00:52
1
848
Aqqqq
74,913,090
3,482,266
How does one use memit magic?
<p>I'm trying to run the following code in a jupyter notebook:</p> <pre><code>%%memit list1 = [i*i for i in range(100_000)] lista2 = list1 </code></pre> <p>However, I get the following error message:</p> <pre><code>UsageError: Cell magic `%%memit` not found. </code></pre> <p>If instead of <code>memit</code>, I use <cod...
<python><memory><jupyter-notebook>
2022-12-25 11:45:43
1
1,608
An old man in the sea.
74,913,020
12,858,691
Pandas get postion of last value based on condition for each column (efficiently)
<p>I want to get the information in which row the value <code>1</code> occurs last for each column of my dataframe. Given this last row index I want to calculate the &quot;recency&quot; of the occurence. Like so:</p> <pre><code>&gt;&gt; df = pandas.DataFrame({&quot;a&quot;:[0,0,1,0,0],&quot; b&quot;:[1,1,1,1,1],&quot;c...
<python><pandas>
2022-12-25 11:28:40
3
611
Viktor
74,912,686
2,391,859
Question about using multiprocessing and slaves in Python. Getting error: <class 'TypeError'> 'bytes' object is not callable
<p>I just started with trying to use multiprocessing in Python to offload some tasks. This is the basic code here, but I am using it as part of a 'Python Plug-in' that is part of Orthanc, as referenced here: <a href="https://book.orthanc-server.com/plugins/python.html?highlight=python#slave-processes-and-the-orthanc-...
<python><python-3.x><multiprocessing>
2022-12-25 10:08:52
2
2,338
SScotti
74,912,653
10,181,236
How can I efficiently plot a distance matrix using seaborn?
<p>So I have a dataset of more ore less 11.000 records, with 4 features all them are discrete or continue. I perform clustering using K-means, then I add the column &quot;cluster&quot; to the dataframe using <code>kmeans.labels_</code>. Now I want to plot the distance matrix so I used <code>pdist</code> from <code>scip...
<python><seaborn><cluster-analysis><distance-matrix>
2022-12-25 10:01:16
2
512
JayJona
74,912,638
7,702,011
How to use current chrome with selenium with python
<p>I want to use my local chrome with selenium, but every time I just get a new chrome without any cookies</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options option = webdriver.ChromeOptions() option.add_argument(r'--user-data-dir=/U...
<python><selenium><selenium-webdriver>
2022-12-25 09:57:59
2
323
SylorHuang
74,912,330
20,612,566
How to add a Django custom signal to worked out request
<p>I have a Django project and some foreign API's inside it. So, I have a script, that changes product stocks in my store via marketplace's API. And in my views.py I have a CreateAPIView class, that addresses to marketplace's API method, that allows to get product stocks, and writes it to MYSQL DB. Now I have to add a ...
<python><django><django-rest-framework><django-signals>
2022-12-25 08:49:16
1
391
Iren E
74,912,100
4,429,265
Set dynamic values from a dictionary for select values inside a Django template using Javascript or other method
<p>I have three consecutive select options that their values change according to the previous select. The purpose is to categorize products using these select options. First option is to either categorize products with their <code>usage</code> or <code>model</code> value. If <code>usage</code> is selected as the first ...
<javascript><python><django><django-views><django-templates>
2022-12-25 07:46:05
1
417
Vahid
74,911,971
7,339,624
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'
<p>I'm exploring ubuntu and for a small project, I'm writing a <code>.sh</code>(bash) file that will activate a Conda environment and run a python file. Here is my <code>.sh</code> file:</p> <pre><code>#!/bin/sh conda activate simple_python3.10 python3 code.py </code></pre> <p>When I run the bash file it conda gives ...
<python><bash><ubuntu><anaconda><conda>
2022-12-25 07:09:04
1
4,337
Peyman
74,911,643
15,982,771
Can I use sync_to_async for any function in Python?
<p>Background: I'm working on a Discord bot that uses requests. The requests are asynchronous, so I'm using the library <em>asgiref.sync</em>.</p> <p>(I know I obviously can't use this function for asynchronous functions.)</p> <p>I implemented <em>sync_to_async</em> into all the requests and things that may take long t...
<python><asynchronous>
2022-12-25 05:26:22
4
1,128
Blue Robin
74,911,624
2,037,787
ctypes python create string structure
<p>I have a struct like below in dlang</p> <pre><code>struct gph { string x; string y; } </code></pre> <p>and a function as follows:</p> <pre><code>pragma(mangle, &quot;print_gph&quot;) void print_gph(gph g) { stderr.writeln(g.x); } </code></pre> <p>I have created a .so file and trying to access it fro...
<python><ctypes><d>
2022-12-25 05:17:44
1
8,154
backtrack
74,911,605
2,359,865
python lambda functions behavior
<p>I am having a hard time understanding the behavior of these lambda functions in python 3.10.0</p> <p>I am trying to define the <code>NOT</code> logical operator from lambda calculus (see, e.g., the definition on <a href="https://en.wikipedia.org/wiki/Lambda_calculus#Logic_and_predicates" rel="nofollow noreferrer">wi...
<python><lambda>
2022-12-25 05:11:11
3
462
acortis
74,911,598
9,707,286
python compare strings return difference
<p>Consider this sample data:</p> <pre><code>str_lst = ['abcdefg','abcdefghi'] </code></pre> <p>I am trying to write a function that will compare these two strings in this list and return the difference, in this case, 'hi'</p> <p>This attempt failed and simply returned both strings.</p> <pre><code>def difference(string...
<python><string><difference>
2022-12-25 05:08:05
2
747
John Taylor
74,911,597
9,050,514
Garbage collection is not happening properly when using boto3
<p>I'm just running the code to listen to sqs messages in a loop for n times. After each iteration I'm calling <code>gc.collect()</code> but it's returning some unreachable objects and also I'm checking the <code>gc.garbagge</code> for the objects not collected by <code>gc</code> this list also keep on increasing with ...
<python><boto3><amazon-sqs>
2022-12-25 05:07:50
1
9,077
deadshot
74,911,596
2,009,441
How do I fill in missing numbers in a predictable stepped list?
<p>I have a list of the 3–5 high and low tide events throughout a 24 hour period, placed at the appropriate index based on their timestamp:</p> <pre class="lang-py prettyprint-override"><code>tides = [None, None, None, (0.07, 'low'), None, None, None, None, None, None, (2.14, 'high'), None, None, None, None, None, (0.3...
<python>
2022-12-25 05:07:37
1
515
Danny
74,911,498
7,778,016
Unable to get image src attribute in python using selenium
<p>When I try to get the <code>src</code> it returns <code>None</code>. The code should locate the image by its class name and get the attribute.</p> <pre><code>import selenium.webdriver as webdriver import time from selenium.webdriver.common.by import By driver = webdriver.Firefox() url = ('https://www.instagram.com...
<python><selenium>
2022-12-25 04:23:51
2
1,012
P_n
74,911,490
13,489,398
Sharing Schema across different services
<p>I have an ETL pipeline that extracts data from several sources and stores it within a database table (which has a fixed schema).</p> <p>I also have a separate FASTAPI service that allows me to query the database through a REST endpoint, which is called to display data on the frontend (React TS).</p> <p>The issue now...
<python><database><architecture>
2022-12-25 04:20:11
2
341
ZooPanda
74,911,467
4,002,633
Customising Categorical axis labels in Bokeh 3 (showing every nth one), or otherwise labeling duration bins sensibly
<p>I have Bokeh histogram plots showing the number of events in duration bins. Basically we're measuring visit durations to a site and they are typically a few minutes, so we've divided the data into 30 second bins labelled like &quot;0:00-0:30&quot;, &quot;0:30-1:00&quot;, &quot;1:00-1:30&quot; ... etc.</p> <p>Unfortu...
<python><histogram><categories><bokeh>
2022-12-25 04:12:15
0
2,192
Bernd Wechner
74,911,401
343,215
Calculate time difference as decimal in a difference matrix
<p>I'm analyzing timecard data and comparing employee's clockin/out times to each other. I'm exploring the data using <a href="https://stackoverflow.com/a/46266707/343215">a difference matrix in a DataFrame</a>. How do I convert the day, hour timedelta to decimal, or even just a sensible +/- without the <code>-1 days +...
<python><pandas>
2022-12-25 03:43:04
2
2,967
xtian
74,911,393
726,802
Read page source of window opened in new tab
<p><strong>Code for trying to read elements of window opened in new tab. I always get to see message &quot;Not entered&quot;</strong></p> <pre><code>webd = webdriver.Chrome(service=s, options=options) url = &quot;some url&quot; webd.execute_script(&quot;window.open('&quot; + url + &quot;','_blank');&quot;) if len(webd....
<python><selenium><selenium-webdriver><selenium-chromedriver>
2022-12-25 03:39:29
3
10,163
Pankaj
74,911,283
17,464,023
Click on SVG image selenium python
<p>I am trying to use selenium for clicking on a svg element in order to close a pop up:</p> <pre><code>&lt;div class=&quot; light-ui-pop-up--header&quot;&gt; &lt;svg name=&quot;ClosePopUp&quot; class=&quot;pop-up--close-btn&quot; width=&quot;14&quot; height=&quot;14&quot; viewBox=&quot;0 0 14 14&quot; xmlns=&quot;http...
<python><html><selenium><svg>
2022-12-25 02:34:53
1
309
Per Mertesacker
74,911,243
3,508,956
How to do broadcasting addition in Keras Functional API?
<p>I have the following layer defined in Keras:</p> <pre class="lang-py prettyprint-override"><code>class TextDec(tf.keras.Model): def __init__( self, n_vocab: int, n_ctxs: int, n_states: int, n_heads: int, n_layers: int, ): super(TextDec, self).__init__(n...
<python><tensorflow><keras>
2022-12-25 02:15:43
1
7,107
laptou
74,911,033
14,287,127
How to query in SQLAlchemy[Asyncio] (Sanic)
<p>I am new to sanic and SQLAlchemy, I am implementing c2c ecom. I have a many-to-many relationship between orders and products that is joined by order_products table with quantity as an extra field on the join table (i.e. order_products)</p> <pre><code> class Order(Base): __tablename__ = &quot;orders&quot; uui...
<python><postgresql><sqlalchemy><sanic>
2022-12-25 00:38:52
1
329
Shreyas Chorge
74,911,025
12,214,867
How do I put a pair of parentheses on each matched line with Python regex?
<p>I'm trying to convert the following code</p> <pre><code>print &quot;*** Dictionaries&quot; dictionaries = json.loads(api.getDictionaries()) print dictionaries ... print(bestMatch) ... </code></pre> <p>to</p> <pre><code>print(&quot;*** Dictionaries&quot;) dictionaries = json.loads(api.getDictionaries()) print(diction...
<python><regex>
2022-12-25 00:35:47
1
1,097
JJJohn
74,910,864
1,019,250
Why is the [:] included in `.removeprefix()` definition?
<p>In <a href="https://peps.python.org/pep-0616/" rel="nofollow noreferrer">PEP-616</a>, the specification for <code>removeprefix()</code> includes this code block:</p> <pre><code>def removeprefix(self: str, prefix: str, /) -&gt; str: if self.startswith(prefix): return self[len(prefix):] else: r...
<python><string>
2022-12-24 23:39:19
1
1,429
Philip Massey
74,910,845
3,696,118
pyqt QListModelView IconMode highlight to be constant size and add one more line to text?
<p>I posted this question below and I was told of a possible alternative <code>QListModelView.IconMode</code> which I never heard of before <a href="https://stackoverflow.com/questions/74909513/issue-with-filtering-flowlayout-items-in-pyqt5">Issue with filtering FlowLayout items in PyQt5</a></p> <p>I have found this qu...
<python><qt><pyqt><qt5>
2022-12-24 23:32:59
1
353
user3696118
74,910,809
20,102,061
Error: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, None, None, 224, 224, 3)
<p>I am trying to create a model that can detect balloons by creating a CNN model. When I try to <code>fit()</code> the model I get this error: <code>ValueError: Input 0 of layer &quot;sequential&quot; is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, None, None, 224, 224, 3)</code>...
<python><python-3.x><tensorflow><keras><tf.keras>
2022-12-24 23:18:55
0
402
David
74,910,798
16,319,191
Subset rows based on multiple iterative columns in Pandas
<p>I need to subset rows of df based on several columns (c1 through c100 columns) which have strings. Subset rows which equal a particular value for any of the 100 columns. Minimal example with 3 columns is:</p> <pre><code>df = pd.DataFrame({&quot;&quot;: [0,1,2,3,4,5,6,7,8], &quot;c1&quot;: [&quot...
<python><pandas><subset>
2022-12-24 23:15:23
1
392
AAA
74,910,632
3,826,115
Read compressed GRIB file from URL into xarray dataframe entirely in memory in Python
<p>I am trying to read the gzipped grib2 files at tis URL: <a href="https://mtarchive.geol.iastate.edu/2022/12/24/mrms/ncep/SeamlessHSR/" rel="nofollow noreferrer">https://mtarchive.geol.iastate.edu/2022/12/24/mrms/ncep/SeamlessHSR/</a></p> <p>I want to read the grib file into an xarray DataFrame. I know I could write ...
<python><gzip><urllib><python-xarray><grib>
2022-12-24 22:24:43
1
1,533
hm8
74,910,446
3,247,006
Is there "non-lazy mode" or "strict mode" for "querysets" in Django?
<p>When I use <a href="https://docs.djangoproject.com/en/4.1/ref/models/querysets/#select-for-update" rel="nofollow noreferrer"><strong>select_for_update()</strong></a> and <a href="https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.update" rel="nofollow noreferrer"><strong>upda...
<python><python-3.x><django><django-queryset><lazy-evaluation>
2022-12-24 21:37:06
1
42,516
Super Kai - Kazuya Ito
74,910,408
1,609,514
Sympy is not doing the substitution of a symbol with a value when it has a specified assumption
<p>I'm using the subs method to replace certain parameters in an expression with values prior to solving the equation.</p> <p>The following simple example works fine:</p> <pre><code>from sympy import Symbol Q = Symbol(&quot;Q&quot;) exp1 = Q + 1 print(exp1.subs({'Q': 1})) # prints 2 </code></pre> <p>However, if the s...
<python><sympy><substitution><symbolic-math>
2022-12-24 21:26:07
1
11,755
Bill
74,910,342
4,133,384
aws python cdk: how to solve constructs version conflict (trying to create httpapi)
<p>Goal (quite simple, or at least I thought so):</p> <ul> <li>Returning HTML-Content from a lambda for a web browser.</li> <li>Defining it with python aws cdk</li> </ul> <p>As far as I understand it, I've got to put my lambda into an <code>HttpLambdaIntegration</code> which I can use in a route added to my <code>HttpA...
<python><amazon-web-services>
2022-12-24 21:10:19
0
996
evilive
74,910,304
6,271,800
How to add GCP bucket to the Firestore with Python SDK?
<p>I am trying to upload the file to the custom Google Cloud Storage bucket with a Flutter web app.</p> <pre><code>final _storage = FirebaseStorage.instanceFor(bucket: bucketName); Reference documentRef = _storage.ref().child(filename); await documentRef.putData(await data); </code></pre> <p>The code works fine for a d...
<python><flutter><firebase><google-cloud-platform>
2022-12-24 21:01:23
1
611
Sergii
74,910,225
13,828,837
Implementation of an algorithm for simultaneous diagonalization
<p>I am trying to write an implementation of an algorithm for the simultaneous diagonalization of two matrices (which are assumed to be simultaneously diagonalizable). However, the algorithm does not seem to converge. The algorithm is described in SIAM J. Matrix Anal. Appl. <strong>14</strong>, 927 (1993).</p> <p>Here ...
<python><matrix><linear-algebra><numeric><diagonal>
2022-12-24 20:43:22
0
344
schade96
74,910,223
2,584,772
Trying to connect from a docker container to docker host running Django in development mode gets connection refused
<p>I'm running a django development server in my Debian GNU/Linux host machine with <code>python manage.py runserver</code>.</p> <p>After running a Debian docker container with</p> <p><code>$ docker run -it --add-host=host.docker.internal:host-gateway debian bash</code></p> <p>I expected I could make a curl in http://l...
<python><django><docker>
2022-12-24 20:42:23
0
1,684
Caco
74,910,208
2,049,312
How do I patch a python @classmethod to call my side_effect method?
<p>The following code shows the problem.</p> <p>I can successfully patch object instance and static methods of this <code>SomeClass</code></p> <p>However, I can't seem to be able to patch classmethods.</p> <p>Help much appreciated!</p> <pre><code>from contextlib import ExitStack from unittest.mock import patch class ...
<python><mocking><patch>
2022-12-24 20:40:41
1
457
OldSchool
74,909,716
4,115,031
How can I get pdb's debugger working while running uvicorn using uvicorn.run()?
<p>I'm trying to debug a FastAPI application and came across <a href="https://jaketrent.com/post/debug-fastapi-pdb/" rel="nofollow noreferrer">this blog post</a> describing how to run uvicorn from the command line with a <code>--debug</code> flag to get <code>import pdb; pdb.set_trace()</code> to work.</p> <p>But I'm r...
<python><fastapi>
2022-12-24 18:53:08
0
12,570
Nathan Wailes
74,909,513
3,696,118
Issue with filtering FlowLayout items in PyQt5
<p>I am trying to get a filter feature working for this browser type interface i wrote, but I am facing an issue where when i filter the icon layouts looks all wrong.</p> <p>Here is what it looks like normally: <a href="https://i.sstatic.net/lZusd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lZusd.png...
<python><qt><pyqt><pyqt5><maya>
2022-12-24 18:15:10
1
353
user3696118
74,909,205
19,625,920
How can I use Python's exec() and eval() to execute arbitrary code AND return a value afterwards?
<p>I'm looking for a function that will let me execute code passed as a string, but also return a value upon completion. I have found Python's <code>exec</code> and <code>eval</code>, each of which manage to do a part of what I want:</p> <ul> <li><code>exec</code> lets me execute some lines of code which I pass as a st...
<python>
2022-12-24 17:16:42
1
518
whatf0xx
74,909,164
310,370
Is that possible to reset / empty / free up Google Colab notebook GPU VRAM? Without restarting the session
<p>Currently I am trying to run Whisper on my Google Colab.</p> <p>It throws a GPU memory error. However after error is thrown, GPU ram usage is still maximum</p> <p>There are i don't know maybe 100 questions but none of the given answers are working</p> <p>I need a way to free up GPU memory without restarting the sess...
<python><tensorflow><pytorch><google-colaboratory>
2022-12-24 17:08:59
1
23,982
Furkan Gözükara
74,909,112
12,242,085
How to convert object column with date, time and NaN to datetime64 column in DataFrame in Python Pandas?
<p>I have DataFrame in Python Pandas like below:</p> <p>date type</p> <ul> <li><p>COL1 - object</p> </li> <li><p>COL2 - object</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>COL1</th> <th>COL2</th> </tr> </thead> <tbody> <tr> <td>abc</td> <td>2019-11-12T20:15:08+030</td> </tr> <tr> <td>ddd...
<python><pandas><datetime><object><nan>
2022-12-24 17:02:23
1
2,350
dingaro
74,908,952
8,372,455
Pandas calculating time deltas from index
<p>I have a months time series data that I am trying calculate total hours, minutes, seconds in the dataset as well as for a unique Boolean column for when the column is True or a 1. And for some reason I am doing something wrong where the total time calculations don't appear correct. The code (runs) below goes through...
<python><pandas><data-science><data-wrangling><data-scrubbing>
2022-12-24 16:31:32
1
3,564
bbartling
74,908,823
9,808,098
How to convert a string into Hex in TypeScript and back to String in Python
<p>I have a use-case where a TypeScript application should print a string in hex and a Python application should read this hex and convert it back to string.</p> <p>The TypeScript code I have:</p> <pre class="lang-js prettyprint-override"><code>function stringToHex(str: string): string { return str.split('').map(char...
<python><typescript><hex>
2022-12-24 16:09:15
1
3,186
vesii
74,908,633
13,132,728
How to optimize turning a group of wide pandas columns into two long pandas columns
<p>I have a process that takes a dataframe and turns a set of wide pandas columns into two long pandas columns, like so:</p> <p>original wide:</p> <pre><code>wide = pd.DataFrame( { 'id':['foo'], 'a':[1], 'b':[2], 'c':[3], 'x':[4], 'y':[5], 'z':[6] } ) wid...
<python><pandas><dataframe>
2022-12-24 15:35:53
1
1,645
bismo
74,908,506
13,507,819
Ensemble LDA: How to find more than 1 stable topic?
<p>I used LDA (Latent Dirichlet Allocation) algorithm to analyse corpus from <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwi10uCnvJL8AhV-RmwGHec6DmQQFnoECBEQAQ&amp;url=https%3A%2F%2Fconsole.cloud.google.com%2Fmarketplace%2Fproduct%2Fstack-exchange%2Fstack-ove...
<python><nlp><gensim><lda><ensemble-learning>
2022-12-24 15:15:33
0
369
gunardilin
74,908,080
12,862,712
Why is fractional part not discarded in python in some cases
<p>In python<br /> <code>3//2</code> evaluates to <code>1</code>, in this case, the fractional part is discarded<br /> while <code>1.2//1</code> evaluates to <code>1.0</code></p>
<python><floor-division>
2022-12-24 13:50:48
1
1,238
rohitt
74,908,005
389,717
Error while loading a remote file via the _load_file( ) method - Thonny IDE Plugin
<p>I am trying to load a remote <strong>.py</strong> file in Thonny editor but I get the following error:</p> <pre><code>File &quot;/Applications/Thonny.app/Contents/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/thonny/editors.py&quot;, line 193, in _load_local_file with open(filename, &quot;...
<python><tkinter><thonny>
2022-12-24 13:35:01
0
2,386
limitcracker
74,907,879
1,720,743
plotly subpot legend item spacing `legend_tracegroupgap`, how to define as percentage of figure height?
<p>I am trying to make a function using plotly 5.9.0 that will reproduce a specific type of plot. I am having trouble aligning legend entries with their subplots, especially when the figure is resizable.</p> <p>This is what i currently have:</p> <pre><code>import pandas as pd import numpy as np import plotly.graph_obje...
<python><plotly>
2022-12-24 13:15:38
1
770
XiB
74,907,839
6,718,626
Pydantic returns 'field required (type=value_error.missing)' on an Optional field with a custom model
<p>I'm trying to build a custom field in Fastapi-users pydantic schema as follows:</p> <pre class="lang-py prettyprint-override"><code>class UserRead(schemas.BaseUser[uuid.UUID]): twitter_account: Optional['TwitterAccount'] </code></pre> <p>On UserRead validation Pydantic returns</p> <pre class="lang-none prettypri...
<python><fastapi><python-typing><pydantic><fastapiusers>
2022-12-24 13:07:27
2
581
Jakub Królikowski
74,907,735
8,848,630
Difference between '?' and 'help()'
<p>What is the difference between '?' and 'help()' in Python Jupyter Notebooks. E.g.</p> <pre><code>import scipy help(scipy) ?scipy </code></pre>
<python>
2022-12-24 12:49:11
2
335
shenflow
74,907,336
1,167,835
Validation errors on output model when input model is populated by alias
<p>Given an input model with a field <code>alias</code>, and a output model without, shouldn't FastAPI still be able to implicitly <a href="https://fastapi.tiangolo.com/tutorial/response-model" rel="nofollow noreferrer">convert the output data</a> according to <code>response_model</code>? In the example below, a valida...
<python><fastapi><pydantic>
2022-12-24 11:29:20
2
769
Kjell-Bear
74,907,244
13,745,926
How can I use batch embeddings using OpenAI's API?
<p>I am using the OpenAI API to get embeddings for a bunch of sentences. And by a bunch of sentences, I mean a bunch of sentences, like thousands. Is there a way to make it faster or make it do the embeddings concurrently or something?</p> <p>I tried Looping through and sending a request for each sentence but that was ...
<python><embedding><openai-api>
2022-12-24 11:12:42
2
417
Constantly Groovin'
74,907,221
5,429,320
JavaScript fetch to Django view: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
<p>I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user.</p> <p><strong>Error in views.py:</strong></p> <pre><code>Traceback (most recent call last): File &quot;C:\Python310\lib\site-packages\django\core\handlers\exception.py&quot;, line 47, in inner response = g...
<javascript><python><django><fetch>
2022-12-24 11:08:31
2
2,467
Ross
74,907,157
19,826,650
How to change color figure dots of matplotlib cursor? in python
<p>i have a data of csv Longitude,latitude and labels</p> <pre><code> Longitude Latitude 0 106.895231 -6.302275 1 106.900976 -6.285152 2 106.873755 -6.237447 3 106.894059 -6.238875 4 106.820816 -6.311941 .. ... ... 225 106.938847 -6.131683 226 106.937381 -6.109117 227 106.932118 -...
<python><matplotlib>
2022-12-24 10:55:49
1
377
Jessen Jie
74,907,060
17,148,496
Taking two samples from the data but with different observations
<p>My data is made of about 9000 observations and 20 features (Edit - Pandas dataframe). I've taken a sample of 200 observations like this and conducted some analysis on it:</p> <pre><code>sample_data = data.sample(n = 200) </code></pre> <p>Now I want to randomely take a sample of 1000 observations from the original da...
<python><pandas><dataframe><sampling>
2022-12-24 10:39:19
1
375
Kev
74,906,942
12,108,866
Parent class instance variable getting overridden when executing from the parent class
<pre class="lang-py prettyprint-override"><code>class Foo: def __init__(self): self.model = &quot;A&quot; def create(self): print(f&quot;Model in class {self.model}&quot;) class Bar(Foo): def __init__(self): super().__init__() self.model = &quot;B&quot; def save(self)...
<python><class><inheritance><attributes>
2022-12-24 10:17:51
2
343
ABHIJITH EA
74,906,750
6,599,648
Python Flask WTForm Email validation does not allow a dash
<p>I'm looking to validate an email input field for a user in Flask. I'm currently using WTForms Email validation, but this does not allow the user to input a dash as part of their email address. My code is below:</p> <pre class="lang-py prettyprint-override"><code>from flask_wtf import FlaskForm from wtforms import St...
<python><flask><flask-wtforms><wtforms>
2022-12-24 09:36:36
1
613
Muriel
74,906,457
7,462,275
Problem with apply(int) to convert string to int in pandas
<p>This question follows the question: <a href="https://stackoverflow.com/q/74903173/7462275">Problem in Pandas : impossible to do sum of int with arbitrary precision</a> and I used the accepted answer from there: <code>df[&quot;my_int&quot;].apply(int).sum()</code></p> <p>But it does not work in all cases.</p> <p>For...
<python><pandas>
2022-12-24 08:29:19
2
2,515
Stef1611