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,334,862
1,436,800
How to use an API-provided proxy with rotating proxy middleware in Scrapy?
<p>I'm trying to scrape websites using Scrapy and want to use an API-provided proxy with the rotating proxy middleware. The proxy is provided by an API endpoint that returns a new proxy IP with each request. I have already installed the scrapy-rotating-proxies package and configured it with the rotating proxy list in t...
<python><proxy><scrapy>
2023-05-25 17:23:33
1
315
Waleed Farrukh
76,334,816
3,911,443
Dynamically add tab in Textual
<p>In <a href="https://textual.textualize.io/" rel="nofollow noreferrer">Textual</a> I'm trying to dynamically add a tab to an application. Here's the full code:</p> <pre><code>from textual import on from textual.app import App, ComposeResult from textual.widgets import DataTable, Select from textual.widgets import Fo...
<python><textual>
2023-05-25 17:17:51
1
390
pcauthorn
76,334,787
7,655,687
Python given dict of old index: new index move multiple elements in a list
<p>In Python 3 what would be the best way to move multiple potentially non-contiguous elements to new potentially non-contiguous indexes given a <code>dict</code> of <code>{old index: new index, old index: new index, old index: new index}</code></p> <p><strong>Important Note</strong>: the <code>dict</code> may not cont...
<python><python-3.x><list>
2023-05-25 17:14:18
2
2,005
ragardner
76,334,733
2,010,880
How can I avoid main plot stopping when closing a second figure?
<p>I have a small python script that displays a Matplotlib plot. This main plot is continously updated in a loop. In this plots figure, I have a button that when pressed, executes a callback that opens a second plot in a figure. The main plot continues to update like expected while this second &quot;Pop up&quot; figure...
<python><matplotlib><user-interface><button><callback>
2023-05-25 17:07:12
0
302
Diarmaid O Cualain
76,334,702
8,442,560
How to get the integer value out of a string that might not always contain a number
<p>I have a list comprehension which now contain this hillarious list comprehension below.</p> <pre><code>[int([y or 0 for y in [&quot;&quot;.join(re.findall(r'[0-9*]', x))]][0]) for x in [acc['id_number']]][0] </code></pre> <p>The <code>int</code> function in python is not that effective.</p> <p>The issue is I wish th...
<python>
2023-05-25 17:03:36
2
652
surge10
76,334,678
11,665,178
StringParam not working in python Cloud Function Gen2 for global vars
<p>I am using the new Cloud Function gen 2 in python and following this <a href="https://firebase.google.com/docs/functions/config-env?gen=2nd" rel="nofollow noreferrer">guide</a> and this code sample :</p> <pre><code>from firebase_functions import https_fn from firebase_functions.params import IntParam, StringParam M...
<python><firebase><google-cloud-functions>
2023-05-25 17:00:13
2
2,975
Tom3652
76,334,532
1,714,385
How to fix ConvergenceWarning in Gaussian process regression in sklearn?
<p>I am trying to use fit a sklearn Gaussian process regressor to my data. The data has periodicity but no mean trend, so I defined a kernel similarly to the <a href="https://scikit-learn.org/stable/auto_examples/gaussian_process/plot_gpr_co2.html" rel="nofollow noreferrer">tutorial on the Mauna Loa data</a>, without t...
<python><scikit-learn><gaussian-process>
2023-05-25 16:41:12
1
4,417
Ferdinando Randisi
76,334,511
9,731,347
Seaborn convert BarPlot to histogram-like chart
<p>I have a pandas <code>DataFrame</code> that looks like this, and I'm using it to graph the life of a character over period of days. The <code>days</code> column is really &quot;days since birth.&quot; For this example, the character was born on May 26th, 2023.</p> <pre><code> days health months 0 0 30 ...
<python><pandas><matplotlib><seaborn>
2023-05-25 16:37:27
2
1,313
SanguineL
76,334,453
12,884,304
Install private gitlab package with specific version
<p>I have private gitlab package. His current version == 0.2.15</p> <p>I am build and publish package with poetry. Always I install package as</p> <p><code>pip install sdk --index-url https://__token__:&lt;token&gt;@gitlab.example.com/api/v4/projects/6/packages/pypi/simple</code></p> <p>I need to install specific versi...
<python><pip><gitlab><pypi><python-poetry>
2023-05-25 16:30:04
1
331
unknown
76,334,452
4,931,657
How to append additional tasks in asyncio.as_completed(task_list)
<p>I have a coroutine function to fetch results from a URL:</p> <pre><code>async def create_task_form_url(aio_session, form_url: str) -&gt; [Future]: loop = get_running_loop() task = loop.create_task(async_get_results(form_url, aio_session)) return task </code></pre> <p>I'm trying to create the initial task...
<python><python-asyncio>
2023-05-25 16:29:40
2
5,238
jake wong
76,334,295
8,895,744
Python regex, one word with n characters followed by two words with one char
<p>I need to filter strings that start with a word containing 3 or more characters, followed by exactly two words that have only one character. After these three words, anything can follow.</p> <p>What I tried is this expression:</p> <pre><code>pattern = r'\w{3,}\s\w\s\w.*' </code></pre> <p>but it matches a string <cod...
<python><pandas><regex>
2023-05-25 16:05:38
1
563
EnesZ
76,334,289
2,422,125
model.fit calculates validation only once after validation_freq train epochs and then never again
<p>First: I'm not able to provide any code - if that's enough reason to close this - so be it.</p> <p>The codebase I was provided is confidential and I was not able to reproduce this behavior in a standalone example after multiple hours of work. It's too much custom code that I barely understand which makes isolating s...
<python><tensorflow><keras>
2023-05-25 16:05:05
1
3,868
Fabian N.
76,334,272
4,404,805
Pandas: Apply function to each group and store result in new column
<p>I have an item dataframe such as:</p> <pre><code>item_df = pd.DataFrame({'BarCode': ['12345678AAAA', '12345678BBBB', '12345678CCCC', '12345678ABCD', '12345678EFGH', '12345678IJKL', '67890123XXXX', '67890123YYYY', '67890123ZZZZ', ...
<python><pandas><function><group-by><apply>
2023-05-25 16:02:39
1
1,207
Animeartist
76,334,209
1,424,729
Connections leak from a Psycopg connection pool
<p>Connections leak with resulting timeout error at the connection get. I am using connection pool configured as follows:</p> <pre><code>from psycopg_pool import ConnectionPool pool = ConnectionPool(conninfo=config['postgres']['url']) @atexit.register def pool_close(): pool.close() </code></pre> <p>Then I use the...
<python><psycopg3>
2023-05-25 15:55:38
3
749
Dmitry
76,334,048
15,637,940
ResourceWarning: unclosed socket.socket using unittest.IsolatedAsyncioTestCase
<p>Very similar problem described in another question and have <a href="https://stackoverflow.com/a/54612520/15637940">good answer</a>, but didn't help to solve the problem.</p> <p>I wrote <code>Scraper</code> class which support async context manager. <code>COUNT_OF_TESTS</code> is defining number of methods which wil...
<python><unit-testing><python-unittest>
2023-05-25 15:38:24
0
412
555Russich
76,334,025
13,534,060
Accessing default value of decorator argument in Python
<p>I am trying to write a custom Python decorator which wraps the decorated function in a <code>try ... except</code> block and adds a message with additional context to make debugging easier.</p> <p>Based on different resources (see <a href="https://www.geeksforgeeks.org/decorators-with-parameters-in-python/" rel="nof...
<python><python-decorators>
2023-05-25 15:35:28
1
851
henhesu
76,333,958
10,266,106
Applying np.linspace to Multi-Dimensional Array
<p>I have a multi-dimensional Numpy array of the following size:</p> <pre><code>(1200,2600,200) </code></pre> <p>At each point <code>i, j</code>, there is an assortment of unordered data which vary at each point. I'm performing some analyses which require the use of evenly spaced numbers with size 200. My current appro...
<python><arrays><numpy><numpy-ndarray>
2023-05-25 15:26:56
1
431
TornadoEric
76,333,954
254,725
Geopandas: overlay(how="union") can't handle more than one geometry columns
<p><strong>Goal:</strong> Merge country polygons from Natural Earth with the disputed areas. So that I have undisputed and disputed areas in one geodataframe</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code> import geopandas as gpd gpd.read_file(&quot;ne_50m_admin_0_countries.shp&quot;...
<python><geopandas>
2023-05-25 15:26:29
1
956
Jonas
76,333,507
4,954,037
Inherit/subclass from `tuple` with correct indexing and slicing
<p>i am trying to sublass <code>tuple</code> and make <code>mypy</code> happy in the process. i would like to make slicing and indexing work.</p> <p>here is what i have tried:</p> <pre><code>from functools import singledispatchmethod from typing import Iterable class MyIntTuple(tuple[int, ...]): def __new__(cls, ...
<python><python-3.x><mypy>
2023-05-25 14:39:28
3
47,321
hiro protagonist
76,333,373
20,266,647
MLRun, ErrorMessage, No space left on device
<p>I got this error during ingest data to FeatureSet:</p> <pre><code>Error - Failed to save aggregation for /k78/online_detail/nosql/sets/on line_detail/0354467518.ed74fc2b Response status code was 400: b'{\n\t&quot;ErrorCode&quot;: -28,\n\t&quot;ErrorMessage&quot;: &quot;No space left on device&quot;\n} Update expres...
<python><health-check><feature-store><mlrun>
2023-05-25 14:25:07
1
1,390
JIST
76,333,357
1,096,660
How to choose template in DetailView based on a field of the model shown?
<p>I have a model with a choice field:</p> <pre><code>type = models.CharField(choices=TYPE_CHOICES, max_length=1, default=UNSET, db_index=True) </code></pre> <p>Depending on the type I'd like to show a different template in the class based DetailView:</p> <pre><code>class AlbumDetailView(Det...
<python><django><django-views>
2023-05-25 14:23:23
1
2,629
JasonTS
76,333,327
4,439,753
Modifying a numpy array from multiple processes without locks
<p>I have a big <em>numpy.array</em> shared across multiple processes (created using <em>pool.map</em>), and I want each process to modify a different part of the array. Since there is no 2 processes that can modify the same part of the array, I can get away without using any locks, and therefore without slowing down t...
<python><numpy><multiprocessing><python-multiprocessing>
2023-05-25 14:20:07
1
4,761
Neabfi
76,333,028
7,945,506
LGBM model: What could cause varying results with fixed seed?
<p>I train a LightGBM model with the following Python code:</p> <pre class="lang-py prettyprint-override"><code>import lightgbm as lgb # Set parameters params = { &quot;objective&quot;: &quot;regression&quot;, &quot;num_leaves&quot;: 16, &quot;learning_rate&quot;: 0.05, &quot;feature_fraction&quot;: 0....
<python><lightgbm>
2023-05-25 13:49:07
1
613
Julian
76,333,004
8,869,570
Why do absolute imports not work in this circular dependency case?
<p>I have a circular dependency problem. In the direction <code>/path/to/src</code>, there are 2 files <code>a.py</code> and <code>b.py</code>.</p> <p>In <code>a.py</code>, there is a</p> <pre><code>from . import b </code></pre> <p>and in <code>b.py</code>, there is a</p> <pre><code>from . import a </code></pre> <p>So ...
<python><circular-dependency>
2023-05-25 13:45:55
0
2,328
24n8
76,332,990
7,437,143
"Callable[list, Dict]: has too many arguments in its declaration; expected 2 but 3 argument(s) declared" when using Typeguard runtime type checker
<h2>Context</h2> <p>The (typed) <code>get_next_actions</code> function below returns a (typed) function, called <code>actions_0</code> (or None). The <code>actions_0</code> function takes in 3 arguments, and returns a Dict.</p> <pre class="lang-py prettyprint-override"><code>from typing import TYPE_CHECKING, Callable, ...
<python><python-typing><callable>
2023-05-25 13:44:59
0
2,887
a.t.
76,332,844
11,645,617
Django serve views asynchronously
<p>Django 3.2.8 (a relatively old version)</p> <pre class="lang-py prettyprint-override"><code>@csrf_exempt def xhrView(request, ms, status=200): sleep(ms / 1000) response = HttpResponse( f'{status} DUMMYXHRRESPONSE IN {ms}ms' ) response['Access-Control-Allow-Origin'] = '*' response.status_c...
<python><django><python-asyncio><coroutine><asgi>
2023-05-25 13:28:33
0
3,177
Weilory
76,332,840
1,136,512
Scrapy: select last decendant node?
<p>I have a <code>dict</code> with selectors which I use to get data:</p> <pre><code>for key, selector in selectors.items(): data[key] = response.css(selector).get().strip() </code></pre> <p>One of the selectors is <code>span::text</code>, but sometimes the text is wrapped in an additional <code>a</code> tag. My so...
<python><scrapy><selector>
2023-05-25 13:28:24
1
899
bur
76,332,802
9,182,743
Plotly: difference between fig.update_layout({'yaxis': dict(matches=None)}) and fig.update_yaxes(matches=None)
<p>I am trying to work out the difference between:</p> <ul> <li><code>fig.update_layout({'yaxis': dict(matches=None)})</code></li> <li><code>fig.update_yaxes(matches=None)</code></li> </ul> <p>I thought they were the same, but <code>fig.update_layout({'yaxis': dict(matches=None)})</code> doesn't change the yaxis as exp...
<python><plotly><axis>
2023-05-25 13:24:10
1
1,168
Leo
76,332,782
17,200,348
Measuring Top-1 and Top-5 Accuracy using TensorFlow Model Garden
<p>I've been using the <a href="https://github.com/tensorflow/models" rel="nofollow noreferrer">TensorFlow Model Garden</a> to train a set of models on custom datasets that I've created for image classification. Now that it's time to evaluate them, I've run into an issue when trying to measure the top-k accuracies of m...
<python><tensorflow><tensorflow-model-garden>
2023-05-25 13:21:31
1
1,629
B Remmelzwaal
76,332,407
687,739
Rendered Liquid template to Python dict
<p>I have the following Liquid template:</p> <pre><code>{%- capture vars -%} {%- capture articleHeadline -%}This is the article of the headline{%- endcapture -%} {%- capture intro -%} Introduction to the document {%- endcapture -%} {%- capture articleHighlights -%} Step 1: Get up Step 2: Go to kitchen Step 3...
<python><liquid>
2023-05-25 12:44:08
1
15,646
Jason Strimpel
76,332,295
8,101,253
How do I run python code on each task in Airflow
<p>I have a sequence of Tasks on my DAG</p> <p>eg.</p> <pre><code>task1 &gt;&gt; task2 &gt;&gt; task3 </code></pre> <p>What I need is to put across the tasks functionality without repeating code. For example logging, would like to execute log.info(task_id) per task Or some external operation, like http call per task</p...
<python><airflow><airflow-2.x>
2023-05-25 12:30:55
1
1,091
Panos K
76,332,293
11,665,178
How to change cloud function parameters when deploying python gen2?
<p>I am writing Firebase Cloud Function in python using the new <a href="https://firebase.google.com/docs/functions/get-started?gen=2nd" rel="nofollow noreferrer">&quot;Firebase way&quot;</a>.</p> <p>I would like to be able to set the <code>region</code> and memory for the function when i deploy them, in Node JS this i...
<python><firebase><google-cloud-functions>
2023-05-25 12:30:44
1
2,975
Tom3652
76,332,198
192,923
aiobotocore - AttributeError: 'ClientCreatorContext' object has no attribute 'send_message'
<p>I have a working application that interacts with SQS using python 3.6 and I am required to upgrade the same to Python3.8. Locally, I am using elasticmq as part of the development.</p> <p>I have a SQSWrapper class that initializes queues and associates sqs_client with each queue. So if I have 10 queues, I will be cre...
<python><aws-cli><amazon-sqs><python-3.8><botocore>
2023-05-25 12:18:45
0
5,527
nimi
76,332,142
11,052,072
Install Python packages from tar.gz or .whl in GCP Composer
<p>I need to install some packages in a GCP Composer environment directly from a tar.gz or .whl file. In a normal environment I can just use <code>pip install https://url.to.package/package.whl</code> but Composer seems to not allow this.</p> <p>Checking the documentation (<a href="https://cloud.google.com/composer/doc...
<python><google-cloud-platform><google-cloud-composer>
2023-05-25 12:11:11
1
553
Liutprand
76,331,894
2,960,978
Custom FastAPI middleware causes LocalProtocolError("Too much data for declared Content-Length") exception
<p>I have a middleware implemented for FastAPI. For responses that includes some content, it works perfectly. But if a response has no body, it is causing <code>LocalProtocolError(&quot;Too much data for declared Content-Length&quot;)</code> exception.</p> <p>To isolate the problem, I've reduced the middleware class to...
<python><fastapi><middleware><starlette>
2023-05-25 11:43:41
1
1,460
SercioSoydanov
76,331,840
6,017,833
MongoDB schema optimisation for finding documents with foreign key in list
<p>I have the following two MongoDB database collections.</p> <p><code>races</code></p> <pre><code>{ &quot;_id&quot;: ..., (index) &quot;track&quot;: ..., &quot;distance&quot;: ..., &quot;timestamp&quot;: ..., ... &quot;runners&quot;: [ { &quot;horse_id&quot;: ..., ...
<python><database><mongodb><pymongo>
2023-05-25 11:37:04
0
1,945
Harry Stuart
76,331,812
20,770,190
Problem with updating an ENUM type in postgresql and alembic
<p>I have an issue with <code>ENUM</code> in postgresql and alembic and I couldn't resolve the problem using the existing topics in the StackOverflow in this regard.</p> <p>I had the following code:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.dialects.postgresql import ENUM from enum import Enum...
<python><postgresql><sqlalchemy><enums><alembic>
2023-05-25 11:33:44
2
301
Benjamin Geoffrey
76,331,512
1,334,752
How calculate an average value of the most recent events across groups in pandas dataframe?
<p>I have a pandas dataframe with events (timestamp, value, company id etc).</p> <p>EXAMPLE:</p> <pre><code> timestamp value name nusers 0 2023-06-01 10:46:11 -1 A 1000 1 2023-06-01 11:12:12 1 A 1000 2 2023-06-01 15:52:44 0 A 1000 3 2023-06-01 18:24:15 0 A 1000 4 2023-06-01 19:19:58 1 ...
<python><pandas>
2023-05-25 10:53:44
1
2,092
Philipp Chapkovski
76,331,447
9,536,103
Create count of categorical column 1 hour ahead and 1 hour behind current time
<p>I have a dataframe with two columns: <code>time_of_day</code> and <code>categorical column</code>. I want to count the number of values that have the same value in the <code>categorical_column</code> that are 1 hour ahead and 1 hour behind the current time:</p> <p>Example Input:</p> <pre><code>time_of_day c...
<python><pandas>
2023-05-25 10:46:22
2
1,151
Daniel Wyatt
76,331,409
2,354,908
Parse JSON string within dataframe and insert extracted information into another column
<p>I am trying to extract information from each cell in a row from a data frame and add them as another column.</p> <pre><code>import json import pandas as pd df_nested = pd.read_json('train.json') df_sample = df_nested.sample(n=50, random_state=0) display(df_sample) for index, row in df_sample.iterrows(): table_j...
<python><json><pandas><dataframe>
2023-05-25 10:41:51
1
1,270
Betafish
76,331,334
5,618,251
How to make a boxplot in using month as x-axis and data as y-axis
<p>I have the following datasets (see below).</p> <pre class="lang-py prettyprint-override"><code>import numpy as np date_month =\ np.array([ 4, 5, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
<python><matplotlib><boxplot>
2023-05-25 10:34:18
1
361
user5618251
76,331,220
10,981,411
using python to open my excel and save and close
<p>The code works fine, the only issue is the excel.Visible = False works fine on my colleague's laptops but doesnt on mine. Also I think there is same issue with excel.DisplayAlerts = False.</p> <p>any reason why this is happening?</p> <p>below are my codes</p> <pre><code>import win32com.client as win32 excel = win32....
<python><win32com>
2023-05-25 10:19:38
0
495
TRex
76,331,183
9,848,968
Python List Comprehension: Add n specific elements after each element in a list
<p>I would like to add <code>n</code> specific elements after each element in a list using only list comprehension.</p> <p>Example:</p> <p><code>l = [A, B, C, D, E]</code></p> <p><code>element = ''</code></p> <p>for <code>n = 1</code> should result in</p> <p><code>l = [A, '', B, '', C, '', D, '', E, '']</code></p> <p>o...
<python><list-comprehension>
2023-05-25 10:15:02
3
385
muw
76,331,049
7,965
ruamel.yaml anchors with Roundtriploader/Roundtripdumper
<p>I am trying to load below example yaml file using the ruamel.yaml python package.</p> <pre><code>- database: dev_db &lt;&lt;: &amp;defaults adapter: postgres host: localhost username: postgres password: password - database: test_db &lt;&lt;: *defaults - database: prod_db &lt;&lt;: *defaults ...
<python><ruamel.yaml>
2023-05-25 09:59:24
1
9,317
Sirish Kumar Bethala
76,330,816
9,454,531
Why is my Python file watcher not writing the data from Parquet files to a data frame?
<p>I have written a file watcher in Python that will watch a specific folder in my laptop and whenever a new parquet file is created in it, the watcher will pull it and read the data inside using Pandas and construct a data frame from it.</p> <p><strong>Issue:</strong> It does all those activities with perfection excep...
<python><pandas><jupyter-notebook><parquet><watchdog>
2023-05-25 09:32:40
1
317
Arnab Roy
76,330,770
7,847,906
Creating a PDF file from a folder structure containing images
<p>I am looking for a way to generate a PDF from a Folder with several pictures.</p> <p>I have many pictures like this:</p> <pre><code>folder1/ Image1.jpg Image2.jpg ...... folder2/ img1.jpg pict.jpg name1.jpg </code></pre> <p>I am looking for a way where we can automatically generate a PDF using the name of the pict...
<python><windows><pdf-generation>
2023-05-25 09:27:26
1
347
maxasela
76,330,655
13,086,128
AttributeError: module 'numpy' has no attribute 'complex'
<p>I am trying to make a real number complex using numpy. I am using numpy version <code>1.24.3</code></p> <p>Here is the code:</p> <pre><code>import numpy as np c=np.complex(1) </code></pre> <p>However, I get this error:</p> <pre><code>AttributeError: module 'numpy' has no attribute 'complex'. </code></pre>
<python><python-3.x><numpy><complex-numbers>
2023-05-25 09:14:48
1
30,560
Talha Tayyab
76,330,509
17,718,870
Unexpected module object on Runtime Execution
<p>I have two modules mod1.py and mod2.py. In the first one i have the following code:</p> <pre><code># mod1.py # ------- import inspect def get_module_object(): curr_frame = inspect.currentframe() return inspect.getmodule(curr_frame) # ======================================= # mod2.py # ------- from mod1 i...
<python>
2023-05-25 08:57:57
0
869
baskettaz
76,330,456
7,257,089
Slow responses using Using Google Cloud Run, FastAPI and the Meta Whatsapp API
<p>This is quite a sepcific problem but I'm wondering if anyone else has encountered it. I'm using the Whatsapp Cloud API (<a href="https://developers.facebook.com/docs/whatsapp/cloud-api/" rel="nofollow noreferrer">https://developers.facebook.com/docs/whatsapp/cloud-api/</a>) for a question-answer chatbot. These messa...
<python><fastapi><whatsapp><google-cloud-run>
2023-05-25 08:50:46
1
372
millsy
76,330,421
9,370,733
Specifying a different input type for a Pydantic model field (comma-separated string input as a list of strings)
<p>Using Pydantic, how can I specify an attribute that has an input type different from its actual type?</p> <p>For example I have a <code>systems</code> field that contains a list of systems (so a list of strings) and the user can provide this systems list as a comma separated string (e.g. <code>&quot;system1,system2&...
<python><python-3.x><pydantic>
2023-05-25 08:47:34
2
684
cylon86
76,330,146
8,930,395
FastAPI: AttributeError: 'myFastAPI' object has no attribute 'router'
<p>I have created a child class and inherited FastAPI class. I want to define a function lifespan inside it. To implement lifespan I need to create constructor inside myFastAPI class. Below is sample code.</p> <pre><code>class myFastAPI(FastAPI): def __init__(self): self.lifespan = self.lifeSpan @asyn...
<python><fastapi><lifespan>
2023-05-25 08:08:01
1
4,606
LOrD_ARaGOrN
76,329,988
2,118,666
Why is asyncio.Future.done() not set to True when the task is done?
<p>In this example code a <code>asyncio.Future</code> is created and run. However the state is not set to done once it is complete.</p> <pre><code>import asyncio from concurrent.futures.thread import ThreadPoolExecutor from time import sleep _executor = ThreadPoolExecutor(max_workers=32) def test(): print('starti...
<python><asynchronous><python-asyncio>
2023-05-25 07:47:17
1
11,241
tread
76,329,949
2,366,887
I can't get the langchain agent module to actually execute my prompt
<p>I am learning how to use langchain and I have written a small exercise to try and figure out how agents work.</p> <p>I have a small Python program that looks like this:</p> <pre><code>import os from langchain.agents import load_tools ...
<python><langchain>
2023-05-25 07:42:39
2
523
redmage123
76,329,787
13,314,132
ConnectionError in connecting my python code which is in windows os to my hdfs which is in linux os
<p>I am new to using hdfs. I have stored couple of datasets there. Now I have a running code in Python which is in my local machine. I want to connect to the hdfs in the linux os in the code itself. I have gone through some of the documentations and have made the necessary changes to the code as follows:</p> <p>python-...
<python><hadoop><hdfs>
2023-05-25 07:22:45
0
655
Daremitsu
76,329,691
3,590,067
Python: how to reshape a list?
<p>I am trying to append 10 arrays to a list. The arrays have dimensions <code>(400,)</code> and I would like to have a list with shape, <code>shape(myList) = (10,)</code>, where each component has shape <code>(400,2)</code>, such as <code>shape(myList[0]) = (400,2)</code>.</p> <p>This is what I am doing:</p> <pre><co...
<python><arrays><list><numpy>
2023-05-25 07:07:35
2
7,315
emax
76,329,678
8,937,353
How to change color of a 3D scatter plot w.r.t. one value other than X,Y,Z
<p>I have 4 numpy arrays for X, Y, Z, and Values.</p> <pre><code>X= [20,30,50,60,..] Y= [25,35,55,65,...] Z= [5,6,7,8,...] Values = [-8,5,0.8,-1.2....] </code></pre> <p>All arrays are of the same size and the index of all arrays is matched. Eg. X[1],Y[1],Z[1],Values[1] all corresponds to same point.</p> <p>Based on X, ...
<python><numpy><matplotlib><numpy-ndarray><scatter-plot>
2023-05-25 07:06:09
1
302
A.k.
76,329,612
7,441,757
How to list poetry plugins in pyproject.toml?
<p>I've added a poetry plugin manually with <code>poetry self add xxx</code>, but I don't see any line changed in the pyproject.toml or poetry.lock. I want this plugin to be included in the development environment, so it needs to install when others set-up the environment. Can you add plugins to the <code>--dev</code> ...
<python><python-poetry>
2023-05-25 06:55:56
1
5,199
Roelant
76,329,602
7,788,402
How to join two pandas DataFrames on trailing part of path / filename
<p>I have two data Frames as follows.</p> <pre><code>df1 = pd.DataFrame({'PATH':[r'C:\FODLER\Test1.jpg', r'C:\A\FODLER\Test2.jpg', r'C:\A\FODLER\Test3.jpg', r'C:\A\FODLER\Test4.jpg'], 'VALUE':[45,23,45,2]}) df2 = pd...
<python><pandas><merge>
2023-05-25 06:54:18
2
2,301
PCG
76,329,584
4,616,611
PySpark: Most efficient way to query from DB for a specific set of ids from an existing data frame
<p>I have a PySpark dataframe with these fields: ID1, ID2 and DATE. For each ID1, ID2, and DATE I need to write an SQL statement to extract a new field where I include ID1, ID2 and DATE in the WHERE clause.</p> <p>What's the most efficient way to code this?</p> <p>My idea at the moment is to extract ID1, ID2 and DATE f...
<python><apache-spark><pyspark>
2023-05-25 06:50:27
1
1,669
Teodorico Levoff
76,329,489
2,966,197
streamlit app only executing successfully for one cycle and hanging after that
<p>I have <code>streamlit</code> app where on the sidebar I have following sections:</p> <pre><code>1. File uploader 2. 3 buttons - Submit, reset, add new row 3. Row(s) of input text area in Key value manner </code></pre> <p>Now at first there is only single row of point 3 when the app initiates, user enters key and va...
<python><streamlit>
2023-05-25 06:33:26
1
3,003
user2966197
76,329,365
10,003,538
How to add more param to Serialization Model for using at to_presentation
<p>Here is my so</p> <pre><code>class DataFieldSerializer(serializers.ModelSerializer): class Meta: model = DataField fields = [&quot;field&quot;, &quot;topic&quot;, &quot;category&quot;, &quot;group&quot;, &quot;alias&quot;, &quot;units&quot;] def __init__(self, *args, **kwargs): self...
<python><django>
2023-05-25 06:07:58
1
1,225
Chau Loi
76,329,232
1,660,529
Pyspark throwing task failure error while initializing new column with UDF
<p>I have this spark dataframe:</p> <pre><code>+--------------------+--------------------+------+ | qid| question_text|target| +--------------------+--------------------+------+ |403d7d49a9713e6f7caa|Do coconut trees ...| 0| |edc9a2709785501cce09|What are 5 must-r...| 0| |c912510d490de9e8c...
<python><apache-spark><pyspark><user-defined-functions>
2023-05-25 05:43:24
1
321
Alex_ban
76,329,199
10,982,755
How do I update Big Query partition expiration using Python BigQuery Client?
<p>We are currently looking to clean up old Big Query data. While creating the dataset, tables and partitions, we did not update the expiration time until recently. So the old partitions do not have expiration time set. Only the newly created tables and partitions have expiration.</p> <p><a href="https://cloud.google.c...
<python><google-bigquery>
2023-05-25 05:35:40
1
617
Vaibhav
76,328,921
14,109,040
Python group by columns and make sure values in group doesn't skip values in order of another dataframe
<p>I have 2 dataframes with the following structures:</p> <pre><code>df1 Group1 Group2 Label G1 A1 AA G1 A1 BB G1 A1 CC G1 A2 AA G1 A2 CC G2 A1 BB G2 A1 DD G2 A2 AA G2 A2 CC G2 A2 DD G2 A2 BB df2 ID Label_ref 1 AA 2 BB 4 CC 5 ...
<python><pandas><group-by>
2023-05-25 04:21:15
1
712
z star
76,328,903
1,872,234
Resample dataframe to add missing dates
<p>I have a dataframe with multiple string columns, one date column and one int value column.</p> <p>I want to <code>ffill</code> the missing dates for each group of text columns. The missing dates are all dates from the min date to max date in the dataframe. I think this is better explained using an example.</p> <p>Sa...
<python><pandas><dataframe>
2023-05-25 04:17:48
2
1,643
Wajahat
76,328,852
1,718,174
Unable to get typer autocompletion working
<p>Fairly new to typer and trying to get a simple CLI application to auto-complete with [TAB] on my terminal, but without success. Here is my code structure and code itself:</p> <pre><code>vinicius.ferreira@FVFFPG4VQ6L4 dev-env % tree . ├── README.md ├── dev_env │   ├── __init__.py │   ├── main.py │   ├── services.py │...
<python><autocomplete><command-line-interface><typer>
2023-05-25 04:03:06
1
11,945
Vini.g.fer
76,328,830
16,136,190
Can you import a class from a sub-directory (from library.directory import subdirectory.class)?
<p>Can you import a class from a sub-directory like <code>from library.directory import subdirectory.class</code>?</p> <p>Let's take Selenium as an example. Its file structure is like this:</p> <p><code>selenium</code></p> <ul> <li><code>webdriver</code> <ul> <li><code>support</code> <ul> <li><code>ui</code> <ul> <li>w...
<python><python-3.x><syntax-error><python-import>
2023-05-25 03:57:31
1
859
The Amateur Coder
76,328,764
8,968,910
Python: Cannot find the right encoding to print Tableau result
<p>I want to print the result of crosstabs from Tableau worksheet, it contains some Tranditional Chinese words in it.</p> <pre><code>import sys sys.stdout.reconfigure(encoding='utf-8') . . . view_data_raw = querying.get_view_data_dataframe( conn, view_id=visual_c_id) print(view_data_raw.to_string()) #A print(view_d...
<python><unicode>
2023-05-25 03:36:47
1
699
Lara19
76,328,606
10,964,685
Count of unique days grouped by value - pandas
<p>I'm aiming to assign a cumulative count of unique days to a new column in a pandas df. It should count the number of unique days, gathered from <code>Date</code>, grouped by <code>Code</code> and <code>Item</code>. Once consecutive values in <code>Code</code> or <code>Item</code> are broken, the count should reset t...
<python><pandas>
2023-05-25 02:52:42
1
392
jonboy
76,328,503
1,467,079
How to set a stoploss in vectorbt based on the number of ticks or price per contract
<p>There's an options to add <code>tp_stop</code> or <code>sl_stop</code> on <code>vbt.Portfolio.from_signals</code> which is percent based.</p> <blockquote> <p>sl_stop : array_like of float Stop loss. Will broadcast.</p> <p>A percentage below/above the acquisition price for long/short position. Note that 0.01 = 1%.</p...
<python><python-3.x><vectorbt>
2023-05-25 02:24:55
1
653
ralphinator80
76,328,441
6,550,894
Regex to remove captions with condition not to overlap second match
<p>I have the following string, which I extract from a pdf:</p> <pre><code>This is Fig. 13: John holding his present and the flowers Source: official photographer a beautiful Table: a table of some kind and fully complete Table: John holding his present and Source: official photographer sentence </code></pre> <p>The te...
<python><regex>
2023-05-25 02:08:11
1
417
lorenzo
76,328,191
851,699
Tensorflow in Pyinstaller on MacOS. Saving model fails with TensorShapeProto error
<p>I have a simple test script that just saves and loads a tensorflow model.</p> <p>I passes when run from python on my system. But fails to load the model when I run it from a pyinstaller package, it fails with <code>TypeError: Parameter to MergeFrom() must be instance of same class: expected tensorflow.TensorShapePr...
<python><macos><tensorflow><conda><pyinstaller>
2023-05-25 00:33:18
1
13,753
Peter
76,328,171
13,538,030
Interpret one Python function
<p>Could you please help me to interpret the meaning of this function, and the way to use it? Thank you.</p> <pre><code>def isNaN(num): return num != num </code></pre>
<python>
2023-05-25 00:27:25
1
384
Sophia
76,328,094
3,482,266
Adding a Postgresql datasource to Grafana. Plugin health check failed
<p>I'm using a grafana docker container, and a Postgresql docker container. I think I manage to add a data source to Grafana, however, the Plugin health check fails as in the picture below. Also, when I try to query I get a connection error...</p> <p>[![Bookmark Bar Switcher here.][1]][1]</p> <p>I've already checked, a...
<python><postgresql><logging><grafana>
2023-05-25 00:03:49
1
1,608
An old man in the sea.
76,328,026
1,267,218
Alexa Skill needs more than 8s for a Lambda to complete
<p>I'm using Alexa's Python libraries to write a Lambda that hits a couple of APIs. Sometimes, this takes more than 8s. That's when Alexa is set to timeout.</p> <pre class="lang-py prettyprint-override"><code>class CustomIntentHandler(AbstractRequestHandler): def can_handle(self, handler_input): # type: (Ha...
<python><alexa-skills-kit>
2023-05-24 23:40:37
1
513
Luke
76,328,007
512,480
Inconsistent highlighting of default button under tkinter?
<p>The following Python module is designed to be used from any tkinter-based program, to pop up a dialog in front of the parent window. Of particular interest is askquestion, a substitute for the built-in messagebox version which doesn't always appear on top when it needs to. Note the Yes button, which has default=&quo...
<python><tkinter><button>
2023-05-24 23:35:34
1
1,624
Joymaker
76,327,976
1,968,829
How can I efficiently merge these dataframes on range values?
<p>I have two dataframes:</p> <pre><code>section_headers = start_sect_ end_sect_ 0 0 50 1 121 139 2 221 270 sentences = start_sent_ end_sent_ 0 0 50 1 56 76 2 77 85 3 88 111 4 ...
<python><pandas><numpy><merge>
2023-05-24 23:24:44
1
2,191
horcle_buzz
76,327,919
16,988,223
Set first date of the year when only it has only the year in a pandas dataframe
<p>I have a column name called <code>date</code> in one pandas dataframe, this are the first 10 rows:</p> <pre><code>0 22-Oct-2022 1 3-Dec-2019 2 27-Jun-2022 3 2023 4 15-Jul-2017 5 2019 6 7-Sep-2022 7 2021 8 30-Sep-2022 9 17-Aug-2021 </code></pre> <p>I want convert a...
<python><pandas><dataframe><datetime>
2023-05-24 23:06:28
2
429
FreddicMatters
76,327,879
1,751,825
python jsonschema: Use "regex" module to validate "pattern"
<p>I'm trying to use jsonschema for a schema which uses &quot;pattern&quot;. However in this application, the &quot;pattern&quot; needs to be able to match unicode characters, which is not support by python's builtin &quot;re&quot; module.</p> <p>for example</p> <pre><code>import jsonschema import regex schema = { ...
<python><python-re><python-jsonschema><python-regex>
2023-05-24 22:54:27
0
4,337
user1751825
76,327,794
2,893,712
Pandas Join Rows If Time Is Continuous
<p>I have a pandas dataframe that shows when employees want to take time off. The Event Title is always in the format of &quot;User Off&quot; along with the specific time if it is not an all day event. Here is a snippet of the dataframe <code>df</code>:</p> <pre><code> Event Title Start End Emplo...
<python><pandas><dataframe>
2023-05-24 22:32:05
1
8,806
Bijan
76,327,775
12,454,639
Having Trouble finding the correct scope for my API request to Google Drive API
<p>This is likely just a matter of me not knowing how to find the correct scope but I need help all the same.</p> <pre><code>from google.oauth2 import service_account from googleapiclient.discovery import build import requests import pprint from dotenv import load_dotenv import os forcewinds_folder_url = 'fake-folder-...
<python><google-drive-api>
2023-05-24 22:27:26
1
314
Syllogism
76,327,749
6,357,916
What IP HAPROXY adds to the header?
<p>We need to specify the mode in the haproxy service description in docker compose file using long syntax:</p> <pre><code>services: haproxy: ports: # long port syntax https://docs.docker.com/compose/compose-file/compose-file-v3/#long-syntax-1 - target: 80 published: 97...
<python><docker><docker-compose><docker-swarm><haproxy>
2023-05-24 22:18:57
1
3,029
MsA
76,327,605
1,493,192
percent-encoded %2F fail request
<p>I have a dictionary that I pass as a parameter in request:</p> <pre><code>paylod = { 'latitude': 42.406747, 'longitude': 12.154226, 'timezone': 'Europe%2FBerlin', # encoding problem 'time_format': 'iso8601', 'temperature_unit': 'celsius', 'wind_speed_unit': 'ms', 'precipitation_unit...
<python><python-requests>
2023-05-24 21:46:36
2
8,048
Gianni Spear
76,327,478
4,117,496
Django template render a nested dict with tuples
<p>Here's my dict =</p> <pre><code>{ '123': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, '456': {'metric_1': [('url_1', 'caption_1'), ('url_2'...
<python><html><django><django-templates><nested-loops>
2023-05-24 21:21:33
1
3,648
Fisher Coder
76,327,461
6,069,586
Python asyncio REPL behavior vs normal REPL behavior
<p>I'm struggling to understand the difference between these two situations. In a script, I am getting TimeoutErrors from the below websockets.client.connect function, and I can replicate that behavior in a normal python REPL. However, it connects and works correctly in a python asyncio repl <a href="https://github.com...
<python><python-asyncio>
2023-05-24 21:18:46
1
1,223
JWCS
76,327,370
272,023
How to use FastAPI request state variable AND also body parameter when using fastapi-cache?
<p>I have a FastAPI POST endpoint which receives a parameter in the request body. A global FastAPI Depends sets a Request state value which I want to retrieve in my method.</p> <p>The following works fine:</p> <pre><code>from pydantic import BaseModel from fastapi import APIRouter, Request class MyPydanticValue(BaseM...
<python><fastapi>
2023-05-24 20:59:48
0
12,131
John
76,327,286
3,826,115
How to have only Points respond to mouse tap in Holoviews plot with Points and QuadMesh overlaid
<p>The following code generates an interactive plot with a scatter Point plot overlaid on a gridded QuadMesh plot.</p> <pre><code>import holoviews as hv import numpy as np import xarray as xr import pandas as pd hv.extension('bokeh') #create sample gridded data grid_x = np.linspace(0, 5, 10) grid_y = np.linspace(0, 5,...
<python><bokeh><holoviews>
2023-05-24 20:45:17
1
1,533
hm8
76,327,196
6,087,667
call concurrent futures from inside a function in another file
<p>How can I use parallel computing sitting inside a function in another file that is being imported?</p> <p>Here as an example I created a file scratch_tests.py</p> <pre><code>import concurrent.futures def g(): print(__name__) global f def f(x): return x**2 if __name__=='scratch_tests': ...
<python><parallel-processing><multiprocessing><concurrent.futures>
2023-05-24 20:28:02
1
571
guyguyguy12345
76,327,143
4,710,409
django-STATICFILES _DIRS not collecting
<p>In my django project settings, I defined my static files like so:</p> <pre><code>STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR + '/static' STATICFILES_DIRS = [ BASE_DIR +'/folder1', BASE_DIR + '/folder2', ] </code></pre> <p>But collectstatic doesn't collect what is defined in &quot;STATICFILES_DIRS&quot;.</...
<python><django><server><static><django-staticfiles>
2023-05-24 20:19:48
1
575
Mohammed Baashar
76,327,116
10,941,410
How to send logs from a python application to Datadog using ddtrace?
<p>Let's say that I have a python routine that runs periodically using <code>cron</code>. Now, let's say that I want to send logs from it to Datadog. I thought that the simples way to do it would be via Datadog's agent, e.g. using <code>ddtrace</code>...</p> <pre class="lang-py prettyprint-override"><code>import ddtrac...
<python><logging><datadog>
2023-05-24 20:15:32
2
305
Murilo Sitonio
76,326,916
8,367,943
Running R in an AWS Glue job
<p>Imagine you had a set of R scripts that form an ETL pipeline that you wanted to run as an AWS Glue job. AWS Glue supports Python and Scala.</p> <p>Is it possible to call an R as a Python subprocess (or a bash script that wraps a set of R scripts) within an AWS Glue job running in a container with Python and R depend...
<python><r><amazon-web-services><aws-glue>
2023-05-24 19:43:42
2
8,522
Rich Pauloo
76,326,571
525,865
getting data out of a website - using BS4 and request fails permanently - need another method now
<p>i am trying to scrape the data from the site <a href="https://www.startupblink.com" rel="nofollow noreferrer">https://www.startupblink.com</a> with beautiful soup, Pyhon and request</p> <pre><code>from bs4 import BeautifulSoup import requests url = &quot;https://www.startupblink.com&quot; response = requests.get(ur...
<python><pandas>
2023-05-24 18:47:45
1
1,223
zero
76,326,219
20,999,526
How to make changes in a built-in library file in chaquopy?
<p>I am facing a problem where I have to change a line in a built-in file in a particular library (installed using pip). I have located the file in</p> <blockquote> <p>app\build\pip\debug\common\&lt;library folder&gt;</p> </blockquote> <p>But every time I run the Gradle (for installing or creating APK), the entire fold...
<python><android><android-studio><pip><chaquopy>
2023-05-24 17:50:16
1
337
George
76,326,096
8,401,294
requests, urllib3 and CacheControl version downgrade to working in Poetry
<p><a href="https://github.com/urllib3/urllib3/releases" rel="nofollow noreferrer">https://github.com/urllib3/urllib3/releases</a> <code>2.0.0</code> - In this version, <code>strict</code> was removed.</p> <p>As instructed in the link: <a href="https://github.com/python-poetry/poetry/issues/7936" rel="nofollow noreferr...
<python><python-poetry>
2023-05-24 17:34:21
0
365
José Victor
76,326,080
5,924,264
unbound method __init__() error with python2 but not with python3
<p>This is related to my earlier question: <a href="https://stackoverflow.com/questions/76324839/unbound-method-init-error-in-unit-tests-but-not-in-regular-executions?noredirect=1#comment134593579_76324839">unbound method __init__() error in unit tests but not in regular executions</a></p> <p>I made a minimal reproduci...
<python><python-3.x><python-2.7><inheritance>
2023-05-24 17:32:03
1
2,502
roulette01
76,326,040
4,800,907
Azure Functions - BlobTrigger - How to trigger function with any file in a container?
<p>I'm facing a problem with an Azure Function.</p> <p>I've build an Azure Function triggered by a new file on a container of a storage account. The problem is that it seems impossible (to me) to trigger the function with a generic file, without specifing a name!</p> <p>I've searched on official documentation and it's ...
<python><azure><azure-functions><azure-blob-storage><event-driven>
2023-05-24 17:27:28
1
650
walzer91
76,325,736
926,837
Passing a new command to a Powershell Elevated instance using schtasks.exe in python using subprocess.run
<p>I'm trying to execute dynamically some powershell commands that require admin priviledges in my python application. But I'm facing problems to obtain the behaviour I want when stacking commands with <strong>subprocess.run</strong><br> So let's discuss the code:<br> This is an example command that requires admin priv...
<python><powershell><subprocess>
2023-05-24 16:38:58
1
301
Relok
76,325,688
7,657,180
Fix No module named 'openai_whisper'
<p>I have installed the package <code>openai_whisper</code> using this line</p> <pre><code>pip install openai-whisper </code></pre> <p>But when I used this line in the code <code>import openai_whisper</code>, I got an error <code>ModuleNotFoundError: No module named 'openai_whisper'</code>.</p> <p>I also tried this lin...
<python>
2023-05-24 16:31:40
1
9,608
YasserKhalil
76,325,661
3,231,250
how to extend background size in plotly
<p>I have added text-box beside to scatter plot.</p> <p>Since figure size is defined, I can not see text-box proparly. I would like to extend background and put text-box beside to scatter plot.</p> <pre><code>import plotly.graph_objects as go import plotly.express as px config = {'staticPlot': True} fig = go.Figure()...
<python><plotly>
2023-05-24 16:29:26
1
1,120
Yasir
76,325,603
1,607,057
Evaluating forward references with typing.get_type_hints in Python for a class defined inside another method/class
<p>I'm having trouble calling typing.get_type_hints() for classes that have forward references as strings. My code works with not defined inside of a function. I've reproduced a minimal example below in Python 3.10:</p> <pre class="lang-py prettyprint-override"><code>import typing class B: pass class A: some_b: &qu...
<python><python-typing>
2023-05-24 16:23:22
1
411
GoogieK