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
βŒ€
75,816,573
2,406,499
Finding Values in a Panda Series that can't be Converted to a Particular Datatype
<p>I have a dataframe called df which has a series, let's called it 'date', that have strings that refer to dates of the format 'YYYY-mm-dd' and hence every single value on the series should only have strings that can be converted to datetime objects.</p> <p>I need to be able to show/filter only the rows which values o...
<python><pandas><dataframe>
2023-03-22 19:33:13
2
1,268
Francisco Cortes
75,816,464
1,988,046
Strange increase in latency of ZeroMQ between c# and python
<p>I'm trying to send images from C# running on win 11 to a python server running on WSL2.</p> <p>I'm using ZeroMQ to send byte arrays, but as soon as the byte arrays cross a threshold (~8kb) the latency spikes from 0.3ms to 50ms. This 50ms latency remains until I get to ~74KB. Then it reduces back to about 0.3ms.</p> ...
<python><c#><tcp><zeromq><low-latency>
2023-03-22 19:19:43
0
513
mike1952
75,816,380
2,591,343
How to login on Pixelfed instances with Mastodon.py
<p>I used Mastodon.py and successfully had connected to a Mastodon instance using user/password.</p> <p>But what I really need is to connect to a Pixelfed instance. Reading documentation from Pixelfed it's said you can connect to it like you do with Mastodon, just with some caveats, like (if I understood alright) you c...
<python><mastodon><mastodon-py>
2023-03-22 19:10:16
0
463
HufflepuffBR
75,816,237
6,552,666
Why is this JOIN+AND query identical to this JOIN query?
<p>I have an SQLite database with an events, a participants tables, and a third table linking each participant to each event they attended. I wanted a list of the events that a given participant attended.</p> <pre><code>only_joined_table = mydb.execute('SELECT * FROM event_participant_link LEFT JOIN event ' ...
<python><sqlite>
2023-03-22 18:53:30
2
673
Frank Harris
75,816,024
1,319,406
List comprehension vs. for loop performance testing
<p>In an effort to avoid Django ModelSerialization performance hits, I am looking at &quot;serializing&quot; a result set on my own. Many related Stackoverflow questions say that list comprehension should be the fastest, but my own tests are showing nested for loops being consistently faster.</p> <p>I have raw DB resul...
<python><list><performance>
2023-03-22 18:29:34
1
490
Danielle
75,815,967
4,042,278
How to run anaconda python with "execute a process" in Pentaho(PDI) in windows?
<p>I'm going to run a python program by &quot;execute a process&quot; in pdi and on a specific anaconda environment.</p> <p>This is my solution which didn't work:</p> <p><a href="https://i.sstatic.net/L0ELa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L0ELa.png" alt="enter image description here" /></...
<python><pentaho><pentaho-spoon><pentaho-data-integration>
2023-03-22 18:20:57
2
1,390
parvij
75,815,959
10,428,677
Check if columns exist and if not, create and fill with NaN using PySpark
<p>I have a pyspark dataframe and a separate list of column names. I want to check and see if any of the list column names are missing, and if they are, I want to create them and fill with null values.</p> <p>Is there a straightforward way to do this in pyspark? I can do it in Pandas, but it's not what I need.</p>
<python><apache-spark><pyspark>
2023-03-22 18:20:27
1
590
A.N.
75,815,913
1,056,563
ModuleNotFoundError on pytz,yaml, delta even though installed in same python instance
<p>Let's consider carefully the <em><code>pytz</code></em> library (<code>yaml</code> and <code>delta[-spark]</code> have an identical pattern.).</p> <p>'<code>pytz</code> has been installed via <code>pip</code> and then re-confirmed in a couple of different ways:</p> <ul> <li>Initial installation</li> </ul> <pre><code...
<python><pip>
2023-03-22 18:14:50
0
63,891
WestCoastProjects
75,815,782
8,981,425
Using all the div width when using imshow with dash
<p>I am working on an application with Dash. It has a really simple layout: a main area with a viewer and a left column with the controls. I am using Plotly express imshow in order to display the image. The figure is occupying all the width of the main area, but the 'canvas' is centered and keeps the image's original a...
<python><plotly><plotly-dash>
2023-03-22 18:02:15
0
367
edoelas
75,815,764
4,167,457
How can I clear the input in a gradio app automatically?
<p>I want to be able to clear the input with gradio at the end of completing the inference without any additional click from the user. Currently with live=True, the inference function is triggered when the recording is stopped.</p> <p>Here is the relevant part of my code:</p> <pre><code>audio_input = gr.Audio(source=&...
<python><gradio>
2023-03-22 18:00:26
3
310
Corey
75,815,741
5,056
What is the scope inside a comprehension directly in a class?
<p>Note that what I'm after here is deeper understanding of how python works. I am aware that I can use methods or <code>@property</code> and that any practical needs here would be esoteric and odd.</p> <p>It is my understanding that when a class is initialized in python, its body is executed within a new namespace, th...
<python><class><list-comprehension>
2023-03-22 17:57:44
0
122,870
George Mauer
75,815,628
7,059,087
How to trace DNS for intermittent python `socket.gaierror: [Errno -3] Temporary failure in name resolution`
<p>I have an API that calls another API endpoint. An <em>extremely</em> simplified version of the Flask code can be considered</p> <pre><code>@app.route(route, methods=['POST']) async def index(): json = await request.get_json() headers = request.headers endpoint = &quot;some endpoint that comes from other ...
<python><python-3.x><flask><dns>
2023-03-22 17:43:45
0
532
wjmccann
75,815,523
6,849,363
Python sqlite3 .fetchmany(batch_size) while loop exiting after one loop
<p>I have the following code:</p> <pre><code>import openai import sqlite3 import os from dotenv import load_dotenv load_dotenv() def clean_and_save_descriptions_subset(days_old = 7, num_reivew = 1000, batch_size = 50): api_key = os.getenv(&quot;OPEN_AI_API_KEY&quot;) sql = f&quot;&quot;&quot; SELECT e.mp3_...
<python><sqlite><while-loop>
2023-03-22 17:33:28
0
470
Tanner Phillips
75,815,522
6,543,183
Get the name of columns from rows distinct from zero python
<p>I have this dataframe:</p> <pre><code>df0 = pd.DataFrame({'points': [0, 0, -3, 16, 0, 5, -3, 14], 'assists': [0, 0, 2, 0, 1, -7, 0, 6], 'numbers': [0, 0, 1, 6, 10, 5, 8, 7]}) </code></pre> <p>and my desired dataset looks like this:</p> <pre><code>points assists numbers colX 0 ...
<python><pandas><dataframe>
2023-03-22 17:33:12
3
880
rnv86
75,815,457
5,605,510
Custom BooleanField name in Django admin list filter
<p>In Django admin I can change default True/False representation of <code>BooleanField</code> using <code>choices</code> argument. It appears in object page and list page. But it doesn't changes in admin list filter. Why? How can I change defaults 'All/Yes/No/Unknown' in <code>list_filter</code>?</p> <p>app/models.py<...
<python><django><filter><boolean><django-admin>
2023-03-22 17:25:26
1
480
Andrei Alekseev
75,815,288
3,337,089
Slice a multidimensional pytorch tensor based on values in other tensors
<p>I have 4 PyTorch tensors:</p> <ul> <li><code>data</code> of shape <code>(l, m, n)</code></li> <li><code>a</code> of shape <code>(k,)</code> and datatype <code>long</code></li> <li><code>b</code> of shape <code>(k,)</code> and datatype <code>long</code></li> <li><code>c</code> of shape <code>(k,)</code> and datatype...
<python><pytorch><vectorization><slice><numpy-slicing>
2023-03-22 17:09:27
2
7,307
Nagabhushan S N
75,815,275
8,497,979
Filter list for dictionaries for key based on a particular value
<p>I have a list of dictionaries:</p> <pre><code>lst = [ { 'meter_design': {'S': 'digital'}, 'meter_calibration_period': {'S': '2022'}, 'meter_counting_type': {'S': 'Quantity meter'}, 'meter_kind': {'S': 'Gas'}, 'meter_serial_number': {'S': '10030507'} }, { 'm...
<python>
2023-03-22 17:08:16
1
1,410
aerioeus
75,815,249
854,791
Spark container keeps restarting
<p>I'm trying to write some data to a Delta Table using Spark. For this, I'm running Spark in a Docker container through docker compose. Whenever I try to create a Delta Table, the container keeps restarting in a loop, with nothing happening. It's giving me this output:</p> <pre><code>biocloud-core-dockercompose-spark-...
<python><docker><apache-spark><pyspark><delta-lake>
2023-03-22 17:05:01
0
12,536
Leon Cullens
75,815,202
4,115,378
group nearby timestamps together in pandas
<p>I understand Pandas has a <code>pd.Grouper</code> where we can specify time frequency. However, it uses the frequency as border for each sample, similar to how resample does it. For example:</p> <pre><code>df.groupby(pd.Grouper(key='Timestamp', freq='1s')).agg({...}) </code></pre> <p>will create a grouped dataframe ...
<python><pandas>
2023-03-22 17:00:08
1
1,364
A1122
75,815,136
6,077,239
Correlation dataframe convertion from results from pl.corr
<p>I have a simple dataframe as follows:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;group&quot;: [1, 1, 1, 1, 2, 2, 2, 2], &quot;a&quot;: [1, 2, 3, 4, 1, 2, 3, 4], &quot;b&quot;: [5, 1, 7, 9, 2, 4, 9, 7], &quot;c&quot;: [2, 6, 3, 9, 1, 5, 3, 6], } ) </code></p...
<python><python-polars>
2023-03-22 16:53:32
3
1,153
lebesgue
75,815,091
7,437,143
Storing only unique/non-isomorphic undirected networkx graphs?
<h2>Context</h2> <p>After thinking about the most efficient way to store unique graphs (in plain text), I determined the following procedure:</p> <ul> <li>create a folder with the graph size (nr of nodes) as name</li> <li>when storing a new graph of size <code>n</code>, load the graphs inside the folder of graph size...
<python><networkx><graph-theory><isomorphism>
2023-03-22 16:49:15
1
2,887
a.t.
75,814,954
11,143,781
OpenCV imshow window doesnt update itself
<p>I have the code as follows:</p> <pre><code>import cv2 import numpy as np source = 'test.mp4' cap = cv2.VideoCapture(source) window = &quot;Window&quot; cv2.startWindowThread() cv2.namedWindow(window) cv2.moveWindow(window, 10, 10) while cap.isOpened(): ret, img = cap.read() if not ret: break # C...
<python><qt><opencv>
2023-03-22 16:37:18
0
316
justRandomLearner
75,814,843
7,984,318
How to convert a pandas Dataframe to a xml tree format like pattern
<p>I have a Dataframe ,you can have it by running :</p> <pre><code>import pandas as pd from io import StringIO df = &quot;&quot;&quot; Name Type Format loan1 i type:num;width:10 loan2 a type:char;width:2 loan3 i type:date;width:8;dec:0 &quot;&quot;&quot; df= pd.re...
<python><pandas><xml><dataframe><python-xmlschema>
2023-03-22 16:25:30
1
4,094
William
75,814,839
6,524,326
Download all pubmed central article ids that have a keyword appearing in their titles/abstracts and also falling between two dates
<p>I am using the following code to download all pubmed central article ids that have a keyword appearing in their titles/abstracts and also falling between two dates. The code seems to work when I select database = &quot;pubmed&quot; but when I switch to database = &quot;pmc&quot; I get empty list. For example, using ...
<python><biopython>
2023-03-22 16:24:58
1
828
Wasim Aftab
75,814,736
12,743,647
Gracefully handling keyboard interrupt for Python multi-processing
<p>I am working on a project which runs two separate python processes. When I do a <code>ctrl + c</code> to end the program, I would like the program to end gracefully.</p> <p>I can produce a minimum working version of the code through the following:</p> <pre><code>from multiprocessing import Process import os import ...
<python><python-3.x><multithreading><process><multiprocessing>
2023-03-22 16:13:11
1
518
bgmn
75,814,642
1,401,560
How can I fix ModuleNotFoundError: No module named 'pysftp' for an Ansible library?
<p>On a Mac OS</p> <pre><code>$ ansible --version ansible 2.10.8 config file = /Users/cfouts/.ansible.cfg configured module search path = ['/Users/myUser/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/Cellar/ansible/3.3.0/libexec/lib/python3.9/site-pac...
<python><python-3.x><ansible>
2023-03-22 16:03:35
0
17,176
Chris F
75,814,525
19,980,284
Statsmodels Clustered Logit Model With Robust Standard Errors
<p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df.head() id case volfluid map rr o2 fluid 1044 36 3 3.0 1.0 3.0 2.0 0.0 1045 37 3 2.0 3.0 1.0 2.0 1.0 1046 38 3 3.0 2.0 2.0 1.0 0.0 1047...
<python><logistic-regression><statsmodels><stderr>
2023-03-22 15:52:04
1
671
hulio_entredas
75,814,486
9,205,210
In sklearn, is there a way to get access to the .loss_curve_ attribute of an MLPClassifier after using GridSearchCV?
<p>I would like to be able to plot the loss curves for each set of parameter combinations that was used within a run of fitting MLP models within GridSearchCV.</p> <p>I am able to access the loss curve if I have a fixed set of parameters, eg:</p> <pre><code>import matplotlib.pyplot as plt from sklearn.pipeline import P...
<python><scikit-learn>
2023-03-22 15:48:18
0
400
Francisco C
75,814,350
1,158,427
Bamboolib in Databricks
<p>I was looking to have a UI within databricks notebook use it to display data from a dataframe. I also wanted to edit the rows or insert new rows from the UI.</p> <p>I tried bamboolib but the edit button looks disabled. Is there a way I can insert new rows and possibly edit existing ones from the UI itself ?</p> <p><...
<python><azure-databricks>
2023-03-22 15:37:30
2
1,447
Chhaya Vishwakarma
75,814,306
5,090,059
Tensorflow vs. Pytorch β€” identical model leads to different results
<p>I'm trying to implement 2 identical models in Tensorflow and Pytorch. I am using an extremely simple network. To make sure they are identical I am copying over the initial weights from Tensorflow to Pytorch. This seems to work if I don't fit the model. The initial weights lead to identical predictions.</p> <p>Howeve...
<python><tensorflow><pytorch>
2023-03-22 15:34:15
0
429
Nils Mackay
75,814,043
5,212,614
How can we convert a Pandas Core Series into separate and distinct columns?
<p>I am normalizing a JSON response, like this.</p> <pre><code>df = pd.json_normalize(response, record_path=['data']) </code></pre> <p>Now, if I run this: <code>print(type(df['locations']))</code></p> <p>I get this result: <code>&lt;class 'pandas.core.series.Series'&gt;</code></p> <p>So, <code>'df['locations']'</code> ...
<python><python-3.x><dataframe><series>
2023-03-22 15:10:07
0
20,492
ASH
75,813,849
10,428,677
Approach for improving runtime of Python function
<p>I have a function that relies on a dictionary to identify the files it needs to read and the variable names they're linked to. The function then reads the file, calculates the outputs (in this case a mean value) and returns it as a column in an existing dataframe. This all works well when the files are different, bu...
<python><pandas><dictionary><geopandas>
2023-03-22 14:54:17
1
590
A.N.
75,813,754
13,484,397
Validate audio coming from FastAPI using Pydantic
<p>I'm working on a transcriber API. It has one endpoint /transcribe, and takes an audio file to be transcribed. I want to add some Pydantic validators (make sure that the MIME type is audio/, make sure that the audio is big enough (bigger than 1 sec). I have not found any way to validate data coming from a form.</p> <...
<python><validation><fastapi><mime-types><pydantic>
2023-03-22 14:45:42
0
414
Ralph Aouad
75,813,713
3,924,118
Is it possible not to show the arguments in a specific parametrized test function?
<p>I have a pytest's paremetrized test function like this</p> <pre><code># imports LONG_STRING = &quot;hello world &quot; * 10000 @mark.parametrize(&quot;a,c,b&quot;, [[LONG_STRING, 2, 3], [LONG_STRING, 2, 3]]) def test_something(a, b, c): # test whatever </code></pre> <p>Now, when I run this test function, I see...
<python><pytest>
2023-03-22 14:42:25
1
16,044
nbro
75,813,668
528,369
Read pandas dataframe from file until sentinel value?
<p>Given the CSV file below that stores multiple dataframes, can I use <code>pd.read_csv()</code> to read until a sentinel value is detected, in this case &quot;#&quot;?</p> <pre><code>x,y 2,4 3,9 # x,y 2,8 3,27 </code></pre>
<python><pandas>
2023-03-22 14:39:26
1
2,605
Fortranner
75,813,646
19,889,754
Why am I getting 'Different version pinnings of the same package' error when pinning python version in Foundry Code Repository?
<p>I'm facing an error when trying to require a minimum python version for my shared library in the <code>meta.yml</code> file (by pinning python &gt;= 3.6) in order to use it in various repositories supporting different python version (3.6, 3.8 for instance).</p> <p>When pinning Python&gt;= 3.6 the checks are not pass...
<python><palantir-foundry><foundry-code-repositories>
2023-03-22 14:37:14
1
355
Max Magid
75,813,603
14,607,802
Python, working with sound: librosa and pyrubberband conflict
<p>I have the following script that I was using to manipulate an mp3:</p> <pre><code>import librosa import soundfile as sf from playsound import playsound from direct.showbase.ShowBase import ShowBase #import pyrubberband as pyrb filename = &quot;music.mp3&quot; y, sr = librosa.load(filename) tempo, beat_frames = lib...
<python><librosa>
2023-03-22 14:33:16
2
817
Charmalade
75,813,474
12,214,867
I'm trying to scrape a Bing dict page with BeautifulSoup. However, response.content doesn't contain the actual data, how do I do?
<p>I'm trying to scrape a Bing dict page <a href="https://cn.bing.com/dict/search?q=avengers" rel="nofollow noreferrer">https://cn.bing.com/dict/search?q=avengers</a></p> <p>Here is the code</p> <pre class="lang-py prettyprint-override"><code>import requests from bs4 import BeautifulSoup url = &quot;https://cn.bin...
<python><web-scraping><beautifulsoup>
2023-03-22 14:21:50
3
1,097
JJJohn
75,813,381
21,037,446
Python for loop through nested dictionary question?
<p>Trying to loop through a nested dictionary and want to store values into name, age and occupation. Without manually creating those variables within the for loop. Is this even possible? Just trying to create cleaner looking code. Thank you.</p> <pre><code>people = { 1: {&quot;name&quot;: &quot;Simon&quot;, &quot;...
<python><dictionary><for-loop><nested>
2023-03-22 14:13:59
2
439
RishV
75,813,348
9,182,743
Missleading display of values in pandas column when each cell is a list
<p>In jupiter notebook</p> <p>This column made up of two different lists, are displayed the same way.</p> <pre class="lang-py prettyprint-override"><code>pd.DataFrame({ &quot;user&quot;: [&quot;a&quot;, &quot;b&quot;], &quot;values&quot;: [['1', '2, 1', '2', '3'], ['1, 2', '1, 2, 3']] }) </code><...
<python><pandas>
2023-03-22 14:10:32
1
1,168
Leo
75,813,337
1,298,461
How to save/load faiss KMeans for later inference
<p>I have successfully clustered a bunch of vectors using the faiss kmeans. But now I am not able to store the model and load it later for inference.</p> <pre><code>clustering = faiss.Kmeans(candles.shape[1], k=clusters, niter=epochs, gpu=gpu, verbose=True) clustering.train(X) cluster_index = clustering.index # failed...
<python><faiss>
2023-03-22 14:09:42
1
6,069
KIC
75,813,310
11,829,398
Is it possible to have a pandas categorical column where each row can contain multiple categories?
<p>I would like to categorize the rows in my dataframe. Each row can belong to multiple categories.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'A': ['a, b', 'b, c, d', 'c'], 'B': [1, 2, 3] }) </code></pre> <p>If I do</p> <pre class="lang-py prettyprint-override"><code>df['A'].astyp...
<python><pandas>
2023-03-22 14:06:56
3
1,438
codeananda
75,813,294
351,885
How should I obtain the covariance matrix for the fit parameters calculated by numpy.polynomial.polynomial.polyfit?
<p>In the past I have used the numpy.polyfit function for least-squares fitting to a straight line in a first-year programming course for physics students. However, the NumPy documentation now recommends using numpy.polynomial.polynomial.polyfit instead as this newer Polynomial library is more stable numerically. Howev...
<python><numpy>
2023-03-22 14:05:38
0
2,398
Ben
75,813,223
6,224,975
Get columns of 2D ndarray defined by index' in another 2D ndarray
<p>I have an ndarray <code>arr = np.array([[1,2,3],[4,5,6],[7,8,9]])</code> and an index-array</p> <p><code>arr_idx = np.array([[0,2],[1,2],[2,1]])</code> where each row in <code>arr_idx</code> corresponds to the index of <code>arr</code> which I want to have i.e the result should be <code>[[1,3],[5,6],[9,8]]</code>.</...
<python><arrays><numpy>
2023-03-22 13:58:40
1
5,544
CutePoison
75,813,077
4,907,339
Peewee x Dash: DB connections aren't reused when called inside a Dash callback function
<p>I'm noticing that within a Plotly Dash app that uses a DB managed by Peewee, I'm getting <code>playhouse.pool.MaxConnectionsExceeded: Exceeded maximum connections.</code>, which is visible here:</p> <pre class="lang-sql prettyprint-override"><code>ariobot=# SELECT count(*) FROM pg_stat_activity where client_port &gt...
<python><plotly-dash><peewee>
2023-03-22 13:46:01
1
492
Jason
75,812,976
5,212,614
How to normalize JSON response and convert it into a DataFrame?
<p>I am trying to standardize a JSON string and convert it into a dataframe. My actual data is for work and it's confidential so I can't show it here, but I think this small made-up scenario below illustrates the point I'm trying to make.</p> <pre><code>import json import requests import pandas as pd from pandas.io.jso...
<python><json><python-3.x><dataframe>
2023-03-22 13:37:45
1
20,492
ASH
75,812,786
6,197,439
Have Python output .csv with space-padded, fixed width, but comma-separated columns?
<p>Let's say I have CSV data as note below; let's call this <code>original.csv</code>:</p> <pre><code>name,value1,value2 firstname,34326408129478932874,553 secondname_a_very_long_one,65,123987 thirdname_medium,9686509933423,33 </code></pre> <p>Basically, it's either single word text (no space separation, so no need for...
<python><csv><string-formatting><fixed-width>
2023-03-22 13:21:25
1
5,938
sdbbs
75,812,672
5,969,893
Airflow Trigger Rule Wait for Parent Tasks to finish
<p>For my DAG I have a main task(task_1) and then I have 4 additional tasks that follow and need to be executed in sequential order due to system constraints.</p> <p>Tasks 2,3,4, and 5 need to be executed in sequential order but are dependent on task_1 being successful but are not dependent on other tasks being success...
<python><airflow><directed-acyclic-graphs>
2023-03-22 13:10:23
0
667
AlmostThere
75,812,616
9,301,805
Pandas does not respect conversion to time type
<p>I have this dataframe:</p> <pre><code> site date time 1 AA 2018-01-01 0100 2 AA 2018-01-01 0200 3 AA 2018-01-01 0300 4 AA 2018-01-01 0400 5 AA 2018-01-01 0500 6 AA 2018-01-01 0600 7 AA 2018-01-01 0700 8 AA 2018-01-01 0800 9 AA 2018-01-01 0900 df.dtypes &gt;&gt;&gt; sit...
<python><pandas><datetime><filter><time>
2023-03-22 13:04:14
1
1,575
user88484
75,812,512
8,497,979
Filter List of Dictionaries and omit keys
<p>I have a list of dictionaries:</p> <pre><code>resp = [ { 'meter_id': {'S': 'M#G000140'}, 'meter_reading_reader': {'S': 'Meyer'}, 'meter_reading_date': {'S': '2021-12-21T12:00:00'}, 'item_type': {'S': 'READING'}, 'meter_reading_value': {'S': '225'}, 'meter_reading_u...
<python>
2023-03-22 12:52:15
4
1,410
aerioeus
75,812,487
1,667,018
Custom method decorator aware of a class
<p>I had an idea for a simple decorator that would probably not be very useful (feel free to comments on that, but it's not my main focus here). Regardless of that, I think it'd show how to achieve certain things and these are my main interest.</p> <p><strong>The idea:</strong> A decorator <code>@inherit_docs</code> th...
<python><python-decorators><python-class>
2023-03-22 12:50:21
2
3,815
Vedran Ε ego
75,812,439
4,676,162
How to override QMessageBox blocking behavior?
<p>I have 2 blocking actions, one of them being QMessageBox <code>exec_</code> method. Second one is a <code>get_weight()</code> function that when it's executed it waits until user puts an item on a scale.</p> <p>What I'm trying to accomplish is to inform the user with <code>QMessageBox</code> that he needs to do put ...
<python><pyqt5>
2023-03-22 12:46:15
0
633
Sir DrinksCoffeeALot
75,812,382
11,635,654
crash of a nb 22thMarch23 while it was ok 19thJan2023
<p>I have a problem that I do not know how to tackle it. I have a nb on Colab that was working perfectly on CPU <a href="https://colab.research.google.com/drive/1gOk9-DqZqF6xbdHM5GBopjOmMAKioSgD" rel="nofollow noreferrer">Here is the working nb 19th Jan 23</a></p> <p>Then, I was looking to get a new nb working in the ...
<python><git><google-colaboratory><jax>
2023-03-22 12:40:32
1
402
Jean-Eric
75,812,237
5,359,846
How to send API call when the payload contains lists and objects?
<p>I need to send a Post request via Python code, like using Postman.</p> <p>When I look at the Payload tab under the Network in Google Chrome I see this data:</p> <pre><code>version: abcd password: Somepassowrd links[0].XYZ: DC-DC-02-01 links[0].Change: 4321 </code></pre> <p>How to send links[0].xyz? Is is a dictionar...
<python><request><postman>
2023-03-22 12:25:00
2
1,838
Tal Angel
75,811,998
19,467,973
Set cookies and return the message in FastAPI
<p>Why don't I have cookies installed in my browser when I try to return a message in this code?</p> <pre><code>@post(&quot;/registration_user&quot;)#, response_class=JSONResponse) async def sign_in_user(self, item: schemas.RegistrWithoutLogin): print(&quot;--------------------------------------------------...
<python><cookies><fastapi><jsonresponse>
2023-03-22 12:02:18
1
301
Genry
75,811,990
5,452,365
Check if pathlib.Path is a file or directory without pathlib.Path exist on directory
<p>How to tell if pathlib.Path is a file or dir path without being physically present on disk. I do not want to check if the actual file exists on the disk. Something like this.</p> <pre><code>from pathlib import Path home = Path.home() def function_to_differentiate_file_and_dir(filepath): return 'file' is filepa...
<python>
2023-03-22 12:01:21
1
11,652
Rahul
75,811,936
7,822,387
how to create this linear program in PULP
<p>How can I create the following linear program using PuLP? The structure is as follows. A list of orders must be processed in the order they came in, and has a list of items that can be made by a set of different machines. Each machine can only process one item per order, but each item can be processed by multiple ma...
<python><pulp>
2023-03-22 11:54:44
1
311
J. Doe
75,811,897
567,595
Separate comma-separated values within pandas dataframe cells
<p>I am getting data from an API in CSV format, which I read into a pandas dataframe like this:</p> <pre><code>import io import requests import pandas as pd response = requests.get(url, params=params, headers=headers) df = pd.read_csv(io.StringIO(response.content.decode(&quot;utf-8&quot;))) </code></pre> <p>(As request...
<python><pandas><csv>
2023-03-22 11:50:59
2
9,877
Stuart
75,811,887
6,543,836
Dependency Injector. Inject a dependency into a route method from app.py
<p>I have a small flask application that consists only from one <code>app.py</code> file. I'm using <a href="https://python-dependency-injector.ets-labs.org/" rel="nofollow noreferrer">python-dependency-injector</a> package. I want to inject a service into the <code>hello_world()</code> route method.</p> <pre><code>cla...
<python><flask><dependency-injection>
2023-03-22 11:50:18
0
519
Eugeniu Znagovan
75,811,845
1,613,983
How to visualize timeseries output at each epoch in tensorboard
<p>I have a keras model that outputs an MxN tensor along with several scalar metrics. The metrics show up just fine in the <em>SCALARS</em> and <em>TIME SERIES</em> tabs:</p> <p><a href="https://i.sstatic.net/uv5Au.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uv5Au.png" alt="enter image description he...
<python><tensorflow><tensorboard>
2023-03-22 11:45:14
0
23,470
quant
75,811,688
2,281,274
How to avoid showing orginal exception in pytest when reraising exception?
<p>I use a library with very deep stack. When there is an exception, trace is enormous (~6 pages), even the true reason is a side effect (no permission), and it's very clear from exception text. It is really confusing in tests, so I wrote this code:</p> <pre><code>def _command(self, lib_handler, cmd): try: ...
<python><pytest><traceback>
2023-03-22 11:29:53
1
8,055
George Shuklin
75,811,600
11,803,687
Convert stringified json objects to json
<p>I'm using MariaDB, and unfortunately, JSON objects are returned as strings. I want to convert these stringified JSON objects back to JSON, but the problem is - I only want to do so if they are actually JSON objects, and ignore all fields that are, for example, just normal strings (but <strong>can</strong> convert to...
<python><json><mariadb>
2023-03-22 11:20:41
2
1,649
c8999c 3f964f64
75,811,420
8,472,781
Add Python entry point to local APPDATA
<p>I am writing a command line tool with Python. It should be as easy as possible for Windows 10 / 11 users to install and use. My goal is to make the following procedure work:</p> <ol> <li>Install Python from the Microsoft Store</li> <li>Install my program using <code>pip install &quot;C:\path\to\myprogram.zip&quot;</...
<python><windows-10><setuptools><python-packaging><windows-11>
2023-03-22 11:04:12
1
586
d4tm4x
75,811,395
1,736,294
FastApi Sessions for Anonymous Users
<p>I'm looking for a simple way to achieve this:</p> <p>Anonymous users access a fastapi service. From a client, a user begins a session and sends a request. The fastapi service captures dependency data from the request. If the user makes further requests during the same session, the dependency data is updated and so o...
<python><security><fastapi>
2023-03-22 11:02:03
0
4,617
Henry Thornton
75,811,312
2,958,883
12 hperthread used evenly with 7 processes in multiprocessing.Pool
<p>I have a task <code>get_geotif_by_band(band_number):...</code>.</p> <p>Now my multiprocessing code is as follow:</p> <pre><code>if __name__ == '__main__': with Pool(12) as p: p.map(get_geotif_by_band, [1,2,3,4,5,6,7]) </code></pre> <p>My cpu has 6 cores and 12 Logical processors.</p> <p>Now I expect 7 lo...
<python><multiprocessing><python-multiprocessing>
2023-03-22 10:52:47
1
1,406
wrufesh
75,811,178
7,800,760
Folium: how to create some leeway for displayed placemarkers
<p>The following simple code creates three placemarks, computes the proper NE and SW bounding box and uses folium.Map.fit_bounds to set the proper zoom level to display them on the map.</p> <p>What I'd like to achieve if possible is to have some more space around the placemarks, just like the user would have clicked on...
<python><plotly><plotly-dash><folium>
2023-03-22 10:39:55
0
1,231
Robert Alexander
75,810,821
188,331
How to specify a PyTorch script to use specific GPU unit?
<p>I have a Python training script that makes use of CUDA GPU to train the model (Kohya Trainer script available <a href="https://github.com/Linaqruf/kohya-trainer/blob/main/train_network.py" rel="nofollow noreferrer">here</a>). It encounters out-of-memory error:</p> <pre><code>OutOfMemoryError: CUDA out of memory. Tri...
<python><pytorch><gpu>
2023-03-22 10:05:04
1
54,395
Raptor
75,810,448
2,546,099
String-based flags in python
<p>For my python-based class I'd like to limit the input strings to certain strings, as they represent the file endings I want to allow to be loaded, i.e.</p> <pre><code>class DemoClass: def __init__(self, allowed_endings: Literal[&quot;.csv&quot;, &quot;.txt&quot;, &quot;.docx&quot;] = &quot;.docx&quot;) -&gt; Non...
<python><string><flags>
2023-03-22 09:30:20
2
4,156
arc_lupus
75,810,407
19,574,336
Django AttributeError: type object 'Admin' has no attribute '_meta' error when creating custom user
<p>I'm learning django and I want to have my custom user and admin object but I'm encountering an error when running server after applying my changes. I'm not sure if this is the right approach to do this so do enlighten me if I'm following the wrong approach.</p> <p>So I have created an app called 'core' where I want ...
<python><django><django-models>
2023-03-22 09:26:18
1
859
Turgut
75,810,403
1,754,221
How to access a TypeVariable's instance from a class decorator
<p>I'm creating a class decorator but have some issues getting the typing right. Below is a minimal reproducable example which runs (no run-time errors) but lets pylance (using the static type checker pyright) complain.</p> <p>My issue is, that <code>cls</code> in the wrapper function is <code>Type[T@wrapper]</code> (w...
<python><python-decorators>
2023-03-22 09:25:56
0
1,767
Leo
75,810,397
7,074,716
How to draw edge labels when there are multi edges in networkx?
<p>I have a node called T in the middle that has two bidirectional nodes going from it to other 2 nodes. I want to draw the edge weight in the plot.</p> <pre><code>import matplotlib.pyplot as plt import networkx as nx G=nx.MultiGraph() edge_list = [(&quot;1&quot;,&quot;2&quot;, 1), (&quot;3&quot;, &quot...
<python><graph><networkx>
2023-03-22 09:25:20
0
825
Curious
75,810,342
7,214,714
Porting third-party python packages onto Snowpark
<p>I'm trying to port the Googletrans package onto Snowflake snowpark, and use it in a UDf.</p> <p>As the package is unsupported by Snowpark natively, I zipped up the package folder, and uploaded it to a snowpark stage at <code>@DWH.MY_SCHEMA.PACKAGES</code> stage. My code then looks like this</p> <pre><code>import fr...
<python><snowflake-cloud-data-platform>
2023-03-22 09:19:20
1
302
Vid Stropnik
75,810,318
12,769,783
Hint instance of subtype of type
<p>I want to write a type hint that allows a function argument to be an instance of an arbitrary subtype of a previous type (that is derived from a type hint).</p> <p>I know that <code>Type[cls]</code> indicates that we receive a type that derives from <code>cls</code>. Is there a way to express that I would like to re...
<python><python-typing>
2023-03-22 09:17:36
1
1,596
mutableVoid
75,810,236
3,564,468
Does the python requests library support query param with no value?
<p>I have a server side API with the following URL</p> <pre><code>https://example.com/abc/JSONInterface.jsp?param1=param1_val&amp;param2=param2_val&amp;param3 </code></pre> <p>If you notice the param3 it has no value nor is it null/None</p> <p>As per this <a href="https://stackoverflow.com/a/4557490/3564468">source</a>...
<python><python-3.x><python-requests>
2023-03-22 09:07:22
1
3,023
amitection
75,810,215
6,840,039
Pandas: changing the data after saving and loading
<p>I have a dataframe, which contains column <code>user_pseudo_id</code> and it looks like</p> <pre><code>user_pseudo_id 2041513012.1676969234 2041513191.1677359234 2041513765.1677359510 </code></pre> <p>And it's a string type. Then I try to save it and load it again. So the problem is that I get the different values i...
<python><pandas>
2023-03-22 09:05:10
1
4,492
Petr Petrov
75,810,214
14,917,676
Resizing Image Data Pixel-by-Pixel using Python
<h2>Description</h2> <p>Say, I have the data about an 4x4 image:</p> <pre class="lang-py prettyprint-override"><code>IMG = ( [ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9,10,11,12], [13,14,15,16] ) </code></pre> <p>How would I, without using those of &quot;heavy&quot; big-data modules, Scale it up to 6x6 or 8x8?</p...
<python><algorithm><image><vector><scaling>
2023-03-22 09:05:09
1
487
whmsft
75,810,163
13,158,157
pyspark to pandas dataframe: datetime compatability
<p>I am using pyspark to do most of the data wrangling but at the end I need to convert to pandas dataframe. When converting columns that I have formatted to date become &quot;object&quot; dtype in pandas.</p> <p>Are datetimes between pyspark and pandas incompatible? How can I keep dateformat after pyspark -&gt; pandas...
<python><pandas><pyspark>
2023-03-22 08:58:50
1
525
euh
75,810,094
19,580,067
Automate Python Script in Microsoft Power Automate
<p>I tried to automate the python script in Microsoft Power Automate to run daily. The python Script is all about doing some enquiries from the newly received emails and fetching keywords and sending all of them as a new email. The Script is working fine in visual studio code, command prompt. But not sure what I'm doin...
<python><power-automate-desktop>
2023-03-22 08:52:13
1
359
Pravin
75,809,897
11,703,015
pd.groupby in two columns sum() function does not work
<p>I am trying to do the next example. I want to get the total number of survivors (<em>survived</em>) and the total amount paid per class (<em>fared</em>) using the Titanic dataset.</p> <pre><code>import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/bvalgard/data/main/titanic.csv') df.groupby(['pcl...
<python><pandas><dataframe><group-by>
2023-03-22 08:29:37
1
516
nekovolta
75,809,848
10,037,034
How to filter date column data from sas with saspy (Python)?
<p>I want to filter date column for a table</p> <pre><code>data = sas.sasdata(&quot;METEOGROUP&quot;, &quot;ABC&quot;, &quot;PANDAS&quot;, { &quot;where&quot;: &quot;DATE_DAY&gt;'2021-04-20'&quot; } ).to_df() </code></pre> <p>But there ...
<python><sas><where-clause><saspy>
2023-03-22 08:23:46
1
1,311
Sevval Kahraman
75,809,832
16,475,089
"image" is not accessed - Pylance
<p>Pyance is showing false warnings in certain functions.</p> <p><a href="https://i.sstatic.net/qP7we.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qP7we.png" alt="enter image description here" /></a></p> <p>Even the variable is used it still shows as it. For example in the above picture</p> <ul> <li>T...
<python><visual-studio-code><pylance>
2023-03-22 08:21:58
1
1,839
ilyasbbu
75,809,698
1,838,230
Python using self to call function syntax
<p>Been digging into the source code of the Python package <code>transformers</code>, saw this code and am stumped.</p> <pre><code>model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs) outputs = self( **model_inputs, return_dict=True, output_attentions=output_attenti...
<python><class>
2023-03-22 08:04:34
0
892
ZWang
75,809,648
12,242,085
How to upper all columns from DataFrame except columns from list if columns from list exists in DataFrame in Python Pandas?
<p>I have DataFrame in Python Pandas like below (my real DF has many many more columns):</p> <p><strong>Input data:</strong></p> <pre><code>COL1 | col2 | col3 ------|--------|------- X | 11 | 2021 Y | 22 | 1990 </code></pre> <p><strong>Requirements:</strong></p> <p>And I need to make upper each colum...
<python><pandas><dataframe><list><uppercase>
2023-03-22 07:58:24
1
2,350
dingaro
75,809,249
16,869,946
Generating new dataframe based on combination of rows
<p>I have a dataframe that is indexed by <code>Race_ID</code></p> <pre><code>Race_ID Student_ID Rank 1 1 3 1 2 2 1 3 1 1 4 4 2 1 2 2 ...
<python><python-3.x><pandas><dataframe>
2023-03-22 07:07:00
1
592
Ishigami
75,809,212
19,945,688
Python - How can I simplify updating dictionary value to update it with substring of it
<p>Instead of repeating or assigning it to a new variable how can I simplify this expression?</p> <blockquote> <pre class="lang-py prettyprint-override"><code> dict['key'] = dict['key'][0:100] </code></pre> </blockquote> <p>In Dart one can do</p> <pre><code> map.update('key', (v)=&gt; v.substring(0,100)); </code></...
<python><python-3.x>
2023-03-22 07:00:56
3
1,396
Soliev
75,808,891
4,447,853
Alternatives to brute force algebra with additive/sigma functions
<p>I have an equation</p> <pre><code> 7405 210000 = Ξ£ (x * (1 - 1/y)^n) n = 0 </code></pre> <p>My goal is to find various x and y values that make it true. I also require for x and y to be whole numbers.</p> <p>The way I have been doing it so far takes an incredible amount of time and is not very efficient...
<python><math><sum><brute-force><algebra>
2023-03-22 06:06:54
1
527
chriscrutt
75,808,619
992,165
Overriding method python class of a pip module to update its behavior globally
<p>Using OOP I want to do something like</p> <pre><code>from django.contrib import admin class NavigateFormAdmin(admin.ModelAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): context['next_record_id'] = custom_function_to_calculate(context['obj'].id) ...
<python><django><oop><overriding><monkeypatching>
2023-03-22 05:08:34
1
8,449
Sami
75,808,346
6,546,694
How to manage python dependencies based upon user input? A question about structuring the python code
<p>I am trying to implement the methodology described <a href="https://medium.com/optuna/lightgbm-tuner-new-optuna-integration-for-hyperparameter-optimization-8b7095e99258" rel="nofollow noreferrer">here</a>. The details except for the ones I will post here are irrelevant to the scope of the question</p> <ol> <li>The i...
<python><python-3.x><design-patterns>
2023-03-22 03:59:24
1
5,871
figs_and_nuts
75,808,155
4,299,527
How to apply a function while filtering using loc method in pandas?
<p>I have a dataframe <strong>A</strong> and dataframe <strong>B</strong> in pandas. I want to update one of A's column based if certain conditions for a row is matched in B. While matching with multiple conditions, I want to apply a function called &quot;<strong>similar</strong>&quot; on the current row like below:</p...
<python><pandas>
2023-03-22 03:14:52
2
12,152
Setu Kumar Basak
75,808,091
12,702,027
Python skips coroutine evaluation
<p>I've been trying to get around Python's recursion limit using coroutines, and through trial and error arrived at <a href="https://github.com/jc65536/pyrecfun/blob/main/fibawait2.py" rel="nofollow noreferrer">this code</a> which recursively calculates Fibonacci numbers:</p> <pre class="lang-py prettyprint-override"><...
<python><recursion><python-asyncio><coroutine>
2023-03-22 02:57:37
1
386
Jason
75,808,046
2,128,799
Strange errors using factory_boy and DjangoModelFactory
<p>I've created several factories including a user factory that looks like so</p> <pre><code>class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User django_get_or_create = ('phonenumber',) uuid = factory.Faker('uuid4') email = factory.Faker('email') phonenu...
<python><django><django-rest-framework><django-orm><factory-boy>
2023-03-22 02:44:04
1
1,294
Dash Winterson
75,807,897
1,857,373
NotOneValueFound: Expected one value, found 0 sklean 1.02 updated to sklean 1.2.2 then code broke
<p><strong>problem</strong></p> <p>Defining models for OneVsRestClassifier and OneVsOneClassifier for SVC kernel='rbf'. Code was running fine until I updated sklearn from 1.02 to 1.2.2</p> <p>I first perform a min max scaler to transform the training data, working code. Perform standard scaling. Then select with iloc[]...
<python><python-3.x><scikit-learn>
2023-03-22 02:08:35
1
449
Data Science Analytics Manager
75,807,664
3,944,252
Issues Handling ChatGPT Streaming Response in Terminal using OpenAI API - Using Python, rich library
<p>I am trying to integrate the <strong>openAi API</strong> model - <code>gpt-4</code> with Terminal to enable <strong>ChatGPT</strong>. My objective is to receive streaming responses from <strong>ChatGPT</strong> and print them in the Terminal. Although I can successfully print the entire response without streaming, I...
<python><openai-api><rich><gpt-4>
2023-03-22 01:09:17
1
1,588
sparker
75,807,577
820,088
Convert a Python List Stored in a Pandas Dataframe Column, to CSV List
<p>I have a pandas dataframe column that stores a list. i.e.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>State</th> <th>City</th> </tr> </thead> <tbody> <tr> <td>Oregon</td> <td>[u'Eugen', u'Portland']</td> </tr> <tr> <td>New York</td> <td>[u'New Jersey', u'Buffalo']</td> </tr> <tr> <td...
<python><pandas>
2023-03-22 00:50:20
2
4,435
Mike
75,807,522
6,197,439
Exporting arbitrary fields in list of dataclass objects to a dict?
<p>Consider this example:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict, astuple @dataclass class Player: id: int name: str color: str players = [ Player(123, &quot;Alice&quot;, &quot;green&quot;), Player(456, &quot;Bob&quot;, &quot;red&quot;), Player(789, &...
<python><list><dictionary><python-dataclasses>
2023-03-22 00:35:55
2
5,938
sdbbs
75,807,443
13,566,716
redis lock acquiring not working - stays running and never acquires
<p>this is my code:</p> <pre><code>pool = aioredis.ConnectionPool.from_url(&quot;redis://localhost:6379&quot;) redis = await aioredis.Redis(connection_pool=pool, ssl=False, ssl_cert_reqs=&quot;None&quot;) async with redis.lock(&quot;hello_lock&quot;) as lock: print(&quot;hello&quot;) await redis.hset(&quot;hel...
<python><python-3.x><redis><locking><aioredis>
2023-03-22 00:18:18
1
369
3awny
75,807,298
3,915,051
Sympy: drop terms with small coefficients
<p>Is it possible to drop terms with coefficients below a given, small number (say 1e-5) in a Sympy expression? I.e., such that</p> <pre><code>0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u) </code></pre> <p>becomes</p> <pre><code>0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u) </code></pre> <p>for instance.</p...
<python><sympy><coefficients>
2023-03-21 23:47:09
3
678
Tamas Ferenci
75,807,210
10,363,163
How to speed up sentence tokenization with Spacy
<p>I am trying to extract the first sentences from a list of paragraphs with the following function (that I apply in a for loop):</p> <pre class="lang-py prettyprint-override"><code>def extract_first_sentence(text): doc = nlp(text) return [sent.text for sent in doc.sents][0] </code></pre> <p>The code does what I wa...
<python><spacy><spacy-transformers>
2023-03-21 23:25:14
0
3,489
dufei
75,807,012
21,420,742
How to map previous values by ID. Python
<p>I tried asking this before and the last post was hard to understand. I have a dataset that looks at Employee IDs, their job, manager, and previous managers. What I want to do is update the previous manager column so that it displays only the most recent of the previous managers. Here is what I have:</p> <pre><code> ...
<python><python-3.x>
2023-03-21 22:47:49
1
473
Coding_Nubie
75,806,892
1,763,602
Is it possible to build an ARM64 linux wheel on Github?
<p>Currently I use <code>cibuildwheel</code> for building a c extension on Github.</p> <p><code>cibuildwheel</code> supports ARM64 for Windows (experimental) and Mac. It seems to support also ARM64 linux, with the name aarch64 (that is the &quot;canonical&quot; name of ARM64).</p> <p>AArch64 linux needs QEMU. The probl...
<python><arm><github-actions>
2023-03-21 22:28:51
2
16,005
Marco Sulla