QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
76,104,462
1,481,986
Typer - group/inheritance arguments
<p>I have several commands in the same typer app that get the same params or at least some of them (e.g. database connection arguments), but they are not sub-commands of each other.</p> <p>I want to avoid copy-pasting those arguments for each command but rather define some sort of inheritance or grouping of arguments.<...
<python><argparse><typer>
2023-04-25 18:45:33
2
6,241
Tom Ron
76,104,459
6,679,011
Multiple program execute one after first one finished, python
<p>Using python, I need to call a program three times with different parameters. What I need is no parallel running these programs. Start a new program only after the previous one finish. How should I modify the following script?</p> <pre><code> os.system(&quot;start MSSQL2PostgreSQLPro_Cons.exe /Session:{}&quot;.forma...
<python><python-3.x>
2023-04-25 18:45:16
1
469
Yang L
76,104,417
935,376
dictionary of dictionaries is not ordering properly
<p>I have a list of logs that show 3 items - userid, time, sign-in or sign-out</p> <pre><code>logs = [&quot;12 150 sign-out&quot;,&quot;30 90 sign-in&quot;,&quot;12 10 sign-in&quot;,&quot;30 120 sign-out&quot;] </code></pre> <p>I am trying to create a dictionary of jsons dictionaries</p> <pre><code>outlist = {} for log...
<python><json><dictionary>
2023-04-25 18:39:30
1
2,064
Zenvega
76,104,294
15,112,182
Selenium / python - Execute a call-back function inside an iframe
<p>I am using Selenium web driver (python) to scrape/interact with websites.</p> <p>I have the target code below, (please note it has been simplified to highlight the important target code only).</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;iframe id=&quot;main-iframe&quot;&gt;...
<javascript><python><selenium-webdriver><iframe>
2023-04-25 18:20:35
1
398
constantlyFlagged
76,104,090
9,809,135
Using the Azure DevOps Python API to create a new work-item
<p>Similar to the question posted <a href="https://stackoverflow.com/questions/60441473/creating-a-workitem-in-azure-devops-via-python/76102850#76102850">here</a>, I am trying to manage Azure DevOps work items via python.</p> <p>The accepted answer refers to the official <a href="https://github.com/microsoft/azure-devo...
<python><azure-devops>
2023-04-25 17:53:21
1
355
davjfish
76,104,022
1,601,443
Unable to run python project. `__main__` module not found
<p>I cloned a git repository that I would like to run, the project folder structure is shown bellow.</p> <p><a href="https://i.sstatic.net/KQAat.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KQAat.png" alt="enter image description here" /></a></p> <p>I installed the dependencies using,</p> <p><code>pyt...
<python><python-3.x>
2023-04-25 17:42:05
1
4,050
rksh
76,104,000
676,192
How do I create a checkerboard of two specific colors with python
<p>I have managed to create a black and white checkerboard like this:</p> <pre><code>import numpy as np import cv2 checkers = np.tile( np.array([[0, 1], [1, 0]]), (16 // 2, 16 // 2)) </code></pre> <p>but now I am struggling to transform that into - sa - a blue and yellow checkerboard.</p> <p>I tried a lambda transform...
<python><numpy>
2023-04-25 17:38:57
1
5,252
simone
76,103,950
436,826
Cannot run celery worker while importing playwright library
<p>I'm trying to run a simple playwright code with celery as you can see below:</p> <pre class="lang-py prettyprint-override"><code>@shared_task def get_title(): with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page() page.goto('https://github.c...
<python><django><celery><playwright>
2023-04-25 17:33:14
0
334
Ekin Ertaç
76,103,908
19,980,284
Wrapping Y-tick labels in Bold Removes whitespace
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>s = &quot;&quot;&quot;level,cvc Vasopressor dose,0 Low, 0.263 Med, .563 High, 0.777 Vasopressor trend,0 Decreasing, 0.367 Stable, 0.521 Increasing, 0.714 Duration,0 8 hours, 0.478 24 hours, 0.591 PIV Location,0 Upper Arm, 0.528 Forearm, 0.541 Case...
<python><pandas><matplotlib><list-comprehension>
2023-04-25 17:28:12
1
671
hulio_entredas
76,103,900
12,226,377
Pandas merge two data frames on a specific condition
<p>I have two different dataframes df1 and df2 which I would like to merge based on the following condition:</p> <pre><code>id category 1 cat1 2 cat2 </code></pre> <p>df2:</p> <pre><code>id category_name 1 shoes 1 car </code></pre> <p>resultant df:</p> <pre><code>id category catego...
<python><pandas><merge>
2023-04-25 17:27:16
1
807
Django0602
76,103,876
10,966,786
Why does Shamir secret sharing appear to need ordered shares?
<p>The implementation of Shamir secret sharing in this code, only generates the original image if the shares are provided in consecutive order (ex: [2,3,4]) and won't work in any other share order (ex: [2,4,6] or [4,1,3]). However, Shamir secret reconstruction does not require the shares to be in any order, then why do...
<python><numpy><cryptography>
2023-04-25 17:24:42
1
496
Raisa A
76,103,811
12,282,349
FastAPI_Login RedirectResponse after authorization fails
<p>I have a simple login form that is opened using a <code>GET</code> request, and the user submits the form with a <code>POST</code> request. After successful authentication, I redirect the user to the main page of my web application using a <code>RedirectResponse</code> object.</p> <p>However, despite the successful ...
<python><http-redirect><fastapi><httpresponse><setcookie>
2023-04-25 17:14:44
1
513
Tomas Am
76,103,804
1,914,034
numpy - dynamic slicing using mix of all() and any()
<p>I am trying to slice a point cloud numpy array dynamically. The slicing would filter points that x/y coordinates fall inside a list of boundaries defined by <code>minx</code>, <code>miny</code>, <code>maxx</code>, <code>maxy</code></p> <p>I thought I had a working algorithm but Im facing the <code>The truth value of...
<python><numpy>
2023-04-25 17:13:19
1
7,655
Below the Radar
76,103,582
6,496,267
How to upload JSON string to GCP bucket using Python without having to write it to a file?
<p>I have been uploading JSON file to GCP bucket like this</p> <p>data_array is an array containing JSONs for each row. It looks like this &quot;[{key1: value1, key2: value2},{key1: value1, key2: value2},{key1: value1, key2: value2}...]&quot;</p> <pre><code>path_to_file = # i dump array to file blob = bucket.blob(bl...
<python><google-cloud-platform>
2023-04-25 16:41:33
0
717
john
76,103,488
3,719,167
Django using database without migration
<p>I have a Django application running using MySQL database, and everything works fine.</p> <p>For another part of the same application, I want to create a new Django application, implement database sharding, and have a separate database to store the tracking data and use the existing database (used by previous Django ...
<python><django>
2023-04-25 16:29:11
0
9,922
Anuj TBE
76,103,440
7,879,074
Build a dictionary from large lists in python
<p>I have two lists, <code>A_flat</code>, which contains 1,000,000 sentences, and <code>B_flat</code> which for each sentence contains a list of four labels. This is my code:</p> <pre><code># Find indices of sentences with length &lt;= max_length short_sent_indices = [i for i, sent in enumerate(A_flat) if len(sent.spli...
<python><dictionary>
2023-04-25 16:24:56
0
631
Abrar
76,103,342
74,562
Pygame slowdown on Raspberry Pi with multiple surfaces?
<p>I'm trying to do a small visualizer project on a Raspberry Pi (was aiming for a 3B but went to a 4 to have the better processing capabilities), and I noticed an odd behavior that I can't account for.</p> <p>Initially, I was just drawing to a main <code>display</code> surface (at 1920x1080 resolution) and the applica...
<python><pygame><raspberry-pi><raspberry-pi4>
2023-04-25 16:13:09
1
3,862
erik
76,103,340
8,280,171
Consuming Secret Values when building React using CDK
<p>I'm trying to consume secret values that already exist in Secret Manager when building my frontend react app using CDK and Python</p> <pre><code>secret_arn = f&quot;arn:aws:secretsmanager:us-west-2:1234:secret:my_variables-123456&quot; my_variables = secretmanager.Secret.from_secret_complete_arn( self, ...
<python><aws-cdk><aws-secrets-manager>
2023-04-25 16:12:59
1
705
Jack Rogers
76,103,279
4,502,950
Apending values in google sheets add ' with the values using gspread
<p>I am following <a href="https://medium.com/@jb.ranchana/write-and-append-dataframes-to-google-sheets-in-python-f62479460cf0#:%7E:text=Once%20you%20write%20the%20data,tolist()%20before%20appending." rel="nofollow noreferrer">this</a> tutorial to append new rows to my existing dataset which is working fine except one ...
<python><pandas><google-sheets><gspread>
2023-04-25 16:06:33
1
693
hyeri
76,103,278
6,626,531
Mypy error when an attribute is initialized to None and then used later
<p>Using <code>mypy==0.991</code> and Python <code>3.8</code>.</p> <p>I have a class that initializes its attribute <code>kfp</code> to <code>None</code>. The user should run the <code>open</code> method first and then <code>produce</code>, and so at that point in time, <code>self.kfp</code> will not be <code>None</cod...
<python><mypy><python-typing>
2023-04-25 16:06:32
1
1,975
Micah Pearce
76,103,041
1,405,543
How to change background color of the title of legend
<p>In the example below, how can I change the <strong>background</strong> color of &quot;Title&quot; to be red (with alpha=.5), not the font color of &quot;Title&quot;?</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,2,3,], [1,2,3], label='Series')...
<python><matplotlib><colors><legend>
2023-04-25 15:42:48
4
1,165
jII
76,103,001
2,482,149
Python Logging is Blocking: Datadog
<p>There's a custom log handler in Python called <code>DataDogCustomLogHandler</code>.</p> <p>This is the function to initialise the logger:</p> <pre><code>os.environ[&quot;DD_API_KEY&quot;] = 'XXXXX' os.environ[&quot;DD_SITE&quot;] = 'XXXXX' host_name = socket.gethostname() def init_datadog_logging(service_name: str...
<python><logging><python-asyncio>
2023-04-25 15:38:15
1
1,226
clattenburg cake
76,102,935
777,593
pandas group by with reset index
<p>Given I have following pandas dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>UserID</th> <th>LoginDate</th> <th>PlacedOrderItems</th> <th>Other column</th> </tr> </thead> <tbody> <tr> <td>A123456</td> <td>2023-04-01</td> <td>1</td> <td>a</td> </tr> <tr> <td>A123456</td> <td>20...
<python><pandas><group-by><dataframe>
2023-04-25 15:28:21
2
2,411
Khurram Majeed
76,102,887
4,819,376
Plotly range of subplot doesn't change
<p>I'm trying to set the range of subplots using <code>xaxis_range</code> but I found it's working on the left subplot only</p> <h1>Data</h1> <pre class="lang-py prettyprint-override"><code>import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots data = {'variable': {0: 'Case', 1...
<python><pandas><plotly>
2023-04-25 15:23:47
1
13,495
rpanai
76,102,677
14,485,257
Expanding a pandas dataframe based on new values of a column
<p>I have two pandas dataframes called &quot;data&quot; and &quot;temp_data&quot;:</p> <p><a href="https://i.sstatic.net/EGd3K.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EGd3K.png" alt="enter image description here" /></a></p> <p>&quot;data&quot; has columns &quot;date_time&quot; and &quot;Voltage&q...
<python><pandas><dataframe>
2023-04-25 15:03:12
1
315
EnigmAI
76,102,484
21,404,794
Sum of columns over threshold in pandas
<p>I'm trying to sum a bunch of columns in pandas and check whether that sum is over 100 or not.</p> <p>I already have the sum part sorted, what I'm trying to find is a way to compare each value of the sum to a scalar.</p> <p>Here's my first attempt:</p> <p><code>df[[col1,col2]].sum(axis=1) &gt; 100.0</code></p> <p>thi...
<python><pandas><dataframe><comparison>
2023-04-25 14:45:09
1
530
David Siret Marqués
76,102,444
13,219,123
Filter pyspark dataframe
<p>I have the following pyspark dataframe.</p> <pre><code># Define the schema for the dataframe schema = StructType([ StructField(&quot;dt&quot;, StringType(), True), StructField(&quot;id&quot;, StringType(), True), StructField(&quot;value&quot;, FloatType(), True) ]) # Create the PySpark dataframe data = ...
<python><pyspark>
2023-04-25 14:41:06
1
353
andKaae
76,102,415
7,599,062
Implementing a transformer-based span retrieval model for a document-grounded dialogue system
<p>I am working on a project that aims to develop a document-grounded dialogue system with a transformer-based span retrieval model. The system will be trained on a dataset of multiturn conversations where users ask questions that require information from multiple documents.</p> <p>I am currently struggling with the im...
<python><machine-learning><deep-learning><nlp>
2023-04-25 14:37:59
1
543
SyntaxNavigator
76,102,235
4,819,376
y-ticks between sublopts in Plotly
<p>I had a look at <a href="https://stackoverflow.com/questions/76073586/generate-bidirectional-bar-chart-in-matplotlib-with-variables-in-center-of-chart/76076468?noredirect=1#comment134210758_76076468">this</a> question and I was wondering if there is a way to put the y-ticks and names between 2 subplots.</p> <h1>Data...
<python><pandas><plotly>
2023-04-25 14:20:42
1
13,495
rpanai
76,102,050
950,854
"No data found for this date range, symbol may be delisted"
<p>I'm trying to deploy a working Python 3.10 function to AWS Lambda, but I'm stuck with these yfinance (0.2.18) errors:</p> <p>This call <code>yf.Ticker('QQQ').history(period='6mo')</code> generates <code>QQQ: No data found for this date range, symbol may be delisted</code></p> <p>While this call <code>yf.download('QQ...
<python><aws-lambda><yfinance>
2023-04-25 14:02:44
0
649
chris
76,101,799
7,194,375
Pycaret, predict soil moisture to minimize water consumption
<p>I want to predict soil moisture for a field to minimize water consumption. For that I recorded only soil moisture and soil temperture over the course of two months. There are four devices that give me the values in 10min interval for one field. So I did combine those four soil moisture values in a moving average. He...
<python><time-series><regression><forecasting><pycaret>
2023-04-25 13:38:13
1
408
AldegarRızvan
76,101,635
12,902,027
Kaggle Code doesn't download "gpt2" language model
<p>I am using kaggle code to download gpt2 language model.</p> <pre class="lang-py prettyprint-override"><code>from transformers import AutoTokenizer, AutoModelForCausalLM device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot; model_name = &quot;gpt2-xl&quot; tokenizer = AutoTokenizer.from_pretrai...
<python><huggingface-transformers><kaggle><gpt-2>
2023-04-25 13:20:15
1
301
agongji
76,101,543
1,026,990
How to access Firebird system tables through SQLalchemy?
<p>I want to use automap to get database schema and start working with system tables (like MON$ RDB$) as objects.</p> <p>like</p> <pre class="lang-py prettyprint-override"><code> Base = automap_base() Base.prepare( autoload_with=engine ) Session().query(Base.classes.mon.Statements).all() </code>...
<python><sqlalchemy><firebird>
2023-04-25 13:11:04
0
3,768
uralbash
76,101,516
5,547,553
How to create a rank based on multiple columns in Polars?
<p>Suppose we have this dataframe in polars:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( { &quot;era&quot;: [&quot;01&quot;, &quot;01&quot;, &quot;02&quot;, &quot;02&quot;, &quot;03&quot;, &quot;03&quot;], &quot;pred&quot;: [3,5,6,8,9,1] } ).wit...
<python><dataframe><python-polars><ranking>
2023-04-25 13:08:20
1
1,174
lmocsi
76,101,455
19,980,284
Reformat bidirectional bar chart to match example
<p>I have generated this bar-chart</p> <p><a href="https://i.sstatic.net/QS9v7.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QS9v7.jpg" alt="enter image description here" /></a></p> <p>Using this code:</p> <pre class="lang-py prettyprint-override"><code>s = &quot;&quot;&quot;level,margins_fluid,margins...
<python><pandas><matplotlib><plotly><bar-chart>
2023-04-25 13:01:59
2
671
hulio_entredas
76,101,366
10,232,932
Upgrade python version in virtualenviornment in visual studio code
<p>I have a combination of this two questions on stackoverflow: <a href="https://stackoverflow.com/questions/58562928/how-do-i-update-a-python-virtual-environment-with-venv-in-python-3-3-to-use">How do I update a Python virtual environment with `venv` (in Python 3.3+) to use a newer version of Python?</a></p> <p><a hre...
<python><visual-studio-code><virtualenv>
2023-04-25 12:51:25
1
6,338
PV8
76,101,074
10,544,599
How to find multiple tags at once along with attributes using BeautifulSoup in python3?
<p>I am trying to find different tags at once using <code>find_all()</code> method of BeautifulSoup. I found a way to include all tags in the list to get the respective tags. But I am trying to get tags along with their attributes. I am not sure how to get it.</p> <p>This is the reference HTML structure.</p> <pre><code...
<python><html><python-3.x><beautifulsoup><html-parsing>
2023-04-25 12:16:05
2
379
David
76,101,024
14,220,087
How to keep dtype in 0-dim array arithmetics in Numpy?
<pre class="lang-py prettyprint-override"><code>import numpy as np x=np.array(2, dtype=np.float32) y=x+1 print(y.dtype) # float64 </code></pre> <p>As shown above, <code>x</code> is a 0D array and its dtype is float32. But if you add 1 to it, the output <code>y</code> will be float64.</p> <p>This only happens when x is ...
<python><arrays><numpy>
2023-04-25 12:11:15
2
829
Sam-gege
76,100,975
13,636,586
YOLOv8 custom save directory path
<p>I'm currently working in a project in which I'm using Flask and Yolov8 together.</p> <p>When I run this code</p> <pre class="lang-py prettyprint-override"><code>from ultralytics import YOLO model = YOLO(&quot;./yolov8n.pt&quot;) results = model.predict(source=&quot;../TEST/doggy.jpg&quot;, save=True, save_txt=True...
<python><flask><yolo><yolov8>
2023-04-25 12:06:36
1
399
Hariharan
76,100,972
11,725,056
How to solve a Custom Optimisation problem which uses Matrix Factorisation and custom loss in Pytorch?
<p>I am trying to replicate the paper <a href="https://dl.acm.org/doi/10.1145/3448139.3448177" rel="nofollow noreferrer">Recommendation for Effective Standardized Exam Preparation</a> where they have used a special term called <strong>correctness probability function</strong> and is described as:</p> <blockquote> <p>co...
<python><numpy><machine-learning><pytorch><torch>
2023-04-25 12:06:04
1
4,292
Deshwal
76,100,754
12,858,691
Pandas find values that could be a date
<p>I have large and messy dataframe and want to identify date-like values if there are any. These date-like values could have any kind of date format and data type.</p> <p>Is there a generic (pandas in-built) way to achieve this?</p> <p>My code:</p> <pre><code>&gt;&gt; data.info() &lt;class 'pandas.core.frame.DataFrame...
<python><pandas>
2023-04-25 11:41:18
0
611
Viktor
76,100,752
11,295,602
How do I pass custom metadata from setup.py to my application code
<p>I'm writing a setup.py file for my python package and have information in a dictionary that I want to pass to the setup command that will then be accessible to the application code when the package is installed.</p> <p>Is there a standard way to pass information like this in the setup function without writing and th...
<python><setuptools><setup.py><python-packaging>
2023-04-25 11:41:01
0
303
squashed
76,100,746
610,569
Simplifying ngram loops to compress the string given a fix set of ngrams
<p>Given in list of characters, <code>list('Hello▁world▁')</code> and a list of character tuples, i.e.</p> <blockquote> <p>[('l', 'l'), ('ell', 'o▁'), ('Hell', 'o▁'), ('w', 'or'), ('o', 'r'), ('e', 'l'), ('el', 'l'), ('H', 'ell'), ('H', 'e'), ('He', 'll'), ('worl', 'd▁'), ('wor', 'l'), ('l', 'd▁'), ('d', '▁'), ('wor', ...
<python><string><while-loop><byte-pair-encoding>
2023-04-25 11:40:07
2
123,325
alvas
76,100,520
11,198,558
How can I customize hover for plotly.graph_object.Scattergeo?
<p>I have problem to customize the hoverbox when ploting using ScatterGeo of Plotly.graphic_object. Specifically, I have dataframe like this</p> <pre><code>data = pd.DataFrame({'country': &lt;list of country&gt;, 'importValue': &lt;list of data&gt;, 'lat': &lt;list of latitude ...
<python><plotly>
2023-04-25 11:11:02
1
981
ShanN
76,100,518
21,787,377
'TemporaryUploadedFile' object has no attribute 'get'
<p>I'm getting this error every time I'm trying to upload video file, and I think the problem is come from the <code>moviepy</code> library that I'm using to cut every video that are higher than 10 minute.</p> <p>the error: <code>AttributeError at /CreateVideo 'TemporaryUploadedFile' object has no attribute 'get'</code...
<python><django><moviepy>
2023-04-25 11:10:39
1
305
Adamu Abdulkarim Dee
76,100,345
1,341,942
How does Python decide wherever to call __setitem__ or __getitem__ methods?
<p>As a C++ programmer, I am looking at the things from position of C++ language. If I want to define an indexing operator, I do it like this:</p> <pre><code>struct S { auto operator [](int) -&gt; string { throw 0; return &quot;hello&quot;; } }; </code></pre> <p>Notice that my method always ...
<python>
2023-04-25 10:49:25
2
4,713
nikitablack
76,100,078
9,749,124
Python pip error - AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'
<p>I was installing Python libraries with pip on my Mac Catalina for the last 3 years. Command: <code>sudo pip3 install &lt;lib_name&gt;</code> Suddenly, that stopped workinng. When ever I want to install something I get this error:</p> <pre><code>Traceback (most recent call last): File &quot;/Library/Frameworks/Pyth...
<python><pip>
2023-04-25 10:19:25
1
3,923
taga
76,099,798
11,901,834
Print all python logs within GitHub Action
<p>I have a GitHub Action that calls a python script:</p> <pre><code>- name: Test Python Script run: | python python_script.py </code></pre> <p>This runs fine and prints me the logs from within here:</p> <pre><code>if __name__ == &quot;__ main __&quot;: print('Calling function') func_call() print('End o...
<python><github-actions>
2023-04-25 09:48:40
2
1,579
nimgwfc
76,099,788
8,040,369
Multiprocessing: Python code to call my method with pool.map_async().get() is not working
<p>I am trying to run the below basic example code for multiprocessing in my Jupyter Notebook.</p> <pre><code>import multiprocessing import time def square(x): print('=====&gt; ',x) return x * x if __name__ == &quot;__main__&quot;: pool = multiprocessing.Pool() inputs = [0,1,2,3,4] outputs_async ...
<python><python-3.x><multithreading><jupyter-notebook><multiprocessing>
2023-04-25 09:47:31
1
787
SM079
76,099,547
11,321,089
How to extract into lists all the values for each key in a nested dictionary
<p>I have some code which loops through a nested dictionary and extracts the nested values into lists but thought there has to be a more pythonic way of doing it.</p> <p><strong>Code</strong></p> <pre><code>if __name__ == &quot;__main__&quot;: master_dict = {&quot;1&quot;: {&quot;1&quot;: 11, &quot;2&quot;:22, &qu...
<python><dictionary><nested>
2023-04-25 09:21:18
3
909
Windy71
76,099,406
603,774
'Set as interpreter' for a .py file in VS Code
<p>During the execution of one of the examples, the video tutorial in VS Code indicates the message <code>Set as interpreter</code>, which allows you to explicitly specify which interpreter should be used for the py file.</p> <img src="https://i.sstatic.net/OwFO9.png" width="400" /> <p>My VS Code doesn't have this mess...
<python><python-3.x><visual-studio-code><ros2>
2023-04-25 09:06:35
0
5,241
Ali Mamedov
76,099,336
4,623,971
Maximum recursion depth exceeded in databricks when converting pandas dataframe to spark dataframe
<p>I'm currently writing some code in databricks, with the default language in my notebook being python. I have a function that takes a pandas dataframe as input, does some calculations, and then outputs the dataframe with a new column that contains the output from the function. The function works as expected, and it...
<python><dataframe><pyspark><azure-databricks>
2023-04-25 08:59:43
1
334
JGW
76,099,325
3,427,777
pandas: summarize df with conditional based on another column
<p>I have a df with many factors as columns, and many samples as rows; many of the entries are <code>NaN</code>. There is also a single <code>value</code> column that is always non-NaN. I would like to summarize the factors across all samples. The summarized <code>value</code> for each factor should be the total of all...
<python><pandas><dataframe>
2023-04-25 08:58:32
2
22,862
fantabolous
76,099,315
3,329,877
Adding custom entries to legend gradually
<p>I want to build up a plot gradually in multiple functions like this</p> <h2>Example</h2> <pre class="lang-py prettyprint-override"><code>import matplotlib.patches as mpatches import matplotlib.pyplot as plt import numpy as np def plot_on_axis(ax: plt.Axes, x: np.ndarray, y: np.ndarray, color, name) -&gt; plt.Axes: ...
<python><matplotlib>
2023-04-25 08:57:00
1
397
VaNa
76,099,307
10,889,650
Python list from lists, somewhat like flattening a zip
<p>EDIT: Unlike <a href="https://stackoverflow.com/questions/61943924/python-flat-zip">python: flat zip</a>, I'm asking about a list of lists, not two lists.</p> <p>I have a list of lists, for example:</p> <pre><code>[[a,b,c], [d,e,f], [g,h,i,j,k]] </code></pre> <p>And I wish to interleave them such that we take the fi...
<python><python-itertools>
2023-04-25 08:56:26
3
1,176
Omroth
76,099,217
10,035,190
How can I delete rows containing nonsense characters in pandas?
<p>I need to be able to remove all rows containing nonsense characters such as the ones shown below in a pandas dataframe.</p> <p><a href="https://i.sstatic.net/DCIeg.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DCIeg.png" alt="enter image description here" /></a></p> <p>I have tried this code to dele...
<python><pandas><dataframe>
2023-04-25 08:46:38
2
930
zircon
76,099,093
14,109,040
splitting a list into sublists based on the element immediately before another
<p>I have a list of flight details that I scraped from google flights:</p> <pre><code>result = ['12:10\u202fPM', ' – ', '5:20\u202fPM', 'AirAsia X', '3 hr 10 min', 'SYD–AKL', 'Nonstop', '139 kg CO2', 'Avg emissions', 'A$540', 'round trip', '7:50\u202fPM', ' – ', '1:00\u202fAM+1', 'Jetstar', '3 hr 10 min', 'SYD–AKL', 'N...
<python>
2023-04-25 08:29:03
3
712
z star
76,099,043
10,533,225
java.lang.IllegalStateException - Couldn't find column
<p>I have this code which corrects the MLE value to MALE. I first make a distinct value of Gender, then next is I will correct the wrong spelling.</p> <pre><code>genderTypeDim = ( qualificationConsolidatedData.select(&quot;GenderType&quot;)) .distinct() .dropna(&quot;all&quot;) ) genderTypeDim.show() gend...
<python><pyspark><azure-databricks>
2023-04-25 08:23:17
1
583
Tenserflu
76,098,861
11,426,624
get minimum value which is greater than some value from column in pandas dataframe
<p>I have a pandas dataframe and would like to create a column <code>min_date_after_ref_date</code> which shows the minimum date after a given ref_date. I have the following code.</p> <pre><code>ref_date = datetime.strptime('2023-04-21 12:00', '%Y-%m-%d %H:%M') df = pd.DataFrame({'id':[1,2,1,1,3], 'time_stamp': ['2023-...
<python><pandas><dataframe><group-by>
2023-04-25 08:00:24
1
734
corianne1234
76,098,857
5,581,413
Add a filter/classifier to the Python function for generating documentation for custom tags
<p>I want to generate the documents for my Python project.</p> <p>I know that there are a lot of useful tools that I have read about, such as pdoc and Sphinx.</p> <p>One of my biggest requirements is that I want to add a tag or classifier for some functions located in different modules.</p> <p><strong>Suppose I have th...
<python><documentation><python-sphinx><pdoc>
2023-04-25 07:59:59
0
387
codebrew
76,098,792
5,370,631
Explode a json string present in pyspark dataframe
<p>I have a JSON string <code>substitutions</code> as a column in dataframe which has multiple array elements that I want to explode and create a new row for each element present in that array. There are other columns present in the df</p> <p>My dataframe looks like this:</p> <pre><code>+--------------------+----------...
<python><json><apache-spark><pyspark><apache-spark-sql>
2023-04-25 07:51:19
2
1,572
Shibu
76,098,609
4,723,732
Why Ansible molecule path is not detected? molecule: command not found
<p>I tried to init</p> <pre><code>molecule init role mikitovcluster </code></pre> <p>got</p> <pre><code>molecule: command not found </code></pre> <p>I listed my collections</p> <pre><code>ansible-galaxy collection list # /usr/lib/python3/dist-packages/ansible_collections Collection Version ---------...
<python><ansible><molecule>
2023-04-25 07:29:31
0
8,250
Richard Rublev
76,098,566
12,304,000
intentionally raise an exception and fail the DAG
<p>In my Airflow dag, I am doing this:</p> <pre><code> try: response = requests.get(url, params=params, headers=headers) if response.status_code == 403: raise Exception(f&quot;Data Unavailable for metric: {m}, account: {accou...
<python><python-3.x><exception><airflow><airflow-2.x>
2023-04-25 07:24:07
1
3,522
x89
76,098,535
4,481,287
Handling async streams in flask with twilio
<p>I have a basic flask app to serve twilio calls. When a call is generated via twilio it goes to my <code>/test</code> http api.</p> <p>In this api I'm generating a twiml conversation where the first thing that happens is a verb just saying &quot;hello world&quot;. Then, concurrently I start a stream in the backgroun...
<python><python-3.x><flask><twilio><flask-sockets>
2023-04-25 07:20:18
1
1,371
Kevin Cohen
76,099,791
758,979
Printing from the command-line on a modern continuous paper printer without wasting paper?
<p>I have a Peripage A4 continuous paper roll thermal printer, connected via USB-C to a MacBook with 13.3.1. Printing works fine from within all applications and via the commandline using <code>lpr</code>:</p> <pre><code>lorem --faust --lines 20 --randomize | lpr -P &quot;PeriPage_A4&quot; -o orientation-requested=1 </...
<python><cups><lpr>
2023-04-25 07:19:41
1
1,301
Christian
76,098,496
19,674,402
Typehint tuple of ints gives IDE warning. List of ints does not. Why?
<p>Why does the typehint <code>tuple[int]</code> behave differently from <code>list[int]</code>?</p> <p>This gives me a visual warning:</p> <pre><code>def func_with_tuple(x: tuple[int]): pass func_with_tuple((1, 2, 3)) # ^ # warning _________| </code></pre> <blockquote> <p>Expected type ...
<python><pycharm><type-hinting>
2023-04-25 07:15:21
1
496
PythonForEver
76,098,338
388,359
Validating a AWS ACM Certificate using aws.acm.CertificateValidation in Pulumi using python
<p>In Pulumi I create a ACM Certificate with a domain-name and a number of SAN. This is set to get verified using DNS.</p> <p>The Route53 records get created using the following function. This works as expected in that the records get created and the certificate status changes to valid in AWS.</p> <pre><code> # Crea...
<python><amazon-web-services><pulumi><pulumi-python>
2023-04-25 06:53:23
1
1,251
alexis
76,098,104
6,774,444
How to get SSL Cipher used when using boto3 to interact with AWS?
<p>We are using boto3 to to authenticate in AWS using STS AssumeRoleWithSAML. I need to know the cipher suite used when establishing connection with AWS. I added below code but it doesn't logs any info about the SSL connection:</p> <pre class="lang-py prettyprint-override"><code>boto3.set_stream_logger('', logging.DEBU...
<python><amazon-web-services><ssl><boto3><python-logging>
2023-04-25 06:16:56
0
485
Faiz Kidwai
76,097,925
9,848,043
AssertionError: query should be unbatched 2D or batched 3D tensor but received 4-D query tensor: Pytorch
<p>I have this <a href="https://paperswithcode.com/method/cct" rel="nofollow noreferrer">CCT</a> Encoder</p> <pre><code>class CctEncoder(nn.Module): def __init__(self, in_channels, cct_block_params, num_layers): super().__init__() self.conv = nn.Conv2d(in_channels, cct_block_params[0][0], kernel_siz...
<python><deep-learning><pytorch><tensor>
2023-04-25 05:43:59
0
1,115
Joyanta J. Mondal
76,097,868
10,294,022
Python subprocess output stream stdout.read hangs forever for input prompt
<p>I am trying to run a subprocess with Popen, and at a time it asks for an input prompt without any <code>EOF</code>, so <code>stdout.read()</code> blocks the while loop until an <code>EOF</code> is found, like forever because there will be none.</p> <p>I am unable to detect if we are in an input prompt coming next vi...
<python><stdout><popen>
2023-04-25 05:28:33
1
803
Thomas Aumaitre
76,097,825
13,581,071
Detect SIGUSR1 in C code and print Hello World
<p>I have a relatively trivial problem, with working reproducible code (you can run it direct from your environment</p> <p>Essentially</p> <p>I have some C and Python code.</p> <p>My python code</p> <p>Creates two pipes tomcat_1 and tomcat_2, these pipes can read and write respectively.</p> <p>Now using my tomcat_2 pi...
<python><c><pipe><signals>
2023-04-25 05:19:05
1
301
HyperCoderSuperion
76,097,788
8,294,738
Is there a way to get all namespace scoped resource objects by label selector using python kubernetes client?
<p>I want to achieve this command use kubernetes python client.</p> <pre class="lang-bash prettyprint-override"><code>kubectl -n namespace get all -l key=value </code></pre> <p>I've seen several questions here <a href="https://stackoverflow.com/questions/61787779/list-all-resources-in-a-namespace-using-the-kubernetes-p...
<python><kubernetes><kubernetes-python-client>
2023-04-25 05:09:57
1
657
romlym
76,097,697
755,934
send SSE only to specific clients using flask
<p><a href="https://github.com/singingwolfboy/flask-sse" rel="nofollow noreferrer">flask-sse</a> provides some example code in its <a href="https://flask-sse.readthedocs.io/en/latest/quickstart.html" rel="nofollow noreferrer">quickstart</a> section. However that code publishes events to all subscribed clients. To publi...
<python><flask><server-sent-events>
2023-04-25 04:43:50
0
5,624
Daniel Kats
76,097,693
3,507,127
Return results of Django Query as Dictionary
<p>Suppose I have a Django model that looks like this:</p> <pre><code>class User(models.Model): customer_id = models.TextField() date_time_period_start = models.DateField() date_time_period_end = models.DateField() total_sales = models.IntegerField() </code></pre> <p>The underlying table looks like this...
<python><django>
2023-04-25 04:43:11
1
9,006
Vincent
76,097,512
4,083,786
Detail not found error using FastAPI's APIRouter
<p>I have a directory structure as follows:</p> <pre><code>app &gt;routers &gt;items.py __init__.py main.py </code></pre> <p>Inside main I have the following code:</p> <pre><code>from typing import Union import uvicorn from fastapi import FastAPI, APIRouter from routers import items app = FastAPI() app.incl...
<python><fastapi>
2023-04-25 03:41:24
1
1,182
turtle_in_mind
76,097,342
1,461,972
Can PythonAnywhere Free Account code call outside https Apis?
<p>I'm writing a telegram bot to serve a set of relational card games, and used a blend of ChatGPT output with what I found at <a href="https://blog.pythonanywhere.com/148/" rel="nofollow noreferrer">https://blog.pythonanywhere.com/148/</a>.</p> <p>I can get the bot to start, which is great. The issue is that when I ca...
<python><telegram-bot><pythonanywhere><urllib3>
2023-04-25 02:48:30
1
1,805
MrWater
76,097,199
5,383,733
Install Sentence-Transformers as a Workspace package on Azure Synapse Analytics
<p>I'm trying to install sentence-transformers python package as a workspace package for Azure Synapse Analytics.(To be used on Apache Spark Pool)</p> <p>Tried installing it through magic command <code>%pip install sentence-transformers</code> through a notebook and it works.</p> <p>Following the steps for uploading th...
<python><apache-spark><pip><azure-synapse><sentence-transformers>
2023-04-25 02:04:12
2
876
Haritha Thilakarathne
76,097,141
15,542,245
Why is a tuple with length=2 described as an 'int object' and therefore not iterable
<p>I have asked the question of ChatGPT, in Neeva, Google &amp; here. On SO there are a lot of similar questions but I can't relate any of them to my example.</p> <p>Small example that hopefully illustrates my problem:</p> <pre><code>import numpy as np # Small function that returns an array of values def npArrayReturn...
<python><arrays><loops>
2023-04-25 01:45:19
2
903
Dave
76,097,074
5,680,504
How to restore objects in s3 using pyspark
<p>I am trying to restore object which is in the glacier in s3 using Pyspark. After searching about it, I found that the code below works for my case, converting object from glacier to the standard class in s3.</p> <pre><code>import boto3 s3 = boto3.client('s3') bucket = 'bucket_name' key = 'object_name' response = s...
<python><amazon-web-services><amazon-s3><pyspark>
2023-04-25 01:17:25
1
1,329
sclee1
76,096,999
1,797,498
How to create a custom bullet-shaped gauge using Plotly?
<p>How to create a custom bullet-shaped gauge using Plotly?</p> <pre><code>import plotly.graph_objects as go fig = go.Figure( go.Indicator( mode = &quot;number+gauge+delta&quot;, gauge = {'shape': &quot;bullet&quot;, 'axis': {'range': [0, max]}, 'threshold': { 'l...
<python><plotly>
2023-04-25 00:50:30
0
1,385
J. Ceron
76,096,896
11,854,490
Scipy curve_fit RuntimeWarning: overflow encountered in exp
<p>I am trying to fit a function with two independent variables <code>a</code> and <code>k</code> to an exponential curve using scipy's <code>curve_fit</code>. I have defined the function and tried to calculate it like this:</p> <pre><code>print(np.min(x_data)) 1 print(np.max(x_data)) 44098 print(x_data.dtype) int64 pr...
<python><scipy>
2023-04-25 00:16:37
1
822
Christian Seitz
76,096,860
1,584,066
scrap 2 text values from html using python selenium chromedriver
<p>I have webdriver which filters most of the required fields which I need from a webpage, but I am stuck in this part. I have to get 61 and 70% from the below. Can someone please help. I have tried driver.find_element_by_xpath(&quot;//p[@class=&quot;stock-score tykr-score-box&quot;], but am lost in the text after that...
<python><selenium-chromedriver>
2023-04-25 00:07:09
1
426
SudipM
76,096,846
8,068,825
Python - Is it possible to get the init params of a Python class?
<p>So for example let's say I initialize a class like so</p> <pre><code>blah = SomeClass(a=10,b=20) </code></pre> <p>is it possible to get a dictionary of the initialization parameters and their values from <code>blah</code>? So like</p> <pre><code>get_init_params_and_values(blah) </code></pre> <p>should return {'a':10...
<python>
2023-04-25 00:02:07
1
733
Gooby
76,096,800
2,735,009
IndexError: pop from an empty deque while using map in Python
<p>I have the following piece of code in which I am trying to calculate sentence embeddings in parallel.</p> <pre><code>import multiprocessing from tqdm import tqdm # Define the function to be executed in parallel def process_data(chunk): results = [] for row in tqdm(chunk): work_id = row[1] me...
<python><machine-learning><nlp><multiprocessing><mapreduce>
2023-04-24 23:48:44
1
4,797
Patthebug
76,096,512
3,144,108
Bash fails to create venv (python3 -m ven venv) remotely via SSH
<p>I'm trying to create venv using &quot;python3 -m venv venv&quot; remotely. However, it fails:</p> <pre><code>&gt; ssh sv3-01 &quot;python3 -m venv venv&quot; Error: Command '['/home/ubuntu/venv/bin/python3', '-m', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1. </code></pre> <p>FYI:</p> ...
<python><python-3.x><bash><ssh><python-venv>
2023-04-24 22:22:05
1
525
uzla
76,096,409
5,583,772
Conditional assignment to multiple columns in polars
<p>How can I make a conditional assignment to multiple columns in polars if I have an external condition and a list of columns to assign to? In my example I have:</p> <pre><code>df = pl.DataFrame({'a':[0,1,2,3,4], 'b':[10,20,30,40,50], 'c':[100,200,300,400,500]}) </code></pre> <p>...
<python><python-polars>
2023-04-24 22:02:32
2
556
Paul Fleming
76,096,345
16,305,340
gaussian mixture model is inconsistent in its results using sklearn library
<p>so I am trying to segment a hand from an image using the Gaussian mixture model, so read <a href="https://www.iosrjournals.org/iosr-jece/papers/Conf.MAM-2019/Volume-1/6.%2037-41.pdf" rel="nofollow noreferrer">this paper (Hand Gesture Based Recognition And Voice Conversion System For Physically Disabled People)</a> w...
<python><image-processing><scikit-learn>
2023-04-24 21:48:24
1
1,893
abdo Salm
76,096,342
360,553
How to resolve "JSONDecodeError" when using LinkedIn API in Python?
<p>I'm trying to access the LinkedIn API in Python and I've been able to successfully obtain an access token and instantiate an <code>application</code> object using the <code>linkedin</code> library.</p> <pre><code># Set up LinkedIn API credentials and scope LINKEDIN_CLIENT_ID = &quot;myappclientid&quot; LINKEDIN_CLIE...
<python><json><linkedin-api>
2023-04-24 21:47:19
0
5,762
Claus
76,096,103
8,068,825
Remove n duplicates from Pandas DataFrame
<p>I'm trying to make a way to find duplicates and remove the last n duplicate rows so for example if I have</p> <pre><code>df = pd.DataFrame({ 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'], }) </code></pre> <p>and I want to remove 2 duplicates. It should return</p> <pre><code>df = pd.DataFrame({...
<python><pandas>
2023-04-24 21:06:29
2
733
Gooby
76,096,026
968,132
Using Mammoth style_map to apply inline styles and custom attributes
<p>I'd like to use Mammoth's style map to apply inline styles, like <code>color:red</code> and custom tags/attributes, though I cannot seem to find anything in <a href="https://github.com/mwilliamson/python-mammoth" rel="nofollow noreferrer">the docs</a> that suggest I can. Does mammoth have the capability to do inline...
<python><mammoth>
2023-04-24 20:53:01
1
1,148
Peter
76,095,955
6,929,343
python make sure () aren't passed in parameter
<p>I have a function that works fine if <code>()</code> isn't used in the function name:</p> <pre class="lang-py prettyprint-override"><code>answer = message.AskQuestion( self.loc_top, thread=self.refresh_play_top, align='left', icon='warning', title=&quot;Forget Location Confirmation&quot;, text=text) </code><...
<python>
2023-04-24 20:42:27
1
2,005
WinEunuuchs2Unix
76,095,579
2,954,547
Safely convert a Pandas datetime Series to Int64 epoch timestamp, preserving nulls
<p>Consider a datetime-dtype Series containing some null values:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd t = pd.date_range('2022-01-01', '2022-01-02', freq='4H').to_series('t') t.iat[2] = None </code></pre> <pre class="lang-none prettyprint-override"><code>2022-01-01 00:00:00 2022-01-...
<python><pandas><numpy><datetime><unix-timestamp>
2023-04-24 19:49:45
1
14,083
shadowtalker
76,095,574
14,875,027
Python Union Types with Objects
<p>I am writing my own classes for int, str, bool, etc. that have generators on them. I am using this to fuzz the function based on the type annotations. This is going fine, with the exception of the <code>|</code> notation for union type. If I type something like:</p> <pre><code>def test_handles_none_with_arged_types(...
<python><python-typing>
2023-04-24 19:49:11
1
370
dvr
76,095,455
21,420,742
Finding last value and second to last value In Python
<p>I have a dataset and would like to see that last and second to last person to hold the same position.</p> <p>Sample Data</p> <pre><code> ID Date Name Job Job_ID 101 01/2022 Adam Sales 1234 101 02/2022 Adam Sales 1234 101 03/2022 Adam Sales ...
<python><python-3.x><pandas><dataframe><numpy>
2023-04-24 19:33:39
3
473
Coding_Nubie
76,095,453
3,903,762
Unable to install and use R packages in Docker (along with Python)
<p>I am stuck on this issue and I am new to R.</p> <p>What is the <em>correct</em> way of installing R and Python within Docker? (general approach).</p> <p>I tried this to run Python and R in a Docker with these Dockerfiles (after checking multiple answers on SO):</p> <pre><code>FROM ubuntu:latest ENV DEBIAN_FRONTEND=...
<python><r><docker>
2023-04-24 19:33:29
0
1,486
MANU
76,095,390
1,914,034
numpy - round columns to closest decimal value
<p>I have an array of floats of shape <code>(N,3)</code>. I would like to round the two first columns to the closest decimal values varing from 1 to 0 which is derived from a parameter.</p> <p>I have already a solution, but I am wondering if there is a more efficient or &quot;numpy&quot; way to achieve it.</p> <p>For i...
<python><numpy>
2023-04-24 19:23:20
1
7,655
Below the Radar
76,095,388
2,989,642
pandas: how to get pandas.compare() to return all columns of the other row?
<p>With dataframes <code>df_a</code> and <code>df_b</code>, how do I return the difference (meaning, the data in <code>other</code> at variance with <code>self</code>) as complete rows (e.g., all columns)? If I do</p> <pre><code>first = { 'Name': ['Bob', 'Mike', 'Alex'], 'Job': ['Forklift Operator', 'Forklift ...
<python><pandas>
2023-04-24 19:23:10
2
549
auslander
76,095,343
18,189,817
How do I descriptively debugprint objects of custom classes in Python? (Like Rust’s derive(Debug))
<p>I have been working in both Python and Rust for quite a while now, and have started to get irritated about python’s lack of a proper default <code>__repr__</code>. (or, as I understand <code>__repr__</code> is not supposed for default printing: a good human-redable, debug oriented representation.)</p> <p>By default,...
<python><python-3.x><debugging><printing>
2023-04-24 19:15:16
0
579
Egeau
76,095,267
1,096,660
How to do type checking while using Django?
<p>There are linters that support type checking, however they become a mess in a Django project. Is there any way to have type checking for where I define type hints, but not do it for all the Django bits and pieces?</p> <p>I'm using Conda and VS Code.</p>
<python><django>
2023-04-24 19:04:44
1
2,629
JasonTS
76,095,123
881,411
pytest how to exit only on error not on failure
<p>Similar to <a href="https://stackoverflow.com/questions/36804181/long-running-py-test-stop-at-first-failure">this question</a>, except desiring to exit only on errors encountered, not on failures.</p> <p>In theory, this would be useful because:</p> <ul> <li>A &quot;failed&quot; test indicates something wrong with th...
<python><unit-testing><pytest>
2023-04-24 18:44:54
0
1,192
Jon