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,523,132
9,751,398
Actual Python version in conda environment when running in Google Colab?
<p>I run notebooks in Google Colab and there I install miniconda and create an appropriate environment for the application. It is good to be able to read out what Python version you actually have in the environment.</p> <p>For example:</p> <p>Calling platform.python_version() gives 3.10.12</p> <p>Calling !Python --vers...
<python><jupyter-notebook><google-colaboratory><miniconda>
2024-05-23 12:30:37
1
1,156
janpeter
78,523,114
1,084,174
Why I am getting IndexError
<p>Why following code:</p> <pre><code>import torch import torch.nn as nn input_tensor = torch.tensor([[2.0]]) target_tensor = torch.tensor([0], dtype=torch.long) loss_function = nn.CrossEntropyLoss() loss = loss_function(input_tensor, target_tensor) print(loss) input_tensor = torch.tensor([[2.0]]) target_tensor = to...
<python><pytorch><loss-function>
2024-05-23 12:27:10
1
40,671
Sazzad Hissain Khan
78,523,087
14,463,396
Pandas .replace() with multiple many to one mappings
<p>I have a pandas column with some strings in. I want to group up the strings that are similar, and replace with their category. In my real example, I have 6 different strings, and I wanted to replace then with 3 different strings for their categories.</p> <p>I found <a href="https://stackoverflow.com/questions/4692...
<python><pandas>
2024-05-23 12:21:42
1
3,395
Emi OB
78,523,044
12,137,722
MT5 python module: downloading OHLC data
<p>I am trying to download OHLC data from MT5 using the python module. if I use copy_rates_from_pos, all works fine.</p> <p>If I use dates, the problem is the resulting data is not aligned with the times on the chart.</p> <p>Background: My broker is GMT +2/+3. It changes daylight savings based upon NYC. So there are...
<python><pandas><metatrader5>
2024-05-23 12:12:50
1
314
Jonathan Stearns
78,522,584
8,675,314
Is it possible to change the display of a Binaryfield model attribute in the Django admin panel, based on the value of another attribute?
<p>I'm working on a project where I have a model which stores some BinaryField in the database.</p> <pre class="lang-py prettyprint-override"><code> class Entry(models.Model): ... params = models.JSONField() body = models.BinaryField() ... </code></pre> <p>params will have a tag with the type of the bod...
<python><django><django-models><django-admin>
2024-05-23 10:48:13
1
415
Basil
78,522,348
1,473,517
How to register np.float128 as a valid numba type so I can sum an array?
<p>I want to write a numba function that takes the sum of an array of np.float128s. These have 80 bits of precision on my set up but if it is easier to cast them to real float128s I would be happy with that as well. My goal is to be able to sum an array of np.float128s quickly and without loss of precision, ultimately...
<python><numba><llvm-ir>
2024-05-23 10:05:08
3
21,513
Simd
78,522,302
3,608,591
Python (Jupyter) Notebook in browser: no horizontal scrollbar at the bottom of a cell?
<p>I use python notebook (browser) often.</p> <p>There's a vertical scrollbar on a cell, but <strong>no horizontal scrollbar</strong> to allow me to access columns on the <strong>right side of a cell</strong>:</p> <p><a href="https://i.sstatic.net/BHifLl3z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/...
<python><pandas><jupyter-notebook><display>
2024-05-23 09:57:57
1
317
Xhattam
78,522,213
16,219,380
How to use elements created in a kivy file to create another element in another kivy file?
<p>I'm creating a button in StackLayout in file <code>info_options.kv</code>. Now I want to call a function in class <code>InfoOptionsPanel</code> whenever this button is pressed. I'm able to call this funtion when I'm replacing <code>return MainPanel()</code> with <code>return InfoOptionsPanel()</code> i.e. when I'm n...
<python><user-interface><kivy>
2024-05-23 09:41:01
1
350
Aman
78,522,199
1,191,058
Type hint for descriptor in abstract class/interface
<p>I want to have a class with custom properties defined by descriptor classes and an interface that hides implementation details.</p> <p>My code currently looks like this. It works, type checkers do not complain, but it looks ugly because of the <code>cast</code> from <code>Ten</code> to <code>int</code>. Intermediate...
<python><python-typing>
2024-05-23 09:38:51
1
3,487
j123b567
78,522,148
13,706,389
Change Axes of legend in Matplotlib
<p>I have a figure with some inset axes at variable positions. Each of these inset axes has the same lines and thus the same legend. To avoid cluttering the figure, I would like to only show the legend of one of these insets and position it (for example) in the top right corner of the main ax to indicate that this is a...
<python><matplotlib>
2024-05-23 09:28:42
1
684
debsim
78,521,853
15,162,230
RecursionError: maximum recursion depth exceeded | [Previous line repeated 972 more times] | socket.io
<p>I need help that why i am getting error like <code>RecursionError</code>, i am using the <code>python-socket</code></p> <p><strong>BTW before moving ahead i want to make it clear that this issue is not because of socket configuration it is working fine the simple test events work fine.</strong></p> <p>Here is my soc...
<python><sockets><websocket><fastapi><asgi>
2024-05-23 08:36:06
1
517
Abidullah
78,521,791
13,638,219
Remove gaps with xOffset
<p>Is there a way to not have gaps at non-existing data when using x/yOffset? In the example below, category B only has 1 group (x) and I would like that bar to be centered at the B-tick.</p> <pre><code>source = pd.DataFrame({ &quot;Category&quot;:list(&quot;AAABCCC&quot;), &quot;Group&quot;:list(&quot;xyzxxyz&...
<python><altair>
2024-05-23 08:22:36
1
982
debbes
78,521,776
1,473,517
Can you make a random numpy.float128?
<p>I want to make a random array of type numpy.float128s. This is not valid:</p> <pre><code>import numpy as np a = np.random.random(100, dtype=np.float128) # not valid code </code></pre> <p>I could do</p> <pre><code>a = np.random.random(100).astype(np.float128) </code></pre> <p>but this creates 64 bit floats and then ...
<python><numpy><random><floating-point>
2024-05-23 08:20:21
2
21,513
Simd
78,521,674
1,320,143
Custom JSONResponse response for FastAPI - cannot access field in subclass
<p>I want my FastAPI application to return JSON:API responses. It would be really cumbersome to craft each response manually so I've looked into creating a custom response class, one based on <code>JSONResponse</code>, since the responses have to be in JSON format.</p> <p>They have an example here:</p> <p><a href="http...
<python><fastapi>
2024-05-23 07:59:01
0
1,673
oblio
78,521,607
3,494,047
How to get the browser view file link of a file using Dropbox python API?
<p>I am using the python api for dropbox and my question is the same as <a href="https://stackoverflow.com/questions/40754573/how-to-get-the-link-of-a-file-using-dropbox-python-api">this</a> one except I would like to get a link which shows the image in the browser. Not a link which downloads the files.</p> <p>So I hav...
<python><dropbox-api><dropbox-sdk>
2024-05-23 07:45:13
1
1,723
user3494047
78,521,530
8,884,239
xml.etree.ElementTree.ParseError: unclosed token with XML Library
<p>I am getting following error when I am trying to parse XML using Python XML library.</p> <pre><code>xml.etree.ElementTree.ParseError: unclosed token </code></pre> <p>I am using following code to parse xml string.</p> <pre><code>from xml.etree import ElementTree as ET try: root = ET.fromstring(xml_string) emp =...
<python><xml><apache-spark><pyspark><lxml>
2024-05-23 07:27:35
1
301
Bab
78,521,358
159,072
Why am I seeing Index error in this Python script?
<pre><code>#ResidueNoInEachProtein,Residue,TrueLabel,Feature1,Feature2,Feature3,Feature4,Feature5,Feature6,Feature7,Feature8,Feature9 0 GLN C 0.000 0.000 0.000 1 1 1 1 1 0 1 THR E 7.057 10.394 0.000 1 1 1 1 1 0 2 VAL E 6.710 9.449 13.140 0 0 0 0 1 0 3 PRO E 6.552 9.752 12.974 0 0 0 0...
<python><classification><lazypredict>
2024-05-23 06:45:32
1
17,446
user366312
78,520,833
2,817,520
How to convert a list of Pydantic objects to a JSON string
<p>The following code successfully converts a list of <code>UserSQLAlchemyModel</code> to a list of <code>UserPydanticModel</code>:</p> <pre><code>users_from_db = session.scalars(select(UserSQLAlchemyModel)).all() users = TypeAdapter(list[UserPydanticModel]).validate_python(users_from_db) </code></pre> <p>Now how can I...
<python><pydantic>
2024-05-23 03:34:59
3
860
Dante
78,520,746
20,235,789
What is the correct way to use classes as dependencies(parameter check)?
<p>Main goal here is mapping UI sent parameters to match my db tables.</p> <hr /> <p>Now call me crazy but this was working a second ago and now its not.</p> <p>I have a few classes and one function(in <code>S_Sorting</code>) here</p> <pre><code>class ScanSort(str, Enum): ASSET_NAME = &quot;assetName&quot; CR...
<python><dependency-injection><fastapi><pydantic>
2024-05-23 02:58:48
1
441
GustaMan9000
78,520,581
17,835,120
limited trade execution using using backtesting.py library
<p>My goal is to backtest data where you provide buy/sell dates and closing prices to backtest module in order to backtest data from one source csv (instead of having 3 separate files such as price data, buy signals and sell signals)</p> <p>I am not sure why not all of the trades execute here. Currently, my trades are ...
<python><algorithmic-trading><quantitative-finance><back-testing>
2024-05-23 01:29:01
0
457
MMsmithH
78,520,256
6,440,589
How to merge dictionaries contained in a Pandas dataframe as a groupby operation
<p>Let us consider a pandas dataframe <code>df</code> containing dictionaries in one of its columns (column <code>mydict</code>):</p> <blockquote> <pre><code> mystring mydict 0 a {'key1': 'value1'} 1 a {'key2': 'value2'} 2 b {'key2': 'value2'} </code></pre> </blockquo...
<python><pandas><dictionary><group-by>
2024-05-22 22:34:06
1
4,770
Sheldon
78,520,245
214,526
Redundant print with multiprocessing
<p>This is my first attempt with multiprocessing using Python multiprocessing library. The simple version of the code is like below -</p> <pre><code>import multiprocessing as mp from dataclasses import dataclass from typing import Dict, NoReturn import time import logging import signal import numpy as np @dataclass ...
<python><python-3.x><multiprocessing>
2024-05-22 22:30:04
1
911
soumeng78
78,520,187
8,652,920
How to remove last parentheses in string with its contents in python using regex?
<p>Say we have a list of files like</p> <p>(these aren't symlinks btw, I'm just using the arrows to indicate input -&gt; output relationship)</p> <pre><code>test(1) -&gt; test test2(1) -&gt; test2 test3(note to self) (6) -&gt; test3(note to self) </code></pre> <p>edit(not sure why there is a request to close for lack o...
<python><regex>
2024-05-22 22:06:56
1
4,239
notacorn
78,520,027
1,806,566
In python, is there a way to use shlex to split a line but leave quotes intact?
<p>I know there have been similar questions about shlex, but none that seem to directly address this issue.</p> <p>I would like to do basically what shlex.split() does (in POSIX mode), except <em>just</em> split - don't remove any quotes or backslashes. I would still like quotes and backslashes to function as they nor...
<python><shlex>
2024-05-22 21:14:26
0
1,241
user1806566
78,520,016
15,140,144
Python: Heaptypes with metaclasses
<p>In Python c-api: how can I create a heap type that has a metaclass? I'm well aware of <code>PyType_FromSpec</code> and derivatives and they can do this (from documentation):</p> <blockquote> <p>Changed in version 3.12: The function now finds and uses a metaclass corresponding to the provided base classes. Previously...
<python><c><metaclass><python-c-api>
2024-05-22 21:11:16
1
316
oBrstisf8o
78,519,953
11,751,799
`matplotlib` figure text automatically adjusting position to the corners with multiple axes in the figure
<p><a href="https://stackoverflow.com/questions/78519044/matplotlib-figure-text-automatically-adjusting-position-to-the-top-left/78519857#78519857">This</a> question address how to put text in the top left corner, higher than everything else in the figure, left of everything else in the figure.</p> <p>Now I want text i...
<python><matplotlib><plot><graphics>
2024-05-22 20:54:00
0
500
Dave
78,519,657
3,100,515
How to make a "factory" to create dependent fixtures for multiple parametrizations?
<p>I have a test setup wherein I have multiple parametrizations, and I have secondary tests that depend on primary tests for each parametrization. I have got the following dependency setup working (see my SO question <a href="https://stackoverflow.com/questions/78491778/pytest-dependency-doesnt-work-when-both-across-f...
<python><pytest><pytest-dependency>
2024-05-22 19:35:39
1
5,678
Ajean
78,519,636
850,781
Lookup by datetime in timestamp index does not work
<p>Consider a date-indexed DataFrame:</p> <pre><code>d0 = datetime.date(2024,5,5) d1 = datetime.date(2024,5,10) df0 = pd.DataFrame({&quot;a&quot;:[1,2],&quot;b&quot;:[10,None],&quot;c&quot;:list(&quot;xy&quot;)}, index=[d0,d1]) df0.index Index([2024-05-05, 2024-05-10], dtype='object') </code></pre> <p>Note that <code>d...
<python><pandas><dataframe><datetime><indexing>
2024-05-22 19:29:05
1
60,468
sds
78,519,594
2,934,290
How can I have a @classmethod of a generic class act on the type parameter?
<p>How can I call a classmethod by its generic only? Let's use following example:</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod from typing import Generic, TypeVar class Base(ABC): @classmethod @abstractmethod def test(cls): print('foo') class B(Base): ...
<python>
2024-05-22 19:16:54
1
722
Bin4ry
78,519,418
2,986,153
How to create nested list columns in polars
<p>In R with tidyverse, using group_by() and nest() I can create list columns that are very useful for fitting models to multiple datasets.</p> <p>How can I achieve the same outcome in polars in Python, such that each element of the data column is a small dataframe?</p> <pre><code>df = pl.DataFrame( [ pl.Se...
<python><python-polars>
2024-05-22 18:34:32
1
3,836
Joe
78,519,254
850,781
How to expand a DataFrame by adding index values?
<p>I have a data frame</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;a&quot;:[1,2,3]},index=[5,7,6]) a 5 1 7 2 6 3 </code></pre> <p>and I want to add some &quot;missing&quot; index values:</p> <pre><code>pd.DataFrame(index=range(3,9)).join(df) a 3 NaN 4 NaN 5 1.0 6 3.0 7 2.0 8 Na...
<python><pandas><dataframe><join>
2024-05-22 17:56:19
1
60,468
sds
78,519,217
2,547,570
ContextVar MemoryLeak
<p>The following code has a memory leak and I don't understand why there are references to <code>MyObj</code>. <code>run(1)</code> and <code>run(2)</code> are finished, the context is cleared.</p> <pre class="lang-py prettyprint-override"><code>import asyncio import gc from contextvars import ContextVar import objgrap...
<python><garbage-collection><python-asyncio><python-contextvars>
2024-05-22 17:45:42
1
1,319
mq7
78,519,123
6,915,206
ModuleNotFoundError: No module named 'django.utils.six.moves'
<p>While deploying my Django 3 code on AWS EC2 server I'm getting the error below. I uninstalled <strong>six</strong> many times and deleted the <strong>cache</strong> folder and installed different versions of <strong>six</strong> but none of them are working.</p> <p><div class="snippet" data-lang="js" data-hide="fals...
<python><python-3.x><django><amazon-web-services><amazon-ec2>
2024-05-22 17:18:21
1
563
Rahul Verma
78,519,081
19,299,757
How to reconnect to a URL with python selenium
<p>I've a Selenium-Python test suite which is used to run regression tests for an UI application.</p> <pre><code>@pytest.fixture(scope='class') def setup(request): driver = None try: options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument(&quot;--window-size=1920,10...
<python><selenium-webdriver>
2024-05-22 17:08:01
1
433
Ram
78,519,077
1,497,199
Python: async function without await
<p>Is this a true statement?</p> <blockquote> <p>An <code>async</code> python function that does not include an <code>await</code> statement itself will not yield execution to any other <code>async</code> functions, even though it's invoked by an <code>await</code> call.</p> </blockquote> <p>FastAPI example</p> <pre><c...
<python><async-await><fastapi>
2024-05-22 17:07:48
1
8,229
Dave
78,519,069
5,573,170
Variable visibility in python
<p>Maybe a stupid question but I'm new to python.</p> <p>The following code throws an error:</p> <pre><code>deck = [10, 2, 5, 8, 2, 7] deck_idx = 0 def deal(): card = deck[deck_idx] deck_idx += 1 return card print(deal()) </code></pre> <pre class="lang-none prettyprint-override"><code>Traceback (most recent cal...
<python><scope>
2024-05-22 17:06:28
0
1,601
Disti
78,519,044
11,751,799
`matplotlib` figure text automatically adjusting position to the top left
<p>When I run the following code, I have no issue.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.scatter([1, 2, 3], [4, 5, 6]) fig.text( 0, 1, s = &quot;ABCD&quot;, ha = &quot;left&quot;, va = &quot;bottom&quot;, transform = fig....
<python><matplotlib><plot><graphics>
2024-05-22 17:00:38
1
500
Dave
78,518,976
6,642,051
Can I update the type annotation of a variable over time?
<p>I'm making a Blender addon, and part of the flow of one of its functions involves de-duplicating vertices and returning vertex and index lists. Part of the algorithm I'm using involves setting duplicate elements to None, then clearing those elements later using a comprehension. My problem comes from the fact that I'...
<python>
2024-05-22 16:47:09
2
444
ProgramGamer
78,518,954
1,686,814
Unwanted spaced in format string when running Python code in snakemake
<p>I have a project that was running fine until I had to update the conda environment. Suddenly, certain strings got extra spaces around variables that are inserted in the string with <code>f&quot;...&quot;</code>.</p> <p>Consider this:</p> <pre><code>foo = &quot;bar&quot; print(f&quot;foo is now:{foo}.&quot;) </code><...
<python><snakemake>
2024-05-22 16:42:37
0
17,210
January
78,518,777
294,657
Rolling mean over an unstacked, multi-index
<p>I have a CSV file like the following:</p> <pre><code>Animal,Day,Action,Seconds dog,1,eat,10 dog,1,play,20 dog,1,drink,30 cat,1,eat,18 cat,1,play,28 cat,1,drink,21 rabbit,1,eat,34 rabbit,1,play,19 rabbit,1,drink,29 dog,2,eat,20 dog,2,play,20 dog,2,drink,10 cat,2,eat,28 cat,2,play,38 cat,2,drink,31 rabbit,2,eat,24 rab...
<python><pandas><dataframe>
2024-05-22 16:06:48
1
16,064
kaqqao
78,518,728
10,787,371
How to specify a generic over TypedDict?
<p>I want to have a class, that has the following members:</p> <ul> <li>function <code>f</code>, that takes argument of type <code>In</code>, and <code>kwargs</code> specified by <code>Parameters</code></li> <li>function <code>make_parameters</code> that returns <code>Parameters</code>, that can be directly fed into <c...
<python><generics><python-typing>
2024-05-22 15:56:53
1
707
aurelia
78,518,643
10,331,807
How to make a grid of plots that include subplots?
<p>Ηi, I want to create a grid of plots that each plot has a subplot. The reason for this is that one of my columns (area1) has very high values compared to the other (area2, area3), therefore making the rest look negligible.</p> <p>Here is my current code:</p> <pre><code>import matplotlib.pyplot as plt import seaborn ...
<python><matplotlib><seaborn><matplotlib-gridspec>
2024-05-22 15:40:06
0
305
Anas.S
78,518,562
3,973,269
Azure app function - stuck on using storage blob on localhost
<p>I have an azure app function, very basic that runs well when deployed but locally, when I'm sending a post request it just get stuck and eventually the whole shuts down with the message shown below. When I comment out the line <code>from azure.storage.blob import BlobServiceClient</code>, the whole works and a respo...
<python><azure-functions><azure-blob-storage>
2024-05-22 15:23:06
1
569
Mart
78,518,498
7,441,757
Using fsspec with aws profile_name
<p>With S3fs we can set</p> <pre><code>fs = s3fs.S3FileSystem(profile=profile_name) </code></pre> <p>However this passing doesn't work for fsspec with caching:</p> <pre><code> fs = fsspec.filesystem( &quot;filecache&quot;, target_protocol=&quot;s3&quot;, cache_storage=&quot;some/dir&...
<python><python-s3fs><fsspec>
2024-05-22 15:11:07
1
5,199
Roelant
78,517,765
273,593
explicit tuple generic expansion
<p>Simplified scenario (<a href="https://mypy-play.net/?mypy=latest&amp;python=3.12&amp;gist=765b3582ed8b99e2a546fe1bfb4cd0e3" rel="nofollow noreferrer">playground</a>):</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, reveal_type class A: ... class B(A): ... class C(A): ... T = TypeVar...
<python><mypy><python-typing>
2024-05-22 13:07:11
1
1,703
Vito De Tullio
78,517,713
66,191
Python MySQL mypy typing complaining about incorrect types
<p>I'm using python with mysql-connector and am running my code through mypy and it's complaining about types which I can't seem to get around.</p> <p>for instance. I have code like this</p> <pre><code> today = datetime.now().date() mysql_cursor = mysql_connection.cursor() cursor.execute( &quot;select holida...
<python><python-3.x><mysql-connector>
2024-05-22 12:57:52
1
2,975
ScaryAardvark
78,517,650
3,412,316
Bulk insert rasters into GPKG
<p>I wonder if there is a way to bulk insert TIFF rasters into a geopackage using python or gdal, to increase write performance.</p> <p>GDAL needs to open an SQLite connection per added raster file (subdataset, RASTER_TABLE), which prevents you from using a single transaction to insert multiple rasters.</p> <p>Concurre...
<python><gdal><geopackage>
2024-05-22 12:47:22
0
2,193
Kiruahxh
78,517,594
2,304,735
How to read only two numbers from python STDIN Function?
<p>I want to take two numbers through the stdin python function and output their total.</p> <pre><code>import sys num1 = None num2 = None print('Please Enter Two Numbers to Find their Sum or Enter q to quit') for line in sys.stdin: if('q'==line.strip()): break else: num = int(line.strip()) ...
<python><python-3.x>
2024-05-22 12:35:59
2
515
Mahmoud Abdel-Rahman
78,517,501
6,862,405
Unordered y-axis in multiline chart using dash
<p>I am new to dash and struggling to create a multi line chart. I have a data and plotted it using dash and created a multiline chart. The reproducible code is given below-</p> <pre><code>import pandas as pd import plotly.express as px from dash import Dash, dcc, html, callback, Output, Input df = pd.DataFrame({ ...
<python><plotly-dash>
2024-05-22 12:20:04
1
831
Ankit Seth
78,517,342
2,955,884
np.save() works with reproducible example but not mith my own numpy array ("NotImplementedError")
<p>np.save() works with a reproducible example but not with my data. How can I save my numpy array as binary?</p> <p>np.save works in this reproducible example:</p> <pre><code>a = np.arange(12, dtype='float32').reshape(2,2,3) a.shape Out[42]: (2, 2, 3) a.dtype Out[43]: dtype('float32') np.save(&quot;delme&quot;,a) </co...
<python><numpy>
2024-05-22 11:50:51
2
576
user2955884
78,517,203
13,506,329
Unable to import function from custom package built using pyproject.toml
<p>This is my project structure</p> <pre><code>pkg_root └───venv └───requirements.txt └───pyproject.toml ├───src │ ├───pkg │ │ ├───__init__.py │ │ ├───test_main.py │ │ ├───config │ │ │ ├───json │ │ ├───data │ │ │ ├───input │ │ │ │ └───data_file │ │ │ └───output │ │ │ ...
<python><python-3.x><setuptools><python-packaging><pyproject.toml>
2024-05-22 11:26:46
1
388
Lihka_nonem
78,517,171
8,654,320
How to locate image on a large image with different target size
<p>I am trying to use <code>pyautogui.locateOnScreen(btn, confidence=0,8, grayscale=True)</code> to locate image, but if the search image has a different size, it cannot be able to locate.</p> <p>In my case, I want to locate the confirm button on screen. I take the shortcut of button on site A (a small size), and locat...
<python><opencv><pyautogui>
2024-05-22 11:21:37
1
1,185
afraid.jpg
78,517,021
6,695,608
Prevent a class variable from being modified outside the class
<p>I have the following class where I have defined couple of class variables and a helper class method where I am updating the value of these class variables based on some condition.</p> <pre><code>class Foo: _UPDATED_AT: datetime = datetime.datetime(2000, 1, 1) STATUS: bool = False @classmethod def b...
<python>
2024-05-22 10:52:39
1
4,308
Rohit
78,516,967
4,586,008
How to log the peak memory usage of Jupyter Notebook
<p>I have a Jupyter Notebook on cloud for a long-running job. The job uses considerable RAM, thus I assign a high-memory (and expensive) machine for it.</p> <p>However, I know that the maximum RAM required is more or less constant among runs, so I want to know the RAM usage at its peak and switch to a cheaper machine w...
<python><memory><jupyter-notebook>
2024-05-22 10:42:20
0
640
lpounng
78,516,819
258,825
How/where does pyca/cryptography "embed" OpenSSL dependency?
<p>I'm using cryptography in a project that is targeting both EL8 and EL9 (we're using Rocky Linux 8/9). We're using python3.9 in both cases. The problem/doubt I'm having is that OpenSSL v3 is not available on EL8 (unless built from sources which is not something we're doing), yet when I install cryptography v42, it re...
<python><python-wheel>
2024-05-22 10:17:38
1
566
IvanR
78,516,801
10,242,990
How to get data validation
<p>Usecase: I am iterating through rows in a Google sheet and taking some actions dependant on the value in different fields.</p> <pre><code> client = authorize() worksheets_data = get_worksheet(client, CAREEM_SHEET, &quot;UAE&quot;) sheet_data = SheetData(worksheets_data) rows = sheet_data.get_all_value...
<python><validation><google-sheets><pygsheets>
2024-05-22 10:13:23
1
1,649
lammyalex
78,516,674
2,657,641
matplotlib: precise inset plot location and size with transformations
<p>I have created a plot with several &quot;inset&quot; axes in matplotlib with the intent of visualizing the meaning of error bars. Please consider the following example:</p> <pre><code>import matplotlib.pyplot as plt from numpy import linspace, random from scipy.stats import norm from mpl_toolkits.axes_grid1.inset_lo...
<python><matplotlib><statistics>
2024-05-22 09:53:09
1
1,385
carsten
78,516,650
4,247,881
Perform aggregation using min,max,avg on all columns
<p>I have a dataframe like</p> <pre><code>┌─────────────────────┬───────────┬───────────┬───────────┬───────────┬──────┐ │ ts ┆ 646150 ┆ 646151 ┆ 646154 ┆ 646153 ┆ week │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ datetime[μs] ┆ f64 ┆ f64 ...
<python><dataframe><python-polars>
2024-05-22 09:49:01
3
972
Glenn Pierce
78,515,954
16,569,183
Suppressing recommendations on AttributeError - Python 3.12
<p>I like to use <code>__getattr__</code> to give objects optional properties while avoiding issues with <code>None</code>. This is a simple example:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any class CelestialBody: def __init__(self, name: str, mass: float | None = None) -&gt; None:...
<python><python-3.12>
2024-05-22 07:37:43
2
313
alfonsoSR
78,515,887
4,453,737
How to get printed response from async function in Python
<p>I want to get printed response of sync function. for that am using, <code>StringIO</code>.</p> <pre><code>import sys from io import StringIO def sample(): print('started to fetch log!') print('response:body') print('status:200') def get_log(): sys.stdout = StringIO() sample() log = sys.stdout.getvalue(...
<python><python-asyncio><stringio>
2024-05-22 07:22:25
1
20,393
Mohideen bin Mohammed
78,515,729
10,200,497
How can I compare a value in one column to all values that are BEFORE it in another column?
<p>My DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'high': [100, 102, 120, 150, 125, 115], 'target': [99, 105, 118, 108, 140, 141] } ) </code></pre> <p>Expected output is creating column <code>x</code>:</p> <pre><code> high target x 0 100 99 99 1 102 1...
<python><pandas><dataframe>
2024-05-22 06:46:31
4
2,679
AmirX
78,515,642
2,467,772
How to dump to pickle file for each iteration without saving in memory?
<p>I have a python code which save dictionary to data array and dump data array to a pickle file.</p> <p>This is original code.</p> <pre><code>with torch.no_grad(): char_bboxes, char_scores, word_instances = charnet.find_charbox(im, scale_w, scale_h, original_w, original_h, word_boxes, os.path.splitext(im_name)[0]) ...
<python><pickle>
2024-05-22 06:25:46
1
7,346
batuman
78,515,406
7,700,802
Changing values in a dataframe under growth change with year condition
<p>Suppose I have</p> <pre><code>sample = {&quot;Location+Type&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;], &quot;Year&quot;: [&quot;2010&quot;, &quot;2011&quot;, &quot;2012&quot;, &quot;2013&quot;, &quot;2010&quot;, &quot;2011...
<python><pandas>
2024-05-22 05:04:33
4
480
Wolfy
78,515,242
487,993
Combining derivatives when taken with respect to the same variable
<p>Is there a way to collect derivatives w.r.t. the same symbol in a sum? There are several questions that go around this point, but I haven't found an answer for the simple situation:</p> <pre class="lang-py prettyprint-override"><code>from sympy import * x,y,z,t = symbols('x y z t') expr = z * (Derivative(x,t) + Deri...
<python><sympy><derivative><simplify>
2024-05-22 03:55:47
0
801
JuanPi
78,515,065
1,424,739
lxml.etree.tostring show both start and end tags for empty node
<pre><code>from lxml import etree tree = etree.XML('&lt;foo class=&quot;abc&quot;&gt;&lt;/foo&gt;') print(etree.tostring(tree, encoding='utf-8').decode('utf-8')) </code></pre> <p>The above code shows the following.</p> <pre><code>&lt;foo class=&quot;abc&quot;/&gt; </code></pre> <p>How can I make it not to contract the ...
<python><xml><lxml>
2024-05-22 02:26:23
1
14,083
user1424739
78,514,884
5,284,054
Python tkinter root close
<p>As an interim to my full application, I'm closing the window with buttons at different places in the file. Now originally, it works fine: I can close the application from both location within the file. However, I'm trying to clean the code up and have a better style.</p> <p>Here's the code I have (with the better ...
<python><tkinter>
2024-05-22 00:38:40
1
900
David Collins
78,514,849
2,593,878
pytorch matrix multiplication accuracy depends on tensor size
<p>I have the following code where I multiply tensor <code>X</code> by a matrix <code>C</code>. Depending on the size of <code>X</code> and whether <code>C</code> is attached to the computation graph, I get different results when I compare batched multiplication vs looping over each slice of <code>X</code>.</p> <pre><c...
<python><pytorch><floating-point><precision>
2024-05-22 00:13:50
1
7,392
dkv
78,514,800
2,986,153
Can't pip install pystan on Mac
<p>When I try to pip install pystan I get the following error:</p> <pre><code> error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─&gt; [1 lines of output] Cython&gt;=0.22 and NumPy are required. [end of output] note: This error...
<python><pystan>
2024-05-21 23:45:13
1
3,836
Joe
78,514,732
11,516,350
Flask blueprints: declaration on each module __init__.py vs inside routes files
<p>This is my project structure:</p> <p><a href="https://i.sstatic.net/l5JTRL9F.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/l5JTRL9F.png" alt="project structure" /></a></p> <p>As you can see, I have two modules: transactions and categories. I'll use the categories module as an example (the transactio...
<python><flask><blueprint>
2024-05-21 23:18:42
0
1,347
UrbanoJVR
78,514,520
3,487,441
How to resolve "Unclosed client session" from aiohttp
<p>I'm pulling data from an API and populating Janusgraph DB running in the docker container per the installation site:</p> <pre><code>docker run --name janusgraph-default janusgraph/janusgraph:latest </code></pre> <p>The python script I'm using worked well at first, but won't connect at all now. I've removed and recre...
<python><aiohttp><janusgraph><tinkerpop3>
2024-05-21 21:56:14
1
1,361
gph
78,514,357
9,310,154
python requests different from curl request
<p>Hi I want to get some informations from one website. This is the curl command:</p> <pre><code>curl 'https://www.kleinanzeigen.de/s-iphone-13/k0' \ -H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7' \ -H 'accept-lang...
<python><curl>
2024-05-21 21:06:03
0
2,075
otto
78,514,335
11,530,164
How to create a tensorflow dataset from a list of filenames that need to be loaded and transformed and their corresponding labels
<p>Given a list of npy filenames <code>x</code>:</p> <pre><code>x = ['path/to/file1.npy', 'path/to/file2.npy'] </code></pre> <p>and a list of labels <code>y</code>:</p> <pre><code>y = [1, 0] </code></pre> <p>I want to create a tensorflow <code>Dataset</code> that consists of pairs of the labels and the loaded and trans...
<python><tensorflow><dataset>
2024-05-21 21:00:26
1
573
Mario
78,514,193
8,024,622
Pandas resample per ID
<p>I have a DataFrame that looks like this</p> <pre><code>ID DateHour Value A 2024-05-03 07:00:00 5 A 2024-05-03 09:00:00 2 A 2024-05-03 22:00:00 9 A 2024-05-03 23:00:00 1 B 2024-05-03 02:00:00 8 B 2024-05-03 09:00:00 7 B 2024-05-03 20:00:00 8 </code></p...
<python><pandas><resample>
2024-05-21 20:19:37
1
624
jigga
78,514,084
850,781
`conda list` mis-reports package version
<p>How come</p> <pre><code>$ conda list --show-channel-urls dateutil # packages in environment at .../miniconda3/envs/c312: # # Name Version Build Channel python-dateutil 2.9.0post0 py312haa95532_0 defaults </code></pre> <p>but</p> <pre><code>$ python -c 'import dat...
<python><conda><miniconda>
2024-05-21 19:50:41
0
60,468
sds
78,513,947
5,464,233
Creating a Two-dimensional NumPy Array from a Database Resultset
<p>I have created a table <code>yokes</code> in a PostgreSQL database:</p> <pre class="lang-sql prettyprint-override"><code>mydb=# CREATE TABLE yokes(id INT, name TEXT, size FLOAT); CREATE TABLE mydb=# INSERT INTO yokes(id, name, size) VALUES(1, 'foo', 0.5); INSERT 0 1 mydb=# INSERT INTO yokes(id, name, size) VALUES(2,...
<python><numpy><psycopg2>
2024-05-21 19:17:50
0
2,432
Guido Flohr
78,513,944
9,403,794
How to convert np.NaN to string in ndarray/list?
<p>I have a simple Python code:</p> <pre><code>l2 =[4,np.nan, 5.1] a2 = np.array(l2) a3 = np.where(np.isnan(a2), '3.3', a2) a3 = a3.astype(float) print(a3) a3 = np.where(np.isnan(a2), 'x', a2) print(a3) </code></pre> <p>The code above produce two lines:</p> <pre><code>[4. 3.3 5.1] ['4.0' 'x' '5.1'] </code></pre> <p>...
<python><numpy>
2024-05-21 19:17:09
1
309
luki
78,513,619
13,186,897
How do I set user Profile using add_argument?
<p>I try to launch Chrome with my Profile, but it doesn't open the profile. (User 1, the login has not been completed in Browser window)</p> <pre><code>from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager options = webdriver.ChromeOptions() options.add_argument(&quot;--window-size=19...
<python><selenium-webdriver><selenium-chromedriver>
2024-05-21 17:57:11
1
424
shulya403
78,513,399
1,245,262
Why does torch.utils.collect_env claim I've pip installed modules that I used conda to install
<p>I've had some odd behavior with a torch installation, so I ran <code>python -m torch.utils.collect_env</code> to get a clear idea of ehat was in my environment, but it claimed I had used both pip3 and conda to install some modules.</p> <p>So, I created a simplified conda env, which still gives this problem:</p> <pre...
<python><pytorch><pip><conda>
2024-05-21 17:08:16
1
7,555
user1245262
78,513,318
5,589,640
Remove e-mail address with whitespaces
<p>I am working with call centre transcripts. In an ideal case the speech-to-text software will transcribe an e-mail as follows: maya.lucco@proton.me. This will not always be the case. So I am looking at a regular expression (RegEx) solution that accommodates whitespaces in the e-mail address, e.g. maya lucco@proton.me...
<python><python-3.x><regex><email><python-re>
2024-05-21 16:52:43
1
625
Simone
78,513,109
986,896
How to fix DeprecationWarning when concurrent.futures with multiprocessing.Process are used together?
<p>How to fix the DeprecationWarning in the following pytest example? Note this is minimalistic reproducer.</p> <p>Use case is rather simple:</p> <ul> <li>I have an object (represented as <code>Obj</code>) that is tested;</li> <li><code>Obj</code> interacts with an external server;</li> <li>For testing purposes, extern...
<python><linux><pytest><python-multiprocessing><python-3.12>
2024-05-21 16:09:07
0
755
Kuchara
78,513,041
125,673
OpenAI Completions API: How do I extract the text from the response?
<p>I am attempting to extract text from OpenAI, but I need some help with the correct syntax.</p> <p>My code:</p> <pre><code>_model = &quot;gpt-3.5-turbo-instruct&quot; # Summarize the text using an AI model (e.g., OpenAI's GPT) try: summary = openai.completions.create( model=_model, prompt=f&quot;S...
<python><openai-api><gpt-3>
2024-05-21 15:56:11
1
10,241
arame3333
78,512,968
1,422,096
Order of execution in try except finally
<p>I never really use <code>finally</code>, so I wanted to test a few things before using it more regularly. I noticed that when running:</p> <pre><code>def f(): try: 1/0 # 1/1 except: print('except') # 1 raise # 2 finally: print('finally') # 3...
<python><exception><try-catch><try-catch-finally>
2024-05-21 15:39:38
1
47,388
Basj
78,512,927
7,189,440
How to flush/reset the backlog of a python observer and PatternMatchingEventHandler when lots of changes happen in close succession?
<p>I'm using a python <code>PatternMatchingEventHandler</code> watchdog to call a function each time a file is created (using <code>self.on_created</code>) within a watched directory tree. Minimal code example below. The function is slow, so if a lot of new files are created in a short time period, I can end up with a ...
<python><python-watchdog>
2024-05-21 15:32:49
1
873
AstroBen
78,512,754
114,708
Change the font name of exponent labels in plotnine/matplotlib
<p>I am trying to make a plot using plotnine. The y-axis is in log-scale and has an exponential labels. I want to change the font of the whole plot to something else such as &quot;Gill Sans&quot;. The font is reflected everywhere except the exponential labels. How to fix that? Below is a working example.</p> <pre><code...
<python><matplotlib><plotnine>
2024-05-21 15:04:51
1
1,712
max
78,512,720
1,115,833
python requests Content-Disposition: form-data
<p>I am looking into using cloudflare's KV and I see a nasty looking requests snippet here:<a href="https://developers.cloudflare.com/api/operations/workers-kv-namespace-write-key-value-pair-with-metadata" rel="nofollow noreferrer">https://developers.cloudflare.com/api/operations/workers-kv-namespace-write-key-value-pa...
<python><python-requests>
2024-05-21 14:56:23
1
7,096
JohnJ
78,512,558
7,958,562
Streaming file from one webserver to another
<p>I'm trying to stream a file from one webserver (Jfrog) to another (nexus content server). I have working code that does this like this:</p> <pre><code>def get_file(): url = &quot;https://webserver.com/big_file.zip&quot; with requests.get(url,, stream=True) as file_stream: self.stream_file_to_webserve...
<python>
2024-05-21 14:26:05
3
437
John
78,512,493
3,057,377
Display calendar with week numbers
<p>I would like to display a calendar with week numbers.</p> <p>Python provides a nice <code>calendar</code> module that can generate such a calendar, but I can’t find a way to display week numbers.</p> <p>Here is an example of the command and its output:</p> <pre><code>python -m calendar --locale fr --encoding utf-8 -...
<python><calendar>
2024-05-21 14:11:57
2
1,380
nico
78,512,350
17,917,952
Different output order in custom Object Detection model causing error in android application
<p>I followed the steps as outlined in the following documentation: <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html" rel="nofollow noreferrer">https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/training.html</a> to train my custom object detection ...
<python><metadata><tensorflow2.0><object-detection><tensorflow-lite>
2024-05-21 13:52:42
1
310
peru_45
78,512,247
3,070,181
Simpleaudio causes a segmentation fault in Tkiinter
<p>I am agnostic as to which solution I use, but in the following code, the <em>simpleaudio</em> solution outputs the sound, but causes a segmentation fault, whereas the <em>pygame</em> solution works perfectly.</p> <p>Why is this?</p> <pre><code>import tkinter as tk from tkinter import ttk import simpleaudio as sa fro...
<python><tkinter><audio>
2024-05-21 13:35:17
1
3,841
Psionman
78,512,177
6,618,051
Playwright Python: 'retain-on-failure'
<p>For Node.js it's mentioned option 'retain-on-failure' (<a href="https://playwright.dev/docs/videos" rel="nofollow noreferrer">https://playwright.dev/docs/videos</a>) to preserve only videos for failed tests. Nothing similar for the Python. How can it be solved (delete videos for passed tests)? Thanks</p> <pre class=...
<python><playwright><playwright-python>
2024-05-21 13:20:31
1
1,939
FieryCat
78,512,062
850,781
Conda update flips between two versions of fmt
<p>When I do <code>conda update -n base --all</code>, I get this:</p> <pre><code>The following packages will be UPDATED: libmamba artifactory/api/conda/conda-forge::li~ --&gt; pkgs/main::libmamba-1.5.8-h99b1521_2 libmambapy artifactory/api/conda/conda-forge::li~ --&gt; pkgs/main::libmambapy-1.5.8...
<python><conda><miniconda>
2024-05-21 12:58:14
2
60,468
sds
78,511,805
1,169,091
Click a particular button on a page using By.LINK_TEXT but find_element throws exception
<p>On this page: <a href="https://finance.yahoo.com/quote/KO/options" rel="nofollow noreferrer">https://finance.yahoo.com/quote/KO/options</a></p> <p>Is this button:</p> <pre><code>&lt;button class=&quot;tertiary-btn fin-size-small menuBtn tw-justify-center rounded rightAlign svelte-xhcwo&quot; data-ylk=&quot;elm:inpt;...
<python><selenium-webdriver>
2024-05-21 12:18:05
2
4,741
nicomp
78,511,656
17,220,672
"not enough memory" error using multiprocessing
<p>I have a <code>table_data</code> which is a type of list. It has 3.5 million <code>sqlalchemy</code> ORM-Models stored in it.</p> <p>Now for each element in <code>table_data</code> list I want to preprocess some fields in these models and convert each one of them to the new sqlalchemy <code>FooModel</code>.</p> <p>S...
<python><sqlalchemy><multiprocessing>
2024-05-21 11:49:09
2
419
mehekek
78,511,620
18,091,040
Install fastapi using an older version of pip (9.0.3)
<p>I am in a project that requires an older version of pip (9.0.3) and I wanted to install fastapi on it. When I run:</p> <pre><code>pip install fastapi </code></pre> <p>I got:</p> <pre><code>Collecting fastapi Could not find a version that satisfies the requirement fastapi (from versions: ) No matching distribution ...
<python><python-3.x><pip><fastapi>
2024-05-21 11:44:17
0
640
brenodacosta
78,511,471
13,919,925
how to get distinct record based on specific fields in django orm?
<pre><code> def get_queryset(self): # current_date = datetime(2024, 9, 2, 12, 56, 54, 324893).today() current_date = datetime.today() # get the booking data from the current date --------- requested_datetime is when the patient has scheduled the booking for booking_data = PatientBo...
<python><django>
2024-05-21 11:15:13
0
302
sandeepsinghnegi
78,511,206
1,333,025
How to get docstrings of fields of a NamedTuple or dataclass?
<p>I'm using a <code>NamedTuple</code> with comments <a href="https://stackoverflow.com/q/1606436/1333025">as suggested</a> for Python 3.6+:</p> <pre><code>from typing import NamedTuple class Config(NamedTuple): buy_fee: float &quot;&quot;&quot;My field description...&quot;&quot;&quot; # ... </code></pre> <p>Now...
<python><python-dataclasses><docstring>
2024-05-21 10:28:02
1
63,543
Petr
78,511,133
14,253,961
Pytorch : Early stopping Mechanism
<p>I work with Pytorch and CIFAR100 dataset, While I'm newer, I would like to incorporate the early stopping mechanism in my code,</p> <pre><code>def train(net,trainloader,epochs,use_gpu = True): ... net.train() for epoch in range(epochs): print (&quot;Epoch {}/{}&quot;.format(epoch+1, epochs)) ...
<python><pytorch><early-stopping>
2024-05-21 10:14:49
1
741
seni
78,510,975
4,732,111
Polars read AWS RDS DB with a table containing column of type jsonb
<p>I'm trying to read AWS RDS DB using the following method through polars:</p> <pre><code>df_rds_table_test = pl.read_database_uri(sql_query, uri) </code></pre> <p>Postgres DB contains a table with column name <em>'json_message'</em> of type <em><strong>jsonb</strong></em> and other columns of type String. When the ta...
<python><pandas><amazon-web-services><python-polars><duckdb>
2024-05-21 09:47:18
1
363
Balaji Venkatachalam
78,510,809
7,597,536
Airflow - login next query param does not match the base_url #
<p>I deployed my airflow application behind a <code>Microsoft application gateway</code>. I updated the base_url to match the public IP provided by the application gateway, for example, <code>1.2.3.4</code>.</p> <p>However, when I try to access the login page, the &quot;next&quot; query parameter refers to the internal...
<python><azure><airflow>
2024-05-21 09:18:00
0
1,167
Mattia
78,510,594
10,595,871
Unable to scrape XHR elements from webpage (python)
<p>I've already searched for similar questions but due to errors on deprecated methods I'm still not able to solve this.</p> <p>I just need to extract the JSON provided by the only xhr element in this page: <a href="https://certificatoricreditors.mimit.gov.it/Consultazione" rel="nofollow noreferrer">https://certificato...
<python><web-scraping><python-requests>
2024-05-21 08:40:54
1
691
Federicofkt