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,133,547
3,337,597
Using decorators cause not showing parameter unfilled for function call (Python)
<p>I have a function named 'sample_func'. As you can see when I call the function without passing the required parameter, there is a red warning.</p> <p><a href="https://i.sstatic.net/H3vFJ.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/H3vFJ.jpg" alt="enter image description here" /></a></p> <p>I have ...
<python><python-3.x><decorator><python-decorators>
2023-01-16 11:25:00
0
805
Reyhaneh Sharifzadeh
75,133,515
4,555,441
Get list of columns names with cells satisfying a condition and store in separate column for each row in df
<p>I have a df with structure similar to below data with more cols and more rows. How to get the expected result. My code has an error - I interpret that the list cannot be saved in df cell? How to avoid loops if possible?</p> <pre><code>data = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 0, 1], [0, 0, 0]] df = pd.DataFrame(...
<python><pandas>
2023-01-16 11:22:16
2
648
pranav nerurkar
75,133,458
1,354,400
Polars str.starts_with() with values from another column
<p>I have a polars DataFrame for example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df = pl.DataFrame({'A': ['a', 'b', 'c', 'd'], 'B': ['app', 'nop', 'cap', 'tab']}) &gt;&gt;&gt; df shape: (4, 2) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ A ┆ B β”‚ β”‚ --- ┆ --- β”‚ β”‚ str ┆ str β”‚ β•žβ•β•β•β•β•β•ͺ═════║ β”‚ a ┆ app β”‚ β”‚ b ┆ nop β”‚ β”‚ c...
<python><python-polars>
2023-01-16 11:16:11
3
902
Syafiq Kamarul Azman
75,133,401
15,215,859
In Airflow version 2, create a DAG to Archive Mysql table into bigquery
<p>I basically want to fetch the data older than 2 weeks from a my_sql_table called &quot;testing_monitor_archive&quot; and put it into a bigquery table &quot;monitoring_table&quot;. I am using airflow version 2.1.4 currently. This is the DAG which i have created currently which is failing in &quot;GCSCreateBucketOpera...
<python><airflow><airflow-2.x>
2023-01-16 11:10:35
1
317
Tushaar
75,133,201
7,089,239
Incorrect format of labels in custom dataset for multi-label classification
<p>I'm trying to implement a custom <code>Dataset</code> for multi-label classification. That is, one element may have multiple classes simultaneously. I tried returning the one-hot encoded representation or the class indices from the dataset directly, but neither of them works.</p> <ul> <li>One-hot encoded produces <c...
<python><pytorch>
2023-01-16 10:53:20
1
2,688
Felix
75,133,181
4,835,496
Find point where touching geometries touch each other
<p>I have a GeoDataFrame with LineStrings and want to get all coordinates where the Geometries touch each other. I can find the ones who touch each other so far but how do I get the coordinates of the touching point? It should be as fast as possible because I have a lot of data.</p> <pre><code>data = gpd.read_file(&quo...
<python><geopandas>
2023-01-16 10:51:11
1
1,681
Kewitschka
75,133,059
5,437,090
selenium.common.exceptions.StaleElementReferenceException | python
<p>I am doing web scraping using <code>selenium</code> in python with the following code:</p> <pre><code>from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrom...
<python><selenium><web-scraping><exception><staleelementreferenceexception>
2023-01-16 10:40:07
1
1,621
farid
75,133,025
10,710,625
using testing.assert_series_equal when series are not in the same order
<p>I have two series that are equal but in different order.</p> <pre><code>data1 = np.array(['1','2','3','4','5','6']) data2=np.array(['6','2','4','3','1','5']) sr1 = pd.Series(data1) sr2=pd.Series(data2) </code></pre> <p>the two series are outputs of different functions and I'm testing if they are equal:</p> <pre><cod...
<python><pandas><dataframe><series><python-unittest>
2023-01-16 10:36:32
2
739
the phoenix
75,133,008
2,735,636
Why does Pymodbus change baudrate when running on linux without requesting a baudrate change?
<p>I have python3 program that acts as a Modbus Master. I start a ModbusSerialClient and then proceed to read register from the slave. This is working fine on Windows. The issue is that on Ubuntu I am seeing that the ModbusSerialClient keeps changing the baudrate which makes the communication inconsistent.</p> <p>I sta...
<python><python-3.x><pymodbus>
2023-01-16 10:34:22
1
460
Ricard Molins
75,132,832
1,877,010
Create Python alternating range programmatically
<p>I am looking for a convenient way to create an ordered, alternating (negative, positive while decrementing and incrementing by one from previous pair) list of integers in the form of</p> <pre><code>[-1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10] </code></pre> <p>with Python with variable len...
<python><python-3.x>
2023-01-16 10:17:31
5
377
DaHoC
75,132,827
8,318,946
docker-compose not working on Azure App Service
<p>I have pushed 4 images to Azure Container Registry: django-app, celery-worker, celery-beats and nginx. I have created docker-compose file that I used to created images and I want to upload to Azure App Service but I am getting this error:</p> <pre><code>Exception in multi-container config parsing: YamlException: (Li...
<python><django><azure><docker><celery>
2023-01-16 10:16:49
1
917
Adrian
75,132,758
8,282,898
How set charset encoding of pytest mock response?
<p>I learned about the encoding of python string.</p> <p>In python, strings are all same though there were encoded with different types.</p> <pre class="lang-py prettyprint-override"><code>error_msg = 'text' response_text = error_msg.encode().decode('ISO-8859-1') response_target1 = error_msg.encode().decode('cp949') re...
<python><mocking><pytest>
2023-01-16 10:11:53
0
985
Lazyer
75,132,544
11,852,936
Change boolean value to True for duplicates with more distant/far date pandas
<p>Given dataframe I want to set <code>isActive</code> column value to <code>True</code> only duplicated value and add '_duplicate' to the <code>Name</code> column.</p> <pre><code>df = Name isActive LoginDate John False 2021 John False 2022 Fred False 2020 </code></pre> <p>De...
<python><pandas>
2023-01-16 09:55:46
1
772
Mamed
75,132,451
14,004,563
Custom Euler method implementation always tends to infinity
<p>I have a system of differential equations:</p> <p><a href="https://i.sstatic.net/zeaK7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zeaK7.png" alt="enter image description here" /></a></p> <p>I'm using the following code to run Euler's method:</p> <pre><code>import numpy as np from scipy.integrate ...
<python><math>
2023-01-16 09:45:21
0
467
Berlm
75,132,358
5,573,294
In pandas, filter for duplicate values appearing in 1 of 2 different columns, for list of certain values only
<pre><code>zed = pd.DataFrame(data = { 'date': ['2022-03-01', '2022-03-02', '2022-03-03', '2022-03-04', '2022-03-05'], 'a': [1, 5, 7, 3, 4], 'b': [3, 4, 9, 12, 5] }) </code></pre> <p>How can the following dataframe be filtered to keep the earliest row (earliest == lowest date) for each of the 3 values <code>1, 5, 4</co...
<python><pandas>
2023-01-16 09:34:39
2
10,679
Canovice
75,132,235
898,042
Userdata partially working but not installing boto3 on EC2 launch, have to explicitly install it
<p>The userdata script for my EC2:</p> <pre><code>#!/bin/bash curl https://raw.githubusercontent.com/erjan/MyVoteAWS/main/vote-processor/processor.py &gt; /home/ec2-user/processor.py cd /home/ec2-user/ sudo chmod +x processor.py sudo yum -y install python3-pip sudo yum -y install python3 python3-setuptools pip3 install...
<python><amazon-web-services><shell><boto3><ec2-userdata>
2023-01-16 09:22:11
1
24,573
ERJAN
75,132,232
2,755,116
Why \n does not expand when read file but yes in built-in strings?
<ul> <li><p>If you run</p> <pre><code>tmpl = &quot;This is the first line\n And this is the second line&quot; print(&quot;tmpl) </code></pre> <p>you get</p> <pre><code> This is the first line And this is the second line </code></pre> <p>So you get a new line <em>expanded</em>.</p> </li> <li><p>But if you write in a fi...
<python><string><carriage-return>
2023-01-16 09:21:46
1
1,607
somenxavier
75,132,191
10,844,607
How to Grab All Globals as a Reference in Python?
<p>I'm working on a project that's written in Go and uses <a href="https://github.com/go-python/gpython/" rel="nofollow noreferrer">go-python</a> to run Python code inside. The way it works is you write <code>code.py</code> snippits, then the Go code throws in Global variables to use the internal API.</p> <p>i.e. <code...
<python><python-3.x><go><global-variables><go-python>
2023-01-16 09:17:13
3
5,694
Dr-Bracket
75,132,137
5,802,479
Web scraping LinkedIn job posts using Selenium gives repeated or empty results
<p>I am trying to get the job post data from LinkedIn using Selenium for a practice project.</p> <p>I am getting the list of job card elements and the job IDs and clicking on each of them to load the job post, and then obtaining the job details.</p> <pre><code>import time import pandas as pd from selenium import webdri...
<python><selenium><web-scraping><linkedin-api>
2023-01-16 09:10:10
2
686
Fleur
75,132,080
15,175,627
importing modules best practice
<p>I wrote a package with several modules</p> <pre><code>pkg/ β”œβ”€β”€ __init__.py β”œβ”€β”€ mod.py β”œβ”€β”€ mod_calc.py └── mod_plotting.py </code></pre> <p><code>mod.py</code> uses functions from <code>mod_calc.py</code> and <code>mod_plotting.py</code>, so in <code>mod.py</code> I use:</p> <pre class="lang-py prettyprint-override">...
<python><import><module>
2023-01-16 09:04:08
0
511
konstanze
75,131,507
8,282,898
compare response.text and string failed in python
<p>I have a mission to filter response whether it's a normal response or not.</p> <p>I should log the response if response.text is not<code>'&lt;Br&gt;No match&lt;br&gt;OK!!'</code>.</p> <pre class="lang-py prettyprint-override"><code>if not response.text == '&lt;Br&gt;No match&lt;br&gt;OK!!': logger.info('ERROR!!'...
<python><python-requests>
2023-01-16 07:59:41
0
985
Lazyer
75,131,492
13,638,219
Altair: custom format axis title in a Repeat
<p>Is there a way to access the label/title of a datum when using it in a Repeat?<br /> I would like to change the Y-axis title by applying a custom function to the default label (simple example below).<br /> I know I can change the columns in the dataframe or do a manual loop to get the result, but I wonder if there i...
<python><altair>
2023-01-16 07:57:50
0
982
debbes
75,131,490
1,668,622
Is there a way to wrap pygame.midi.Input.read() in an asynchronous task without polling or an extra thread?
<p>I have basically the following code and want to embed it in an <code>async</code> coroutine:</p> <pre><code>def read_midi(): midi_in = pygame.midi.Input(0) while True: if midi_in.poll(): midi_data = midi_in.read(1)[0][0] # do something with midi_data, e.g. putting it in a Queu...
<python><pygame><python-asyncio><midi>
2023-01-16 07:57:34
1
9,958
frans
75,131,418
13,708,824
Pulp - Constraints
<p>I'm essentially trying to emulate an excel problem in pulp, thus far I think that the problem was frame correctly, with the exception of the constraints, in essence, the constraints compare the demand for each flight with the estimated demand, that depends on one of the variables from solver</p> <p><a href="https://...
<python><pulp>
2023-01-16 07:47:52
0
399
Francisco Colina
75,131,158
1,436,800
It is impossible to add a non-nullable field 'name' to table_name without specifying a default
<p>I have added a following field in my already existing model:</p> <pre><code>name = models.CharField(max_length=128, unique=True) </code></pre> <p>But it is giving following prompt when applying migrations:</p> <pre><code> It is impossible to add a non-nullable field 'name' to table_name without specifying a default....
<python><django><django-models><django-rest-framework><django-views>
2023-01-16 07:14:13
3
315
Waleed Farrukh
75,131,112
16,295,405
How to install python3.10 virtual environment when python3.10-venv has no installation candidate?
<p>I had just upgraded to Ubuntu 22.04.1 LTS, which comes preinstalled with python3.10. I tried creating a virtual environment but it was unsuccessful. Trying to install the virtual env package gets an error <code>E: Package 'python3-venv' has no installation candidate</code></p> <pre><code>python3 -m venv newpy310 The...
<python><python-3.x><ubuntu><virtualenv>
2023-01-16 07:07:38
3
412
fatbringer
75,131,103
4,733,871
For loop does not update Python Pandas data-frame when importing data using SQL Alchemy
<p>I have a for loop that should update a pandas data frame from a postgres table that is updated by another thread every 5 seconds.</p> <p>if I run the code without the for loop I get what I want which is just the latest update time. However, if I run the code by using the for loop the results do not update and remain...
<python><dataframe><for-loop><sqlalchemy>
2023-01-16 07:06:25
2
1,258
Dario Federici
75,130,984
10,829,044
pandas dynamic wide to long based on time
<p>I have pandas dataframe that contains data given below</p> <pre><code> ID Q1_rev Q1_transcnt Q2_rev Q2_transcnt Q3_rev Q3_transcnt Q4_rev Q4_transcnt 1 100 2 200 4 300 6 400 8 2 101 3 201 5 301 7 401 9 </code></...
<python><pandas><dataframe><group-by><transformation>
2023-01-16 06:48:14
2
7,793
The Great
75,130,761
2,998,077
To find commonality/characteristics of in a group of lists
<p>A group of lists of equal length (strings as elements). I want to find out their commonality/characteristics.</p> <p>Let’s call them β€œgood” lists - I want to find out what makes a β€œgood” list.</p> <p>A thinking is to output all 3-element combination from each list, then summarize the occurrences of the 3-element to ...
<python><list>
2023-01-16 06:15:56
1
9,496
Mark K
75,130,738
19,238,204
Check Why Sympy in Python so Slow to Calculate Symbolic Integration for Sphere Surface Area
<p>is SymPy the only reliable package in Python to do symbolic integration? I try SymPy for Julia, and it can compute faster. Please check whether this code is efficient, or something wrong in it. Thanks all..</p> <p>It is just to prove that the surface of area of a sphere is the one and only 4 pi times r square.</p> <...
<python><sympy>
2023-01-16 06:12:46
1
435
Freya the Goddess
75,130,595
8,481,155
Cloud Function to retrieve attributes from PubSub - Python
<p>I created a GCP Cloud Functions which is triggered by a PubSub topic.</p> <pre><code>import base64 def hello_pubsub(event, context): pubsub_message = base64.b64decode(event['data']).decode('utf-8') print(pubsub_message) </code></pre> <p>I publish messages using the below command which triggers the Cloud Fun...
<python><google-cloud-platform><google-cloud-functions><google-cloud-pubsub>
2023-01-16 05:44:26
1
701
Ashok KS
75,130,303
1,306,186
Python - Detect type of private key (rsa/dsa/ecc)
<p>I have many private keys in a format looking like this:</p> <pre><code>-----BEGIN ENCRYPTED PRIVATE KEY----- ... -----END ENCRYPTED PRIVATE KEY----- </code></pre> <p>I would like to remove the passphrase from these keys using the python <code>PyCryptodome</code> lib. I do know the passphrase.<br /> However, I do not...
<python><pycryptodome>
2023-01-16 04:41:19
0
8,462
Zulakis
75,130,239
20,508,530
How to keep deleted rows from table in variable in Django
<p>I want to delete all the rows in a tables but before that I want to store the old data and do some operation between old and new data.</p> <p>This is what I have tried.</p> <pre><code>old_data = Rc.object.all() Rc.object.all().delete() # Now I fetch some api and apply saving operation on table </code></pre> <p>I hav...
<python><django>
2023-01-16 04:26:22
1
325
Anonymous
75,130,124
2,998,077
Search keys and read from multiple dictionaries
<p>Several dictionaries containing different keys and values.</p> <p>By looping a list of keys, I want to return their values in the dictionaries (when the key is available), and sum them.</p> <p>The problem is, some keys are not available in all the dictionaries.</p> <p>I need to come up with different IF statements, ...
<python><loops><dictionary><if-statement>
2023-01-16 03:57:25
4
9,496
Mark K
75,130,063
16,971,617
Filter numpy array base 1-0 mask
<p>Say I have a numpy ndarray of shape (172,40,20) and a 1-0 mask of shape (172, 40). I would like to do something similar to bitwise_and: to keep those values where the mask value is 1 while other values set to 0 where the mask value is 0.</p> <p>Is there a way that I can do without looping? for example</p> <pre class...
<python><numpy>
2023-01-16 03:42:46
2
539
user16971617
75,129,995
10,062,025
How to scrape a website based on response headers using requests?
<p>I am trying to scrape <a href="https://www.foodhall.co.id/grand-indonesia/catalog" rel="nofollow noreferrer">https://www.foodhall.co.id/grand-indonesia/catalog</a> . I found the api <a href="https://api.foodhall.co.id/v1/catalog/productbycategoryv2" rel="nofollow noreferrer">https://api.foodhall.co.id/v1/catalog/pro...
<python><python-requests>
2023-01-16 03:26:49
0
333
Hal
75,129,827
20,536,016
Failed to run /bin/build: for Python, an entrypoint must be manually set, either with "GOOGLE_ENTRYPOINT" env var or by creating a "Procfile" file"
<p>I'm trying to automate a CloudDeploy pipeline by following the instructions here:</p> <p><a href="https://davelms.medium.com/automate-gke-deployments-using-cloud-build-and-cloud-deploy-2c15909ddf22" rel="nofollow noreferrer">https://davelms.medium.com/automate-gke-deployments-using-cloud-build-and-cloud-deploy-2c159...
<python><google-cloud-platform><cicd><google-cloud-build><google-cloud-deploy>
2023-01-16 02:44:55
1
389
Gary Turner
75,129,826
17,696,880
Add letters with diacritics, and u with umlauts, to a pattern that captures strings tolerant of the rest of the letters
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;HabΓ­a... ; MartΓ­n ZΓ‘zza no se trata de un nombre&quot; #example 1 input_text = &quot;asasjhsah; Carolina MarΓ­a Sol no se tratarΓ­a de un nombre&quot; #example 2 input_text = &quot;IsaΓ­as no se tratarΓ­a de un nombre&quot; #example 3 word = &qu...
<python><python-3.x><regex><string><regex-group>
2023-01-16 02:44:46
0
875
Matt095
75,129,712
5,924,264
Interpolating column of first dataframe based on second dataframe
<p>Suppose that I have 2 dataframes <code>df1</code>:</p> <pre><code>col1 0 10 20 30 </code></pre> <p>and <code>df2</code>:</p> <pre><code>col1 val 0 0 5 2 15 4 25 5 33 8 </code></pre> <p>I want to compute <code>val</code> column for <code>df1</code> that is linearly interpolated fro...
<python><dataframe><interpolation>
2023-01-16 02:17:21
1
2,502
roulette01
75,129,600
11,919,198
Python Weird Scope
<p>Given the following:</p> <pre><code>a = 0 def func(): a += 2 print(a) func() print(a) </code></pre> <p>I get a <code>UnboundLocalError: local variable 'a' referenced before assignment</code> error. Fair enough, since <code>a</code> is local to <code>func</code>.</p> <p>However when remove the increment state...
<python><scope>
2023-01-16 01:43:59
2
334
doofus
75,129,097
7,575,552
IndexError: too many indices for array: array is 2-dimensional, but 4 were indexed
<p>I am training a multilabel VGG-16 based classification model. There are 25 labels for this task. I am trying to replicate this code at <a href="https://towardsdatascience.com/multi-label-classification-and-class-activation-map-on-fashion-mnist-1454f09f5925" rel="nofollow noreferrer">https://towardsdatascience.com/mu...
<python><tensorflow><keras><indexing>
2023-01-15 23:25:49
1
1,189
shiva
75,129,055
6,676,101
How can we convert an arbitrary iterable of iterables into a nested list of lists of strings?
<p>Suppose <code>obj</code> has an <code>__iter__()</code> method.</p> <p>We want to write a function which accepts <code>obj</code> as input and outputs a nested list of lists of lists .... of lists of strings.</p> <p>If an object is iterable, and is not a string, we recur.</p> <p>If an object is a string, we return t...
<python><python-3.x><recursion><tree>
2023-01-15 23:15:26
2
4,700
Toothpick Anemone
75,129,034
9,400,421
Is there a library in python to accomplish cross platform OS binary installation? Cross platform dependency installation via Python
<p>I often write Jupyter notebooks (python) and since you can execute them in Windows or Linux (and the many flavors thereof), when I have a dependency for the notebook's activity (like let's say the notebook is meant to demo a proof of concept for a Node.js module CVE), well I can execute a command to install that nod...
<python>
2023-01-15 23:11:01
0
847
J.Todd
75,128,970
6,676,101
How do I merge two objects into one?
<p>How can we create dynamically (procedurally.... at run-time) one new object from two old objects so that operations performed on the new object are performed on both of the two old objects?</p> <p>As just one example, we might have two streams:</p> <blockquote> <ol> <li>a string stream ... <code>str_strm = io.String...
<python><python-3.x><oop><wrapper>
2023-01-15 22:58:11
0
4,700
Toothpick Anemone
75,128,941
4,070,660
Gunicorn with django giving 500 with no extra information
<p>I am trying to run django 3.2.16 with gunicorn, I get this output in console:</p> <pre><code>[2023-01-15 23:45:39 +0100] [210935] [INFO] Starting gunicorn 20.1.0 [2023-01-15 23:45:39 +0100] [210935] [DEBUG] Arbiter booted [2023-01-15 23:45:39 +0100] [210935] [INFO] Listening at: http://0.0.0.0:8000 (210935) [2023-01...
<python><django><gunicorn><wsgi>
2023-01-15 22:50:36
1
1,512
K.H.
75,128,758
9,137,211
Django Path.home() giving servers directory instead of users home directory
<p>I am on a Django Project. Using version 4 and Python 3.10. I want to download file and my code is :</p> <pre><code>downloads_path = str(Path.home() / &quot;Downloads&quot;).replace('\\','/') if not os.path.isdir(f&quot;{downloads_path}/{str(row['CUSTOMER NAME'])}&quot;): os.makedirs(f&quo...
<python><django>
2023-01-15 22:13:50
0
335
Mayanktaker
75,128,656
3,611,472
Why do I get RecursionError in this implementation of sorted dictionary as Binary Search Tree?
<p>I am trying to implement a kind of sorted dictionary as a Binary Search Tree. The idea is that no matter what operation I do on this new dictionary-like object, the elements of the dictionary are always sorted with respect to the keys. My implementation is not complete - there are some issues of performance that I w...
<python><dictionary><recursion><binary-search-tree>
2023-01-15 21:50:46
0
443
apt45
75,128,633
4,709,889
Calculate percent of values based on column in dataframe
<p>I am trying to get the percent of values in a column based on a list of unique values in another column. My dataframe has the following structure:</p> <pre><code>property_state_code | converted -------------------------------- NY converted TX converted TX ...
<python><pandas>
2023-01-15 21:45:41
1
391
FrenchConnections
75,128,584
596,057
Compute shader won't write to texture
<p>I'm porting an application from Windows to Ubuntu 20.04 and none of my compute shaders will write to a texture. I've reproduced the problem in the following program. I initialize the texture to zeros and after the shader runs the texture is still filled with zeros.</p> <pre><code>import numpy import moderngl impor...
<python><glsl><compute-shader>
2023-01-15 21:37:32
1
1,638
HahaHortness
75,128,500
4,700,367
Relative path ImportError when trying to import a shared module from a subdirectory in a script
<p>I am trying to import a util package one directory up from where my code is, but I get an ImportError which I don't understand.</p> <p>I have a number of different variations on the import syntax in Python, none of which are working.</p> <p>There are a number of similar questions on Stack Overflow, but none have hel...
<python><python-3.x><python-import>
2023-01-15 21:24:02
1
438
Sam Wood
75,128,494
14,167,846
Subset a list in python on pre-defined string
<p>I have some extremely large lists of character strings I need to parse. I need to break them into smaller lists based on a pre-defined character string, and I figured out a way to do it, but I worry that this will not be performant on my real data. Is there a better way to do this?</p> <p>My goal is to turn this li...
<python><string><list><split>
2023-01-15 21:23:11
1
545
pkpto39
75,128,468
558,619
Conditionally including multiple keyword arguments in a function call
<p>What is the 'pythonic' way to implement a waterfall if-statement like situation like this, when it applies to <code>kwargs</code>? I'm trying to avoid a situation where <code>c=None</code> is added to <code>kwargs</code> (because having <code>c</code> in the <code>kwargs</code> keys causes all sorts of problems down...
<python>
2023-01-15 21:18:17
3
3,541
keynesiancross
75,128,463
104,910
macOS trusts Python whl files, but not tar files
<p>I provide my python c extension as both as a tar file, as well as a whl file.</p> <p>On macOS, I am surprised that there are no problems installing the wheel for my extension. When setting PYTHONPATH to my python extension in the tarball, I am immediately met with the dialog about unverified developers.</p> <p>Coul...
<python><macos><security><pip><shared-libraries>
2023-01-15 21:17:30
1
3,813
Juan
75,128,358
3,714,982
Pandas: Convert multiple columns in DataFrame from object to float
<p>To clean up data I want to convert several columns that should be numeric to numeric. Assignment of multiple columns has no effect.</p> <p>Minimal (non-)working example. The column 'S' is a string, 'D' and 'L' should be converted to numeric. The <code>dtypes</code> are <code>object</code> - as expected</p> <p>1)</p>...
<python><pandas>
2023-01-15 20:56:59
2
343
truschival
75,128,330
1,523,238
How do I read the local storage of my Safari Web Extension using Selenium in Python?
<p>With the Firefox WebDriver I can read the local storage of my extension like so:</p> <pre class="lang-py prettyprint-override"><code>extension_path = &quot;/path/to/my/extension&quot; info = { &quot;extension_id&quot;: f&quot;foobar&quot;, &quot;uuid&quot;: uuid.uuid4(), } base_url = f&quot;moz-extension://...
<javascript><python><selenium><safari><safari-web-extension>
2023-01-15 20:54:08
1
6,845
Oskar Persson
75,128,123
11,092,636
Is there a difference between torch.IntTensor and torch.Tensor
<p>When using PyTorch tensors, is there a point to initialize my data like so:</p> <pre><code>X_tensor: torch.IntTensor = torch.IntTensor(X) Y_tensor: torch.IntTensor = torch.IntTensor(Y) </code></pre> <p>Or should I just do the 'standard':</p> <pre><code>X_tensor: torch.Tensor = torch.Tensor(X) Y_tensor: torch.Tensor ...
<python><types><tensor><torch>
2023-01-15 20:16:29
2
720
FluidMechanics Potential Flows
75,128,113
10,817,571
Django GPU model deployed in Nivdia/Cuda container consumes all GPU memory
<p>I'm using an Nvidia/Cuda container to host my Django website. It's a new deployment of an old website that used to utilize CPU scored models. The rationale for using the Nivida/Cuda docker is to accelerate scoring speed when requesting an analysis through the Django interface.</p> <p>The difficulty I am running in...
<python><django><tensorflow><cuda><celery>
2023-01-15 20:14:53
1
591
C. Cooney
75,128,068
396,014
Can't get correct input for DBSCAN clustersing
<p>I have a node2vec embedding stored as a .csv file, values are a square symmetric matrix. I have two versions of this, one with node names in the first column and another with node names in the first row. I would like to cluster this data with DBSCAN, but I can't seem to figure out how to get the input right. I trie...
<python><scikit-learn><dbscan>
2023-01-15 20:08:38
1
1,001
Steve
75,127,956
14,391,210
ModuleNotFoundError and circular import
<p>I can't manage to import some functions in the files. Here is the structure</p> <pre><code>. β”œβ”€β”€ main.py β”œβ”€β”€ src β”‚ β”œβ”€β”€ mypandas.py β”‚ β”œβ”€β”€ labelling.py </code></pre> <p>Labelling uses class from mypandas and mypandas uses functions from labelling.</p> <p>Labelling imports mypandas as</p> <pre><code>import mypandas...
<python><import><modulenotfounderror>
2023-01-15 19:47:56
0
621
Marc
75,127,817
50,959
Using or reusing Wagtail StreamField blocks as Fields in other models
<p>I have a Wagtail project with two different <code>Page</code> models that use identical gallery blocks, but in different ways. In one model, I want to use the gallery in a list of other freeform blocks; but in the other model there is only one gallery appearing in a specific place on the page. The galleries are pret...
<python><wagtail><wagtail-streamfield>
2023-01-15 19:26:22
1
514
axoplasm
75,127,731
3,770,251
Given specifc pixel coordinates, get the color at the python
<p>Let's say i have an 800x600 image: <a href="https://i.sstatic.net/4FmR0.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4FmR0.jpg" alt="enter image description here" /></a></p> <p>and I have an HTML map element where it defines multiple poly areas(in this case only one is defined which is Tenessee):</...
<python><numpy><opencv><coordinates><object-detection>
2023-01-15 19:12:24
2
405
MOHAMMAD RASIM
75,127,383
1,449,982
How to remotely debug Python with IntelliJ?
<p>Is there a way for remotely debugging Python3 with IntelliJ? I couldn't find any options for it. With VS Code, it's as simple as having this file:</p> <h4>launch.json</h4> <pre><code> { &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Py...
<python><python-3.x><debugging><intellij-idea>
2023-01-15 18:20:12
1
8,652
Dima
75,127,370
12,248,328
How to get list of parent methods in VSCode?
<p>In PyCharm I can hit Ctrl/Cmd + O and it'll give me a modal with all methods I can override. What's the equivalent in VSCode?</p>
<python><visual-studio-code><vscode-python>
2023-01-15 18:18:29
0
423
Epic Programmer
75,127,347
15,537,675
Group pandas DataFrame on column and sum it while retaining the number of sumed observations
<p>I have a pandas Dataframe that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({'id':[1, 1, 2, 2], 'comp': [-0.10,0.20,-0.10, 0.4], 'word': ['boy','girl','man', 'woman']}) </code></pre> <p>I would like to group the dataframe on <code>id</code>, and calculate the sum of corresponding <code>comp...
<python><pandas><dataframe><group-by>
2023-01-15 18:16:03
1
472
OLGJ
75,127,295
12,851,199
How to solve a problem while trying install a pipenv with python 3.11?
<p>Preconditions:</p> <ul> <li>python 3.11</li> <li>pipenv 2022.12.19</li> </ul> <p>Problem: I want to create a new pipenv virtual environment for my project with command:</p> <pre><code>pipenv --python 3.11 </code></pre> <p>or</p> <pre><code>pipenv --python /usr/bin/python3.11 </code></pre> <p>I have the next error:</...
<python><pipenv><python-3.11>
2023-01-15 18:09:37
0
438
Vadim Beglov
75,126,908
9,494,140
how to change shape color using `simple_kml` in python
<p>I'm using <code>simple_kml</code> library to generate a kml file with data sent from <code>drawing manager</code> on google Maps using Javascript, everything goes fine except the color of the shape .. the color send in this format <code>#ec0909</code>, and here is how am trying to add it to the shape:</p> <pre class...
<python><kml><simplekml>
2023-01-15 17:14:29
2
4,483
Ahmed Wagdi
75,126,772
1,003,190
yolo v8: does segment contain point?
<p>I'm using yolo v8 to detect subjects in pictures. It's working well, and can create quite precise masks over subjects.</p> <pre class="lang-py prettyprint-override"><code>from ultralytics import YOLO model = YOLO('yolov8x-seg.pt') for output in model('image.jpg', return_outputs=True): for segment in output['se...
<python><pytorch><computer-vision><geometry><yolo>
2023-01-15 16:53:36
1
3,925
aspyct
75,126,685
9,715,163
Why doesn't numpy allow broadcasting when a dimenison of first array is a multiple of corresponding dimension of second array?
<p>Two dimensions are compatible when</p> <ul> <li>they are equal, or</li> <li>one of them is 1</li> </ul> <p>Can't they also be made compatible if one of them is a multiple of another?</p> <p>Consider the following example when shape of array A is (2,3) and shape of array B is (4,3):</p> <p><code>A = [[1,2,3], [4,5,6]...
<python><numpy>
2023-01-15 16:43:19
0
521
mangesh
75,126,565
11,170,350
Save ImageGrid without ploting it on jupyter notebook
<p>I am using following function to save ImageGrid, but i dont want to show it on jupyter notebook. How can i do that?</p> <pre><code>from mpl_toolkits.axes_grid1 import ImageGrid def save_img(hists,path): fig = plt.figure(figsize=(8, 8)) grid = ImageGrid(fig, 111, # similar to subplot(111) ...
<python><matplotlib><jupyter-notebook>
2023-01-15 16:24:26
1
2,979
Talha Anwar
75,126,554
4,589,608
Use lark to analyze reST markup language like sections
<p>I would like to define one basic grammar such as to start to work with <code>lark</code>. Here is my M(not)WE.</p> <pre class="lang-py prettyprint-override"><code>from lark import Lark GRAMMAR = r&quot;&quot;&quot; ?start: _NL* (day_heading)* day_heading : &quot;==&quot; _NL day_nb _NL &quot;==&quot; _NL+ (paragra...
<python><restructuredtext><lark>
2023-01-15 16:23:01
1
1,504
projetmbc
75,126,461
465,159
Dockerfile and multiple images (for github codespace)
<p>I am trying to set up a <code>.devcontainer.json</code> file to use in Github Codespace. What I want is to have a container which has the basic python image, plus the bazel image so that I can use bazel without having to install it any time I create a new workspace.</p> <p>How can I achieve this?</p> <p><strong>My c...
<python><docker><bazel><codespaces><github-codespaces>
2023-01-15 16:08:17
1
5,474
Ant
75,126,395
17,227,709
django Count aggregate is not working as I intended
<p>It's a code that reproduces the problem I experienced.</p> <p><strong>models.py</strong></p> <pre><code>from django.db import models class User(models.Model): pass class Group(models.Model): users = models.ManyToManyField( User, related_name='groups', ) class Notice(models.Model): ...
<python><django><orm><aggregate><annotate>
2023-01-15 15:58:21
1
343
gypark
75,125,728
10,844,937
Cannot get all the rows but can get all single row by using iloc?
<p>Today I have faced an issue while using <code>pandas</code>. The problem is very simple, <code>df.iloc[:][0]</code> gives me such error.</p> <pre><code> File &quot;C:\workspaces\venv\lib\site-packages\pandas\core\frame.py&quot;, line 3805, in __getitem__ indexer = self.columns.get_loc(key) File &quot;C:\works...
<python><pandas><dataframe>
2023-01-15 14:17:20
2
783
haojie
75,125,715
15,724,084
scrapy python cannot parse with condition
<p>With an assitance I have written a scipt in scrapy, which should previously read excel file -&gt; take plate number then put it <code>plate_num_xlsx</code> variable. Although for not being an empty I have assigned a value to it. But the logic is to take one by one the values from excel file column A with pandas th...
<python><scrapy>
2023-01-15 14:15:54
1
741
xlmaster
75,125,519
12,684,429
Monthly averages to daily granularity
<p>I have a dataframe which is monthly averages which looks like the following;</p> <pre><code> A B C D E 1 3 21 3 22 3 2 4 32 3 24 0 3 5 1 12 3 12 . . 11 5 4 9 85 85 3 12 43 4 48 3 84 4 </code></pre> <p>I'm looking to convert this data to a daily timeframe so that the dataframe would be a ...
<python><pandas><indexing><time-series><resample>
2023-01-15 13:47:02
2
443
spcol
75,125,468
6,054,404
Pandas concat() in Python 3.9 in a def returning the error: No objects to concatenate, while inline scripting there is no error
<p>Using Python 3.9 I have several pandas dataframes, each are stored within the <code>self.pointcloud.&lt;dict&gt;</code>. This looks something like the following, named after their date of capture:</p> <pre><code>self.pointcloud['20180712']['data'] self.pointcloud['20180713']['data'] self.pointcloud['20180714']['data...
<python><pandas><concatenation>
2023-01-15 13:38:41
0
1,993
Spatial Digger
75,125,364
7,347,925
How to use respective colorbar when using facet_col with plotly.express?
<p>I have a data which has three variables whose magnitudes are different.</p> <p>I'm trying to apply <code>animation_frame</code> and <code>facet_col</code> to make them animate at the same time.</p> <p>Here's the code:</p> <pre><code>import plotly.express as px import xarray as xr # Load xarray from dataset included...
<python><plotly><imshow>
2023-01-15 13:22:16
1
1,039
zxdawn
75,125,300
3,672,716
SQLAlchemy connect through specific network interface
<p>I have a client computer (now Windows 10, soon to be Ubuntu Server) connected through a LAN Ethernet interface to a remote DB server using SQLAlchemy. The same client holds a Wifi network interface connected to Internet in order to provide external access to the client. Within the client there is a Python script tha...
<python><linux><windows><network-programming><sqlalchemy>
2023-01-15 13:11:48
0
394
Alejandro QA
75,125,292
9,879,869
Plot existing covariance dataframe
<p>I have computed a covariance of 26 inputs from another software. I have an existing table of the results. See image below: <a href="https://i.sstatic.net/ZSAYI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZSAYI.png" alt="enter image description here" /></a></p> <p>What I want to do is enter the tab...
<python><pandas><plot><covariance-matrix>
2023-01-15 13:11:03
2
1,572
Nikko
75,125,236
18,937,024
Sqlalchemy does not return an model object with `session.scalars` on mapped objects
<pre class="lang-py prettyprint-override"><code>from attrs import define from sqlalchemy.orm import ( registry, ) from sqlalchemy.sql import ( schema, sqltypes, ) @define(slots=False) class Cat(): id: int name: str mapper_registry = registry() cat_table = schema.Table( &quot;cat&quot;, ...
<python><asynchronous><sqlalchemy><python-asyncio>
2023-01-15 13:00:10
1
341
LEv145
75,125,197
9,182,743
Remove/handle experimental type pd.NA pandas?
<p>I am unsure how to remove/handle pd.NA experimental data type, it is causing me problems, for example in the code snipped below, with pd.NA it functions differently:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np print (pd.__version__) print (&quot;with pd.nan --&gt; wor...
<python><pandas>
2023-01-15 12:52:23
0
1,168
Leo
75,125,180
13,345,744
How to manipulate Pandas Series without changing the given Original?
<p><strong>Context</strong></p> <p>I have a method that takes a Pandas Series of categorial Data and returns it as an indexed version. However, I think my implementation is also modifying the given Series, not just returning a modified new Series. I also get the following Errors:</p> <blockquote> <p>A value is trying t...
<python><pandas><numpy><data-science><series>
2023-01-15 12:49:26
1
1,721
christophriepe
75,125,121
13,550,050
Python initialize class with list/mutable attribute
<p>If I want to initialise a class which has a list attribute, then I can directly assign an list to the attribute in the class <strong>init</strong>.</p> <p>Doing this however would just be an assignment of list reference, and my class attribute would be changed if I update the original list.</p> <p>What is the best w...
<python><class><initialization>
2023-01-15 12:39:53
2
369
crixus
75,125,081
8,995,741
Matplotlib: Rotating labels on lower half of pie chart and repositioning text labels
<p>I am using the following code to create the attached visualization:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.textpath import TextPath from matplotlib.patches import PathPatch fig = plt.figure(figsize=(6, 6)) ax = fig.add_axes([0, 0, 1, 1], aspect=1) size = 0.1 params = [ ...
<python><matplotlib>
2023-01-15 12:32:44
1
1,439
slothfulwave612
75,125,071
16,169,533
Extend list with another list in specific index?
<p>In python we can add lists to each other with the extend() method but it adds the second list at the end of the first list.</p> <pre><code>lst1 = [1, 4, 5] lst2 = [2, 3] lst1.extend(lst2) Output: [1, 4, 5, 2, 3] </code></pre> <p>How would I add the second list to be apart of the 1st element? Such that the result i...
<python><arrays><python-3.x><list>
2023-01-15 12:30:43
3
424
Yussef Raouf Abdelmisih
75,125,034
2,302,244
Getting the query string out of an rdflib prepared query
<p>How do I recover the original string from an <code>rdflib</code> preparedQuery.</p> <p>In other words,</p> <pre class="lang-py prettyprint-override"><code>query_string = &quot;select ?s {?s ?p ?o.}&quot; q = prepareQuery(query_string) </code></pre> <p>I would like to run some function against <code>q</code> to recov...
<python><rdflib>
2023-01-15 12:22:53
1
935
user2302244
75,124,894
361,455
Linking errors when using setuptools
<p>I am extending C++ library with functionality that requires GRPC. GRPC dependencies are added through VCPKG (example from CMakeLists.txt):</p> <pre><code>find_package(gRPC CONFIG REQUIRED) target_link_libraries( mylib PRIVATE gRPC::grpc++) </code></pre> <p>Now, that same library has python bindings (where I ent...
<python><c++><grpc><setuptools><vcpkg>
2023-01-15 11:58:09
0
8,318
Klark
75,124,867
12,057,138
How can I either use arguments or constructor values in a python class
<p>I have a python class and a main function next to it so I can execute it from command line. My <strong>init</strong> function deals my provided arguments:</p> <pre><code>import argparse class Tester: def __init__(self): self.args_parser = argparse.ArgumentParser(description='Test') self.args = ...
<python>
2023-01-15 11:53:10
2
688
PloniStacker
75,124,795
2,105,338
Looping over and mapping slices of a DataArray in xarray
<p>Say I have a multidimensional DataArray and I would like to loop over slices according to some dimension and change them. For example, the first dimension is time and I would like for each time to receive a DataArray that represents a slice of that time and map it to a different DataArray of the same size.</p> <p>I ...
<python><numpy><data-science><python-xarray>
2023-01-15 11:43:46
1
2,286
davegri
75,124,624
5,353,753
Comparing two dataframes if one contains the other
<p>I have two dataframes <code>A</code> and <code>B</code>. For example:</p> <p>A:</p> <pre><code>Key | Col1 | Col2 A aa bb B bb bc C cc bd </code></pre> <p>B:</p> <pre><code>Key | Col1 | Col2 A a b B ab c C cc b </code></pre> <p>Both have one unique...
<python><pandas><dataframe>
2023-01-15 11:13:45
2
40,569
sagi
75,124,580
9,218,680
Creating a new df joining two data frames (iterating each row) with multiple conditions
<p>I have a couple of decent sized dataframes that look like:</p> <p><strong>df_B</strong></p> <pre><code>id start_time end_time side cost 1234 2021-01-01 16:00:00.100000 2021-01-01 16:02:00.100000 BUY 100 1564 2021-01-01 16:05:00.100000 2021-01-01 16:10:0...
<python><pandas>
2023-01-15 11:06:03
2
2,510
asimo
75,124,417
4,371,803
Python Selenium: send keys to tag 'input type="hidden" '
<p>I try to log in to this web page with my credentials.</p> <p><a href="https://www.oddsportal.com/login" rel="nofollow noreferrer">https://www.oddsportal.com/login</a></p> <p>I am able to get the &quot;username&quot; and &quot;password&quot; input boxes but I am not able to send the data.</p> <p>Selenium locates the ...
<python><selenium><hidden><sendkeys><clickable>
2023-01-15 10:37:41
4
689
daniel2014
75,124,341
3,716,664
PySide6 - high datarate from DLL to QTableWidget
<p>I have a python (3.11) project with PySide6. Application connects to DLL for CAN communication with other nodes. As part of configuration, approx 50-70 CAN messages are sent in short timeframe (but I added delays up to 50ms per message) and still see data loss.</p> <p>A DLL callback function properly receives all pa...
<python><qt><pyqt><pyside6>
2023-01-15 10:21:49
1
7,472
unalignedmemoryaccess
75,124,041
764,195
asyncio or threads for long running background tasks
<p>I'm a relative python noob so apologies if this is a stupid question, but what is the best approach for handling long-running background jobs? So the basic premise of what I'm trying to achieve</p> <ul> <li>Web app running FastAPI handles all user &quot;interaction&quot;</li> <li>Background task responsible for stre...
<python><multithreading><python-asyncio>
2023-01-15 09:17:27
0
4,448
PaReeOhNos
75,123,988
7,800,760
SPARQLWrapper query error with an f-string : QueryBadFormed
<p>I am trying to lookup the names of Italian Senators in a public SPARQL endpoint.</p> <p>Starting sample data is the following set:</p> <pre class="lang-py prettyprint-override"><code>longnames = ['Lars Danielsson', 'Giorgia Meloni', 'Ursula von der Leyen', 'Filippo Mannino', 'Matteo Piantedosi', 'Lamberto Giannini']...
<python><sparql><f-string><sparqlwrapper>
2023-01-15 09:07:48
0
1,231
Robert Alexander
75,123,754
7,865,368
How to filter child element by putting condition on another child element in XML
<p>In below XML, I need to extract the <code>BinaryImage</code> if the <code>ImageType</code> is <code>fullimage</code>.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope...
<python><xml><xpath><lxml>
2023-01-15 08:14:13
2
6,252
Vishal Singh
75,123,646
13,087,576
Understanding fancy einsum equation
<p>I was reading about attention and came across this equation:</p> <pre class="lang-py prettyprint-override"><code>import einops from fancy_einsum import einsum import torch x = torch.rand((200, 10, 768)) y = torch.rand((20, 768, 64)) res = einsum(&quot;batch query_pos d_model, n_heads d_model d_head -&gt; batch que...
<python><torch><array-broadcasting><einops><einsum>
2023-01-15 07:46:24
1
307
Sai Prashanth
75,123,599
1,521,585
problem with adding javascript to django view form update
<p>I have a django view to add an invoice to my application, that has added javascript, and it works fine.</p> <pre><code>&lt;p&gt; &lt;label for=&quot;id_total_without_vat&quot;&gt;Price&lt;/label&gt; &lt;input type=&quot;number&quot; name=&quot;total_without_vat&quot; step=&quot;any&quot; required=&quot;&quot...
<javascript><python><django>
2023-01-15 07:37:25
1
350
Daniel Ben-Shabtay
75,123,539
17,347,824
Nested SQL Queries using multiple tables and pymssql in Python
<p>I have 2 tables with information about contestant races that I need to organize into one clean output statement (not a tuple or list) that only gives each unique contestant along with their region, average race time, and a count of how many races they competed in.</p> <p>Using <code>&quot;SELECT TABLE_NAME, COLUMN_N...
<python><sql><pymssql>
2023-01-15 07:21:30
1
409
data_life
75,123,366
3,135,025
Pandas concat with outer join - Reindexing only valid with uniquely valued Index objects
<p>I have 6 dataframes that contain information about unique customers like one df for emails the second one for first name .. etc</p> <p>I am doing concat with outer join to have one df with all customer and information columns.</p> <p>This is what I did so far:</p> <pre><code>info_dfs = (df1,df2,df3,df4,df5,df6) </co...
<python><python-3.x><pandas><numpy><concatenation>
2023-01-15 06:37:02
1
1,842
MTALY