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,638,644
442,945
How to declare a method on a Python union type alias?
<p>Suppose I have two classes, <code>A</code> and <code>B</code>:</p> <pre><code>class A: def f(self) -&gt; bool: ... class B: def f(self) -&gt; bool: ... </code></pre> <p>And later I type alias these:</p> <pre><code>from typing import Union FClass: TypeAlias = Union[A, B] </code></pre> <p>So that in anoth...
<python><python-typing>
2024-06-18 16:33:18
1
21,319
Nathaniel Ford
78,638,603
958,004
Python processes being leaked when using Reticulate and joblib
<p>I'm having a issue when using <code>joblib.Parallel</code> through <code>reticulate</code>. Basically, if I have an R script call a python function that uses <code>joblib.Parallel</code> to parallelize running of code, and then run that R script, the Python executables are left running after the script has completed...
<python><r><joblib><reticulate>
2024-06-18 16:23:31
0
2,802
T. Kiley
78,638,576
3,159,428
Error RuntimeError: CUDA error: operation not supported when tried to locate something into CUDA
<p>Here is my code:</p> <pre><code>from transformers import AutoModelForCausalLM, AutoTokenizer, QuantoConfig import torch device = &quot;cuda:0&quot; model_id = &quot;bigscience/bloom-560m&quot; quantization_config = QuantoConfig(weights=&quot;int8&quot;) model = AutoModelForCausalLM.from_pretrained(model_id, torch_d...
<python><pytorch><huggingface-transformers>
2024-06-18 16:15:28
2
486
Fermin Pitol
78,638,542
6,867,048
Flatmap for deeply nested lists
<p>I have the following list in Python:</p> <pre><code>N = [1, [2, 2], [[3, 3], 3], [[[4, 4], 4], 4], [[[[5, 5], 5], 5], 5]] </code></pre> <p>and I want to flatten it out and get a list of lists like this</p> <pre><code>[[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]] </code></pre> <p>I tried:</p> <pre><code>sum(map(lambda x:...
<python><list>
2024-06-18 16:06:49
5
8,893
stack0114106
78,638,521
19,363,912
Apply similar sort of elements across multiple lists (clustering)
<p>I have</p> <ul> <li>dictionary <strong>spots</strong> that contains number of spots per position per day (e.g. on day 0, position 'a' has 3 spots), and</li> <li>dictionary <strong>names</strong> that contains available names per position per day (e.g. on day 0, position 'a' is occupied by John, Claire and Billy)</li...
<python><sorting><clusterize>
2024-06-18 16:02:01
1
447
aeiou
78,638,290
9,779,999
Client error '404 Not Found' for url 'http://localhost:11434/api/chat' while using ReActAgent of llama_index.core.agent
<p>I am following this tutorial, <a href="https://youtu.be/JLmI0GJuGlY?si=eeffNvHjaRHVV6r7&amp;t=1915" rel="noreferrer">https://youtu.be/JLmI0GJuGlY?si=eeffNvHjaRHVV6r7&amp;t=1915</a>, and trying to build a simple LLM agent.</p> <p>I am on WSL2, Windows 11, and I am coding in VSC. I use Ollama to download and store my ...
<python><windows-subsystem-for-linux><large-language-model><llama-index><ollama>
2024-06-18 15:14:30
2
1,669
yts61
78,638,246
3,405,291
PyTorch problem with a specific version of CUDA
<h1>Background</h1> <p>I need to test this AI model on the following CUDA server:</p> <p><a href="https://github.com/sicxu/Deep3DFaceRecon_pytorch" rel="nofollow noreferrer">https://github.com/sicxu/Deep3DFaceRecon_pytorch</a></p> <pre class="lang-bash prettyprint-override"><code>$ nvidia-smi Tue Jun 18 18:28:37 2024 ...
<python><pytorch><build><cuda>
2024-06-18 15:03:12
1
8,185
Megidd
78,638,237
10,868,076
How to Model Multivariate Time Series Using Nixtla's NeuralForecast in Python Without Including the Target Variable as an Input
<p>I want to a model multivariate time series using nixtla's neuralforecast in python. However, do not want the target variable to be part of the input of model. Lets make an example:</p> <pre><code>feature1 = np.sin(np.linspace(0, 2*np.pi, 100)) feature2 = np.cos(np.linspace(0, 2*np.pi, 100)) target = feature1 + fe...
<python><deep-learning><time-series>
2024-06-18 15:00:40
0
549
Felix Hohnstein
78,637,991
12,415,855
Click on button not possible?
<p>I try to click on a button using the following code -</p> <pre><code>import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import ex...
<python><selenium-webdriver>
2024-06-18 14:11:16
1
1,515
Rapid1898
78,637,897
1,635,909
Emulating an array-like in python
<p>I am wondering whether <code>python</code> can have the same facilities as <code>C++</code> when defining a class that is derived from a container class, such as a <code>vector</code>. In short, if I define a class which is based on <code>numpy</code> <code>array</code>, how much of array algebraic operations do I n...
<python><containers>
2024-06-18 13:54:18
1
2,234
Joce
78,637,658
2,170,792
Accessing attributes of a Python Descriptor
<p>Not sure if this is feasible or not. The implementation/example below is dummy, FYI.</p> <p>I have a Python class, <em>Person</em>. Each person has a public first name and a public last name attribute with corresponding private attributes - I'm using a descriptor pattern to manage access to the underlying private a...
<python><python-descriptors>
2024-06-18 13:08:15
3
302
pemm
78,637,536
5,024,426
color half of the borders with GeoPandas
<p>I have three polygons with common borders.</p> <p>I can't figure out how to color only the inner half of the border.</p> <p>For the moment I have:</p> <pre><code>data = [ (gpd.read_file(&quot;shape1.shp&quot;), &quot;#f2a6a5&quot;), (gpd.read_file(&quot;shape2.shp&quot;), &quot;#fbebc0&quot;), ...
<python><matplotlib><geopandas>
2024-06-18 12:45:42
1
1,798
djangoliv
78,637,239
7,699,037
How to type hint class defined in conftest and returned from fixture
<p>I have a class that I want to use in various test cases/files to test certain conditions. Something like the following:</p> <pre><code>class MyTester: @staticmethod def does_string_apply(my_string: str) -&gt; bool: return my_string == 'Hello World' </code></pre> <p>I want to use that class in various test ca...
<python><pytest><python-typing><fixtures>
2024-06-18 11:50:29
1
2,908
Mike van Dyke
78,637,203
9,251,158
How to uninstall partially installed package with poetry?
<p>I tried installing a package with poetry for the first time. It worked on a machine and failed on another because the hardware is not compatible with TensorFlow. I should have installed in a virtual environment, but didn't. I tried uninstalling with <code>poetry remove</code> and <code>poetry uninstall</code> and ne...
<python><installation><package><python-poetry>
2024-06-18 11:41:07
2
4,642
ginjaemocoes
78,637,002
11,098,908
Child class's attribute did not override which was defined in parent class
<p>I have a parent and two child classes defined like this</p> <pre><code>import pygame class Person(): def __init__(self): self.image = pygame.image.load('person.png').convert_alpha() self.image = pygame.transform.scale(self.image, (int(self.image.get_wi...
<python>
2024-06-18 11:00:44
3
1,306
Nemo
78,636,947
23,046,354
A module that was compiled using NumPy 1.x cannot be run in NumPy 2.0.0 as it may crash
<pre><code>Traceback (most recent call last): File &quot;C:\Users\mohit\OneDrive\Desktop\Front End\Flask\pythonProject1\tut2.py&quot;, line 8, in &lt;module&gt; import imutils File &quot;C:\Users\mohit\OneDrive\Desktop\Front End\Flask\pythonProject1\.venv\Lib\site-packages\imutils\__init__.py&quot;, line 8, in &...
<python><numpy><opencv><flask>
2024-06-18 10:49:29
3
365
Mohit Gupta
78,636,936
8,300,917
Avoiding Merge In Pandas
<p>I have a data frame that looks like this :</p> <p><a href="https://i.sstatic.net/51VAUJMH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/51VAUJMH.png" alt="enter image description here" /></a></p> <p>I want to group the data frame by <strong>#PROD</strong> and <strong>#CURRENCY</strong> and replace <...
<python><pandas><merge>
2024-06-18 10:47:59
4
904
Number Logic
78,636,865
13,023,201
Pandas interpretation question with double quotes in csv
<p>I have a csv file whose values are comma separated. One of the values of a column in plain text is inputted as</p> <pre class="lang-none prettyprint-override"><code>&quot;XATO,2xASSY,SSD, 6.4TB Gen2, SFF-2.5&quot;&quot;, N&quot; </code></pre> <p>which is supposed be within double quotes so that the comma inside the ...
<python><pandas><csv><double-quotes>
2024-06-18 10:34:22
1
371
Ritz Ganguly
78,636,490
7,786,149
Counting items in an array and making counts into columns
<p>I am working in databricks where I have a dataframe as follows:</p> <p><strong>dummy_df</strong></p> <pre><code>names items Ash [c1,c2,c2,c3] Bob [c1,c2] May [] Amy [c2,c3,c3] </code></pre> <p>Where <code>names</code> column contains strings for values and <code>items</code> is a column of arrays.</p> ...
<python><pandas><apache-spark><pyspark><databricks>
2024-06-18 09:17:08
5
425
Joe
78,636,351
14,566,295
Finding the indices of continuous 0 from a sequence of 0 and 1
<p>Let say I have a sequence of <code>0 and 1</code> as below example</p> <pre><code>[0,0,0,0,1,1,1,0,1,0,1,0,1,1,1] </code></pre> <p>We can think this sequence as a sequence of continuous <code>0</code> but interrupted by <code>1</code>.</p> <p>My goal is to fetch the indices where sequence of continuous <code>0</code...
<python>
2024-06-18 08:47:42
3
1,679
Brian Smith
78,636,327
10,836,309
Pyinstaller in virtual environment still yields very large EXE file
<p>I have a Python code of 78 lines using the following packages:</p> <pre><code>import pandas as pd import base64 from bs4 import BeautifulSoup import os import win32com.client as win32 import pathlib </code></pre> <p>I ran the following commands:</p> <pre><code>venv\Scripts\activate python -m pip install pandas pytho...
<python><pyinstaller>
2024-06-18 08:43:16
3
6,594
gtomer
78,636,280
5,567,893
How can I ensure whether torch.randint generate the random values at least once?
<p>I want to generate the random value using the pytorch (or python).<br /> I tried to use <code>torch.randperm</code> and <code>torch.randint</code> to do this.<br /> (I guess that <code>torch.randperm</code> isn't proper for the following job since it only can generate the fixed number of range)</p> <p>However, some ...
<python>
2024-06-18 08:31:50
1
466
Ssong
78,636,241
3,979,057
How to manipulate/join multiple strings containing UTF-8 characters
<p>My code needs to be compatible with both Python 2.x and 3.x versions. I am getting both string as input to my function, and I need to do some manipulation on those:</p> <pre><code>if len(str1) &gt; 10: str1 = str1[:10] + '...' if six.PY3: return ' : '.join((str1, str2)) </code></pre> <p>For Python 2.x, the a...
<python><python-3.x><encoding><utf-8><python-2.x>
2024-06-18 08:24:32
1
847
HitchHiker
78,636,238
3,616,293
Wrap around 2D coordinates of numpy array
<p>I have a (5, 5) 2D Numpy array:</p> <pre><code>map_height = 5 map_width = 5 # Define a 2D np array- a = np.arange(map_height * map_width).reshape(map_height, map_width) # a ''' array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23...
<python><arrays><numpy>
2024-06-18 08:23:59
1
2,518
Arun
78,636,212
4,324,329
Dual annotations/decorators of Prometheus Client & FastAPI on same function is not working as expected
<p>I have a use case where I need to have two decorator type of annotation for a single function. I have a rest endpoint for which I need to capture the metrics using prometheus client module. I'm trying something like this, but its not working.</p> <pre><code>rest_app = APIRouter(prefix='/rest') TIME_METRICS_ANNOTATIO...
<python><fastapi><prometheus><python-typing><python-decorators>
2024-06-18 08:16:18
1
367
Sree Karthik S R
78,636,124
9,902,571
Django app with automated file upload from user local filesystem
<p>I want to create a website based on Python and Django on the backend and Bootstrap, CSS, JQuery and Javascript on the frontend. The functionality will be somewhat like: user will provide a &quot;Source_Path&quot; from the user’s local filesystem irrespective of the OS used by the user. It will upload all the files f...
<python><django><file-upload>
2024-06-18 07:51:49
2
1,203
Niladry Kar
78,635,838
10,413,428
Bundling python app compiled with cython with pyinstaller
<h1>Problem</h1> <p>I have an application which is bundled with pyinstaller. Now a new feature request is, that parts are compiled with cyphon to c libraries.</p> <p>After the compilation inside the activated virtual environment (poetry) the app runs as expected.</p> <p>BUT, when I bundle it with pyinstaller the execut...
<python><python-3.x><pyinstaller><cython>
2024-06-18 06:38:04
1
405
sebwr
78,635,753
14,890,683
Pydantic Inheritance Defaults
<p>How can I typehint a parent <code>BaseModel</code> such that a child subclass can provide defaults for some of the fields:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Parent(BaseModel): first: str second: str third: str def run(self): print(self...
<python><inheritance><pydantic>
2024-06-18 06:15:52
2
345
Oliver
78,635,741
672,833
Drop-in replacement for the cgi module
<p>Python 3.13 removed the cgi module.</p> <p>While there are many ways described how to workaround that issue, e.g. via using <code>urllib</code> and the <code>email</code> package, for one project I actually need a drop-in replacement, that is a package which also offers a <code>FieldStorage</code> class which I can ...
<python><cgi>
2024-06-18 06:12:55
1
6,336
Jürgen Gmach
78,635,727
568,289
How to get the Azure Automation Runbook Job Id in a Python Runbook?
<p>Powershell Runbooks allow you to get the Job ID with $PSPrivateMetadata.JobId.Guid</p> <p>How do we get it if the runbook is Python?</p>
<python><python-3.x><azure><azure-automation><azure-runbook>
2024-06-18 06:09:47
3
12,571
richard
78,635,682
4,732,111
DuckDB support for Postgres function WITH ORDINALITY
<p>Currently i'm using DuckDB to execute the following Postgres query containing <strong>WITH ORDINALITY</strong> function on a polars dataframe:</p> <pre><code>with suffixes as ( select ordrnbr,(nr-1)/2 N ,max(case when nr%2=1 then elem end) Nkey ,cast(max(case when nr%2=0 then elem end) as int) Nval from test t l...
<python><python-polars><duckdb>
2024-06-18 05:54:48
1
363
Balaji Venkatachalam
78,635,654
11,163,122
Extract Google style docstring into dataclass using Sphinx Napoleon
<p>I am trying to programmatically ingest (&quot;reflect&quot;) Google style docstrings. I am using <code>sphinx.ext.napoleon</code>, as seemingly not many tools do this. I am following <a href="https://github.com/sphinx-doc/sphinx/blob/v7.3.7/sphinx/ext/napoleon/docstring.py#L120-L146" rel="nofollow noreferrer">this e...
<python><reflection><docstring><sphinx-napoleon>
2024-06-18 05:46:05
1
2,961
Intrastellar Explorer
78,635,591
713,844
Python provider healthcheck doesn't detect virtualenv on MacOs
<p>Switching from vim to neovim. I'm running:</p> <p>MacOS Sonoma 14.4.1</p> <p>brew installed pyenv and neovim</p> <p>created a py3nvim virtualenv for neovim, as per the <code>:help provider-python</code> documentation</p> <p>But I still get this error when I run <code>:checkhealth</code></p> <pre><code>provider.pytho...
<python><neovim>
2024-06-18 05:19:56
1
600
stanm87
78,635,380
16,687,283
Python openpyxl connector with anchor
<p>I really would like to draw a curved arrow connector with anchor to cell with openpyxl library, like the image below;</p> <p><a href="https://i.sstatic.net/mdeEwXrD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mdeEwXrD.png" alt="enter image description here" /></a></p> <p>After I went through the o...
<python><excel><openpyxl>
2024-06-18 03:31:18
1
553
lighthouse
78,634,875
1,298,416
Python get request produces different HTML than view source
<pre><code>import requests # Request to website and download HTML contents url='https://beacon.schneidercorp.com/Application.aspx?AppID=165&amp;LayerID=2145&amp;PageTypeID=2&amp;PageID=1104&amp;KeyValue=0527427230' req=requests.get(url, 'html.parser') </code></pre> <p>produces this result:</p> <pre><code>'&lt;!DOCTYPE ...
<python><html><web-scraping><request><get>
2024-06-17 22:24:55
2
341
user1298416
78,634,831
678,572
How can I structure my Python package/submodules so I do not get a circular import error?
<p>Before marking as duplicate to this one, please look at the details of my layout. I've gone through and this question does not address my issue and I haven't been able to adapt the answer: <a href="https://stackoverflow.com/questions/64807163/importerror-cannot-import-name-from-partially-initialized-module-m">Impor...
<python><module><package><importerror><circular-dependency>
2024-06-17 22:04:05
0
30,977
O.rka
78,634,783
6,440,589
"requests.exceptions.HTTPError: 400 Client Error: BadRequest for url" when querying an Azure Data Explorer table
<p>I am running a <strong>Python</strong> script from the <strong>Azure Machine Learning</strong> (AML) environment. This script queries data from an <strong>Azure Data Explorer</strong> (ADX) table, using the <strong>Kusto Query Language</strong> (KQL).</p> <p>Here is an example KQL query:</p> <pre><code>QUERY = &quot...
<python><azure><kql><azure-data-explorer><azure-machine-learning-service>
2024-06-17 21:47:30
1
4,770
Sheldon
78,634,762
6,760,934
Tooling with Langchain Bedrock for RAG AI-Chat Generation
<p>I have a function that takes in a Langugaue Model, a vector store, question and tools; and returns a response, at the moment the tools argument is not being added because based on this <a href="https://python.langchain.com/v0.1/docs/modules/model_io/chat/function_calling/" rel="nofollow noreferrer">example</a> the f...
<python><artificial-intelligence><langchain><retrieval-augmented-generation><amazon-bedrock>
2024-06-17 21:39:05
1
670
DaviesTobi alex
78,634,687
3,177,186
Using Python's winreg, how can I make changes to the Windows Registry that I can confirm worked in Regedit?
<p>My python code is below. Online guides and Stack Overflow posts suggest this should work, but it doesn't seem to. When I change the registry, it does a new get to confirm the change was made properly and, according to that result, it shows that the value IS changing. Additionally, if I kill the Flask server and rest...
<python><registry><winreg>
2024-06-17 21:10:02
0
2,198
not_a_generic_user
78,634,536
6,227,035
Filtering dictionary elements by few initial values
<p>I have the following data structure:</p> <pre><code>Clients= { &quot;data&quot;: [ { &quot;nClients&quot;: 3 }, { &quot;name&quot;: &quot;Mark&quot;, &quot;roll_no&quot;: 1, &quot;branch&quot;: &quot;c&quot; }, { &quot;na...
<python><dictionary><filter><startswith>
2024-06-17 20:22:45
2
1,974
Sim81
78,634,505
6,631,639
Create regex-like (run length encoding) of string s for blocks of a given length k
<p>I am looking for python code to perform a run length encoding to obtain a regex-like summary of a string s, for a known length k for the blocks. How should I tackle this?</p> <p>e.g.</p> <pre><code>s=TATTTTATTTTATTTTATGTTATGTTATGTTATGTTATGTTATGTTATGTTATGTTATGTTACATTATTTTA </code></pre> <p>with k=5 could become</p> <...
<python><string><bioinformatics><encode><rle>
2024-06-17 20:12:39
4
527
Wouter De Coster
78,634,282
1,911,652
Chainlit: How to know when selection in settings changes
<p>I am using latest version of Chainlit. The Python code below correctly prints which option chosen initially by default. It also displays all available options in given list when clicked on setting. But if I change option, it never runs <code>on_option_change</code></p> <p>How can I handle when user changes option in...
<python><python-3.x><streamlit><chainlit>
2024-06-17 19:05:13
1
4,558
Atul
78,634,246
11,557,264
AWS Redshift parallel query issue in Glue script
<p>I have created a Glue script which is supposed to read data from Redshift. The code works perfectly without hash partitions although as soon as I try to run parallel queries it throws an error like this:</p> <pre><code>Caused by: com.amazon.redshift.util.RedshiftException: ERROR: syntax error at or near &quot;)&quot...
<python><pyspark><amazon-redshift><aws-glue>
2024-06-17 18:55:56
0
450
Shardul Birje
78,634,235
9,357,484
numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject
<p>I want to call my Python module from the Matlab. I received the error:</p> <pre><code>Error using numpy_ops&gt;init thinc.backends.numpy_ops </code></pre> <p>Python Error:</p> <pre><code> ValueError: numpy.dtype size changed, may indicate binary incompatibility. Expected 96 from C header, got 88 from PyObject. </cod...
<python><numpy><matlab><spacy>
2024-06-17 18:52:57
8
3,446
Encipher
78,634,163
1,796,858
How to download a python whl file requiring a different version of python to the one available on the system
<p>I am trying to download a whl file. The only problem is that there's a version constraint on the install. And this constraint on the install, also constrains the download too. This question is how from the client side i can get around this constraint so i can download the whl file.</p> <p>In this project there is a ...
<python><pip>
2024-06-17 18:34:27
1
1,581
Owl
78,633,947
10,327,849
Filter DataFrame events not in time windows DataFrame
<p>I have a DataFrame of events (Event Name - Time) and a DataFrame of time windows (Start Time - End Time). I want to get a DataFrame containing only the events not in <strong>any</strong> of the time windows. I am looking for a &quot;pythonic&quot; way to filter the DataFrame.</p> <p>Example: Events DataFrame:</p> <d...
<python><pandas><dataframe><datetime><filter>
2024-06-17 17:33:44
3
301
Yakir Shlezinger
78,633,814
11,627,201
Object actually takes up more memory when I use __slots__ in Python 3?
<p>Here is the code:</p> <pre><code>&gt;&gt;&gt; class A: ... __slots__ = (&quot;a&quot;,) ... def __init__(self): ... self.a = 1 ... &gt;&gt;&gt; class B: ... def __init__(self): ... self.b = 1 ... &gt;&gt;&gt; import pickle as pk &gt;&gt;&gt; len(pk.dumps(A())) 40 &gt;&gt;&gt; len(pk.dumps...
<python><python-3.x>
2024-06-17 16:53:03
0
798
qwerty_99
78,633,770
1,473,517
Can Neumaier summation be sped up?
<p>Neumaier summation is an improvement of Kahan summation for accurately summing arrays of floats.</p> <pre><code>import numba as nb @nb.njit def neumaier_sum(arr): s = arr[0] c = 0.0 for i in range(1, len(arr)): t = s + arr[i] if abs(s) &gt;= abs(arr[i]): c += (s - t) + arr[i]...
<python><cython><numba><floating-accuracy><pythran>
2024-06-17 16:39:15
1
21,513
Simd
78,633,756
20,770,190
How to resize an image in Gradio?
<p>I'm looking for an approach to resize an image as a header in Gradio generated UI to be smaller.</p> <p>According to a closed issue on their Github, I followed the following manner:</p> <pre class="lang-py prettyprint-override"><code>import gradio as gr with gr.Blocks() as app: gr.Image(&quot;logo.png&quot;, la...
<python><gradio>
2024-06-17 16:33:41
1
301
Benjamin Geoffrey
78,633,516
181,783
Executing non-GUI threads in a separate GIL
<p>My team develops a GTK-Python application that dynamically spawns threads to handle longer running tasks. Recently, we added a feature for requesting some batch computation on demand and this has made the GUI unresponsive. My research and analysis shows that the problem seems to be contention for GIL that starves th...
<python><multithreading><gil>
2024-06-17 15:38:58
1
5,905
Olumide
78,633,502
1,775,741
Why does the PID reported in a dmesg log message differ from that returned by os.getpid() in Python?
<p>When debugging an OOM error in a Python multiprocessing script I noticed that a dmesg log will report</p> <pre><code>[Mon Jun 17 15:26:04 2024] Memory cgroup out of memory: Killed process **1079355** (python3) total-vm:5323820kB, anon-rss:5249840kB, file-rss:3392kB, shmem-rss:8kB, UID:0 pgtables:10448kB oom_score_ad...
<python><kubernetes><out-of-memory><rhel8><dmesg>
2024-06-17 15:36:01
0
809
Ian Danforth
78,633,448
391,445
How to mark an *instance* of a Python class as deprecated?
<p>I have inherited the maintenance on some API code. One of the things I need to update is some environment information (think staging, production). The old names were <code>test</code> and <code>production</code>, while the new names are <code>sandbox</code>, <code>simulator</code> and <code>production</code>. The ol...
<python><instance><deprecated><deprecation-warning>
2024-06-17 15:23:23
1
7,809
Colin 't Hart
78,633,441
238,230
Paketo: Running npm install following Python buildpack
<p>We have added a static build step to our Python app which is triggered by <code>npm build</code> We would like to implement this in our Paketo build so that the built client-side assets are available at runtime.</p> <p>Based on the documentation it appears this should be possible by adding a <code>--post-buildpack</...
<python><node.js><buildpack><paketo>
2024-06-17 15:22:19
0
752
Gids
78,633,275
5,599,687
How can I install extras from a git subdirectory with pip?
<p><code>pip</code> supports VCS installs, as documented in <a href="https://pip.pypa.io/en/stable/topics/vcs-support/" rel="nofollow noreferrer">https://pip.pypa.io/en/stable/topics/vcs-support/</a> (related question: <a href="https://stackoverflow.com/questions/13566200/how-can-i-install-from-a-git-subdirectory-with-...
<python><git><pip><version-control>
2024-06-17 14:41:50
2
751
Gabriele
78,633,207
509,868
How to print a list of numpy.float32 values?
<p>I run some simulations whose result is a <code>dict</code> like this:</p> <pre><code>results = { 'this': 5, 'that': 6, 'those': [2.34, 5.67] } </code></pre> <p>I save it in a human-readable format using code like this:</p> <pre><code>s = '' for key, value in results.items(): s += f'{key}: {value}\n' ...
<python><numpy><representation><numpy-2.x>
2024-06-17 14:27:14
2
28,630
anatolyg
78,633,199
5,547,553
How to include thousand separator in numbers in polars output?
<p>I'd like to generate a html output of a dataframe with thousand separators in the output.<br> However pl.Config does not seem to do anything:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({'prod':['apple','banana','melon'], 'price':[7788, 1122, 4400]}) with pl.Config( ...
<python><html><dataframe><python-polars>
2024-06-17 14:26:00
3
1,174
lmocsi
78,633,156
1,231,055
How to use windows_expand_args with single command click program
<p>I have a Python program and am using Click to process the command line. I have a single command program, as in the example below. On Windows I would like to pass in a valid glob expression like <code>*.py</code> to Click 8.x and have the literal string <code>&quot;*.py&quot;</code> show up in the <code>filepattern...
<python><glob><python-click>
2024-06-17 14:15:53
1
3,111
Brad Campbell
78,633,129
1,422,096
Execute a last line of code when the user closes the console window
<p>If we run a Python program in a console on Windows (<code>python myscript.py</code>), is there a possibility to run a last line of code when the user clicks on the &quot;X&quot; top-right button of the console window?</p> <p>I already tried something similar to <a href="https://stackoverflow.com/questions/16590599/...
<python><windows><atexit>
2024-06-17 14:11:51
1
47,388
Basj
78,632,961
241,552
FactoryBoy: use a factory method on the model instead of __init__
<p>I have a class, for which I would like to write a factory using <code>FactoryBoy</code>. However, this class doesn't produce its instances using the <code>__init__</code> method, but rather a number of factory methods:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: def __init__(): se...
<python><factory-boy>
2024-06-17 13:41:03
1
9,790
Ibolit
78,632,780
4,451,315
How to set pandas or duckdb backend in ibis memtable?
<p>I have a function like this:</p> <pre class="lang-py prettyprint-override"><code>import ibis def my_function(df): t = ibis.memtable(df) t = t.mutate(ibis._['a'] + 1) return to.to_arrow() </code></pre> <p>My question is - if I pass it a pandas dataframe, then which backend is <code>t</code> going to use ...
<python><pandas><ibis>
2024-06-17 13:01:48
1
11,062
ignoring_gravity
78,632,524
7,395,592
Pretty-print indices/coordinates of 2D Numpy array
<p>Does Numpy provide built-in capabilities to print the indices/coordinates of a 2-d Numpy array at its borders?</p> <p>What I mean is the following: Given, for example, the array</p> <pre class="lang-py prettyprint-override"><code>a = np.arange(6).reshape(2, 3).astype(float) </code></pre> <p>I would like to have a pr...
<python><numpy><numpy-ndarray>
2024-06-17 12:05:06
2
6,750
simon
78,632,369
14,348,996
How do I type hint a function using TypedDict that mutates a dictionary in Python?
<p>I am defining a function that takes a dictionary as an input, and does some operations on it that creates a new key/value pair and modifies one existing value's type.</p> <p>I have a <code>TypedDict</code> for both the input and output of the function:</p> <pre><code>from typing import TypedDict class MyDict(TypedD...
<python><python-typing><typeddict>
2024-06-17 11:31:55
1
1,236
henryn
78,632,352
6,386,056
Plotly px.Timeline y marks do not adjust when using facet_row
<p>With a simple dataFrame that look like this</p> <p><a href="https://i.sstatic.net/AJFmYi18.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJFmYi18.png" alt="df" /></a></p> <p>The following code</p> <pre><code>fig = px.timeline(df, x_start=&quot;Target Date Start&quot;, x...
<python><plotly><timeline><gantt-chart><plotly-express>
2024-06-17 11:28:22
1
667
Mth Clv
78,632,287
11,901,834
Only get subsection of Exception
<p>In Python, I'm persisting some errors to a database.</p> <p>I want to be able to group these errors by their error details.</p> <p>However, currently, I am persisting the exception itself as follows:</p> <pre><code>try: # logic except Exception as e: persist(e) # this just does an insert of e </code></pre> <p>...
<python>
2024-06-17 11:11:24
2
1,579
nimgwfc
78,632,056
3,906,713
Is there an intended way to incapsulate SeriesHelper in InfluxDB-python
<p>I would like to create a table in InfluxDB and then write a pandas dataframe to it. Thus, I need to develop a function:</p> <pre><code>def write_df_to_influx(df: pd.DataFrame, client: InfluxDBClient, table_name: str, tag_names: list, field_names: list) </code></pre> <p>The <a href="https://influxdb-python.readthedoc...
<python><pandas><influxdb>
2024-06-17 10:17:14
1
908
Aleksejs Fomins
78,631,897
23,725,389
Saving Excel document removes the chart
<p>I am using OpenPyXL for processing, there are only 2 lines of code:</p> <pre><code>workbook = load_workbook(filename='input.xlsx', keep_vba=True, rich_text=True) # I will do operator here, but there is an error, so I comment this line workbook.save('output.xlsx') </code></pre> <p>Then I get the output with <strong>l...
<python><excel><openpyxl>
2024-06-17 09:40:11
1
806
Nguyen Manh Cuong
78,631,285
4,451,315
Use ibis-framework to compute shifts (lags) in dataframe
<p>Say I want to do the following in Polars:</p> <pre class="lang-py prettyprint-override"><code>df.with_columns( a_1 = pl.col('a').shift(1), a_2 = pl.col('a').shift(2), b_1 = pl.col('b').shift(1), b_2 = pl.col('b').shift(2), ) </code></pre> <p>Say, starting from</p> <pre class="lang-py prettyprint-over...
<python><python-polars><ibis>
2024-06-17 07:13:36
1
11,062
ignoring_gravity
78,630,737
2,975,510
Efficient scipy sparse array and kronecker product computation
<p>I want to compute the Kronecker product of a long list of small matrices (say, Pauli matrices). I tried to define the small matrices using <code>scipy.sparse.csr_array</code>, and use <code>scipy.sparse.kron</code> to perform the Kronecker product. However, the performance isn't ideal.</p> <pre><code> import numpy a...
<python><math><scipy><wolfram-mathematica><sparse-matrix>
2024-06-17 02:47:26
1
2,203
Lelouch
78,630,470
10,028,567
How do I remove characters in a list?
<p>The following command when run in BASH cleans <a href="https://gutenberg.org/cache/epub/17192/pg17192.txt" rel="nofollow noreferrer">The Raven</a>.</p> <pre><code>cat The_Raven.txt | gawk '{print tolower($0)}' | tr -d &quot;\!\&quot;#$%&amp;'()*+,-./:;&lt;=&gt;?@[\\]^_\`{|}~&quot; </code></pre> <p>The following comm...
<python><linux><bash><subprocess>
2024-06-16 23:25:40
3
437
Tom Lever
78,630,207
819,417
Pygame indexed surface won't display
<p>I'm porting <a href="https://www.pygame.org/pcr/numpy_plasma/index.php" rel="nofollow noreferrer">this ancient code</a> to Python 3. I've applied the varied palette to the surfaces and the <code>plasma_buffer</code> matrix changes, but <code>pygame.display.flip()</code> keeps showing a black screen. The surface pixe...
<python><python-3.x><pygame><pygame-surface>
2024-06-16 20:32:43
1
20,273
Cees Timmerman
78,630,094
607,033
Django The included URLconf '_mod_wsgi_...' does not appear to have any patterns in it
<p>I am a Python novice and I am trying to run a Django hello world app on Windows with Apache and mod_wsgi. The upper error message shows up with the following code:</p> <pre><code>import os import sys import site from django.core.wsgi import get_wsgi_application from django.conf import settings from django.urls impor...
<python><django>
2024-06-16 19:38:56
1
26,269
inf3rno
78,630,047
827,927
How to stop numpy floats being displayed as "np.float64"?
<p>I have a large library with many doctests. All doctests pass on my computer. When I push changes to GitHub, GitHub Actions runs the same tests in Python 3.8, 3.9, 3.10 and 3.11. All tests run correctly on on Python 3.8; however, on Python 3.9, 3.10 and 3.11, I get many errors of the following type:</p> <pre><code>Ex...
<python><numpy><doctest><numpy-2.x>
2024-06-16 19:19:38
4
37,410
Erel Segal-Halevi
78,629,960
13,008,170
Multiprocessing Pool: return the minimum element
<p>I want to run a task with a multiprocessing.Pool and return only the minimum element, without taking the memory to store every output.</p> <p>My code so far:</p> <pre class="lang-py prettyprint-override"><code>with Pool() as pool: programs = pool.map(task, groups) shortest, l = min(programs, key = lambda a: len(...
<python><multiprocessing><minimum><memory-efficient>
2024-06-16 18:48:07
1
304
gXLg
78,629,917
2,545,680
"which pip" and "pip --version" give different locations
<p>How's the following possible:</p> <pre class="lang-none prettyprint-override"><code>max@p17:~$ which pip /usr/bin/pip max@p17:~$ pip --version pip 24.0 from /home/user/.local/lib/python3.10/site-packages/pip (python 3.10) </code></pre> <p>so where's my pip installed?</p>
<python>
2024-06-16 18:31:58
1
106,269
Max Koretskyi
78,629,727
33,404
Why does my Python socket.connect() call stall for a minute with IPv6 but not with IPv4?
<p>On my Windows 10 desktop machine, I am running the following bit of Python (3.10.9) to make an HTTP POST request:</p> <pre><code>import json import requests response = requests.post( url=&quot;https://foo.bar/baz&quot;, headers={ 'Content-Type': &quot;application/json&quot;, 'Authorization':...
<python><windows><network-programming><ipv6>
2024-06-16 17:11:12
0
16,911
urig
78,629,435
10,729,292
Numba throws `type error` for my gradient descent
<p>I am trying to build my MNIST Classifier from scratch in Numba, but it throws the error of type error for np.dot(), however, when I run these functions without NUMBA Jit, I find out all the types are of float32 and run without error, I cannot understand whats wrong here.</p> <p>The code is :</p> <pre><code>import nu...
<python><numba><jit>
2024-06-16 14:48:25
0
1,558
Sadaf Shafi
78,629,411
1,382,667
Chrome driver for Selenium Can not connect to the Service
<p>Trying to use Selenium to click a DIV and return the resulting link that should appear afterwards In Python I can get chrome to open but it eventually fails to get url with error <code> Can not connect to the Service D:\Software\chromedriver_126-win64\chrome.exe</code></p> <p>for for what's worth here's my code</p> ...
<python><selenium-webdriver>
2024-06-16 14:36:54
0
333
Holly
78,629,133
561,243
Filling matplotlib stairs with different colors
<p>I have the following problem. I have some data for which I need to make an histogram.</p> <p>For this purpose I use the <code>numpy.histogram</code> to generate the bins and the content and then <code>pyplot.stairs</code> for the visualization.</p> <p>So far so good.</p> <p>Next part is that I would like to have the...
<python><matplotlib>
2024-06-16 12:35:37
1
367
toto
78,629,090
6,124,415
Setting up firebase functions with Python errors and issues
<p>Can anybody explain how correctly to set up firebase-functions with Python? (building in googles &quot;project IDX&quot;)</p> <p>My current steps:</p> <ul> <li><p>create &quot;blank workspace&quot;</p> </li> <li><p>run firebase init functions-&gt; that create &quot;functions&quot; folder as it should but no &quot;ve...
<python><google-cloud-functions>
2024-06-16 12:12:26
0
1,155
pb4now
78,628,959
5,722,359
How to let KP_Down, KP_Up, KP_Next, KP_Prior scroll a `ttk.Treeview` widget like KeyPress-Down, KeyPress-Up, KeyPress-Next, KeyPress-Prior?
<p>I discovered that in <code>tkinter</code>, <code>'&lt;KP_Down&gt;'</code>,<code>'&lt;KP_Up&gt;'</code>, <code>'&lt;KP_Next&gt;'</code>, <code>'&lt;KP_Prior&gt;'</code> does not scroll a <code>ttk.Treeview</code> widget as <code>'&lt;KeyPress-Down&gt;'</code>, <code>'&lt;KeyPress-Up&gt;'</code>, <code>'&lt;KeyPress-N...
<python><tkinter><treeview><tcl>
2024-06-16 11:20:30
2
8,499
Sun Bear
78,628,887
4,961,540
Getting Same result for AES encryption and decryption in python and typescript
<p>I am using the below code to encrypt and decrypt in typescript:</p> <pre><code>const AES = require('crypto-js/aes'); const Utf8 = require('crypto-js/enc-utf8'); export const encrypt = (text, passphrase) =&gt; { return AES.encrypt(text, passphrase).toString(); }; export const decrypt = (ciphertext, passphrase) =&...
<python><typescript><encryption><aes>
2024-06-16 10:45:13
0
657
Kartik Watwani
78,628,816
625,396
Fast hashing of integer sequences in nympy/torch ? (except dot product with random vector - it is quite good, but may be something else?)
<p>Consider sequences of integers like (1,0,2,4,...,100). We have many(!) of them, and we need to hash them and it should be very fast in Python - so I am seeking methods using numpy/torch - i.e. without slow Python loops.</p> <p>The simple and efficient method which works - is to generate random integer vector - and ...
<python><numpy><hash><torch>
2024-06-16 10:09:56
1
974
Alexander Chervov
78,628,679
5,790,653
sqlite insert not adding any records
<p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>import os path = '/home/test/' os.system(f'rm -vf {path}myDB.db') import sqlite3 import datetime conn = sqlite3.connect(f&quot;{path}myDB.db&quot;) conn.execute( ''' CREATE TABLE logs (id INTEGER PRIMARY KEY, userid INTEGER NOT NULL...
<python><sqlite>
2024-06-16 08:52:12
1
4,175
Saeed
78,628,435
17,652,621
Memory Leak Issue with Tkinter GUI application
<p>I'm facing a memory leak issue with a custom widget in a Tkinter/customtkinter application. Despite my efforts to manually delete and clear all member variables, the memory is not being fully cleaned up. Below is the relevant code for one of my custom class.</p> <pre class="lang-py prettyprint-override"><code>import...
<python><python-3.x><tkinter><customtkinter>
2024-06-16 06:34:59
0
320
Thisal
78,628,433
10,994,166
Add one hot feature to tensorflow model
<p>I'm new to deep learning, I'm creating MMOE model with and adding feature step by step in my <em>init</em> function.</p> <pre><code>class TIGMMOE(tfrs.Model): def __init__(self, use_cross_layer, deep_layer_sizes, num_units, num_shared_experts, projection_dim=None): super().__init__() sel...
<python><tensorflow><machine-learning><deep-learning>
2024-06-16 06:33:12
0
923
Chris_007
78,628,191
2,778,405
Get timezone for specific date
<p>I have a list of dates formatted like so:</p> <pre class="lang-py prettyprint-override"><code>'2024-01-01` </code></pre> <p>I need to turn them into ISO datetimes like so:</p> <pre><code>`2024-01-01T00:00:00-08:00` </code></pre> <p>I thought this would be easy, I was wrong. I've seen many questions talk about this ...
<python><datetime><timezone>
2024-06-16 03:23:06
1
2,386
Jamie Marshall
78,628,089
11,121,557
Unable to debug python C extension using valgrind
<p>I am trying to debug a C extension I made using CFFI. I am using Python 3.11 and Valgrind 3.18.1.</p> <p>As far as I can tell from the docs the only setup needed is setting the <code>PYTHONMALLOC=malloc</code> environment variable, but for some reason, valgrind just refuses to report any errors with or without it be...
<python><c><malloc><valgrind><cffi>
2024-06-16 01:29:07
1
376
Slav
78,628,012
21,343,992
How to create AWS EC2 instance using Boto3 for a specific account?
<p>I currently have a regular/non-organization AWS account and I create EC2 instances via Boto3 using code like this:</p> <pre><code>ec2 = boto3.resource('ec2', region_name = region) instances = ec2.create_instances(...) </code></pre> <p>I may need to change my account to an organization and create sub-accounts so I c...
<python><amazon-web-services><amazon-ec2><boto3>
2024-06-16 00:23:55
1
491
rare77
78,627,973
3,347,814
How to extract a substring from a column in a dataframe based in the column from another dataFrame?
<p>I have found a solution from my problem, but it is clearly the most dumb and inefficient one. I was hoping that someone could help me with a proper solution.</p> <p>I have two data frames containing a column with a telephone number. df1[&quot;telephone&quot;] can have one or more numbers separated by commas and df2[...
<python><pandas><dataframe>
2024-06-15 23:56:31
5
1,143
user3347814
78,627,501
202,201
Wildly inconsistent performance of CP-SAT solver
<p>I ran the CP-SAT solver three consecutive times on my model. The wall times were:</p> <ul> <li>0h07m41s</li> <li>0h39m45s</li> <li>2h17m42s</li> </ul> <p>There is almost 18x difference in runtime from the fastest to the slowest. There were no other CPU-intensive jobs on the machine at the time.</p> <p>I understand t...
<python><or-tools><cp-sat>
2024-06-15 18:58:24
1
1,091
ScottJ
78,627,210
417,896
How to style QTabWidget with PySide6
<p>How can I maximize the space taken up by children of QTabWidget using PySide6?</p> <p>IOW, I don't want the padding the QTabWidget container takes up before drawing the child inside of it.</p> <p>In the image you can see there is a lighter shade of gray from the background of the tab widget parent. I want to remove...
<python><pyside><qtabwidget>
2024-06-15 16:47:35
0
17,480
BAR
78,627,164
5,507,389
FastAPI path parameter translation to enumaration member
<p>I started to learn FastAPI by reading the official documentation. I'm having a bit of difficulty understanding the example which illustrate how to work with Python enumarations. The example in the official documentation is a follows:</p> <pre><code>from enum import Enum from fastapi import FastAPI class ModelName...
<python><enums><fastapi>
2024-06-15 16:29:52
1
679
glpsx
78,626,598
7,695,845
sympy.init_printing() not working in IPython terminal session
<p>I wanted to do some quick calculations and I was too lazy to open a notebook file, so I just opened an <code>IPython</code> session in the terminal. According to <a href="https://docs.sympy.org/latest/tutorials/intro-tutorial/printing.html#setting-up-pretty-printing" rel="nofollow noreferrer">sympy's documentation</...
<python><ipython><sympy>
2024-06-15 12:28:42
0
1,420
Shai Avr
78,626,537
6,687,699
Update query not working with Celery and FastAPI
<p>I am using a FastAPI repository pattern, and it works very well in Celery, but I have an Update query it doesn't execute. (The funny part is that, other queries work very well).</p> <p>Here's my query:</p> <pre><code>UPDATE_REMINDER_SENT_AT_QUERY = &quot;&quot;&quot; UPDATE public.trainings SET reminder_sent_at = :n...
<python><postgresql><celery><fastapi><celerybeat>
2024-06-15 12:04:14
1
4,030
Lutaaya Huzaifah Idris
78,626,515
1,473,517
What exactly is slowing np.sum down?
<p>It is known that np.sum(arr) is quite a lot slower than arr.sum(). For example:</p> <pre><code>import numpy as np np.random.seed(7) A = np.random.random(1000) %timeit np.sum(A) 2.94 µs ± 13.8 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) %timeit A.sum() 1.8 µs ± 40.8 ns per loop (mean ± std. dev. of...
<python><numpy>
2024-06-15 11:53:44
2
21,513
Simd
78,626,499
5,836,440
Confusion regarding functions to generate random numbers in numpy
<p>I am confused primarily on two points:</p> <ol> <li><p>Why are there different random number generator functions in numpy that seemingly produce the same thing? e.g. np.random.rand() vs np.random.uniform(); or np.random.randn(), np.random.normal(), np.random.standard_normal()- [I mean, why is the standard_normal() f...
<python><numpy><random><random-seed>
2024-06-15 11:42:53
1
403
Meep
78,626,489
11,022,471
Spatially mapping connections in python
<p>I am trying to plot trade routes of commodities from one country to another in Python using <code>plotly</code>. I want the connections to transition from red at the origin to blue at the destination.</p> <p>However, the connections appear broken (non-straight lines) when I try to interpolate the colors. This could ...
<python><plotly><line-plot>
2024-06-15 11:38:23
0
743
Ep1c1aN
78,626,342
8,110,961
Python Add datetime column in dataframe from an existing column
<p>I have data in csv file as below</p> <pre><code>v,vw,o,c,h,l,t,n 18043.0,374.411,374.69,374.99,374.99,373.8,1656662400000,157 12003.0,375.6296,375.15,375.84,375.9,374.95,1656663300000,98 18426.0,376.0636,375.98,376.02,376.29,375.63,1656664200000,88 4700.0,376.0772,375.88,376.11,376.34,375.85,1656665100000,43 27969.0...
<python><pandas><dataframe>
2024-06-15 10:37:31
1
385
Jack
78,626,196
1,516,331
If sending multiple HTTP GET requests using for loop, why is aiohttp still faster than requests?
<p>I am following the code in this page: <a href="https://www.twilio.com/en-us/blog/asynchronous-http-requests-in-python-with-aiohttp" rel="nofollow noreferrer">https://www.twilio.com/en-us/blog/asynchronous-http-requests-in-python-with-aiohttp</a>. Here is the first approach using <code>aiohttp</code>:</p> <pre class=...
<python><asynchronous><async-await><coroutine><aiohttp>
2024-06-15 09:30:04
1
3,190
CyberPlayerOne
78,626,109
7,978,112
Converting dict to dataclass type dynamically, and an instance back to a dict, results in empty dict
<p>Have a nested dictionary.</p> <pre class="lang-py prettyprint-override"><code>stock_price = {'lastPrice': 129.1, 'open': 126.57, 'close': 0, 'intraDayHighLow': {'min': 126.4, 'max': 129.55, 'value': 129.1}, 'weekHighLow': {'min': 49.7, 'minDate': '26-Jun-2023', 'max': 142.9, 'maxDate':...
<python><dictionary><python-dataclasses>
2024-06-15 08:52:40
2
1,847
reservoirinvest