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
⌀
77,221,779
21,440,451
Azure Function deployment not using VS Code extension
<p>I am trying to deploy Azure Function performing a simple calculation. It is deployed successfully, because I can see <em>Your Functions 4.0 app is up and running</em>. My logic (<a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=python-v2%2Cisolated-process%...
<python><azure><azure-functions><azure-pipelines>
2023-10-03 11:17:44
1
492
danilo
77,221,619
5,359,846
How can I find pseudo element using Playwright?
<p>In my webpage I have some pseudo elements.</p> <p>For example:</p> <p><a href="https://i.sstatic.net/Crzsr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Crzsr.png" alt="enter image description here" /></a></p> <p>How can I find the ::after element using Playwright?</p>
<python><playwright><playwright-python>
2023-10-03 10:51:10
1
1,838
Tal Angel
77,221,564
4,986,615
Add mypy options --enable-incomplete-feature=Unpack in pyproject.toml
<p>I would like to use the experimental <code>typing.Unpack</code> in my project.</p> <p>In the CLI command, it works when adding <code>--enable-incomplete-feature=Unpack</code>.</p> <p>However, I have mypy issues reported by pyright (in neovim), therefore I would like to add this option in the section <code>mypy</code...
<python><mypy><pyproject.toml>
2023-10-03 10:44:31
1
2,916
guhur
77,221,352
3,445,378
How to freeze package version in requirements?
<p>I have installed the a Python Package with <code>pip install pyjwt[crypto]</code> and <code>pip freeze</code> shows me different packages that was installed by that action.</p> <p>What do I need to put in my <code>requirements.txt</code> to correctly freeze the versions I am developing with? I dont want to put to mu...
<python><pip><requirements.txt>
2023-10-03 10:11:46
2
1,280
testo
77,221,047
1,818,935
How to replace the Python interpreter of an existing venv virtual environment in VS Code?
<p>A couple days ago I created a <code>venv</code> virtual environment that uses the Python interpreter version 3.11.6. Now that a new Python version, 3.12.0, has been released, how can I replace the interpreter of my existing virtual environment by the new version? Or must I create a whole new virtual environment if I...
<python><visual-studio-code><python-venv>
2023-10-03 09:21:20
1
6,053
Evan Aad
77,221,003
7,216,834
For each row in a df, I want to calculate the sum of consecutive four values till last value in python?
<p>I have a df,</p> <pre><code> A B C D E F G 1 2 3 4 4 5 5 100 100 Na 100 100 10 5 </code></pre> <p>I want to create a df, that calculates the consecutive sum,that is 1+2+3+4 = D, 2+3+4+4 = E .... If na is there, the output should be na.</p> <p>O...
<python>
2023-10-03 09:13:41
1
1,325
Jennifer Therese
77,220,975
1,624,552
Check if http.client.HTTPSConnection instance returns a correct connection without errors
<p>Basically from Python I am creating an instance of http.client.HTTPSConnection from an url address which is the remote server url in order to download a remote file:</p> <pre><code>try: conn = http.client.HTTPSConnection(remoteServerUrl) conn.request(&quot;GET&quot;, remoteFile) # rest of code except Ex...
<python><https><httpclient>
2023-10-03 09:10:15
1
10,752
Willy
77,220,871
2,562,058
How to interpolate over a piecewise-constant set of points with scipy or numpy?
<p>I am having troubles in interpolating a set of piecewise-constant points. To better explain, consider the following code:</p> <pre><code>import numpy as np from scipy.interpolate import UnivariateSpline import matplotlib.pyplot as plt N = 30 Ts = 0.2 times = np.arange(0.0, N * Ts, Ts) signal = np.concatenate((1...
<python><numpy><scipy>
2023-10-03 08:53:24
1
1,866
Barzi2001
77,220,728
5,316,326
Pydantic accept integer as string input
<p>For a FastAPI Pydantic interface I want to be as tolerable as possible, such as receiving an integer for a string parameter and parse that integer to string:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class FooBar(BaseModel): whatever: str FooBar(whatever=12) </code>...
<python><python-3.x><fastapi><pydantic>
2023-10-03 08:30:23
2
4,147
Joost Döbken
77,220,509
14,954,262
Python Merge 2 DICT objects if matching id within a list with separators
<p>In Python I have those 2 dicts objects :</p> <pre><code>dict1 = [{'id_contact': '1', 'name': 'Rick'},{'id_contact': '9', 'name': 'John'}] dict2 = [{'id_company': ';1;3;4;11;', 'company_name': 'Nike'},{'id_company': ';1;2;9;', 'company_name': 'Adidas'}] </code></pre> <p>I would like to merge those 2 dicts to a new o...
<python><dictionary><merge><match><partial>
2023-10-03 07:48:48
2
399
Nico44044
77,220,394
11,479,825
Llama2 returns multiple [INST] '''json {"action":, "action_input":} answers
<p>I have cloned <a href="https://github.com/PromtEngineer/localGPT" rel="nofollow noreferrer">localGPT</a> and switched to YanaS/llama-2-7b-langchain-chat-GGUF from HuggingFace. The model returns multiple answers instead of just one:</p> <pre><code>Question: {{question}} Answer: ```json {&quot;action&quot;: &quot;Fi...
<python><prompt><llama>
2023-10-03 07:26:33
0
985
Yana
77,220,106
1,832,566
Stream from a google storage signed url to another google storage bucket with Python
<p>I get as an input a valid Google Storage signed url for read</p> <p>I am looking for the most elegant way to stream/upload the file from this signed url to another google storage bucket using Python</p> <p>I guess it's more convenient to do so via generating an upload signed url and then streaming to it the file fro...
<python><google-cloud-storage><signed-url>
2023-10-03 06:31:17
1
7,884
Alexander
77,220,056
499,721
Programmatically adding commands to `fakeredis` in Python
<p>Is there a way to programmatically add commands to <a href="https://fakeredis.readthedocs.io" rel="nofollow noreferrer"><code>fakeredis</code></a>?</p> <p>Unless I'm missing something, the <a href="https://fakeredis.readthedocs.io/en/latest/guides/implement-command/#implementing-support-for-a-command" rel="nofollow ...
<python><redis><mocking><fakeredis>
2023-10-03 06:19:36
1
11,117
bavaza
77,220,025
248,296
Pydantic2 computed field with validate_assignment=True
<p>I have a Pydantic V2 model with a field <code>total_amount</code> which should be automatically computed whenever <code>items</code> field changes:</p> <pre class="lang-py prettyprint-override"><code>from typing import Self import pydantic class Calculation(pydantic.BaseModel): model_config = pydantic.ConfigD...
<python><pydantic>
2023-10-03 06:13:11
1
60,030
warvariuc
77,219,992
1,818,935
What methods of its last estimator does a scikit-learn pipeline have?
<p>I'm trying to understand <code>scikit-learn</code> Pipelines.</p> <p><a href="https://scikit-learn.org/stable/modules/compose.html#pipeline-chaining-estimators" rel="nofollow noreferrer">According to a Note in the scikit user guide</a> a Pipeline &quot;has all the methods that the last estimator in the pipeline has&...
<python><scikit-learn><scikit-learn-pipeline>
2023-10-03 06:05:43
1
6,053
Evan Aad
77,219,925
562,769
Does mypy==x give the same error messages for all Python versions?
<p>I'm the maintainer of pypdf. We use a CI that currently checks mypy for Python 3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12.</p> <p>I am thinking about just running mypy for one Python version.</p> <p>Does mypy in a fixed version x behave the same for all Python versions (we do have pytest covering the code; meaning if we i...
<python><mypy>
2023-10-03 05:48:48
0
138,373
Martin Thoma
77,219,686
9,668,218
How to use Python library in SQL platform without using Databricks?
<p>I have developed a Python library that is installed on a Databricks cluster and is used to apply a few functions on delta tables:</p> <ul> <li><p>Import library into a notebook</p> </li> <li><p>Read required data from delta tables</p> </li> <li><p>Run python functions on the data and store results in a delta table</...
<python><sql><azure><databricks>
2023-10-03 04:33:41
1
1,033
Mohammad
77,219,549
1,049,393
Solving a kinky secondary order ODE via Python Scipy
<p>I have the following second order ODE and I wish to solve it via Python Scipy:</p> <p><a href="https://i.sstatic.net/ymDlV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ymDlV.png" alt="ODE" /></a></p> <p>How can I accomplish this?</p>
<python><math><scipy><numerical-methods><ode>
2023-10-03 03:47:31
0
947
coderodde
77,219,433
20,235,789
Why isn't pydantic v2 finding SettingsSourceCallable?
<p>I'm looking at the migration guide and documentation: <a href="https://docs.pydantic.dev/2.4/migration/#basesettings-has-moved-to-pydantic-settings" rel="noreferrer">https://docs.pydantic.dev/2.4/migration/#basesettings-has-moved-to-pydantic-settings</a></p> <p>I can't seem to find where to locate <code>SettingsSour...
<python><pip><pydantic>
2023-10-03 03:01:15
0
441
GustaMan9000
77,219,339
4,451,521
How to set the range in which a density is shown in seaborn
<p>I have the following plots</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd # read some dataframe and sns.histplot(data=df['error'],bins=20, binrange=(0,2),kde=True) </code></pre> <p><a href="https://i.sstatic.net/YdG6s.png" rel="nofollow noreferrer"><img ...
<python><seaborn>
2023-10-03 02:23:17
1
10,576
KansaiRobot
77,219,194
7,147,717
Visual Studio Code python wrong version
<p>I'm using Visual Studio Code to run python. I'm looking at the python version it says: 2.7.16, which I understand is really old.</p> <p><a href="https://i.sstatic.net/TW5aI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TW5aI.png" alt="enter image description here" /></a></p> <p>Now I click on the ge...
<python><visual-studio-code>
2023-10-03 01:23:24
1
757
hachiko
77,219,154
4,555,765
Adding edge features in heterographs using PyGeometric
<p>For some reason I'm not being able to assign features to edges using <a href="https://pytorch-geometric.readthedocs.io/en/latest/generated/torch_geometric.data.HeteroData.html#torch_geometric.data.HeteroData" rel="nofollow noreferrer"><code>HeteroData</code></a> from PyGeometric package. The version installed are Py...
<python><graph><pytorch><pytorch-geometric>
2023-10-03 01:05:52
1
1,211
Lin
77,219,132
3,786,999
Problem with SDV (synthetic data vault): Getting back identical synthetic datasets
<p>I'm using the following code from the SDV library to create a synthetic dataset that's the same shape as my original dataset. While each synthetic dataset is different than the original dataset, all synthetic datasets are identical to each other. I would have thought there would be some randomness built into the syn...
<python><data-generation><synthetic><sdv>
2023-10-03 00:56:24
1
1,139
user3786999
77,219,012
817,630
When including a date column in a multi-index, then calling asfreq, the other columns in the index are removed
<p>I have some code that uses pandas <code>groupby</code> and <code>apply</code> along with <code>asfreq</code> to fill in date gaps for each grouping value.</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime import pandas as pd # Original data df = pd.DataFrame({ &quot;date&quot;: ...
<python><pandas><dataframe>
2023-10-02 23:51:46
2
5,912
Kris Harper
77,218,845
14,932,271
How can the right object type be chosen, when using operator overloading in inherited classes?
<p>I am currently writing on a project in Python 3, which is quite huge and will consist of multiple classes. As these files are quite huge I came up with a simpler problem, depicted below.</p> <h1>Base Class</h1> <p>I have a base class called <code>Vector()</code> with multiple methods and performing operator overload...
<python><python-3.x><oop><inheritance>
2023-10-02 22:48:23
3
392
destructioneer
77,218,773
298,622
How can I make mypy work with a custom class decorator similar to dataclass?
<p>I need to generate code for classes in a very similar way <code>dataclasses.dataclass</code> does. In my first version, I wrote something like:</p> <pre class="lang-py prettyprint-override"><code>def typedrow(cls: type[_T]) -&gt; type[_T]: cls_annotations = cls.__dict__.get(&quot;__annotations__&quot;, {}) ...
<python><python-decorators><mypy><python-dataclasses>
2023-10-02 22:26:58
1
4,938
Igor Gatis
77,218,738
4,834,431
Azure Pipelines - Variable empty set in python
<p>I have an Azure pipeline defined as:</p> <pre class="lang-yaml prettyprint-override"><code>- task: Bash@3 inputs: targetType: inline script: | python3 script.py echo $(abc) </code></pre> <p>The <code>script.py</code> is loaded and contains the following:</p> <pre class="lang-py prettyprint-over...
<python><azure-pipelines>
2023-10-02 22:17:47
1
5,906
Kevin C
77,218,730
560,110
How to define a minimum width/height for horizontal and vertical lines when finding the number of rows and columns in a table image with Python OpenCV
<p><a href="https://i.sstatic.net/9EJNX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9EJNX.png" alt="processed image" /></a></p> <p>I'm attempting to take images of 8.5 x 11&quot; petitions and determine which rows contain something that resembles a signature. I'm assuming that I will be able to isola...
<python><opencv><image-processing>
2023-10-02 22:15:48
0
345
Chris Keller
77,218,713
9,766,795
binance cancel order request sends back 'unknown unorder received'
<p>I'm using the binance connector API with python <a href="https://binance-connector.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://binance-connector.readthedocs.io/en/latest/</a> with the testnet (<a href="https://testnet.binance.vision/" rel="nofollow noreferrer">https://testnet.binance.vision/</a>) to...
<python><binance><binance-api-client><python-binance>
2023-10-02 22:10:04
1
632
David
77,218,272
308,827
Lollipop plot for dataframe with two groups
<p>I have the following dataframe:</p> <pre><code> Country variable value 0 Afghanistan Area 38.232510 1 Afghanistan Yield 70.081666 2 Argentina Area 96.776730 3 Argentina Area 60.047651 4 Ar...
<python><pandas><matplotlib><seaborn><stem-plot>
2023-10-02 20:14:09
1
22,341
user308827
77,218,039
16,363,897
Ways to speed up rolling weighted mean on a pandas dataframe
<p>I have a large <code>DataFrame</code>, on which I need to calculate the rolling row-wise weighted average.</p> <p>I know I can do the following:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(20000, 50)) weights = [1/9, 2/9, 1/3, 2/9, 1/9] rolling_mean = df.rolling(5, axis=...
<python><pandas><numpy>
2023-10-02 19:29:00
4
842
younggotti
77,217,894
3,851,085
Python ckan get packages for organization
<p>Using CKAN in Python, how can I get all packages for a given organization? I am not seeing this functionality here: <a href="https://docs.ckan.org/en/2.9/api/index.html" rel="nofollow noreferrer">https://docs.ckan.org/en/2.9/api/index.html</a></p>
<python><ckan>
2023-10-02 19:03:07
0
1,110
Software Dev
77,217,624
8,380,272
usage of `OR, AND` operators in set union
<p>Bear with me if the question is duplicate. But cant seem to find any related questions/solutions.</p> <p>Suppose I have tow sets:</p> <pre><code>set_one = {10,5,7} set_two = {10,1,3,6, 5, 7} set_one | set_two # union of two sets {1, 3, 5, 6, 7, 10} set_one.union(set_two) # same as above {1, 3, 5, 6, 7, 10} </code></...
<python><set>
2023-10-02 18:12:07
2
80,265
Onyambu
77,217,521
116
Is psycopg3 a fork of psycopg2, or a replacement upgrade?
<p>I see references to both psycopg2 and psycopg3, but no clear guidance wrt a roadmap for transitioning between the two. I see that over time there is a large body of SO questions regarding psycopg2.</p> <p>Is psycopg3 intended to be a replacement for psycopg2? Has there been a significant uptake of this version?</p...
<python><psycopg2><psycopg3>
2023-10-02 17:53:10
1
305,996
Mark Harrison
77,217,419
9,983,652
how to group columns efficiently?
<p>I have a dataframe with 10000 columns and the column name is just the numerical data like depth, for each column is for each depth. I'd like to group the columns from 10000 column into 5000 columns by increasing spacing between each column. I am not sure how to do it.</p> <p>Here is a simple example for demonstratio...
<python><pandas>
2023-10-02 17:32:33
1
4,338
roudan
77,217,381
9,002,634
FastAPI endpoint receiving bytes/file
<p>how can I create a FastAPI endpoint that can receive the following request example.</p> <pre class="lang-py prettyprint-override"><code>import requests # URL of your FastAPI endpoint url = &quot;http://localhost:8000/upload/?param1=temp&amp;param2=temp&quot; # Path to the file you want to upload file_path = &quot;...
<python><fastapi>
2023-10-02 17:24:11
0
318
Viet Than
77,217,076
9,957,594
Langchain - using filters in a Retriever
<p>Do any of the langchain retrievers provide filter arguments?</p> <p>I'm trying to create an EnsembleFilter using a VectorRetriever (FAISS) and a normal Retriever (BM25), but the filter fails when combining them:</p> <pre><code>documents = [Document(page_content='The Celtics are my favourite team.', metadata={topic=&...
<python><langchain>
2023-10-02 16:24:06
1
350
tcotts
77,216,874
15,209,311
How to toggle on / off microphone using Python and also get its current state?
<p>I found the following code that toggles off / on the microphone using Python and it works well (only on windows).</p> <pre><code>import win32api import win32gui WM_APPCOMMAND = 0x319 APPCOMMAND_MICROPHONE_VOLUME_MUTE = 0x180000 hwnd_active = win32gui.GetForegroundWindow() win32api.SendMessage(hwnd_active, WM_APPCO...
<python><python-3.x><winapi><microphone>
2023-10-02 15:50:38
0
619
Niv
77,216,567
13,142,245
What is the JSON input format for a Lambda function for proxy integration?
<p>I'm using AWS Lambda with an API Gateway proxy integration (<code>AWS_PROXY</code>) such that requests are passed directly without API Gateway imposing any routing.</p> <p>Lambda is hosting a FastAPI application and Mangum is the intermediary that allows Lambda to respond to requests as a uvivorn server would.</p> <...
<python><amazon-web-services><aws-lambda><aws-api-gateway><fastapi>
2023-10-02 15:03:35
1
1,238
jbuddy_13
77,216,542
5,567,893
how to merge the multiple dataframes sequentially?
<p>Although I thought this question should be duplicated, I couldn't find the proper answer.</p> <p>I have some problems merging multiple dataframes sequentially.</p> <p>For example, I have four dataframes as below:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'source': ['A', 'A', 'A', 'B', '...
<python><pandas><dataframe><merge>
2023-10-02 15:00:01
2
466
Ssong
77,216,430
18,349,319
MinIO docker-compose AccessDenied
<p>My MinIO container When I try to create the MinIO bucket, I have an error:</p> <pre><code>S3 operation failed; code: AccessDenied, message: Access denied </code></pre> <p>I'm creating the bucket with Python minio:</p> <pre class="lang-py prettyprint-override"><code>minio_client = minio.Minio(endpoint=os.getenv(&quot...
<python><minio>
2023-10-02 14:45:27
0
345
TASK
77,216,279
3,017,906
list.extend method applied while creating the list
<p><code>Python</code> <code>list.extend()</code> method allows to append a list to an existing one, as detailed <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow noreferrer">here</a></p> <p>I can do something like this:</p> <pre><code>import numpy as np a = [1,2,3] a.extend(list(np.arange(...
<python><list>
2023-10-02 14:25:08
1
1,343
Michele Ancis
77,216,224
10,410,169
Switch directory in a docker container within Vertex
<p>I have a DBT docker container.</p> <p>The WORKDIR is set to <code>dbt/client/client_name</code>.</p> <p>I am easily able to run commands within the docker container using <code>kfp.components.load_component_from_text()</code></p> <p>However, somewhere along the line I need to switch directories to run other commands...
<python><docker><google-cloud-vertex-ai><kubeflow-pipelines>
2023-10-02 14:18:19
1
335
Mengezi Dhlomo
77,216,151
583,464
extract words from list after specific character
<p>I have two lists:</p> <pre><code>list_1 = ['08667\nST 403', '08667\nST 403', '08667\nST 403'] list_2 = ['12233\nFION', '12233\nFION', '12233\nFION', '12233\nFION', '31147\nARAB\nP1454'] </code></pre> <p>I want to be able to extract the names after the '\n' keyword.</p> <p>I am using this code:</p> <pre><code>def par...
<python><python-3.x><list>
2023-10-02 14:04:35
3
5,751
George
77,216,117
15,384,651
ANTLR not generating ParserBase
<p>I am new to ANTLR and was looking into the CPP14 grammar <a href="https://github.com/antlr/grammars-v4/tree/master/cpp" rel="nofollow noreferrer">here</a>. I tried using</p> <p><code>antlr4 -Dlanguage=Python3 CPP14Lexer.g4</code></p> <p><code>antlr4 -Dlanguage=Python3 CPP14Parser.g4</code></p> <p>Then use the follow...
<python><parsing><antlr><antlr4>
2023-10-02 13:59:14
1
520
Vedanta Mohapatra
77,216,057
17,884,397
indexing a numpy array by an array of indices in a loop
<p>i have a vector i want to shuffle in batches.<br /> the idea i came up with is to reshape it into 2D array with each row as a batch.<br /> then i shuffle each row on its own.</p> <p>this is toy example of the approach</p> <pre class="lang-py prettyprint-override"><code># shuffle the matrix mat_size = (8, 8) row_size...
<python><arrays><numpy><for-loop><variable-assignment>
2023-10-02 13:50:56
1
736
Eric Johnson
77,215,858
11,688,559
Google Cloud Function HTTP request connection times out
<p>I am performing an http request to the LibreNMS API via the following Python code:</p> <pre><code>import requests TOKEN = './token.json' def get_request(request_type): url = f'http://192.168.1.141/api/v0/{request_type}' with open(TOKEN,'r') as file: headers = json.load(file) response = requests.g...
<python><http><google-cloud-platform><google-cloud-functions><httprequest>
2023-10-02 13:17:49
1
398
Dylan Solms
77,215,767
13,793,478
How to change app.py variable with HTML button?
<p>How do I add or subtract 1 from the variable num ( in flask route) with an HTML button?</p> <p>So when I click the button it change the var to 1 and refresh the page to show the new value</p> <pre><code>@app.route('/') def note(): num = 1 return render_template('home.html', num=num) </code></pre>
<python><flask><jinja2>
2023-10-02 13:04:02
3
514
Mt Khalifa
77,215,726
15,262,489
The relationship between json pattern in azure python sdk and json view of azure objects
<p>I am writing a python script which will make use of azure python sdk, and inside the script I have some cases of usage of <code>begin_create_or_update</code> function, which is common for most modules in azure python sdk.</p> <p>However, I am having trouble figuring out the proper json pattern for each object to spe...
<python><json><azure><azure-python-sdk>
2023-10-02 12:56:13
1
2,306
Karen Baghdasaryan
77,215,634
127,508
How to send a request to AWS Bedrock properly?
<p>I have the following Python code talking to the Bedrock API:</p> <p>Setting up the session:</p> <pre class="lang-py prettyprint-override"><code>import boto3 dev = boto3.session.Session(profile_name=&quot;dev&quot;) bedrock_runtime = dev.client( service_name=&quot;bedrock-runtime&quot;, region_name=&quot;us-...
<python><amazon-web-services><amazon-bedrock>
2023-10-02 12:41:33
1
8,822
Istvan
77,215,614
12,036,506
Python: Returning reference to a class property from another function instead of the actual value
<p>Imagine a basic python class with a property like :</p> <pre class="lang-py prettyprint-override"><code>class Test(Generic[T]): def __init__(self, x: T): self.__x = x @property def x(self): return self.__x def update(self, value: T): self.__x = value # Note that this...
<python><python-3.x>
2023-10-02 12:36:56
0
368
Gray Hat
77,215,607
4,451,521
How can I create a density plot (using as a reference a histogram)
<p>I have the following script</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fig5 = plt.figure() fig5.subplots_adjust(wspace=0.4, hspace=0.6) ax5_2 = fig5.add_subplot(212) std_error = &quot;{:.2f}&quot;.format(np.std(df['error'])) ave_error = &quot;{:.2f}&quot;.format(np.nanmean(df['error'])) ax5_2...
<python><matplotlib>
2023-10-02 12:35:43
1
10,576
KansaiRobot
77,215,365
1,824,285
Problem installing Pytrends on WIndows: Module not found
<p>I have just begun learning Python so I'm not very confident. I have installed Python 3.8.2 and added the location of my installation directory to my PATH in Windows 11. However I cannot get the Pytrends module to work.</p> <p>I can execute Python commands directly in Command Prompt, and also run scripts in Pycharm.<...
<python>
2023-10-02 11:54:26
2
378
mike_freegan
77,215,333
6,260,154
Get only children folders i.e. exclude current folder using glob.glob * pattern search
<p>This is how my directory structure looks like:</p> <pre><code>&lt;ROOT&gt;/ ├── root.log ├── a/ │ ├── xyz/ │ ├── a_xyz.log ├── b/ │ ├── xyz/ │ └── b_xyz.log ├── c/ │ ├── xyz/ │ └── d/ │ ├── xyz/ │ └── b_xyz.log </code></pre> <p>And this is the piece of code I am using:</p> <pre><code>dirs_where...
<python><glob>
2023-10-02 11:47:39
1
1,016
Tony Montana
77,215,313
8,543,025
Count Instances Until Value Repeats
<p>I have a list/array/series of booleans, and I want a list of the same length that contains <code>NaNs</code> wherever there was a <code>False</code> value in the original, and on <code>True</code> indices I want to plug the number of <code>False</code> elements until the next <code>True</code>. If there is no subseq...
<python><pandas><numpy><vectorization>
2023-10-02 11:45:01
1
593
Jon Nir
77,215,192
2,756,466
Pydantic datetime is stored as String in MongoDB
<p>I am trying to store some date in Mongo collection but it is stored as String in MongoDB.</p> <p>This is the model:</p> <pre><code>def datetime_now() -&gt; datetime: return datetime.now(timezone.utc) class Project(BaseModel): id: uuid.UUID = Field(default_factory=uuid.uuid4, alias=&quot;_id&quot;) ti...
<python><mongodb><pydantic>
2023-10-02 11:22:39
2
7,004
raju
77,215,191
7,074,716
Jetson TX1: No matching distribution found for cplex
<p>I saw a similar question on <a href="https://stackoverflow.com/questions/62437055/no-matching-distribution-found-for-cplex">stackoverflow</a> before, but I couldn't make it run. I am trying to install cplex on a Jetson TX1 that runs Ubuntu 18.</p> <p>When I run</p> <pre><code>$ pip install cplex Collecting cplex ...
<python><installation><cplex>
2023-10-02 11:22:34
0
825
Curious
77,215,176
13,793,478
How to change app.py variable with HTML button?
<p>How do I add or subtract 1 from the variable num ( in flask route) with an HTML button?</p> <pre><code>@app.route('/') def note(): num = 1 return render_template('home.html', num=num) </code></pre>
<python><flask>
2023-10-02 11:19:22
1
514
Mt Khalifa
77,215,129
5,131,139
Python Authentication Issue When Modularizing Tableau API
<p>I have the following Python code that successfully authenticates and retrieves data using the Tableau API:</p> <pre><code># Original Code def get_all_client_users(client): client_users = [] tableau_auth = TSC.TableauAuth( os.getenv('tableau_username'), os.getenv('tableau_pass'), client) server = ...
<python><tableau-api>
2023-10-02 11:12:12
2
1,429
AnandShiva
77,215,107
22,400,527
ImportError: cannot import name 'url_decode' from 'werkzeug.urls'
<p>I am building a webapp using Flask. I imported the <code>flask-login</code> library to handle user login. But it shows an ImportError.</p> <p>Below is my folder structure:</p> <pre><code>&gt;flask_blog1 &gt;flaskblog &gt;static &gt;templates &gt;__init__.py &gt;forms.py &g...
<python><flask><importerror><flask-login><werkzeug>
2023-10-02 11:07:45
6
329
Ashutosh Chapagain
77,214,878
7,695,845
How to add type hints for a dictionary that maps a class to an instance of that class?
<p>I have a dictionary, <code>foo</code>, that maps a type (class) to an instance of that type:</p> <pre class="lang-py prettyprint-override"><code>class Demo: pass foo = { int: 5, str: &quot;Hi&quot;, Demo: Demo() } </code></pre> <p>How can I add type hints to this variable to allow type checkers suc...
<python><mypy><python-typing>
2023-10-02 10:27:01
2
1,420
Shai Avr
77,214,861
11,613,489
Cannot export a pandas DataFrame to Excel in Python
<p>I need some help here, please.</p> <p>An excel file needs to be updated, not overwritten. In particular, I need to add data to an Excel file (row by row) from an external data source (data from my own website), which I scraped using a Python script.</p> <p>The following thus represents the excalty I wish to use in m...
<python><pandas><dataframe>
2023-10-02 10:25:11
0
642
Lorenzo Castagno
77,214,669
458,742
`pip install mysqlclient` fails because `pkg-config --exists mysqlclient` fails
<p>I am trying to <code>pip install mysqlclient</code> on Ubuntu 22.04 but get</p> <pre><code>Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements ...
<python><mysql><ubuntu><pip>
2023-10-02 09:54:10
1
33,709
spraff
77,214,638
1,422,096
Import a RGB array into a PIL image with fromarray
<p>I have a RGB array that I would like to import in <code>PIL</code> with <code>fromarray</code> and save to disk:</p> <pre><code>import numpy as np from PIL import Image from PIL.PngImagePlugin import PngInfo a = np.array([[[255, 0, 0], [0, 255, 0]], # Red Green [[0, 0, 255], [0, 0, 0]]]) # B...
<python><numpy><python-imaging-library>
2023-10-02 09:50:33
1
47,388
Basj
77,214,589
1,432,980
ignore security dependency if environment is set to local or dev
<p>I have this dependency in my REST endpoint definition</p> <pre><code>@api_router.post(path=&quot;/request&quot;) def post_request( request_body: RequestBody, access_token: AccessToken = Security(validate_roles, scopes=[&quot;user.access&quot;]) ) </code></pre> <p>This <code>validate_roles</code> function has...
<python><fastapi>
2023-10-02 09:41:25
1
13,485
lapots
77,214,515
11,283,324
How to split a numpy array to 2d array based on postive/neagtive changes
<p>I have a numpy 1D array:</p> <pre><code>import numpy as np arr = np.array([1, 1, 3, -2, -1, 2, 0, 2, 1, 1, -3, -1, 2]) </code></pre> <p>I want split it into another two-dimensional array, based on changes in positive and negative values of array's elements(0 is placed in the range of positive values). But t...
<python><numpy>
2023-10-02 09:30:01
3
351
Sun Jar
77,214,455
13,618,407
Pytorch CustomDataset TypeError: list indices must be integers or slices, not list
<p>I am facing an error using pytorch custom dataset. The problem is really strange to me because it was working, I didn't change anything on the code. Here is the scenario:</p> <ol> <li><p>After building my deep learning model, I test it by training it in 10 then 100 epochs. It was working fine, but I saw that the mod...
<python><jupyter-notebook><pytorch>
2023-10-02 09:22:26
1
561
stic-lab
77,214,384
13,892,783
Python packaging semantic versioning >= vs. ~= in requirements.txt
<p>I have a general question about handling versions in <code>requirements.txt</code> of my package <code>foo</code>. I cannot decide if <code>&gt;=</code> or <code>~=</code> is better.</p> <ul> <li>assume <code>pandas~=1.3.3</code> in <code>requirements.txt</code> of my package <code>foo</code> <ul> <li>in this case, ...
<python><package><semantic-versioning><requirements.txt>
2023-10-02 09:11:49
0
317
PanchoVarallo
77,214,285
5,359,846
Finding partial text match using any in Python
<p>I have a list of string that contains values like this:</p> <ul> <li>'abc_def'</li> <li>'{xyz_abc}'</li> <li>'{www-ABC-zzz}'</li> </ul> <p>I wish to find partial text match in my list using the <code>any</code> keyword:</p> <pre><code>result = any('abc' in w for w in list) </code></pre> <p>How can I find all the mat...
<python>
2023-10-02 08:51:13
1
1,838
Tal Angel
77,214,118
8,947,333
InvalidRequestError when reading view but not SQL query
<p>I have an SQLAlchemy engine (<code>type(engine)</code> outputs <code>&lt;class 'sqlalchemy.engine.base.Engine'&gt;</code>), when I run this snippet I get an error:</p> <pre><code>with engine.connect() as connexion: pd.read_sql_table(&quot;MY_VIEW&quot;, connexion, schema=&quot;abc&quot;) Traceback (most recent ...
<python><sqlalchemy>
2023-10-02 08:25:07
0
3,008
Be Chiller Too
77,214,056
9,389,353
Python Requests API 403 Error with same HTTP Request
<p>I am attempting to fetch an API using Python requests.</p> <p>The API is documented here: <a href="https://consumerdatastandardsaustralia.github.io/standards/#get-data-holder-brands" rel="nofollow noreferrer">https://consumerdatastandardsaustralia.github.io/standards/#get-data-holder-brands</a></p> <p>The following ...
<python><python-requests>
2023-10-02 08:12:46
2
987
Luke Prior
77,213,856
1,422,096
How to start the Windows screensaver from Python?
<p><strong>How to launch the Windows screensaver from Python ?</strong></p> <p>I have tried methods like</p> <pre><code>import subprocess subprocess.Popen(&quot;C:\Windows\System32\scrnsave.scr&quot;) </code></pre> <p>it starts a screensaver, but it doesn't start the screensaver that has been configured in the Windows ...
<python><windows><screensaver>
2023-10-02 07:33:07
1
47,388
Basj
77,213,826
458,742
Dockerfile from ubuntu:22.04 apt unable to locate package python3
<p>When I <code>docker build</code> this:</p> <pre><code>FROM ubuntu:22.04 RUN apt-get install -y python3 </code></pre> <p>I get</p> <pre><code>Step 1/2 : FROM ubuntu:22.04 ---&gt; c6b84b685f35 Step 2/2 : RUN apt-get install -y python3 ---&gt; Running in d1f4eff8d024 Reading package lists... Building dependency tree....
<python><docker><ubuntu><apt>
2023-10-02 07:27:04
1
33,709
spraff
77,213,592
2,696,565
Plotly-Dash box plot inside Card component
<p>I have a box plot inside a Plotly-Dash Card component and then when I change the dropdown, I get another card added inside the already existing card. How can I have the existing figure update instead of adding a new card please.</p> <pre><code>from dash import Dash import dash_bootstrap_components as dbc from dash_b...
<python><plotly><plotly-dash>
2023-10-02 06:32:36
0
629
user2696565
77,213,450
6,101,713
Scale vertical (z) axis of 3D surface plot with plot_surface
<p>How can I scale the Z-axis of a surface plot in matplotlib? Take the following example dataset and plot.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(-5, 5, 50) y = np.linspace(-5, 5, 50) x, y = np.meshgrid(x, y) # Generate a 3D surface z = np.exp(-0.1*x**2 - 0.1*y**2) fig = p...
<python><matplotlib><matplotlib-3d>
2023-10-02 05:53:32
2
1,346
Muon
77,213,190
815,110
Constructing next-occuring python datetime from only month and day
<p>I have a string representing just the month and day (format: <code>&quot;%m/%d&quot;</code>, e.g. &quot;12/25&quot;) and I would like to construct a datetime for the next occurrence of it, relative to today. Ideally a function like:</p> <pre><code>datetime.next_strptime(&quot;12/25&quot;, &quot;%m/%d&quot;) # return...
<python><datetime>
2023-10-02 04:08:30
0
1,570
Nathan
77,213,101
10,461,632
`open` command not passing `--args`
<p>I'm trying to start a pyinstaller executable with the <code>open</code> command on my Mac, but I need to pass an argument identifying the port to open.</p> <p>When I run <code>./app 5000</code>, the executable opens correctly.</p> <p>When I run <code>open app --args 5000</code>, the executable doesn't recognize the ...
<python><macos>
2023-10-02 03:25:03
1
788
Simon1
77,213,099
14,345,989
Given a list of shapely polygons generate a tree of which polygon contains which other polygons with no repeats
<p>I have a list of shapely polygons, none of which overlap. I intend to do certain operations based on their level of nesting within other polygons (union or difference) to generate one final multipolygon that represents the entire set.</p> <p>As a simple example, see the image below in which four polygons labeled A-D...
<python><recursion><polygon>
2023-10-02 03:23:49
1
886
Mandias
77,213,053
15,233,792
Why did Flask start failing with "ImportError: cannot import name 'url_quote' from 'werkzeug.urls'"?
<p>Environment:</p> <pre class="lang-none prettyprint-override"><code>Python 3.10.11 Flask==2.2.2 </code></pre> <p>I run my Flask backend code in docker container, with BASE Image: <code>FROM pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime</code></p> <p>But when I run the pytest with version <code>pytest 7.4.2</code>,</p...
<python><flask><pytest><werkzeug>
2023-10-02 03:02:00
6
2,713
stevezkw
77,213,003
11,737,958
How to filter a numeric value with spaces using regex in python
<p>I am new to python and using version 3.8. I use regex to filter strings, special characters and numbers from a string. There are spaces in between characters and numbers and i try to filter them. I am able to filter the string upto first number. I am unable to filter the string till the last number. Any help would b...
<python><regex>
2023-10-02 02:35:59
4
362
Kishan
77,212,868
11,933,886
Trying to get rid of a circular Python dependency
<p>I have an application (telegram python bot) with a lot of CONSTANTS in it, so I did a bit of a structure here:</p> <pre><code>bot/ api.py bot.py constants.py functions.py keyboards.py </code></pre> <p>Main execution file is: <code>bot.py</code></p> <p>Below is the imports from those files:</p> <p...
<python><python-3.x><circular-dependency>
2023-10-02 01:26:50
2
361
Alex Lebedev
77,212,767
1,056,563
How can the options set on a Spark DataFrameReader be viewed?
<p>The <code>Spark</code> <code>DataFrameReader</code> has an <code>options()</code> method: but it is a <em>setter</em>: ie it is used to impose options on the <em>Reader</em></p> <pre><code> datasource_options = {'driver': 'com.microsoft.sqlserver.jdbc.SQLServerDriver', 'timestam...
<python><apache-spark><pyspark>
2023-10-02 00:26:08
1
63,891
WestCoastProjects
77,212,657
1,115,716
Writing a SpooledTemporaryFile to disk
<p>I am working on a <code>Strawberry</code> API service that accepts documents. I receive files and process them like so:</p> <pre><code>import typing import strawberry from strawberry.file_uploads import Upload @strawberry.input class FolderInput: files: typing.List[Upload] @strawberry.type class Mutation: ...
<python><temporary-files>
2023-10-01 23:27:50
0
1,842
easythrees
77,212,579
3,081,328
Determine different seeds for which random shuffling list generates the same output
<p>It is pretty intuitive that when shuffling a small enough collection, results will repeat themselves, even using different seeds each time, as it is just a matter of exhausting all unique combinations.</p> <p>However, I can't find such information in the Python documentation. I am especially curious if there is any ...
<python><python-3.x><random>
2023-10-01 22:50:41
0
809
Hunter_71
77,212,471
214,179
Resizing Movie Clip with MoviePy leads to SIGKILL on m1 mac
<p>I'm trying to resize a movie clip using moviepy, but I'm getting a sigkill every time. I've run it on two clips, several times, it seems consistent.</p> <pre><code>Process finished with exit code 137 (interrupted by signal 9: SIGKILL) </code></pre> <p>Reading and writing mp4 files. The source file's info says:</p> <...
<python><macos><apple-m1><moviepy>
2023-10-01 21:59:13
0
1,309
ThoughtfulHacking
77,212,373
6,142,743
Scientific notation in Python - extra digits
<p>I have the following very small floating number in Python:</p> <pre><code>fnum = 0.00012345689000007 </code></pre> <p>When I try to convert to a scientific notation, I am not sure where the extra digits after 7 (the last digit) are coming from:</p> <pre><code>print(&quot;%.40e&quot;%fnum) </code></pre> <p>This is th...
<python><floating-point><scientific-notation>
2023-10-01 21:20:00
0
379
Danny
77,212,120
6,034,925
Plot Imshow on a Torus (lattice with PBC)
<p>Is there any &quot;simple&quot; solution in <code>matplotlib</code> or another Python package to plot a square lattice on a 2d torus (aka lattice with periodic boundary conditions)?</p> <p>Assume i have a simple 2D array</p> <pre><code># ... a = np.random.random((50, 50)) plt.imshow(a) </code></pre> <p><a href="http...
<python><matplotlib><plot><mplot3d>
2023-10-01 20:03:04
2
559
opisthofulax
77,211,990
17,896,651
peewee.OperationalError: database is locked on a single Thread using a locker
<p>I get the issue like 1/10000 times.</p> <p>I have this single code to update the value.</p> <p>I have other places used the database but it seems only this code is crashing with database lock, or it just that this once called most often.</p> <pre><code>class InstaPyLimits(object): @staticmethod def update_da...
<python><database><peewee>
2023-10-01 19:21:46
1
356
Si si
77,211,976
6,115,999
SAWarning error "SELECT statement has a cartesian product" when trying to append to bridging table in many to many relationship
<p>I want to have two tables. One of ideas and another of tags. This relationship should be many to many.</p> <p>I've created a bridging table:</p> <pre><code>tag_idea = db.Table('tag_idea', db.Column('idea_id', db.Integer, db.ForeignKey('idea.id')), db.Column('ideatag_id', db.Integer, db.ForeignKey(...
<python><flask><flask-sqlalchemy>
2023-10-01 19:19:17
2
877
filifunk
77,211,663
14,255,490
Heatmap with sklearn Confusion Matrix issue
<p>I bumped into the following issue:</p> <pre><code>X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=42) y_pred = model.predict(X_test) y_pred = (y_pred &gt; 0.5) from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) sns.heatmap...
<python><matplotlib><seaborn><heatmap>
2023-10-01 17:53:20
0
351
ArtemNovikov
77,211,591
1,008,933
Django cannot run because GDAL is loading wrong libtiff version
<p>I am unable to run Django on my MacOS Ventura. Looking at the error, I think GDAL is unable to load libtiff library.</p> <p>I did some investigation, I do have libtiff installed.</p> <pre><code>% otool -L /opt/homebrew/lib/libgdal.dylib | grep libtiff /opt/homebrew/opt/libtiff/lib/libtiff.6.dylib (compatibility ...
<python><django><gdal><libtiff>
2023-10-01 17:35:24
2
3,391
Axil
77,211,419
1,128,648
Upload file to google drive using service account using python
<p>I am using below python script to upload files to Google drive.I am using service account to remove any interactive authentication.</p> <pre><code>from googleapiclient.discovery import build from google.oauth2 import service_account from googleapiclient.http import MediaFileUpload scopes = ['https://www.googleapis....
<python><google-drive-api>
2023-10-01 16:50:12
0
1,746
acr
77,211,360
2,756,466
How to use MongoObjectId in pydantic models
<p>I have created a simple REST API using Python, FastAPI and Pydantic.</p> <p>It is working OK. But the model file creates <code>_id</code> with <code>uuid</code> instead of Mongo's <code>ObjectId</code>.</p> <pre><code>id: uuid.UUID = Field(default_factory=uuid.uuid4, alias=&quot;_id&quot;) </code></pre> <p>How can I...
<python><fastapi><pydantic>
2023-10-01 16:36:06
1
7,004
raju
77,211,348
2,764,206
Mypy and second-order decorators
<p>I'm trying to implement a second-order decorator that injects a dynamic variable as first argument of the decorated function.</p> <p>Here is what I have so far:</p> <pre><code>from typing import Callable, Concatenate, ParamSpec, TypeVar T = TypeVar('T') U = TypeVar('U') P = ParamSpec('P') def foo(some_arg: U) -&g...
<python><mypy><python-typing><python-decorators>
2023-10-01 16:33:35
1
2,341
Nicolas Appriou
77,211,228
414,506
Can a multi-threaded Python app change the CWD?
<p>Would the <code>assert</code> statement in this code raise an error under any Python 3.11+ interpreter?</p> <p>Can the current working directory be changed by another module without this code using any <code>async</code> features?</p> <pre class="lang-py prettyprint-override"><code>import os cwd1 = os.getcwd() # can...
<python><python-3.x><multithreading><thread-safety><race-condition>
2023-10-01 16:02:00
2
615
Carlos Gil
77,211,155
11,426,624
pandas groupby, transform and join
<p>I have a dataframe and I would like to groupby and join the strings of a column together. So something like the below.</p> <pre><code>df = pd.DataFrame({ 'id': [1, 1, 2, 2, 3, 3], 'txt': ['sth', 'sth else', 'sth', 'one more thing', 'sth else', 'sth else'], 'status': ['open', 'open', 'closed', 'open', 'o...
<python><pandas><dataframe><group-by>
2023-10-01 15:42:31
1
734
corianne1234
77,210,960
9,068,493
Can a class in python not use its generic parameter
<p>If I declare a function that is not using a generic parameter more than once:</p> <pre class="lang-py prettyprint-override"><code>import typing as t T = t.TypeVar(&quot;T&quot;) def bad(a: T) -&gt; None: ... </code></pre> <p>a static type-checker marks this as error (or at least as a warning, if using lenient ...
<python><python-typing>
2023-10-01 14:43:23
1
811
Felix.leg
77,210,935
3,312,274
flask Where to place code to ping elasticsearch
<p>I use elasticsearch in my app. Since I also use blueprints, <code>create_app</code> is defined in the app's <code>__init__.py</code>, which is where <code>app.elasticsearch</code> is initialized.</p> <p>When elasticsearch.ping() fails, I'd like to send an email to an address. I can't send the email in <code>init.py<...
<python><multithreading><elasticsearch><flask>
2023-10-01 14:36:38
1
565
JeffP
77,210,776
22,466,650
How to plot trips durations while considering their deadlines?
<p>My input is a dataframe :</p> <pre><code>df = pd.DataFrame({'blk1': {'a': '12h45', 'b': None, 'c': None, 'd': None}, 'blk2': {'a': None, 'b': None, 'c': '13h15', 'd': '15h15'}, 'blk3': {'a': None, 'b': '12h10', 'c': None, 'd': None}, 'blk4': {'a': None, 'b': '15h45', 'c': '13h30', 'd': None}, 'blk5': {'a': '13h3...
<python><pandas><matplotlib>
2023-10-01 13:57:18
1
1,085
VERBOSE
77,210,676
4,503,189
Inserting the very special unicode character "Left Half Black Star" (aka U+2BE8) in text
<p>I built an app in Python - though this might be a more general question - writing stars into a text. I can write ☆ and ★ easily but I need the half-star, too. So far all my efforts have been a failure, so I ask.</p> <p>Here is a table of the most important information about these characters.</p> <div class="s-table-...
<python><unicode><special-characters>
2023-10-01 13:32:57
0
4,197
BlondCode