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,790,646
3,240,688
importing airflow automatically creates airflow directory
<p>I've noticed that whenever I import airflow in Python, it automatically creates an airflow directory in my home directory. Literally just this</p> <pre><code>$ python Python 3.11.9 | packaged by conda-forge | (main, Apr 19 2024, 18:36:13) [GCC 12.3.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;cred...
<python><airflow>
2024-07-24 21:27:32
1
1,349
user3240688
78,790,594
11,793,491
How to use replace text using a regex in a Pandas dataframe
<p>I have the following dataset:</p> <pre class="lang-py prettyprint-override"><code>meste = pd.DataFrame({'a':['06/33','40/2','05/22']}) </code></pre> <pre class="lang-none prettyprint-override"><code> a 0 06/33 1 40/2 2 05/22 </code></pre> <p>And I want to remove the leading 0s in the text (06/33 to 6/33 for...
<python><pandas><regex>
2024-07-24 21:09:17
1
2,304
Alexis
78,790,306
5,537,840
Python Version Mismatch in Jupyter Notebook Environment
<p>I am experiencing a discrepancy between the Python version reported in the Jupyter notebook startup banner and the version shown when I query <code>python --version</code> within the notebook. The startup banner indicates Python 3.11.9, but when I run <code>!python --version</code>, it returns Python 3.11.7.</p> <p>...
<python><jupyter-notebook><conda><jupyter><jupyter-lab>
2024-07-24 19:50:37
1
9,269
Kenenbek Arzymatov
78,790,220
1,256,347
MATLAB does not read parquet file, simply says "Unable to read Parquet file". How can I still read it?
<p>I have created a parquet file using Python <a href="https://pola.rs/" rel="nofollow noreferrer">polars</a>' <a href="https://docs.pola.rs/api/python/stable/reference/api/polars.DataFrame.write_parquet.html" rel="nofollow noreferrer"><code>.write_parquet</code></a> method. It can be read back by Python without a prob...
<python><matlab><parquet>
2024-07-24 19:24:53
1
2,595
Saaru Lindestøkke
78,790,186
8,941,248
How to find the number of rows within a group since a nonzero value occurred for a pandas dataframe?
<p>I have a dataframe like so:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>ID</th> <th>value</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>0</td> </tr> <tr> <td>A</td> <td>1</td> </tr> <tr> <td>A</td> <td>0</td> </tr> <tr> <td>A</td> <td>0</td> </tr> <tr> <td>B</td> <td>0</td> </tr> <t...
<python><pandas>
2024-07-24 19:15:16
2
521
mdrishan
78,789,998
12,098,671
Unable to make a remote api call to flask app(for MySQL connection) inside my apache server
<p>I have an apache server running on Alma Linux. I have the flask code setup to accept API calls from remote connections. So my API call hits the flask which then connects to MySQL database.</p> <p>When I try to run this database connection code locally inside the server, it works fine. But when I try to hit flask app...
<python><mysql><linux><apache><flask>
2024-07-24 18:33:40
1
759
Yash Khasgiwala
78,789,977
2,153,235
PyPlot plots are bigger with high DPI, but still blurry
<p>I am following a tutorial to generate a scatter plot of points, coloured by cluster and also colour-saturated based each point's strength of membership in its respective clusters. I mention the colouring details in case they affect the resolution, but I suspect they don't.</p> <p>What I find is that if I increase t...
<python><matplotlib><spyder>
2024-07-24 18:27:46
1
1,265
user2153235
78,789,944
1,471,980
how do you sort column names in Date in descending order in pandas
<p>I have this DataFrame:</p> <pre><code>Node Interface Speed Band_In carrier Date Server1 wan1 100 80 ATT 2024-05-09 Server1 wan1 100 50 Sprint 2024-06-21 Server1 wan1 100 30 Verizon 2024-07-01 Server2 wan1 ...
<python><pandas><dataframe><datetime>
2024-07-24 18:16:05
2
10,714
user1471980
78,789,813
6,370,552
ModuleNotFoundError: No module named 'paramiko.auth_strategy' while using fab2 python
<p>I'm trying to execute a python task using fab. I've installed fab2 for python3 and trying to use it to run the task in a venv. Unfortunately using fab2 keeps giving me this error:</p> <pre><code>(venv) My-MacBook-Pro-2:mypath myuser$ fab2 /mypath/venv/lib/python3.12/site-packages/paramiko/pkey.py:82: CryptographyDep...
<python><python-3.x><python-module><python-venv>
2024-07-24 17:42:10
1
344
scottstots
78,789,745
16,869,946
Python scipy integrate.quad with TypeError: 'NoneType' object is not iterable
<p>I am trying to define the following integral using scipy: <a href="https://i.sstatic.net/BHJB7Vpz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BHJB7Vpz.png" alt="enter image description here" /></a></p> <p>and here is my code:</p> <pre><code>import numpy as np import scipy.integrate as integrate fr...
<python><list><scipy><tuples><quad>
2024-07-24 17:27:04
1
592
Ishigami
78,789,622
20,591,261
Get max date column name on polars
<p>I'm trying to get the column name containing the maximum date value in my Polars DataFrame. I found a similar question that was already answered <a href="https://stackoverflow.com/questions/77488797/polars-get-name-of-column-containing-max-value-per-row">here</a>.</p> <p>However, in my case, I have many columns, an...
<python><dataframe><python-polars>
2024-07-24 16:52:53
1
1,195
Simon
78,789,571
11,643,528
Keeping a running total of quantites while matching items and dates within a range
<p>I'm attempting to match job lines to purchase orders on items within a date range while tracking the available quantity of the items.</p> <p>If I have three dataframes:</p> <pre><code> joblines = pd.DataFrame({ 'order': ['1-1', '1-1', '2-1', '3-1'], 'item': ['A1','A2','A1', 'A1'], 'startda...
<python><pandas>
2024-07-24 16:40:16
1
4,695
Warcupine
78,789,533
5,924,264
Vectorized way to check if a string is in a dataframe column (set of strings)?
<p>I have a pandas dataframe <code>df</code>. This dataframe has a column <code>to_filter</code>. <code>to_filter</code> is either an empty set or a set of strings. This dataframe also has an integer column <code>id</code>. The <code>id</code> may not be unique.</p> <p>Given an input string <code>input</code>, is there...
<python><pandas><dataframe>
2024-07-24 16:30:36
2
2,502
roulette01
78,789,244
11,815,097
Writing atomic functions in Python
<p>In many systems, transactions are used to group operations together so that they are atomic—meaning they either all succeed or all fail. However, in Python itself does not seem to have built-in support for transactions outside of the context of databases</p> <p>For example I have two functions as follows:</p> <pre><...
<python><python-3.x><transactions>
2024-07-24 15:23:00
2
315
Yasin Amini
78,789,122
1,883,154
Load multiple large CSV files into parquet while creating new colum for file name
<p>I have collections of CSV files, up to 1000, each being ~1 GB uncompressed. I want to create a single parquet dataset from them.</p> <p>In doing this, I want to record which file each set of rows comes from.</p> <p>I want to do all this in less than ~10 GB of RAM, in Python.</p> <p>The obvious place to start was wit...
<python><dask><parquet>
2024-07-24 14:58:54
1
1,738
Ian Sudbery
78,789,026
2,475,195
Apply sklearn logloss with rolling on pandas dataframe
<p>My function call looks something like</p> <pre><code>loss = log_loss(y_true=validate_d['y'], y_pred=validate_probs, sample_weight=validate_df['weight'], normalize=True) </code></pre> <p>Is there any way to combine this with pandas <code>rolling()</code> functionality, so I calculate it for a trailing 10k rows windo...
<python><pandas><dataframe><rolling-computation>
2024-07-24 14:38:40
1
4,355
Baron Yugovich
78,788,950
4,826,848
Importing rembg in Celery Task breaks workers
<p>I'm trying to use the <code>rembg</code> library in a Celery worker (Django), but once I import the library, the worker is exited prematurely:</p> <pre><code>objc[47160]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork...
<python><django><celery><rembg>
2024-07-24 14:21:01
1
1,851
Cesar Jr Rodriguez
78,788,921
1,814,420
What is the type hint for socket?
<p>Suppose I'm writing a function that takes a <a href="https://docs.python.org/3/library/socket.html" rel="nofollow noreferrer"><code>socket</code></a> as a parameter. How should I type hint it properly?</p> <pre class="lang-py prettyprint-override"><code>def read_socket(socket: ???): .... </code></pre>
<python><python-typing><python-sockets>
2024-07-24 14:15:49
2
12,163
Triet Doan
78,788,919
525,865
trying to find out the logic of this page: approx ++ 100 results stored - and parsed with Python & BS4
<p>trying to find out the logic that is behind this page:</p> <p>we have stored some results in the following db:</p> <p><a href="https://www.raiffeisen.ch/rch/de/ueber-uns/raiffeisen-gruppe/organisation/raiffeisenbanken/deutsche-schweiz.html#accordionitem_18104049731620873397" rel="nofollow noreferrer">https://www.rai...
<python><pandas><web-scraping><beautifulsoup>
2024-07-24 14:15:02
1
1,223
zero
78,788,913
899,862
Errors implementing __eq__ method in OOP class structure
<p>Here are a couple of classes<br /> A parent</p> <pre><code>class GeometricShape: def __init__(self, name): self.set_name(name) def get_name(self): return self.__name def set_name(self,name): validate_non_empty_string(name) self.__name = name def __repr__...
<python>
2024-07-24 14:14:24
1
2,620
Mikef
78,788,751
10,452,700
What is the best practice to calculate global frequency of list of elements with exact orders in python within multiple pandas dataframe?
<p>Let's say I have the following datafarme <code>df1</code> corresponding to <code>user1</code>:</p> <pre class="lang-none prettyprint-override"><code>+-------------------+-------+--------+-------+-------+----------+----------------+ | Models | MAE | MSE | RMSE | MAPE | R² score | Runtime [ms] | +-...
<python><pandas><dataframe><frequency><tf-idf>
2024-07-24 13:47:36
2
2,056
Mario
78,788,714
21,540,734
selenium.webdriver.Firefox with FirefoxOptions().add_argument('--headless') doesn't return a valid hwnd
<p>I've noticed that the headless option in Firefox runs Firefox in the background without a window attached to it, and I haven't been able to find a way to run Firefox in the background and still have the hwnd of the Firefox window to be able to use.</p> <p>I started out using <code>pyvda</code> to get an <code>AppVie...
<python><selenium-webdriver><firefox><headless>
2024-07-24 13:40:05
0
425
phpjunkie
78,788,573
525,865
trying to apply a bs4-approach to wikipedia-page: results do not store in a df
<p>due to the fact that scraping on Wikipedia is a very very common technique - where we can use an appropiate approach to work with many many different jobs - i did have some issues with getting back the results - and store it into a df</p> <p>well - as a example for a very common Wikipedia-bs4 job - we can take this ...
<python><pandas><web-scraping><beautifulsoup>
2024-07-24 13:11:27
1
1,223
zero
78,788,533
13,491,504
Preventing the Gibbs phenomenon on a reverse FFT
<p>i am currently filtering some data and ran into trouble, when filtering smaller frequencies from a large trend.The Reverse FFTs seem to have large spikes at the beginning and the ending. Here is the Data before and after filtering smaller frequencies.<a href="https://i.sstatic.net/LjEbj4dr.png" rel="nofollow norefer...
<python><numpy><fft>
2024-07-24 13:03:58
1
637
Mo711
78,788,454
511,302
Can I get the related data directly when using a join query in django?
<p>Well considering two models:</p> <pre><code>class School(models.Model): name = TextField() class Student(models.Model): school = ForeignKey(School related_name=students ) firstname = TextField() </code></pre> <p>And the query:</p> <pre><code>School.objects.filter(Q(name=&quot;oldschool&quot;...
<python><django><orm>
2024-07-24 12:48:14
1
9,627
paul23
78,788,425
525,865
Python-Scraper with BS4 and Selenium : Session-Issues with chrome
<p>I am trying to grab the list of all the banks that are located here on this page <a href="http://www.banken.de/inhalt/banken/finanzdienstleister-banken-nach-laendern-deutschland/1" rel="nofollow noreferrer">http://www.banken.de/inhalt/banken/finanzdienstleister-banken-nach-laendern-deutschland/1</a> <strong>note</st...
<python><google-chrome><selenium-webdriver><beautifulsoup>
2024-07-24 12:44:01
2
1,223
zero
78,788,298
1,667,895
I can't get pip on my python3 venv on Ubuntu 24.04
<p>I have a fresh install of Ubuntu 24.04. I added pip with the usual <code>sudo apt install python3-pip</code>, and went to install some packages, but got the error: externally-managed-environment. This was all quite new to me, so I did some reading about <code>venv</code>. Using PyCharm, I attached a virtual environm...
<python><ubuntu><pip><python-venv>
2024-07-24 12:17:38
1
18,600
Colin T Bowers
78,788,192
4,505,998
Read CSV with epoch timestamp column as timestamp
<p>I'm using <code>pyarrow.csv</code> to read and convert a CSV file to parquet. This CSV file has a <code>timestamp</code> column with an int representing Unix time.</p> <p>Nevertheless, it reads it as an int64, and if I try to use <code>convertoptions</code>, it raises an error:</p> <pre class="lang-py prettyprint-ov...
<python><csv><pyarrow>
2024-07-24 11:57:31
1
813
David Davó
78,788,090
20,920,790
Why my API request with httpx not working?
<p>I tested my request to API with postman.co.</p> <p>But this request not working when I try run it with httpx library for Python. There's my request.</p> <p><a href="https://i.sstatic.net/f5Pe0is6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/f5Pe0is6.png" alt="enter image description here" /></a> Pa...
<python><httpx>
2024-07-24 11:36:20
1
402
John Doe
78,788,006
2,446,374
is there a better way to share common code across a set of python programs in a repository
<p>I pick python when I want to do a number of different things quickly and easily - ie I always end up with a number of python &quot;programs&quot; - eg a set of scripts - or if I'm playing with something, a bunch of test programs etc - ie always a loose collection of lots of different programs.</p> <p>however, there ...
<python><python-import>
2024-07-24 11:18:48
2
3,724
Darren Oakey
78,787,980
13,086,128
ValueError: Unable to determine which files to ship inside the wheel using the following heuristics:
<p><strong>MRE</strong></p> <p>Python 3.9</p> <p>Windows OS</p> <p>On running the below command:</p> <pre><code>pip install kaggle </code></pre> <p>Complete error message:</p> <pre><code>Defaulting to user installation because normal site-packages is not writeable Collecting kaggle Using cached kaggle-1.6.15.tar.gz (...
<python><python-3.x><pip><kaggle>
2024-07-24 11:11:29
2
30,560
Talha Tayyab
78,787,609
10,861,616
Getting response.status and response.url from the site visited
<p>I am trying to get the <code>page.url</code>, <code>response.url</code> and <code>response.status</code> from the websites. This is what I am trying:</p> <pre><code>from playwright.sync_api import sync_playwright def scrape_page(url): with sync_playwright() as p: browser = p.chromium.launch() page ...
<python><playwright><playwright-python>
2024-07-24 09:56:30
1
662
JontroPothon
78,787,534
1,417,053
Converting a PyTorch ONNX model to TensorRT engine - Jetson Orin Nano
<p>I'm trying to convert a <code>ViT-B/32</code> Vision Transformer model from the <a href="https://github.com/deepglint/unicom" rel="nofollow noreferrer">UNICOM</a> repository on a Jetson Orin Nano. The model's Vision Transformer class and source code is <a href="https://github.com/deepglint/unicom/blob/main/unicom/vi...
<python><pytorch><onnx><tensorrt>
2024-07-24 09:39:22
1
2,620
Cypher
78,787,519
17,721,722
How to Version Control a PostgreSQL Table?
<p>Backend: Python 3.11 and Django 5.0.6<br /> Database: PostgreSQL 15</p> <p>Our app deals with reporting from the database. We don't store report SQL queries in the codebase; instead, we store them in DB tables. However, developers change SQL queries from time to time. How can we track such changes made in the databa...
<python><django><postgresql><git><version-control>
2024-07-24 09:36:37
0
501
Purushottam Nawale
78,787,373
7,932,327
What explains these surprising timings in numpy?
<p>I recently timed several different array allocation and initialization procedures in numpy. I however fail to interpret these timings. Here is a plot of my measurements (size of array in number of elements &quot;n&quot; for a given data type vs time of execution).</p> <p><img src="https://gabrielfougeron.github.io/p...
<python><numpy><numpy-ndarray>
2024-07-24 09:08:46
0
501
G. Fougeron
78,787,332
11,021,175
Selecting default search engine is needed for Chrome version 127
<p>All of my Selenium scripts are raising errors after Chrome updated to version 127 because I always have to select a default search engine when the browser is being launched.</p> <p>I use ChromeDriver 127.0.6533.72.</p> <p>How to fix it?</p>
<python><selenium-webdriver>
2024-07-24 09:00:03
3
407
Ben
78,787,162
9,608,759
How to ignore a certain argument in a `Field` while serializing in pydantic?
<h3>What I am trying to achieve?</h3> <p>I want to filter books based on some criteria. Since the filtering logic is roughly equal to &quot;<em>compare</em> <strong>value</strong> <em>with</em> <strong>column_in_db</strong>&quot;, I decided to create different types of filters for filtering values. I am then using thes...
<python><fastapi><pydantic><pydantic-v2>
2024-07-24 08:25:32
2
6,065
sahinakkaya
78,787,152
6,703,592
dataframe plot histogram boundary bins
<pre><code>bins = [x for x in range(-10, 11)] df['val'].plot(kind='hist', bins=bins) </code></pre> <p>I want to put all the out-range values &gt;10 or &lt;-10 into the boundary right/left bin but not change their widths. btw suppose the max/min value of <code>df</code> is dynamic.</p> <p>I can build two boundary bins ...
<python><pandas><plot>
2024-07-24 08:24:47
1
1,136
user6703592
78,786,982
5,704,198
Comparing string uniforming special characters in python
<p>Probabily I can use a better english but what I want is ignoring accent (and like) in words so:</p> <p><code>renè</code>, <code>rené</code>, <code>rene'</code> and <code>rene</code> should be the same so should</p> <p><code>mañana</code> and <code>manana</code> or</p> <p><code>even-distribuited</code> and <code>even...
<python><string><compare>
2024-07-24 07:46:48
1
1,385
fabio
78,786,800
4,897,017
metadata-generation-failed when installing tf-models-official
<p>I'm trying to install tf-models-official with <code>!pip install tf-models-official</code> and when it started to collecting kaggle&gt;=1.3.9, it returned error below :</p> <pre><code>Collecting kaggle&gt;=1.3.9 (from tf-models-official) Using cached kaggle-1.6.15.tar.gz (9.1 kB) Installing build dependencies .....
<python><tensorflow><machine-learning><pip>
2024-07-24 07:02:59
1
503
Larry Mckuydee
78,786,496
898,042
counting calls decorator - why do I reset function attribute back to 0?
<p>the code below counts the num times the decorated function func was called:</p> <pre><code>from functools import wraps def counting_calls(func): @wraps(func) def inner(*args, **kwargs): inner.call_count += 1 return func(*args, **kwargs) inner.call_count = 0 return inner </code></pre>...
<python><python-decorators>
2024-07-24 05:29:28
1
24,573
ERJAN
78,786,311
10,410,934
How to elegantly combine complex Python object and SQLAlchemy object model classes?
<p>I have a rather complex class with complex properties computed from a provided df to <strong>init</strong> and these properties may be other class types that can be eventually serialized into a string. In Python I want to deal with objects rather than primitive types but also want to use SQLAlchemy for interacting w...
<python><sqlalchemy><flask-sqlalchemy>
2024-07-24 03:49:15
1
396
Stevie
78,786,254
1,510,739
Can you pattern match on Python type annotations?
<p>Can you pattern match on Python types?</p> <p>I've seen simple examples:</p> <pre class="lang-py prettyprint-override"><code>import builtins match x: case builtins.str: print(&quot;matched str&quot;) case buildins.int: print(&quot;matched int&quot;) </code></pre> <p>But I'd like to pattern m...
<python><python-typing><structural-pattern-matching>
2024-07-24 03:15:33
1
487
Torkoal
78,786,208
9,509,245
Polars: Replace elements in list of List column
<p>Consider the following example series.</p> <pre class="lang-py prettyprint-override"><code>s = pl.Series('s', [[1, 2, 3], [3, 4, 5]]) </code></pre> <p>I'd like to replace all 3s with 10s to obtain the following.</p> <pre class="lang-py prettyprint-override"><code>res = pl.Series('s', [[1, 2, 10], [10, 4, 5]]) </code...
<python><python-polars>
2024-07-24 02:43:07
2
508
PydPiper
78,786,150
299,282
Share code across sagemaker pipeline steps without
<p>I am trying to create Sagemaker pipeline with multiple steps. I have some code which I would like to share across different steps. Next example is not exact but simplified version for illustration.</p> <p>I have folder structure which looks next:</p> <pre><code>source_scripts/ ├── utils │ ├── logger.py ├── models/...
<python><amazon-web-services><amazon-sagemaker><mlops>
2024-07-24 02:08:44
1
936
Max Markov
78,786,069
6,005,206
pd.Timestamp() behavior in Pandas
<p>Trying to understand why <code>t1</code> takes current date whereas <code>t2</code> takes the epoch date in Pandas in Python. Any thoughts would help.</p> <pre><code>import pandas as pd t1 = pd.Timestamp(&quot;23:12:05&quot;) print(&quot;t1:&quot;,t1) t2 = pd.Timestamp(1) print(&quot;t2:&quot;t2) </code></pre> <p>...
<python><pandas><datetime><time><timestamp>
2024-07-24 01:05:22
1
1,893
Nilesh Ingle
78,785,682
12,728,698
Distributing pythonnet dll type information in pip package
<p>I've been able to load a <code>C#</code> dll using <code>pythonnet</code> by using the following:</p> <pre class="lang-py prettyprint-override"><code>from importlib.resources import path import sys # Assuming 'my_package.lib' is the sub-package containing the DLLs with path('pyrp.lib', '') as lib_path: sys.path...
<python><pip><python-typing>
2024-07-23 21:46:25
0
856
joshp
78,785,661
11,062,613
Parsing formulas efficiently using regex and Polars
<p>I am trying to parse a series of mathematical formulas and need to extract variable names efficiently using Polars in Python. Regex support in Polars seems to be limited, particularly with look-around assertions. Is there a simple, efficient way to parse symbols from formulas?</p> <p>Here's the snippet of my code:</...
<python><regex><dataframe><python-polars><text-extraction>
2024-07-23 21:34:43
1
423
Olibarer
78,785,646
4,208,228
How can I view all the uploaded files associated with an Azure OpenAI assistant in Python?
<p>I’m using Python to benchmark questions from documents and have instantiated my assistant in a jupyter notebook. I’d like to confirm the assistant has the files I uploaded to it but can’t seem to find documentation on what function would be used for this. Using latest version of Python API for Azure OpenAI.</p>
<python><azure><file><openai-api><assistant>
2024-07-23 21:29:56
1
471
Celi Manu
78,785,590
10,492,911
Numpy: apply mask to values, then take mean, but in parallel
<p>I have an 1d numpy array of values:</p> <pre><code>v = np.array([0, 1, 4, 0, 5]) </code></pre> <p>Furthermore, I have a 2d numpy array of boolean masks (in production, there are millions of masks):</p> <pre><code>m = np.array([ [True, True, False, False, False], [True, False, True, False, True], [True, T...
<python><arrays><numpy><mask>
2024-07-23 21:13:33
2
879
Franc Weser
78,785,221
3,369,545
ValueError when loading sklearn DecisionTreeClassifier pickle in Python 3.10
<p>I'm encountering an issue while transitioning from Python 3.7.3 to Python 3.10 due to the deprecation of the older version. The problem arises when attempting to load a pickled sklearn DecisionTreeClassifier model. Environment:</p> <p>Original: Python 3.7.3, scikit-learn 0.23.1 Current: Python 3.10, scikit-learn 1.3...
<python><scikit-learn><pickle><version-compatibility>
2024-07-23 19:21:12
1
421
user3369545
78,785,166
2,893,712
Pandas Flatten Row When Doing Groupby
<p>I have a Pandas dataframe that has address and contact information. The rows are on occasion duplicated because there are different values in the respective contact information (the address information remains the same for each vendor ID)</p> <pre><code>ID Vendor Name Vendor Address City State Zi...
<python><pandas><flatten>
2024-07-23 19:05:09
1
8,806
Bijan
78,785,096
3,623,537
Why undeclared variables are present in `globals()` after a reload and is it safe to use them to identify a reload?
<p>I've found that the snippet below when reloading a module <code>test</code> unexpectedly has all variables already defined in <code>globals()</code>/<code>locals()</code>.</p> <p>Why this happens?</p> <p>I've noticed this <code>&quot;xxx&quot; in locals()</code> pattern <a href="https://github.com/search?q=%22%5C%22...
<python><python-importlib>
2024-07-23 18:43:34
2
469
FamousSnake
78,785,051
5,522,938
Python import path when executed through symlink
<p>I have a project directory that looks like this:</p> <pre><code>project/ ├── my_input.py ├── run_me.py └── test ├── my_input.py └── run_me.py -&gt; ../run_me.py </code></pre> <p>The <code>run_me.py</code> script imports from input.py. My expectation is that the symlinked <code>test/run_me.py</code> would imp...
<python>
2024-07-23 18:34:16
1
952
roro
78,785,004
511,302
test if any object refer to by a base model has a value specified in django orm
<p>Well consider two models:</p> <pre><code>class School(models.Model): name = models.TextField(default=&quot;hello world&quot;) class Student(models.Model): key = models.TextField(default=&quot;somedata&quot;) a = models.ForeignKey(Vendor) </code></pre> <p>So a many to one relationship from School to Stud...
<python><django><orm><foreign-keys>
2024-07-23 18:17:51
1
9,627
paul23
78,784,850
1,471,980
How do you create a pivot table group by Date and perfom calculation on 2 values in pandas
<p>I have this data frame:</p> <p>df</p> <pre><code>Node Interface Speed Band_In carrier Date Server1 wan1 100 80 ATT 2024-06-01 Server1 wan2 100 60 Sprint 2024-06-01 Server1 wan3 100 96 Verizon 2024-06-01 Server2 wan1 ...
<python><pandas><pivot>
2024-07-23 17:35:58
1
10,714
user1471980
78,784,723
7,339,624
Why my RNN does not converge to a simple task?
<p>I want to create a recursice model to solve the most simple sequence that I know, Arithmetic progression. With having <code>a</code> as the base and <code>d</code> as the step size, the sequence would be as follows:</p> <p><code>a, a+d, a+2d, a+3d, a+4d, ...</code></p> <p>To solve this, denoting hidden state as <cod...
<python><machine-learning><deep-learning><pytorch><recurrent-neural-network>
2024-07-23 16:59:29
1
4,337
Peyman
78,784,712
249,696
How can I write the type of a function that returns a dynamically imported class?
<p>I have a Python function that looks like this</p> <pre class="lang-py prettyprint-override"><code>def my_function() -&gt; Any: from optional_dependency import SomeClass # This will fail if `optional_dependency` is not installed, I'm good with that. return SomeClass() </code></pre> <p>I'm not a huge fan of this...
<python><python-typing><mypy><pyright><ruff>
2024-07-23 16:57:24
1
4,139
Yoric
78,784,687
2,328,154
Setting UserPool Client Attributes to have read/write access with aws cdk - Python
<p>I am trying to give some custom attributes specific read/write access depending on the attribute. I am getting this error.</p> <p>Resource handler returned message: &quot;Invalid write attributes specified while creating a client (Service: CognitoIdentityProvider, Status Code: 400, Request ID: &lt;request_id&gt;)&qu...
<python><amazon-cognito><aws-cdk>
2024-07-23 16:50:55
1
421
MountainBiker
78,784,668
7,106,343
Query a SQLModel class with abstract definition
<p>In this project, we have restricted imports between packages as follows:</p> <ul> <li>We have a shared package.</li> <li>We have a backend package.</li> <li>Imports from the backend package to the shared package are not allowed, but imports from the shared package to the backend package are permitted. I cannot chang...
<python><sqlalchemy><fastapi>
2024-07-23 16:44:59
1
652
Arash
78,784,664
11,748,418
Python imports & interactive window
<p>I am struggling with imports in Python. Currently, this is my file structure:</p> <pre><code>. ├── my_project │   ├── helpers │   │   ├── SomeHelper.py │   │   └── __init__.py │   ├── CalculateStuff │   │   ├── __init__.py │   │   └── CalculateX.py │   ├── __init__.py │   └── main.py ├── poetry.lock ├── pyproject.to...
<python><import><python-interactive>
2024-07-23 16:42:49
1
340
Dennis
78,784,626
11,357,695
Twine/PyPI - Invalid distribution file
<p>I am trying to upload my package (<code>SyntenyQC</code>) to test pypi as described <a href="https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives" rel="nofollow noreferrer">here</a> via Anaconda prompt.</p> <p>I have installed <code>twine</code> and <code>build</co...
<python><build><package><pypi><twine>
2024-07-23 16:33:26
1
756
Tim Kirkwood
78,784,539
2,153,235
Module imported into different scopes, do they both refer to the same object?
<p>At the Spyder console (the REPL), I issue <code>import matplotlib.pyplot as plt</code>. It is the topmost namespace, i.e., corresponding to <code>globals()</code>.</p> <p>In a Spyder startup file, I define a function to raise figure windows to the top.</p> <pre><code>def TKraiseCFG( FigID = None ): import matp...
<python><matplotlib><python-import>
2024-07-23 16:10:19
1
1,265
user2153235
78,784,486
3,120,501
Execution of conditional branches causing errors in Jax (kd-tree implementation)
<p>I'm writing a kd-tree in Jax, and using custom written Node objects for the tree elements. Each Node is very simple, with a single <code>data</code> field (for holding numeric values) and <code>left</code> and <code>right</code> fields which are references to other Nodes. A leaf Node is identified as one for which t...
<python><jax><kdtree>
2024-07-23 15:56:18
1
528
LordCat
78,784,232
5,355,024
AWS Route Calculator API/ Here Maps
<p>I am using AWS Location Services Route Calculator to determine travel time and travel distance of several origin destination pairs. The code is working but it is not reflecting travel delay due to traffic. It calculates the difference between two cities with departure time at 2 AM and 11 AM are only a couple minutes...
<python><amazon-web-services><routes><boto3><calculator>
2024-07-23 15:03:34
1
368
Jorge
78,784,224
3,048,716
Cannot deploy vertex AI model locally using custom predictor
<p>Following the <a href="https://cloud.google.com/vertex-ai/docs/predictions/custom-prediction-routines" rel="nofollow noreferrer">documentation</a> I have what I believe to be a minimal form of a custom predictor which I am trying to deploy locally.</p> <p>I have a model dir which contains an empty requirements.txt a...
<python><google-cloud-vertex-ai><google-cloud-aiplatform>
2024-07-23 15:01:40
0
357
Andy T
78,784,043
15,209,268
How to Stream RTSP Video from IP Camera to HTML Video Element?
<p>I have an IP camera that streams video using the RTSP protocol. My system needs to connect to this IP camera and stream the video to a web browser. Since most browsers don't natively support RTSP, I need an intermediary server to handle the RTSP stream. I implemented a FastAPI web server that uses OpenCV to connect ...
<python><opencv><video-streaming><fastapi><http-live-streaming>
2024-07-23 14:29:16
1
444
Oded
78,783,974
11,117,255
How do I convert a 300-degree equirectangular panoramic image to cube faces?
<p>A 300-degree equirectangular panoramic image I want to convert into cube faces using OpenCV in Python. I found code for 360-degree images. How do I modify it to handle a 300-degree image?</p> <pre><code>import cv2 import numpy as np def equirectangular_to_cube(img, cube_size): h, w = img.shape[:2] # # ...
<python><numpy><opencv><panoramas>
2024-07-23 14:16:11
1
2,759
Cauder
78,783,860
9,315,690
EOFError when trying to call Inhibit method on org.freedesktop.login1.Manager via dbus-fast
<p>I'm developing a Python application which will be distributed to users on Linux in various forms (Flatpak, PyInstaller executable, maybe others). In this application, I want to call the <code>Inhibit</code> method on the <code>org.freedesktop.login1.Manager</code> dbus interface. Due to the relatively complex/divers...
<python><systemd><dbus>
2024-07-23 13:55:44
1
3,887
Newbyte
78,783,835
1,621,041
Find the largest rectangular bounding box containing only ones in a 2d mask NumPy array
<p>I have a 2d mask where I'd like to find the largest rectangular bounding box containing only ones.</p> <p>Is there a more efficient way than determining all possibilities for bounding boxes and then comparing their size?</p> <p>Example code:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.patch...
<python><numpy><mask><bounding-box>
2024-07-23 13:51:13
4
11,522
finefoot
78,783,365
13,757,692
Expand numpy array to be able to broadcast with second array of variable depth
<p>I have a function which can take an <code>np.ndarray</code> of shape <code>(3,)</code> or <code>(3, N)</code>, or <code>(3, N, M)</code>, etc.. I want to add to the input array an array of shape <code>(3,)</code>. At the moment, I have to manually check the shape of the incoming array and if neccessary, expand the a...
<python><numpy><array-broadcasting>
2024-07-23 12:13:02
2
466
Alex V.
78,783,310
3,110,970
Apache Flink Python Datastream API sink to Parquet
<p>I have a Kafka topic that contains json messages. Using Flink Python API I try to process this messages and store in parquet files in GCS.</p> <p>Here is cleaned code snippet:</p> <pre><code>class Extract(MapFunction): def map(self, value): record = json.loads(value) dt_object = datetime.strptime...
<python><apache-flink><parquet>
2024-07-23 12:00:59
1
1,390
xneg
78,783,283
3,768,871
How to run jupyterlab when asdf is installed?
<p>Suppose that asdf is installed and we are using python 3.8.19. How to run &quot;jupyter lab&quot; as the regular command <code>jupyter-lab notebook</code> should be referenced in PATH and not working. On the other hand, it seems that adding specific path from asdf to PATH is not reasonable as we may have different p...
<python><jupyter><shim><asdf>
2024-07-23 11:54:14
1
19,015
OmG
78,783,240
5,893,454
Managing wrong order of strings in R and ggplot. X1, X10, X12: How can I ensure a string with number will be preented in the right numberical order?
<p>Every time that I want to plot or list a string that contains numbers, R (and python) list the values such as &quot;x1, x10, x11, x13, (etc) x2, x3, x4&quot;</p> <p><a href="https://i.sstatic.net/8d7AO4TK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8d7AO4TK.png" alt="image" /></a></p> <p>I tried t...
<python><r><string><ggplot2>
2024-07-23 11:43:44
1
1,574
Luis
78,783,219
20,895,654
discord.py app command error handling won't work because responses take >5 seconds
<p>I'm having this issue where before a few days ago, everything worked fine, but suddenly any error handling will take too long to be in the 3 second time frame for the response to be handled. Nothing will happen for about 5 seconds after the error occurs and then an error happens because the interaction timed out whi...
<python><error-handling><discord><discord.py><python-asyncio>
2024-07-23 11:39:39
2
346
JoniKauf
78,783,045
4,064,958
Python subprocess FILE NOT FOUND error when executing a PyInstaller generated file in Linux from a shared VOLUME under DOCKER
<p>I have generated an executable, say,<code>test</code> (no extension since it's Linux) using PyInstaller and stored it in a directory, say <code>data</code>.</p> <p>I have a Python program that is as below:</p> <pre><code>import subprocess from pathlib import Path ... def run_exe(): try: # get current dir...
<python><subprocess><pyinstaller>
2024-07-23 10:57:38
1
2,345
RmR
78,782,881
22,221,987
Celery returns wrong info about current tasks in one worker
<p>I have a bundle which contains Celery and RabbitMQ for tasks and FastApi app for web requests.<br /> The celery app starts from command prompt with <code>celery -A celery_app worker -l info -P gevent</code>.<br /> Rabbit is deployed in Docker Container.<br /> FastApi starts from python script.</p> <p>Here is the cod...
<python><python-3.x><rabbitmq><celery><fastapi>
2024-07-23 10:17:22
1
309
Mika
78,782,871
8,047,378
About the efficiency of pytorch in Reranker model
<p>I get an efficiency problem in Reranker model.**</p> <p>Here is detail:</p> <p>In inference of PyTorch model, I add <code>time()</code> to collect the time in <code>self.tokenizer</code> and <code>self.model</code>. The inference info like this:</p> <p><strong>token_len</strong>: 2048 ; <strong>all data num</strong>...
<python><pytorch>
2024-07-23 10:14:49
0
939
Frank.Fan
78,782,754
4,306,274
How to remove the large top and bottom paddings due to top-to-bottom lines?
<p>How to remove the large top and bottom paddings due to top-to-bottom lines?</p> <pre><code>import numpy as np import pandas as pd import plotly.graph_objects as go count = 100 df = pd.DataFrame( { &quot;A&quot;: np.random.randint(10, 20, size=(count)), &quot;B&quot;: np.random.randint(10, 20, s...
<python><plotly>
2024-07-23 09:47:50
1
1,503
chaosink
78,782,708
16,389,095
How to automatically resize and reposition controls when the window is resized?
<p>I'm trying to develop a scratch app with Python Flet. My goal is to find a way to position, or alternatively, to specify controls dimensions relatively to their parent control dimensions. For example, a button width of 70% the container width which is, in turn, the 30% of the page width. In this way, every control d...
<python><flutter><flet>
2024-07-23 09:37:18
1
421
eljamba
78,782,629
7,941,944
Understanding Time complexity of nested sorting
<p>I am solving this LeetCode problem <a href="https://leetcode.com/problems/sort-array-by-increasing-frequency/description/" rel="nofollow noreferrer">1636. Sort Array by Increasing Frequency</a>:</p> <blockquote> <p>Given an array of integers <code>nums</code>, sort the array in <strong>increasing</strong> order base...
<python><algorithm><sorting><data-structures><defaultdict>
2024-07-23 09:22:28
1
333
Vijeth Kashyap
78,782,576
7,498,328
How to save the output from using Jupyter Notebook's Python packages tabulate and IPython.display packages
<p>I have the following code that prints some nice tables in a cell of Jupyter Notebook. However, I also want to also export it to a png or pdf file. How am I going to accomplish this?</p> <pre><code>from tabulate import tabulate from IPython.display import Latex, display def display_table(summary, data, best_formula,...
<python><jupyter-notebook>
2024-07-23 09:12:13
1
2,618
user321627
78,782,122
273,593
automatic cleanup of postgres db after each test
<p>I have sqlalchemy application that talks with a postgres db. I want to do some &quot;integration tests&quot; using testcontainers and trying the various scenarios.</p> <p>just to make things simple, let's say that in my application I just expect a single table <code>users</code> with at least the <code>admin</code> ...
<python><postgresql><sqlalchemy><pytest>
2024-07-23 07:27:48
1
1,703
Vito De Tullio
78,782,108
8,055,073
import from & from on python with different levels of modules
<p>I see a code like this:</p> <pre><code>import torch from torch import nn from sklearn.metrics import r2_score </code></pre> <p>i'm learning python but i dont see really a doc where can explain the first import, i think two first lines it's equivalent to this in another languages:</p> <pre><code>from torch import tor...
<python>
2024-07-23 07:24:44
1
1,579
DDave
78,781,475
3,486,684
Python + Polars: a DataFrame which keeps track of the history of operations it was derived from?
<p>I found myself making a variant of <code>pl.DataFrame</code> which keeps track of the operations performed on it. For example:</p> <pre class="lang-py prettyprint-override"><code>from pprint import pformat, pprint import polars as pl import polars._typing as plt from collections import UserList from dataclasses impo...
<python><python-polars>
2024-07-23 03:35:54
0
4,654
bzm3r
78,781,464
4,306,274
Cannot add a vertical line to the second X axis
<p>I can add a horizontal line to the second Y axis, like this:</p> <pre><code>import pandas as pd import plotly.express as px import plotly.graph_objects as go df = pd.DataFrame( { &quot;A&quot;: [5, 4, 7], &quot;B&quot;: [200, 300, 100], }, index=[1, 2, 3], ) fig = px.bar( df[&quot;A...
<python><pandas><plotly>
2024-07-23 03:32:16
1
1,503
chaosink
78,781,452
2,119,941
AWS Lambda OpenSearch Serverless Connection Issues
<p>I am working on an AWS Lambda function written in Python to interact with an OpenSearch Serverless collection. The Lambda function is deployed in a VPC, and the OpenSearch Serverless endpoint is also within the same VPC. Despite ensuring that all permissions and VPC configurations are correct, I keep encountering a ...
<python><amazon-web-services><aws-lambda><aws-sam><amazon-opensearch>
2024-07-23 03:27:23
0
15,380
Hrvoje
78,781,390
16,312,980
HF transformers: ValueError: Unable to create tensor
<p>I was following <a href="https://huggingface.co/docs/transformers/tasks/sequence_classification" rel="nofollow noreferrer">this guide for text classification</a> and i gotten and error:</p> <pre><code>ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'tru...
<python><pytorch><huggingface-transformers>
2024-07-23 02:57:48
1
426
Ryan
78,781,354
15,587,184
Azure AI Search Scoring Profiles are not modifying the score retrival
<p>I have been using Azure Ai search and scoring profiles to boost the documents of my index that come form the 'reviewed' source that means I want to send to the very TOP documents that have the string 'reviewed' on the field source, so I configured this scoring profile:</p> <pre><code> &quot;scoringProfiles&quot;: [...
<python><azure><nlp><azure-ai-search>
2024-07-23 02:37:14
1
809
R_Student
78,780,948
16,852,890
PySpark unpivot or reduce
<p>I have the following dataframe:</p> <pre><code>df = spark.createDataFrame( [ (&quot;D1&quot;, &quot;D2&quot;, &quot;H1&quot;, None, None), (&quot;D1&quot;, &quot;D2&quot;, &quot;H1&quot;, &quot;H2&quot;, None), (&quot;D1&quot;, &quot;D2&quot;, &quot;H1&quot;, &quot;H2&quot;, &quot;H3&quot...
<python><pyspark>
2024-07-22 22:21:34
2
316
tommyhmt
78,780,932
1,116,138
How to tell if a function is wrapped by another specific function
<p>Using the following code:</p> <pre><code>def wrap( x ): def wrapped( y ): return x + y return wrapped f = wrap( 1 ) </code></pre> <p>Is it possible to tell that f is a function wrapped by function <code>wrap</code>?</p> <p>Displaying variable f, it is visible:</p> <pre><code>&gt;&gt;&gt; f &lt;function wrap...
<python>
2024-07-22 22:16:21
2
562
greg
78,780,790
8,887,483
Popening a gnome-terminal in python immediately appears as a zombie
<p>For background I am working on a script to train multiple pytorch models. I have a training script that I want to be able to run as a sub process in a gnome terminal. The main reason for this is so I can keep an eye on the training progress. In cases where I might have multiple GPUs I would like to run my training s...
<python><python-3.x><multiprocessing><popen><psutil>
2024-07-22 21:13:50
1
605
Sami Wood
78,780,728
9,538,252
Difference of top 2 timestamps by group in Pandas
<p>I have a table of users with login date and time stamps.</p> <p>I am attempting to calculate the difference between each user's two most recent logins.</p> <p>For example (df):</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>User</th> <th>logints</th> </tr> </thead> <tbody> <tr> <td>34</t...
<python><pandas>
2024-07-22 20:50:44
2
311
ByRequest
78,780,630
1,431,728
How to replace double slash in URL string with single slash in Python
<p>I've got a URL that contains erroneous double slash(es) (&quot;//&quot;) that I need to turn into single slash. Needless to say, I want to leave the double slash after &quot;https:&quot; untouched.</p> <p>What's the shortest Python code that can make this change in a string?</p> <hr /> <p>I've been trying to use <co...
<python><replace>
2024-07-22 20:16:21
2
7,417
JohnK
78,780,563
1,922,559
Correct pyasn1 data structure for IEC 61850 sample values SavPDU type?
<p>I'm trying to convert a SEQUENCE type to a Python class model following the Berkeley published <a href="http://wla.berkeley.edu/%7Ecs61a/fa07/library/python_modules/gsutil/third_party/pyasn1/doc/pyasn1-tutorial.html#1.4" rel="nofollow noreferrer">PyASN1 programmer's manual</a> documentation.</p> <p>The IEC 61850-9-2...
<python><pyasn1>
2024-07-22 19:55:38
0
737
TWhite
78,780,311
2,409,868
SQLAlchemy scalars and intersect anomaly
<p>The SQLAlchemy manual says* that the <code>Session.scalars()</code> method returns ORM objects.</p> <p>*[Selecting ORM Entries][1]</p> <p>The following code shows two examples one of which returns an ORM object but the other does not. The first uses a select statement which selects a single ORM object. The second ex...
<python><sqlalchemy>
2024-07-22 18:37:50
1
1,380
lemi57ssss
78,780,255
9,097,114
add multiple recipients to sendgrid
<p>i am unable to send mail to multiple receipents with code as below.<br /> adding 3 or more mail ids to 'to_emails'</p> <pre><code>to = 'aaa@mail.com,bbb@mail.com,ccc@mail.com' html_content1 = ''' Sample''' message = Mail( from_email='from@mail.com', to_emails=to, subject=fl, html_content=html_c...
<python><sendgrid>
2024-07-22 18:22:48
1
523
san1
78,780,231
11,748,924
Matplotlib antialiasing of axvline when plotting from label encoded classes when it's zoomed in
<p>I have this code:</p> <pre><code># Display parameter Xt = X_test[0, 0:1024] a = 1 lw = 1 # Get mask of every classes bl_pred = yp == 0 p_pred = yp == 1 qrs_pred = yp == 2 t_pred = yp == 3 # Plotting for i in range(len(Xt)): if bl_pred[i]: plt.axvline(x=i, color='grey', linestyle='-', alpha=a, linewidth=lw) ...
<python><matplotlib><visualization>
2024-07-22 18:16:20
1
1,252
Muhammad Ikhwan Perwira
78,780,083
304,870
Module "twine" not found when using Azure DevOps pipeline
<p>I'm running a pipeline in Azure Devops which is supposed to publish a wheel using &quot;twine&quot;. The pipeline uses a Windows based image.</p> <p>The pipeline is based on the docs from <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/artifacts/pypi?view=azure-devops&amp;tabs=yaml#publish-python-p...
<python><windows><azure-devops><pip><azure-pipelines>
2024-07-22 17:39:56
1
33,166
Krumelur
78,779,795
3,569,246
Force Python auto-imports from current package to be prefixed with this package's name
<p>I use Python and Pylance extensions in VSCode.</p> <p>In my own package that I'm editing, the automatically added imports (with setting &quot;Import Format: absolute&quot;) look like this:</p> <pre><code>from mydirectory.myfile import myclass </code></pre> <p>However, my Python package is being consumed by a (very d...
<python><visual-studio-code><import><autocomplete>
2024-07-22 16:19:38
1
3,756
JoannaFalkowska