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
78,227,090
353,337
Get own pyproject.toml dependencies programatically
<p>I use a <code>pyproject.toml</code> file to list a package's dependencies:</p> <pre class="lang-ini prettyprint-override"><code>[build-system] requires = [&quot;setuptools&quot;] build-backend = &quot;setuptools.build_meta&quot; [project] name = &quot;foobar&quot; version = &quot;1.0&quot; requires-python = &quot;&...
<python><python-packaging>
2024-03-26 17:14:24
1
59,565
Nico Schlömer
78,227,089
12,733,629
Unknown error when trying to 'upsert' with ArcGIS API for Python
<p>I am trying to perform an 'upsert' (update + insert) operation on a feature layer via ArcGIS API for Python. My input data is a geojson file that gets uploaded as per the available <a href="https://developers.arcgis.com/python/guide/appending-features/#add-the-source-csv-item-to-the-gis" rel="nofollow noreferrer">gu...
<python><arcgis>
2024-03-26 17:14:19
1
327
Martim Passos
78,226,932
5,330,527
Filter in Django Admin via a ManyToMany field with Through
<p>My <code>models.py</code>:</p> <pre><code>class Subject(models.Model): name = models.CharField(max_length=200) class Person(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) school = models.ForeignKey(School, on_delete=models.CASCADE, blank=True, null=T...
<python><django><django-models>
2024-03-26 16:46:51
2
786
HBMCS
78,226,758
14,460,824
How to transform dataframe long to wide with "grouped" columns?
<p>When pivoting the following dataframe from long to wide, I would like to get &quot;groups&quot; of columns and mark them with a prefix or suffix.</p> <ul> <li>The groups of elements can have different sizes, i.e. consist of one, two or more grouped elements/rows, I used pairs of two here to keep the example simple.<...
<python><pandas><dataframe><pivot>
2024-03-26 16:15:54
3
25,336
HedgeHog
78,226,689
10,108,726
How to create pdf with multiple pages based on html using python pdfkit
<p>I am trying to create a pdf with python using pdfkit library in my Django project, and I want to separate each content in a different page, how can I do it</p> <pre><code>import pdfkit from django.template.loader import render_to_string my_contents = [ {'title':'Example 1', 'contents': ['Lorem ipsum dorer', 'Lo...
<python><html><django><pdf-generation><python-pdfkit>
2024-03-26 16:07:06
1
654
Germano
78,226,667
9,471,909
How does numpy.unique eliminate duplicate columns?
<p>I cannot understand correctly how Numpy's <code>unique</code> function works on multi-dimensional arrays. More precisely, I cannot comprehend how the documentation of <code>unique</code> describes its operation using the <code>axis</code> parameter:</p> <p><a href="https://numpy.org/doc/stable/reference/generated/nu...
<python><arrays><numpy>
2024-03-26 16:04:44
2
1,471
user17911
78,226,623
1,714,692
Python avoid mypy fails when redefining a class from another class in mutual reference
<p>Consider a pair of classes which represent the same thing in Python and each implements a method that converts one to the other. As an example consider transforming from cartesian to polar coordinates and viceversa.</p> <pre><code>@dataclass class CartesianCoordinates: x: float y: float def toPolarCoordinat...
<python><python-typing><forward-declaration>
2024-03-26 15:57:04
1
9,606
roschach
78,226,484
7,331,538
Scrapy handle closespider timeout in middleware
<p>I have multiple scrapers which I want to put a time limit on. The <code>CLOSESPIDER_TIMEOUT</code> does the job and it returns <code>finish_reason: closespider_timeout</code>.</p> <p>I want to intercept this and use the <code>logging</code> library to log an <code>error</code>. how can I do this? should it go in a m...
<python><logging><scrapy><timeout><middleware>
2024-03-26 15:35:08
1
2,377
bcsta
78,226,481
1,654,143
Image quantization with Numpy
<p>I wanted to have a look at the example code for image quantization from <a href="https://glowingpython.blogspot.com/2012/07/color-quantization.html" rel="nofollow noreferrer">here</a> However, it's rather old and Python and NP have changed since then.</p> <pre><code>from pylab import imread,imshow,figure,show,subplo...
<python><numpy><quantization>
2024-03-26 15:34:47
1
7,007
Ghoul Fool
78,226,424
2,881,414
Custom environment variables with Popen on Windows on Github Actions
<p>I'm using <code>Popen</code> together with custom environment variables. My expectation is when I run something like this:</p> <pre class="lang-py prettyprint-override"><code> proc = Popen( command, universal_newlines=True, bufsize=0, shell=False, env=env, ) </code></pr...
<python><python-3.x><windows><github-actions><popen>
2024-03-26 15:26:04
1
17,530
Bastian Venthur
78,226,139
9,673,864
How to quantify the consistency of a sequence of predictions, incl. prediction confidence, using standard function from sklearn or a similar library
<p>Let's say I let a classification model classify a single object multiple times but under varying circumstances. Ideally it should predict the same class again and again. But in reality its class predictions may vary.</p> <p>So given a sequence of class predictions for the single object, I'd like to measure how consi...
<python><machine-learning><scikit-learn><statistics><classification>
2024-03-26 14:41:53
1
325
wouterio
78,225,973
10,770,967
Checking for substring from a frame A in a different Frame B, with different sizes for each frame
<p>I do have a question hoping - I am confindet that you can help me out. Suppose I do have two frames, each having multiple columns, but for simplicity let's focus on one column per frame. <strong>Important</strong>: <strong>Both frame are different in size, with A being shorter</strong></p> <pre><code>import pandas a...
<python><pandas><numpy>
2024-03-26 14:16:00
3
402
SMS
78,225,962
8,849,071
How to use SQL Alchemy models the same way than django models
<p>I have been using fast api for a few days and passing the <code>db</code> session around is starting to bother me a bit. In my previous project I was using a django backend, where to make queries I only needed to import the model. Something like:</p> <pre class="lang-py prettyprint-override"><code>from models import...
<python><django><sqlalchemy><fastapi>
2024-03-26 14:14:25
0
2,163
Antonio Gamiz Delgado
78,225,953
16,759,116
Why is `if x is None: pass` faster than `x is None` alone?
<p>Timing results in Python 3.12 (and similar with 3.11 and 3.13 on different machines):</p> <pre><code>When x = None: 13.8 ns x is None 10.1 ns if x is None: pass When x = True: 13.9 ns x is None 11.1 ns if x is None: pass </code></pre> <p>How can doing <strong>more</strong> take <strong>less</strong> time?</p> <...
<python><performance><cpython><micro-optimization><python-internals>
2024-03-26 14:12:02
2
10,901
no comment
78,225,920
1,194,864
Why next(iter(train_dataloader)) takes long execution time in PyTorch
<p>I am trying to load a local dataset with images (around 225 images in total) using the following code:</p> <pre><code># Set the batch size BATCH_SIZE = 32 # Create data loaders train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders( train_dir=train_dir, test_dir=test_dir, transform=ma...
<python><pytorch><iteration>
2024-03-26 14:04:35
2
5,452
Jose Ramon
78,225,774
1,073,784
Why does setting flags on an NDArray view result in allocations? Are they guaranteed to be bounded?
<p>Consider this code:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import itertools def get_view(arr): view = arr.view() view.flags.writeable = False # this line causes memory to leak? return view def main(): for _ in itertools.count(): get_view(np.zeros(1000)) ...
<python><numpy><memory-leaks><numpy-ndarray>
2024-03-26 13:41:16
1
1,134
Sami Liedes
78,225,545
5,330,527
Display a filtered result from ManyToMany through model in Admin
<p>This is my models.py:</p> <pre><code>class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{}, {}'.format(self.surname, self.forename) class PersonRole(models.M...
<python><python-3.x><django><django-models>
2024-03-26 13:04:36
1
786
HBMCS
78,225,397
4,435,175
Replace chars in existing column names without creating new columns
<p>I am reading a csv file and need to normalize the column names as part of a larger function chaining operation. I want to do everything with function chaining.</p> <p>When using the recommended <code>name.map</code> function for replacing chars in columns like:</p> <pre><code>import polars as pl df = pl.DataFrame( ...
<python><dataframe><replace><python-polars><chaining>
2024-03-26 12:40:36
1
2,980
Vega
78,225,278
14,034,263
getting "Failed to create meeting error 401 Client Error: Unauthorized for url: https://api.zoom.us/v2/users/me/meetings"
<p>I have added the client id and secrete key and if i am autharizing the app from postman its working but as soon as i tried to ping the api with my app it giving 401 error.</p> <p>how can i authorize my app into zoom app and can create meeting with dynamic token</p> <pre><code> authrization_url = 'http...
<python><django><django-views><zoom-sdk>
2024-03-26 12:17:54
1
359
Vishal Pandey
78,225,208
15,205,097
python-docx: Remove bibliography (w:sdt) section
<p>My end goal here is to find and remove any bibliography section from a Microsoft Word document.</p> <p>As mentioned in <a href="https://github.com/python-openxml/python-docx/issues/155" rel="nofollow noreferrer">this issue</a>. There currently isn't any API support for <code>w:sdt</code> tags (which I think is only ...
<python><python-3.x><ms-word><python-docx>
2024-03-26 12:08:13
2
306
Charlie Clarke
78,225,106
5,980,655
Downsample a pandas dataframe keeping same proportion of target in every month
<p>I have a pandas dataframe <code>df</code> with column <code>'TARGET'</code> which takes values of <code>0</code> or <code>1</code> and column <code>'MONTH'</code> which collects different months:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>MONTH</th> <th>#_OBS_TARGET=0</th> <th>#_OBS_...
<python><pandas><dataframe><data-manipulation><downsampling>
2024-03-26 11:52:45
2
1,035
Ale
78,225,040
3,759,627
In Polars, how do you generate a column of lists, where each list is a range() defined by another column of type Int?
<p>Given a sample DataFrame <code>df</code></p> <pre><code>&gt;&gt;&gt; df = pl.DataFrame({'l': [3,5,8]}) &gt;&gt;&gt; df shape: (3, 1) ┌─────┐ │ l │ │ --- │ │ i64 │ ╞═════╡ │ 3 │ │ 5 │ │ 8 │ └─────┘ </code></pre> <p>How do I make a new column that looks like this?</p> <pre><code>&gt;&gt;&gt; df shape: (3, 2) ┌...
<python><dataframe><python-polars>
2024-03-26 11:41:46
1
339
Horace
78,224,806
3,169,248
Is there a way to use regex in python data.table (apart from re.match)?
<p>I am trying to convert a column in py data.table to integer. The column contains whitespace and other unwanted characters, with those removed it could be cast to integer. I am failing to do this task in py data.table (whereas I can do it in polars, python, R data.table):</p> <pre><code># remove .00 if exists, minus ...
<python><regex><py-datatable>
2024-03-26 11:03:55
1
343
itarill
78,224,725
2,768,038
Sharing venv python packages to optimise docker image size
<p>I have a docker container where I am installing multiple versions of a package into different venvs so that users of the docker image can quickly change between the package using <code>PATH</code> env to point to the version they want.</p> <p>However this docker image is currently growing massively and taking a long...
<python><docker><pip>
2024-03-26 10:51:16
0
4,305
maxisme
78,224,557
6,649,591
langchain: how to use a custom deployed fastAPI embedding model locally?
<p>I want to build a retriever in Langchain and want to use an already deployed fastAPI embedding model. How could I do that?</p> <pre class="lang-python prettyprint-override"><code>from langchain_community.vectorstores import DocArrayInMemorySearch embeddings_model = requests.post(&quot;http://internal-server/embeddi...
<python><python-requests><langchain>
2024-03-26 10:27:08
1
487
Christian
78,224,436
5,550,833
Python - wait for a websocket response in a sync method
<p>i'm facing a problem with Asyncio, web sockets and sync calls.</p> <p>We have an application which uses websockets and Flask.</p> <p>Websockets are managed with asyncio, we receive messages on</p> <pre><code>async def on_message(message): ** some logic await doStuff(message) </code></pre> <p>The problem is tha...
<python><websocket><python-asyncio>
2024-03-26 10:07:19
1
3,258
MarioC
78,224,389
2,862,945
Interpolating 3D volumetric data with scipy's RegularGridInterpolator
<p>I have a 3D array with some volumetric data, i.e. at each grid points I have some value representing a magnitude of a certain quantity. I want to interpolate that array using scipy's <code>RegularGridInterpolator</code>, but I am using it wrong.</p> <p>To have a simple example, I use here a circle which I would like...
<python><numpy><scipy><interpolation>
2024-03-26 09:59:20
2
2,029
Alf
78,224,380
3,827,970
How to derive snakemake wildcards from python objects?
<p>I am learning snakemake to develop genomics pipelines. Since the inputs/outputs will get very diverse very quickly, I thought to spend some extra time understanding the basics of building snakemake script. My goal is to keep the code explicit and extendable by using python objects, but at the same time convert it fr...
<python><bioinformatics><snakemake>
2024-03-26 09:56:37
1
650
Zingo
78,224,291
999,162
VSCode task with pyenv and zsh
<p>I'm having an issue with configuring tasks for VSCode while using pyenv-virtualenv (not virtual env!), kind of similar to <a href="https://stackoverflow.com/questions/71594920/vscode-pyenv-not-integrated">this</a> but it is not solved and it also refers only to .zshrc not .zprofile.</p> <p>I have a a pyenv environme...
<python><zsh><pyenv><zshrc><pyenv-virtualenv>
2024-03-26 09:40:52
1
5,274
kontur
78,224,121
3,433,875
Annotate at the top of a marker with varying sizes in matplotlib
<p>Can I get the coordinates of markers to move the annotation to the top of the triangle?</p> <pre><code>import matplotlib.pyplot as plt X = [1,2,3,4,5] Y = [1,1,1,1,1] labels = 'ABCDE' sizes = [1000, 1500, 2000, 2500, 3000] fig, ax = plt.subplots() ax.scatter(X, Y, s= sizes, marker = 10) for x, y, label, size in ...
<python><python-3.x><matplotlib>
2024-03-26 09:12:32
1
363
ruthpozuelo
78,224,035
12,892,937
Python pyinstaller ModuleNotFoundError even with hidden import
<p>I have 2 files like this. <code>addict</code> is a library, installed by using <code>pip install addict</code>. <a href="https://pypi.org/project/addict/" rel="nofollow noreferrer">https://pypi.org/project/addict/</a></p> <pre><code># myimport.py from addict import Dict </code></pre> <p>and</p> <pre><code># main.py ...
<python><pyinstaller><python-import>
2024-03-26 08:58:10
0
1,831
Huy Le
78,223,861
15,592,363
ChatWork does not give me access token
<p>I am trying to make a small app to send messages to the ChatWork app. I manage to get the code from the authorization when I sign in, but when I try to use this code to generate the token, I am getting 401. So, really do not know what I am doing wrong. I appreciate your help. This is the code:</p> <pre><code>import ...
<python><authentication><oauth><httprequest>
2024-03-26 08:25:31
1
1,008
Luis Alejandro Vargas Ramos
78,223,432
7,393,694
Find the list of "current" maxima with respect to the list index
<p>Given a list <code>a</code>, I'd like to know all indices <code>i</code> such that <code>a[i]&gt;a[j]</code> for all <code>j&lt;i</code>.</p> <p>I can come up with a simple for loop, but wondered whether there's some built in version of that:</p> <pre><code>max_values = [a[0]] indices = [0] for i, x in enumerate(a):...
<python><list>
2024-03-26 06:52:37
1
2,149
Jürg W. Spaak
78,223,249
4,683,697
Disagreement in obtaining inverse of Sympy matrix in two ways
<p>I am attempting to invert a simple numerical matrix in <code>Sympy</code>. I start with a matrix:</p> <pre><code>In [56]: A_MATRIX_M Out[56]: ⎡0.174683794941032 0.174688696013867 0.174688696013957 0.174683794941032 0.174688696013867 0.174688696013957 ⎤ ⎢ ...
<python><matrix><sympy><inversion>
2024-03-26 06:03:09
1
2,544
Joseph Farah
78,223,186
4,443,784
What's the behavior of psycopg2 cursor fetchmany
<p>I am confused about the behavior of psycopg2 cursor fetchmany method compared with paging query</p> <p>Say I have a query that will get 10000 rows in total.</p> <p>When I use <code>fetchall</code>, I understand that the 10000 rows will be fetched back to the python process in one round.</p> <p>But when I use fetchma...
<python><psycopg2>
2024-03-26 05:43:32
0
6,382
Tom
78,223,150
406,281
ruamel.yaml dump: how to stop map scalar values from being moved to a new indented line?
<p>Hard to describe succinctly, so I'll demonstrate.</p> <pre class="lang-py prettyprint-override"><code>from sys import stdout from ruamel.yaml import YAML yml = YAML() doc = &quot;&quot;&quot; kind: ImageSetConfiguration apiVersion: mirror.openshift.io/v1alpha2 storageConfig: local: path: ./operator-images mirr...
<python><ruamel.yaml>
2024-03-26 05:30:47
1
3,577
rsaw
78,222,933
4,399,016
Converting a List of Dictionaries to Pandas Dataframe
<p>I have this code:</p> <pre><code>import urllib.request, json url = &quot;https://api.wto.org/timeseries/v1/indicator_categories?lang=1&quot; hdr ={ # Request headers 'Cache-Control': 'no-cache', 'Ocp-Apim-Subscription-Key': '21cda66d75fc4010b8b4d889f4af6ccd', } req = urllib.request.Request(url, hea...
<python><pandas><dictionary>
2024-03-26 04:08:34
1
680
prashanth manohar
78,222,916
6,702,598
AWS Lambda: python packages not found after deploy
<h5>What I do</h5> <p>I have a the standard hello_world sample code from aws, created via <code>sam init --runtime &lt;runtime&gt; --name &lt;project-name&gt;</code>.</p> <p>I add <code>pytest</code> to requirements.txt and add <code>import pytest</code> to <code>app.py</code>.</p> <p>I build and deploy via <code>sam b...
<python><python-3.x><amazon-web-services><aws-lambda>
2024-03-26 04:03:19
1
3,673
DarkTrick
78,222,808
3,735,871
Airflow schedule once but doesn't start
<p>I scheduled an Airflow dag like below. What I expect to see is the dag runs once with execution date 2023-08-01. However nothing happens and no dag runs were created. How can I schedule a job to be run once on a specific date?</p> <pre><code>start_date: '2023-08-01T00:00:00' catchup: True schedule_interval: 'Once' <...
<python><airflow>
2024-03-26 03:26:48
0
367
user3735871
78,222,738
11,462,274
Tkinter when double-clicking the left mouse button to reach the maximum height of the window, one of the buttons is activated incorrectly
<p>The only desired action in my <code>Tkinter</code> window is when clicking on one of the buttons, it prints the market ID and the player ID.</p> <p>But when I double-click the mouse on the edge of the window in the blue circled region in order to vertically extend the window to maximum fit with the Windows screen, a...
<python><tkinter><tkinter-canvas>
2024-03-26 03:03:04
2
2,222
Digital Farmer
78,222,605
10,300,327
Mounting /usr/local/bin/ to python:3 docker image
<p>I want to mount <code>/usr/local/bin/</code> to my host machine from docker python:3. The reason I want to do this is because I want my PyCharm Community edition to be able to use my docker interpreter for my IDE.</p> <p>Here is my docker compose file:</p> <pre class="lang-yaml prettyprint-override"><code>version: '...
<python><docker><pycharm><jetbrains-ide>
2024-03-26 02:05:16
1
323
James Green
78,222,548
12,462,568
How do I amend this Langchain script so it only outputs the AI response but is still conversational and the AI still has memory
<p>How do I amend this script which uses Langchain's &quot;ConversationChain&quot; and &quot;ConversationBufferMemory&quot; so that it only outputs the AI response but is still conversational and the AI still has memory.</p> <p>I have this Python script below:</p> <pre><code>from langchain_community.llms import Bedrock...
<python><langchain><large-language-model>
2024-03-26 01:45:07
1
2,190
Leockl
78,222,510
1,914,781
print a int value to char sequence
<p>I have a 4 byte int variable which contains 'h264' chars. what's proper way to print it as char sequence as well.</p> <pre><code>x = 0x68323634 # h264 print(str(x)) </code></pre> <p>current output is:</p> <pre><code>1748121140 </code></pre> <p>expect output is:</p> <pre><code>h264 </code></pre>
<python>
2024-03-26 01:33:06
1
9,011
lucky1928
78,222,105
4,873,946
how to remove certain columns from dataframe
<p>I am just starting with python and pandas. I have a dataframe that looks like this:</p> <pre><code>1 2.3 1 2.5 1 4.5 2 2.3 2 2.5 2 4.5 3 2.3 3 2.5 3 4.5 4 2.3 4 2.5 4 4.5 5 2.3 5 2.5 5 4.5 </code></pre> <p>I am trying to remove all the identical columns except for the first one so I want to ...
<python><pandas>
2024-03-25 22:37:48
1
454
lucian
78,222,081
8,761,554
Converting streamlit library time input to milliseconds since epoch
<p>How to convert input from a streamlit time input <a href="https://docs.streamlit.io/library/api-reference/widgets/st.time_input" rel="nofollow noreferrer">widget</a> to milliseconds since Unix Epoch? Time of the day comes from the time input widget and date have in the following string format</p> <pre><code>day = '2...
<python><datetime><time><streamlit>
2024-03-25 22:27:47
1
341
Sam333
78,222,016
2,862,945
Combining multiple plots with mayavi
<p>I have a 3D contour plot, which I make with python's mayavi library, into which I want to overplot some arrows. For the contour plot I use <code>mlab.contour3d</code> and for the arrow <code>mlab.quiver3d</code> (<a href="http://docs.enthought.com/mayavi/mayavi/mlab.html" rel="nofollow noreferrer">link to the mlab d...
<python><3d><mayavi><mayavi.mlab>
2024-03-25 22:06:10
1
2,029
Alf
78,221,936
759,991
Currency format not getting allied to google sheet with gspread library
<p>I have CSV data that looks like this:</p> <pre><code>&quot;Service Name ap-northeast-1&quot;,&quot;2023-03&quot;,&quot;2023-04&quot;,&quot;2023-05&quot;,&quot;2023-06&quot;,&quot;2023-07&quot;,&quot;2023-08&quot;,&quot;2023-09&quot;,&quot;2023-10&quot;,&quot;2023-11&quot;,&quot;2023-12&quot;,&quot;2024-01&quot;,&q...
<python><google-sheets><google-sheets-api><gspread>
2024-03-25 21:44:57
1
10,590
Red Cricket
78,221,903
5,790,653
Using cookies in python requests doesn't login to the website
<p>I use my own laptop's Google Chrome to login to a website a human, and I also use this Chrome's <a href="https://chromewebstore.google.com/detail/cookiemanager-cookie-edit/hdhngoamekjhmnpenphenpaiindoinpo" rel="nofollow noreferrer">extension</a> which gives me a json output of the website's cookies.</p> <p>I save th...
<python>
2024-03-25 21:38:20
1
4,175
Saeed
78,221,858
1,317,018
Adding sliding window dimension to data causes error: "Expected 3D or 4D (batch mode) tensor ..."
<p>I wrote a pytorch data loader which used to return data of shape <code>(4,1,192,320)</code> representing the 4 samples of single channel image, each of size <code>192 x 320</code>. I then used to unfold it into shape <code>(4,15,64,64)</code> (Note that <code>192*320 = 15*64*64</code>). Resize it to shape <code>(4,1...
<python><pytorch><torchvision><pytorch-dataloader>
2024-03-25 21:24:27
0
25,281
Mahesha999
78,221,852
18,814,386
Merging and concatenating simultaneously
<p>I have multiple data frames, each representing monthly progress. My mission is to join them with two condition step by step.</p> <p>So here is three sample data frame, and I will try to explain what I want to achieve.</p> <pre><code>import pandas as pd data_22_3 = { 'id_number': ['A123', 'B456', 'C789'], 'c...
<python><pandas><dataframe><merge><concatenation>
2024-03-25 21:23:40
3
394
Ranger
78,221,628
11,572,712
PyCharm: Unresolved attribute reference for class MyClass - Initialization of variables as instance-level variables
<p>I have code where I want to initialize prometheus variables to get some metrics.</p> <pre><code>from prometheus_client import Counter, Gauge, Histogram import time class MyClass: def __init__(self): self.number_of_clicks: Optional[Counter] self.number_of_items: Optional[Gauge]...
<python><pycharm><prometheus>
2024-03-25 20:30:23
0
1,508
Tobitor
78,221,601
6,331,353
Installing an older version of cli tox
<p>I cannot use the newest version of tox, this is because it automatically installs python3.12, which causes other problems for me, so I must use python3.11</p> <hr /> <h1>Brew</h1> <p>trying to install an older version via <code>brew</code> does not work</p> <pre><code>% brew install tox@4.11.3 Warning: No available ...
<python><tox>
2024-03-25 20:25:57
1
2,335
Sam
78,221,438
13,578,682
Python warnings filter is not hiding this DeprecationWarning
<p>Even when switching to <code>mstrio.project_objects.dashboard</code> it still shows deprecation warning and ignoring it doesn't work</p> <pre><code>$ pip install -Uq mstrio-py $ export PYTHONWARNINGS='ignore:mstrio.project_objects.dossier module is deprecated:DeprecationWarning' $ python3 -c 'from mstrio.project_obj...
<python><microstrategy>
2024-03-25 19:46:12
1
665
no step on snek
78,221,432
726,730
Many QPushButtons clicked connecting using exec()
<p>I have write this code:</p> <pre class="lang-py prettyprint-override"><code> def top_music_clips(self,clips): try: self.top_20_clips = clips counter = 0 for clip in self.top_20_clips: counter += 1 exec(&quot;self.main_self.ui.music_clip_&...
<python><pyqt5><exec><qpushbutton>
2024-03-25 19:45:08
0
2,427
Chris P
78,221,363
4,442,337
AttributeError: '_io.StringIO' object has no attribute 'buffer'?
<p>I have this function that simply writes a string into a stream buffer:</p> <pre class="lang-py prettyprint-override"><code>import sys from typing import IO def write(s: str, stream: IO[bytes] = sys.stdout.buffer): stream.write(s.encode()) stream.flush() </code></pre> <p>I'm using both flake8 and mypy which ...
<python><python-typing><pdoc>
2024-03-25 19:29:41
1
2,191
browser-bug
78,221,169
8,963,682
Single Tenant Teams Bot Authentication Error: Missing access_token
<p>I am developing a Teams bot using <code>FastAPI</code> and the <code>botbuilder-core</code> library in Python. I want to restrict the bot to be used only within my company and keep it as a single tenant application for confidentiality reasons. However, I am encountering an issue where the bot tries to send a message...
<python><azure><botframework><microsoft-teams><microsoft-graph-teams>
2024-03-25 18:53:32
1
617
NoNam4
78,221,152
986,612
How to detect idle time of mouse/keyboard only, not for other input devices?
<p><code>GetLastInputInfo()</code>, eg <a href="https://stackoverflow.com/questions/911856/detecting-idle-time-using-python">detecting idle time using python</a>, is sensitive to mouse and keyboard input, but it's also disturbed by game controller input, which I want to ignore.</p> <p>Is there an easy way to do this?</...
<python><windows><winapi>
2024-03-25 18:49:28
2
779
Zohar Levi
78,221,096
12,309,386
Polars more concise way to replace empty list with null
<p><strong>Question overview</strong></p> <p>I am extracting data from a newline-delimited JSON file by applying a series of transformations. One of my transformations results in a list of values; for cases where the list is empty, I want the value to be null rather than an empty list. I have code that works, but it ...
<python><dataframe><python-polars>
2024-03-25 18:37:21
1
927
teejay
78,220,893
433,926
How do I mock headers with connexion?
<p>I am using connexion to read a few headers in my productive code, i.e.:</p> <pre class="lang-py prettyprint-override"><code>from connexion import request def get_my_header() -&gt; str: return request.headers.get(&quot;my-header&quot;) </code></pre> <p>In the connexion docs I found the <a href="https://connexio...
<python><connexion>
2024-03-25 17:48:18
1
312
marikaner
78,220,785
9,110,646
How to do async SQL bulk insertion with pandas dataFrame.to_sql() and SQLAlchemy?
<p>I am trying to insert a bulk of data with <code>dataFrame.to_sql()</code> asynchronously. I also need to tackle the case that some data is already inside of the table (duplicates). It is a gene DB. My insertion function looks like this and is called in my router endpoint (FastAPI):</p> <pre><code>async def bulk_inse...
<python><pandas><postgresql><asynchronous><sqlalchemy>
2024-03-25 17:27:49
0
423
Pm740
78,220,723
525,865
FaceBook-Scraper (without API) works nicely - but Login Process failes some how
<p>working on the getting to run the Facebook-Scraper (cf <a href="https://github.com/kevinzg/facebook-scraper" rel="nofollow noreferrer">https://github.com/kevinzg/facebook-scraper</a> )</p> <pre><code>import facebook_scraper as fs # get POST_ID from the URL of the post which can have the following structure: # http...
<python><facebook><web-scraping><python-requests><web-crawler>
2024-03-25 17:16:29
0
1,223
zero
78,220,662
759,991
Adding blank row to google spread sheet
<p>I have this simple python script that creates a google spread sheet for me from a CSV file.</p> <pre><code>import gspread import csv import time # Authenticate using gspread.oauth() gc = gspread.oauth() # Open or create a new Google Sheets document spreadsheet = gc.create('Your Spreadsheet Name') # Read CSV data ...
<python><google-sheets>
2024-03-25 17:06:13
1
10,590
Red Cricket
78,220,655
1,421,907
How to enforce sympy to handle simplification with complex numbers?
<p>I am quite new on sympy and I try to make a matrix multiplication. The matrices are complex.</p> <p>Here is the code</p> <pre><code>import sympy as sp eps = sp.exp(2 * sp.pi * sp.I / 6) eps_star = sp.conjugate(eps) M = 1 / sp.sqrt(6) * sp.Matrix([ [1, 1, 1, 1, 1, 1], [1, eps_star, -eps, -1, -eps_star, eps...
<python><matrix><sympy><complex-numbers>
2024-03-25 17:04:17
1
9,870
Ger
78,220,644
1,863,912
how can i fix the ImportError cannot import name 'get_accounts'
<p>hi im trying out python and django for the first time and im trying to set up a simple route to display some data. The issue im running into is that when i try to run the webserver i keep getting this importError regarding one of the functions in my views.py file located in the accounts folder. any help would be gre...
<python><django>
2024-03-25 17:02:16
0
359
jordan
78,220,488
447,426
python mockito mocking of single method not working
<p>In my class under test i have this call that i want to mock:</p> <pre><code>from models.crud import create_plane, get_plane_by_id class PersistAircraftEvents: ... def persist_aircraft_event(self, aircraft_event: ReceivedAircraftEvent): ... # check if aircraft exists a...
<python><mockito-python>
2024-03-25 16:29:46
1
13,125
dermoritz
78,220,433
5,023,667
How to remove traceability relations dynamically in python-sphinx conf.py
<p>I'm using the traceability plugin for python-sphinx: <a href="https://melexis.github.io/sphinx-traceability-extension/readme.html" rel="nofollow noreferrer">sphinx traceaility plugin</a></p> <p>The test has the following .rst documentation:</p> <pre><code>@rst .. item:: TST-Example :applicable_to: PRD-ALL @en...
<python><python-sphinx><traceability>
2024-03-25 16:18:50
1
623
Shlomo Gottlieb
78,220,425
18,030,819
Gunicorn won't start Flask app because "Failed to parse 'app' as an attribute name or function call."
<p>I'm trying to run Flask app locally in the docker and I'm facing the following problem</p> <p>app.py:</p> <pre><code>class App: '''Base flask app''' def __init__(self): self.app = Flask(__name__) @property def flask_app(self) -&gt; Flask: '''Return flask app''' return s...
<python><flask><gunicorn>
2024-03-25 16:17:52
0
326
Devid Mercer
78,220,100
1,254,515
Get the n first elements from a list where list[i][0] == 'value'
<p>How do I get the <code>n</code> first elements from a list of lists where <code>list[i][0] == 'value'</code>?</p> <p>Currently I do these two steps:</p> <pre><code>items = [['value', 0], ['foo', 1], ['value', 2], ['value', 3], ['bar', 4]] n = 2 tmp_list = [] for item in items: if item[0] == 'value': tmp...
<python>
2024-03-25 15:20:33
2
323
Oliver Henriot
78,220,097
4,673,585
Python azure function app not reading sqlite db file correctly
<p>I have a storage account with a container named abc360. There is a folder in this container named sqlite_db_file. Sqlite db files will be dropped in this folder. File name would like this:</p> <pre><code>ABC100102_2_20230202.db </code></pre> <p>Path to the file looks like:</p> <pre><code>abc360/sqlite_db_file/ABC100...
<python><sqlite><azure-functions><azure-storage-account>
2024-03-25 15:19:59
1
337
Rahul Sharma
78,220,062
8,869,570
Canonical way to ensure float point division across py2 and py3?
<p>I have a function that needs to support both py2 and py3, unfortunately.</p> <p>Currently, there's a division op:</p> <pre><code>n = a / b </code></pre> <p><code>a</code> and <code>b</code> are usually whole numbers, but represented as floats, but from what I can see there's no guarantee that either is a float, so t...
<python><python-2.x><integer-division>
2024-03-25 15:14:11
0
2,328
24n8
78,220,036
7,331,538
Scrapy CrawlProcess is throwing reactor already installed
<p>I have N workers in paralell (instantiated from docker) that trigger a scrapy crawl from a script via <code>CrawlProcess</code>. Why is it that I am getting this error: <code>error: reactor already installed</code>? I simply have a function:</p> <pre><code>def foo(): process = CrawlerProcess(settings) stats...
<python><scrapy><twisted>
2024-03-25 15:09:40
0
2,377
bcsta
78,219,476
10,722,752
How to sort x-axis and get bar labels using plt
<p>I am using a subplot to plot 3 dataframes as below:</p> <pre><code>np.random.seed(0) df1 = pd.DataFrame({'id' : np.random.choice(['a', 'b', 'c', 'd', 'e'], size = 20), 'score' : np.random.normal(size = 20)}) df1['score'] = np.abs(df1['score']) df2 = pd.DataFrame({'id' : np.random.choice(['a', 'b',...
<python><pandas><matplotlib>
2024-03-25 13:33:54
1
11,560
Karthik S
78,219,407
2,726,335
Python SFTP Connection Fabric files.exist does not find the file
<p>I'm maintaining code written by a retired colleague. This code uses <code>Fabric</code> 2.7.1 to download files from our old FTP server.</p> <pre><code>from fabric import Connection from patchwork import files ... if not files.exists(conn, groups['file']): raise FileNotFoundError(f'No such file: {groups[&quot;fi...
<python><python-3.x><sftp><fabric>
2024-03-25 13:24:05
1
617
Powerriegel
78,219,238
7,803,702
Why does ` arr[n:].extend(arr[:n]) ` in the 1st example code print the original arr?
<p>1st Example</p> <pre class="lang-py prettyprint-override"><code>def LShift(arr,n): arr[n:].extend(arr[:n]) # changes arr itself print (arr) arr = [10,20,54,5656,30,40,12,11] LShift(arr,2) </code></pre> <p>Output <code>[10,20,54,5656,30,40,12,11]</code> I do not know why the original array is printed. P...
<python>
2024-03-25 12:56:50
2
958
Carl_M
78,219,217
11,159,734
Langchain | ImportError: cannot import name 'create_model' from 'langchain_core.runnables.utils'
<p>I just installed the latest version of langchain in a new empty conda env (python 3.11.7) using pip. Pip now lists me the following langchain packages:</p> <pre><code>langchain 0.1.13 langchain-community 0.0.29 langchain-core 0.1.33 langchain-text-spl...
<python><langchain>
2024-03-25 12:53:07
0
1,025
Daniel
78,219,123
8,289,095
Telemetry in a Python Bottle API
<p>I have a simple Python Bottle API used to support an iOS app. It is hosted on Heroku.</p> <p>I use TelemetryDeck for analytics, so I want to send signals with each API call. I'm not using Node so cannot use their JS SDK and thus I have to send signals over HTTP.</p> <p>Here is my function for sending telemetry signa...
<python><bottle><telemetry>
2024-03-25 12:35:32
1
4,441
Chris
78,219,090
17,471,060
Pythonic way to locate index and column of polars dataframe based on absolute sorted values
<p>I have a dataframe containing multiple columns out of which 1st column is regarded as index. The remaining columns containing values that I want to sort by absolute key and thereafter create new dataframe indicating original dataframe location in terms of index and column of the sorted values. Highly appreciate if s...
<python><dataframe><python-polars>
2024-03-25 12:30:27
1
344
beta green
78,218,927
8,849,071
Why do we need to use a generator when creating a connection to the database in FastAPI?
<p>I have been learning a little bit about API. I have seen this snippet suggested in the <a href="https://fastapi.tiangolo.com/tutorial/sql-databases/#create-the-database-tables" rel="nofollow noreferrer">documentation</a>:</p> <pre class="lang-py prettyprint-override"><code>def get_db(): db = SessionLocal() t...
<python><database><fastapi>
2024-03-25 12:02:17
2
2,163
Antonio Gamiz Delgado
78,218,783
10,800,115
String to Literal throws incompatible type error
<p>Running mypy on the below snippet:</p> <pre class="lang-py prettyprint-override"><code>from typing import Literal, Final def extract_literal(d2: Literal[&quot;b&quot;, &quot;c&quot;]) -&gt; str: if d2 == &quot;b&quot;: return &quot;BA&quot; if d2 == &quot;c&quot;: return &quot;BC&quot; ...
<python><mypy><python-typing>
2024-03-25 11:34:21
1
365
ashnair1
78,218,653
713,200
How to resolve is_selected() not returning True even if the checkbox is selected?
<p>I'm using Selenium + python to check the status of a checkbox but it always returns False.</p> <p>Checkbox HTML <a href="https://i.sstatic.net/6rBsL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6rBsL.png" alt="Checkbox HTML" /></a></p> <p>I'm using XPath</p> <pre><code>value = &quot;//span[@title='...
<python><selenium-webdriver><checkbox><webdriver>
2024-03-25 11:13:11
1
950
mac
78,218,345
3,759,627
In Polars, how do you multiply a column of floats with a column of lists?
<p>Given an example dataframe where we have column 'b' containing lists, and each list has the same length (so it also could be converted to arrays)</p> <pre class="lang-py prettyprint-override"><code>df_test = pl.DataFrame({'a': [1., 2., 3.], 'b': [[2,2,2], [3,3,3], [4,4,4]]}) df_test shape: (3, 2) ┌─────┬───────────┐...
<python><dataframe><list><python-polars>
2024-03-25 10:19:46
4
339
Horace
78,218,276
12,379,095
Getting error "TypeError: no numeric data to plot" in a Time Series ARIMA analysis
<p>I am trying to follow a tutorial whereby an ARIMA time series analysis using <em>differenced data</em> is being done:</p> <p>The following is the python code:</p> <pre><code>def difference(dataset): diff = list() for i in range(1, len(dataset)): value = dataset[i] - dataset[i - 1] diff.append...
<python><pandas><matplotlib><machine-learning><arima>
2024-03-25 10:07:18
2
574
Stop War
78,218,201
12,101,193
Nested dir name in python multiprocess shared_memory - Invalid argument
<p>It seems SharedMemory only supports the flat name, does anyone know why or any ref? I have searched on the internet for quite a long time, but didn't find any relative..</p> <pre><code>from multiprocessing import shared_memory shm = shared_memory.SharedMemory(name='test_dir/test_name', size=16, create=True) </code><...
<python><multiprocessing><shared-memory>
2024-03-25 09:50:46
1
524
moon548834
78,218,026
14,196,341
Type inference across functions / reuse type hints
<p>I have one function within an external library that has a complicated type hint (&quot;inner&quot;). In my code, I have another function (&quot;outer&quot;) calling this function. One of the paramters of this function will be passed on to the hinted function. I would like to have mypy typecheck the parameter. How ca...
<python><mypy><python-typing>
2024-03-25 09:11:13
1
392
Felix Zimmermann
78,217,890
2,989,330
How to mock a function in multiple modules
<p>I am currently working on extending a third-party code base. This code base unfortunately tightly couples its <code>get_args</code> with every other function. <code>get_args</code> is basically just a getter for a global object <code>_ARGS</code>. Now, I'd like to modify the args for a single function call without a...
<python><mocking>
2024-03-25 08:42:23
2
3,203
Green 绿色
78,217,690
6,540,762
Spire.Xls - spire.xls.common.SpireException: TypeInitialization_Type_NoTypeAvailable error when instantiating Workbook object
<p>I'm currently using <code>Spire.Xls==14.2.2</code> (the only version available at this point of writing), using macOS Intel chip.</p> <p>When running a simple code snippet below:</p> <pre><code>from spire.xls import Workbook workbook = Workbook() </code></pre> <p>I'm getting the below error:</p> <pre><code>Tracebac...
<python><excel><spire.xls>
2024-03-25 07:57:57
1
1,546
chaooder
78,217,661
5,790,653
How to count values of each key in a list
<p>I have a list like this:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ {'state': 'active', 'name': 'Name1'}, {'state': 'active', 'name': 'Name2'}, {'state': 'inactive', 'name': 'Name3'}, {'state': 'active', 'name': 'Name2'}, {'state': 'active', 'name': 'Name1'}, {'state': 'ina...
<python>
2024-03-25 07:50:31
2
4,175
Saeed
78,217,260
4,171,008
Caching python in GitHub Actions
<p>I'm trying to cache the Python installation and dependencies in &quot;Self-hosted&quot; GitHub Action, the problem is the restore of cached pip is taking too long and results in timeout, and I could not figure out why.<br /> What I checked:<br /> -&gt; <a href="https://stackoverflow.com/questions/68896173/issue-cach...
<python><caching><pip><github-actions><cicd>
2024-03-25 05:55:23
1
1,884
Ahmad
78,217,187
8,930,751
Schedule calculation exactly at every 15 mins using Python
<p>I have followed the example which is <a href="https://stackoverflow.com/questions/76834821/scheduling-python-calculations-using-schedule-library">shown here</a>.</p> <p>It is working as expected, but with a small problem. If the do_job() method takes more than a minute to finish. It's waiting for another 1 min from ...
<python><python-3.x><schedule>
2024-03-25 05:21:53
2
2,416
CrazyCoder
78,216,921
466,369
Langchain/FastAPI application encountered 404 error
<p>I am following this langchain tutorial example <a href="https://python.langchain.com/docs/get_started/quickstart#client" rel="nofollow noreferrer">here</a>.</p> <p>Why do I get 404 error? Here is the code, which is exactly the same as the example without any modification. After launching the application and navigati...
<python><fastapi><langchain>
2024-03-25 03:16:05
1
572
steamfood
78,216,765
348,168
ModuleNotFoundError: No module named 'PyJSONCanvas'
<p>In windows 11, I am using WinPython64, 3.11 version. Executed the command <code>pip install PyJSONCanvas</code> as per the instruction given in <a href="https://pypi.org/project/PyJSONCanvas/" rel="nofollow noreferrer">https://pypi.org/project/PyJSONCanvas/</a></p> <p><code>import PyJSONCanvas</code> gives the follo...
<python><json>
2024-03-25 02:03:01
0
4,378
Vinod
78,216,652
1,549,736
How do I read the project version number stored in the pyproject.toml file from within the tox.ini file?
<p>I want to include an <code>upload</code> environment in my <code>tox.ini</code> file. But, that requires resolving the project version dynamically; something like:</p> <pre class="lang-yaml prettyprint-override"><code>[testenv:upload] basepython = python3.11 skip_install = true deps = twine commands = twine ...
<python><tox><pyproject.toml>
2024-03-25 01:10:17
2
2,018
David Banas
78,216,636
1,030,648
How do I fix the jsonobject architecture problem I am having in PyCharm CE when the terminal says the package is installed?
<p>How do I get <code>jsonobject</code> to install even though, apparently, my terminal thinks is already installed?</p> <p>I am trying to work through the a Python project that I have copied to a repo and cloned from <a href="https://github.com/InstituteforDiseaseModeling/synthpops" rel="nofollow noreferrer">the open-...
<python><pycharm><x86-64>
2024-03-25 01:00:55
0
1,383
Michelle
78,216,509
13,503,715
Mongo DB + Streamlit + github actions
<p>I am integrating mongoDB with streamlit ! so to store MONGO secrets I am using github actions. I have only one problem.</p> <p>I am not able to read those secrets. in my python file. I have mostly tried everything. so last option i am trying to do is run directly from workflow .YAML file. like a command line file wi...
<python><mongodb><github><github-actions><streamlit>
2024-03-24 23:56:26
0
328
shyam_gupta
78,216,476
1,174,102
How to get kivy to set its defaults in the Config at runtime?
<p>How can I tell Kivy to update a given Config with its default values at runtime?</p> <p>I have a &quot;reset settings to defaults&quot; button in my app that deletes all of the entries in my <a href="https://kivy.org/doc/stable/api-kivy.config.html" rel="nofollow noreferrer">Kivy Config</a>, including in the <code>[...
<python><kivy><default><configparser>
2024-03-24 23:38:37
1
2,923
Michael Altfield
78,216,192
13,705,050
Vertical Scrollbar disappears when window width passes threshold
<p>This code creates a window with a text box and a vertical scroll bar. If the window's width is changed by dragging the edge of the window, and the width decreases below some threshold (~660 pixels) the vertical scrollbar disappears.</p> <p>What is causing the vertical scroll bar to be pushed out of the window when ...
<python><tkinter>
2024-03-24 21:34:26
2
825
TehDrunkSailor
78,216,147
6,606,057
Cannot install Mamba on Python 3.12
<p>I'm trying to get Mamba to run on Spyder 5.5.3 with Python 3.8.10 64-bit | Qt 5.15.2 | PyQt5 5.15.10 | Windows 10 (AMD64)</p> <p>When I run !mamba install bs4==4.10.0 -y</p> <p><a href="https://i.sstatic.net/Bhkk9.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Bhkk9.jpg" alt="enter image description ...
<python><python-3.x><installation><mamba>
2024-03-24 21:18:36
1
485
Englishman Bob
78,216,117
1,853,284
"Variable ${workspaceFolder} can not be resolved" error in new VSC installation
<p>I installed Visual Studio Code 1.87.2 followed by the addons for R and Python. I then opened an .ipynb notebook that a collaborator shared.</p> <p>I tried running the first code section:</p> <pre><code>#load dataframe xdata=read.csv(&quot;/Users/path/xdata.csv&quot;, header = TRUE, sep = &quot;,&quot;,quote = &quot;...
<python><r><visual-studio-code>
2024-03-24 21:08:22
0
679
z8080
78,216,040
1,174,102
How to update all label's text properties after changing default_font in Kivy?
<p>How can I update all of my Kivy widgets to use the new <code>default_font</code> on runtime (without restarting the app)?</p> <p>I created a Settings screen in my kivy app where a user can select the font that they want the app to use. After the user selects their desired font in the GUI, I update the <code>default_...
<python><fonts><kivy><font-face>
2024-03-24 20:43:06
1
2,923
Michael Altfield
78,215,785
726,730
PyCharm & Python: Reboot PyQt5 Application
<p>I use this code to reboot a pyqt5 application:</p> <pre class="lang-py prettyprint-override"><code>os.execl(sys.executable, sys.executable, *['&quot;'+sys.argv[0]+'&quot;', &quot;-t&quot;, '2']) </code></pre> <p>The main problem with this command is that after pyqt5 exit on first exit, then i cannot manage the scrip...
<python><pyqt5><restart>
2024-03-24 19:11:11
0
2,427
Chris P