QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
78,003,563
11,330,134
Add column to Pandas dataframe based on dictionary lookup multiplication then sum
<p>I have a sample dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'id' : [1 ,2, 3], 'pts': [25,20,9], 'ast': [8, 14, 7], 'reb': [1, 4, 9], 'oth': [5,6,7], 'tov': [4, 2, 1] }) print(df) id pts ast reb oth tov 0 1 25 8 1 5 4 1 2 20 14 4 6 ...
<python><pandas>
2024-02-15 19:43:58
4
489
md2614
78,003,363
5,790,653
How to use join method for a list of dictionaries and then add a string for the value
<p>This is a list of dicts:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ {'unique_id': '1qaz2wsx', 'db_id': 10}, {'unique_id': '2qaz2wsx', 'db_id': 20}, {'unique_id': '3qaz2wsx', 'db_id': 30}, {'unique_id': '4qaz2wsx', 'db_id': 40}, ] </code></pre> <p>I'm trying to have like this as exp...
<python>
2024-02-15 19:06:04
3
4,175
Saeed
78,003,276
1,554,020
How to generate uniformly distributed subintervals of an interval?
<p>I have a non-empty integer interval <em>[a; b)</em>. I want to generate a random non-empty integer subinterval <em>[c; d)</em> (where <em>a &lt;= c</em> and <em>d &lt;= b</em>). The <em>[c; d)</em> interval must be uniformly distributed in the sense that every point in <em>[a; b)</em> must be equally likely to end u...
<python><algorithm><random><distribution>
2024-02-15 18:48:58
2
14,259
yuri kilochek
78,003,185
14,775,478
How to properly instantiate an empty pandas Series for "any" dtype in version 2.2.0?
<p>Pandas <code>2.2.0</code> raises a FutureWarning <code>Setting an item of incompatible dtype is deprecated</code>.</p> <p>While this sounds like a helper to avoid possible type casting issues, it's actually introducing a new problem if you want to initialize an empty Series and only later fill it, for example by cop...
<python><pandas>
2024-02-15 18:33:51
2
1,690
KingOtto
78,003,119
8,737,016
Allow multiple Ray workers to fill a common queue which can be accessed from the main thread
<p>I have a <code>DataGenerator</code> class</p> <pre class="lang-py prettyprint-override"><code>@ray.remote class DataGenerator: def generate_continuously(self): while True: time.sleep(5) data = random.rand() # I need data to be put into a queue common to all instances ...
<python><ray>
2024-02-15 18:22:00
1
2,245
Federico Taschin
78,003,018
759,880
Plotting histograms with pandas DataFrame
<p>I am trying to plot feature distributions per label value for a ML project, but I'm not getting the plot I want.</p> <p>I'm doing:</p> <pre><code>import pandas as pd import numpy as np x1 = np.random.randn(1000) x2 = np.random.randn(1000) y = np.random.randint(0,2,size=1000) df = pd.DataFrame({'x1':x1, 'x2':x2, 'y'...
<python><pandas><dataframe>
2024-02-15 18:04:49
2
4,483
ToBeOrNotToBe
78,002,829
11,092,636
lru_cache vs dynamic programming, stackoverflow with one but not with the other?
<p>I'm doing this basic dp (Dynamic Programming) problem on trees (<a href="https://cses.fi/problemset/task/1674/" rel="nofollow noreferrer">https://cses.fi/problemset/task/1674/</a>). Given the structure of a company (hierarchy is a tree), the task is to calculate for each employee the number of their subordinates.</p...
<python><time-complexity><space-complexity>
2024-02-15 17:30:43
1
720
FluidMechanics Potential Flows
78,002,577
15,411,076
How to dynamically modify Airflow task decorator attributes?
<p>I want my extractor task to use a string variable to set the <code>pool</code>.</p> <p>I realised I can do it like this:</p> <pre><code>@task(pool=&quot;my_pool&quot;) def extractor_task(**kwargs): </code></pre> <p>But how can I do it dynamically, or how can I access those attributes and change them? Because I canno...
<python><airflow>
2024-02-15 16:53:27
1
349
Doraemon
78,002,573
22,054,564
Unable to print the website status after the 1st URL in the given list using Python code
<p>This is the Python file that checks the given CSV file that contains the web url's and their status is ok or not found:</p> <pre class="lang-py prettyprint-override"><code>import csv import requests from http import HTTPStatus from fake_useragent import UserAgent def get_websites(csv_path: str) -&gt; list[str]: ...
<python><python-3.x><azure><csv>
2024-02-15 16:53:06
0
837
VivekAnandChakravarthy
78,002,555
14,250,641
How to train Random Forest classifier with large dataset to avoid memory errors in Python?
<p>I have a dataset that is 30 million rows. I have two columns: one that contains a 1 or 0 label and the other column has a list of 1280 features for each row (181 GB total). All I want to do is plug this dataset into a Random Forest algorithm, but the memory runs out and it crashes (I've tried using memory of 400 GB,...
<python><pandas><numpy><performance><scikit-learn>
2024-02-15 16:50:25
2
514
youtube
78,002,459
2,990,379
Determine if a Python string contains any kind of quote character
<p>I need to write a regex that will determine if a string contains any kind of single or double quotation mark character, including the specialty ones that you find in Word etc. Is there a list somewhere of what all the special characters are that a human would read as an opening or closing single or double quote, and...
<python><regex>
2024-02-15 16:35:19
1
1,281
PurpleVermont
78,002,134
9,545,165
Django REST Framework: static file serve does not work only when the url is "static/"
<p>I have the following <code>urls.py</code> -</p> <pre><code>urlpatterns = [ path('admin/', include(&quot;admin.urls&quot;)), path('accounts/', include(&quot;accounts.urls&quot;)), path('blogs/', include(&quot;blogs.urls&quot;)), ] + static(settings.S...
<python><django><django-rest-framework>
2024-02-15 15:47:54
0
312
Muhib Al Hasan
78,002,075
12,400,088
Fitz removes page when inserting text
<p>I have a 2-page PDF, and when I try to insert text onto the last page, the page is getting removed. I believe the error is related to the PDF itself as the behavior is not consistent across all PDFs. But I am not sure what could be causing Fitz to remove the page.</p> <p>The code to add text is as follows:</p> <pre>...
<python><python-3.x><pymupdf>
2024-02-15 15:39:08
0
588
kravb
78,002,011
8,414,030
Understanding Scrapy Python: Refactoring parse method does not work
<p>I have a spider code that works.</p> <pre class="lang-py prettyprint-override"><code>class MySpider(BaseScrapper): name = &quot;my_spider&quot; def parse(self, response, **kwargs): self.logger.info(f&quot;Parse: Processing {response.url}&quot;) yield ScrapyItem( source=response....
<python><python-3.x><scrapy>
2024-02-15 15:30:05
1
791
inquilabee
78,001,923
3,375,695
Extend python enum in __new__ with auto()
<p>I have a question related to using auto() with python enum.</p> <p>I have a base clase like this:</p> <pre><code>class TokenEnum(IntEnum): def __new__(cls, value): member = object.__new__(cls) # Always auto-generate the int enum value member._value_ = auto() # &lt;&lt; not working !! ...
<python><enums><auto>
2024-02-15 15:18:36
1
891
Juergen
78,001,855
8,118,238
How to convert cftime to unix timestamp?
<p>I am looking for some convenient way to convert time in cftime format available in netcdf files to unix timestamp(ms), what is a suitable way to do this without several <code>for</code> loops, of extracting date and time string followed by <code>datetime</code> type conversion in python, and few other steps to final...
<python><datetime><timestamp><python-xarray><netcdf4>
2024-02-15 15:10:11
1
593
hillsonghimire
78,001,815
14,114,654
generate col of the first index position until the value changes
<p>I have a df of fruits</p> <pre><code> fruit 0 apple 1 apple 2 apple 3 banana 4 apple 5 pear </code></pre> <p>How could I create indexy -- the first index position +1 until the value changes?</p> <pre><code> fruit indexy 0 apple 1 1 apple 1 2 apple 1 3 banana 4 4 a...
<python><pandas><group-by>
2024-02-15 15:04:06
1
1,309
asd
78,001,753
1,606,022
multivariate derivatives in jax - efficiency question
<p>I have the following code which computes derivatives of the function:</p> <pre class="lang-py prettyprint-override"><code>import jax import jax.numpy as jnp def f(x): return jnp.prod(x) df1 = jax.grad(f) df2 = jax.jacobian(df1) df3 = jax.jacobian(df2) </code></pre> <p>With this, all the partial derivatives a...
<python><jax>
2024-02-15 14:54:26
1
1,249
mrkwjc
78,001,750
9,506,773
Error adding skillset to Azure Search Indexer
<p>I am trying to add a custom skillset to my indexer. I am however facing some issues which I don't know how to solve. My skills:</p> <pre class="lang-py prettyprint-override"><code># https://learn.microsoft.com/en-us/python/api/azure-search-documents/azure.search.documents.indexes.models.splitskill?view=azure-python ...
<python><azure-cognitive-search><azure-python-sdk>
2024-02-15 14:54:12
1
3,629
Mike B
78,001,691
3,070,181
Tkinter How to set focus from a function
<p>I am trying to set the focus to <em>entry_1</em> in a function, but <em>entry_2</em> gets the focus. What's wrong?</p> <pre><code>import tkinter as tk def _test_entry(event): if value_1.get() == 'a': entry_1.focus_set() win = tk.Tk() win.geometry(&quot;200x100&quot;) value_1 = tk.StringVar(value='')...
<python><tkinter>
2024-02-15 14:44:59
0
3,841
Psionman
78,001,538
5,571,914
populate pandas dataframe using csv file
<p>I have two files:</p> <p>File1: An empty dataframe with only a header. (the data frame I wish to populate)</p> <pre><code>item A B C D E F G H </code></pre> <p>File2: A CSV file with space-delimited elements with uneven column numbers</p> <pre><code>item1 A B D F item2 A B C D E item3 A H I item4 C D E F G item5 K...
<python><pandas>
2024-02-15 14:23:26
3
669
Arun
78,001,480
3,828,463
Passing a modifiable two dimensional array from Python to Fortran
<p>In a previous post <a href="https://stackoverflow.com/questions/77989853/ctypes-argumenterror-dont-know-how-to-convert-parameter-1">ctypes.ArgumentError Don&#39;t know how to convert parameter 1</a>, I received a solution for passing a modifiable one dimensional array from Python to Fortran, which is (the first argu...
<python><fortran>
2024-02-15 14:12:57
1
335
Adrian
78,001,467
22,221,987
How to use decorator, defined inside the class, with no warnings
<p>I've defined decorator inside the class and trying to use it in the same class.<br /> I've created the decorator according to <a href="https://stackoverflow.com/questions/1367514/how-to-decorate-a-method-inside-a-class">this</a> topic. But PyCharm tells me, that this is veeery sus way to do this.<br /> Here is the c...
<python><python-3.x><exception><decorator>
2024-02-15 14:10:23
1
309
Mika
78,001,435
3,575,623
Remove central noise from image
<p>I'm working with biologists, who are imaging DNA strands under a microscope, giving greyscale PNGs. Depending on the experiment, there can be a lot of background noise. On the ones where there is quite little, a simple threshold for pixel intensity is generally enough to remove it. However for some, it's not so simp...
<python><image><png><noise>
2024-02-15 14:04:54
1
507
Whitehot
78,001,405
9,582,542
Selenium click on div text that is a variable
<p>I have an array of strings that varies and some strings have an apostrophe</p> <pre><code>array = [&quot;It's a Joke&quot;, &quot;It's not a Joke&quot;,&quot;No more Jokes please&quot;] strNo = 0 if (strNo == 0): rpstring = array[strNo] print(f'&quot;&quot;&quot;//div[text()=&quot;{rpstring}&quot;]&quot;&quo...
<python><selenium-webdriver>
2024-02-15 14:00:37
1
690
Leo Torres
78,001,359
10,037,034
Flask app not return any response when raising error (python)
<p>I am building a Flask API in Python. When a function inside the API throws an error, the server does not return any response. I have tried using try-except blocks and print statements to debug the issue, but I am still unable to resolve it.</p> <p>Here is some relevant code:</p> <pre><code>import json from flask imp...
<python><json><flask>
2024-02-15 13:53:21
1
1,311
Sevval Kahraman
78,001,058
8,760,028
How to remove multiple values from a tuple in python
<p>I have a tuple which is an output of a select query. The tuple looks like this:</p> <p><code>('checkStatus id \n========================= ==================== \nfalse adcs-fddf-sdsd \n', None)</code></p> <p>I am trying to retrieve only the two values i.e. false and adcs-fddf-sdsd</p> <p>This is the code...
<python>
2024-02-15 13:10:41
2
1,435
pranami
78,001,042
19,356,117
How to solve duplicated lists in numpy 1.24?
<p>Now I have a 2-dimensional list which have many duplicated lists in it:</p> <pre><code>sta_list = [[31, 30, 11, 3, 1, 0], [31, 30, 11, 3, 1, 0], [31, 30, 11, 3, 1, 0], ……, [31, 30, 11, 3, 1, 0], [31, 30, 11, 3, 1, 0], [34, 33, 1, 0], ……] </code></pre> <p>In numpy 1.22, I can use np.unique to remove duplicated lists ...
<python><arrays><numpy>
2024-02-15 13:08:08
2
1,115
forestbat
78,001,004
10,590,609
Typehint the type of a collection and the collection itself
<p>Say I want to collect and iterable into another type in the collect method:</p> <pre class="lang-py prettyprint-override"><code>from typing import Generic, TypeVar, Collection from dataclasses import dataclass T = TypeVar(&quot;T&quot;) @dataclass class Example(Generic[T]): data: list[T] def collect(se...
<python><generics><python-typing>
2024-02-15 13:02:34
1
332
Izaak Cornelis
78,000,943
7,408,848
In Mongoengine add a document and update a reference field in another document
<p>I have two documents and I would like to link together through a reference Field using the _ID. The idea was to create the documents, save them to the database, take the _ID information and append it to a reference list of another document. As the documents will be created at different times, I cannot have both esta...
<python><mongoengine>
2024-02-15 12:54:09
1
1,111
Hojo.Timberwolf
78,000,812
11,913,986
Map columns of two df based on array intersection of individual columns and based on highest common element Pandas Memory error Pyspark/Pandas
<p>I have a dataframe df1 like this:</p> <pre><code>A B AA [a,b,c,d] BB [a,f,g,c] CC [a,b,l,m] </code></pre> <p>And another one as df2 like:</p> <pre><code>C D XX [a,b,c,n] YY [a,m,r,s] UU [e,h,I,j] </code></pre> <p>I want to find out and map column C of df2 with column A of df1 based on the highest element m...
<python><pandas><dataframe><list><pyspark>
2024-02-15 12:35:18
1
739
Strayhorn
78,000,787
1,866,775
How to obtain a 2d transformation matrix from two pairs of points?
<p>OpenCV provides:</p> <ul> <li><code>getRotationMatrix2D</code> to get a 2x3 transformation matrix (rotation, scale, shift) defined by <code>center</code>, <code>angle</code> and <code>scale</code></li> <li><code>getAffineTransform</code> to get a 2x3 transformation matrix (rotation, scale, shift, sheer) defined by t...
<python><opencv><computer-vision><linear-algebra><affinetransform>
2024-02-15 12:30:08
1
11,227
Tobias Hermann
78,000,777
9,173,710
Improve scipy.integrate.quad_vec performance for fitting integral equation, workers keyword non-functional
<p>I am using <code>quad_vec</code> in a function that contains an integral not solvable with analytic methods. I need to fit this equation to data points.</p> <p>However, even the evaluation with fixed values takes multiple seconds, the total fit time grows to 7 min.</p> <p>Is there a way to accelerate the computation...
<python><performance><scipy><curve-fitting>
2024-02-15 12:28:53
1
1,215
Raphael
78,000,614
9,582,542
Press button when class name changes using Selenium and the text has an apostrophe
<p>This is a similar question to a prior question but the previous method wont work if the text has an apostrophe in the string. I need to click the this class with changing value.</p> <pre><code>&lt;div class=&quot;x1g731 xwtio9w y99xum8 x168nmei x13lgxp2 x5pf9jr xo71vjh r7s2etuq x1plvlek xstyops x1iyjqo2 x2lwn1j xeuu...
<python><selenium-webdriver>
2024-02-15 12:01:04
1
690
Leo Torres
78,000,602
567,059
Get the total count of 1 field of a list of namedtuple objects
<p>In Python, what is the easiest way to get the total count of one field from a set of named tuples?</p> <p>In this example, I'm looking for the total count of <code>TestResults.failed</code>, which should be 4. It's doable with a <code>for</code> loop, but it feels like there could be a more efficient way.</p> <pre c...
<python><namedtuple>
2024-02-15 11:58:49
1
12,277
David Gard
78,000,520
22,538,132
ERROR: failed to solve: process "/bin/sh -c python3
<p>I'm getting an error when I try to run a python script <code>docker build -t my_img .</code> inside a Dockerfile while building the image:</p> <pre class="lang-dockerfile prettyprint-override"><code>FROM nvidia/cuda:11.7.1-cudnn8-runtime-ubuntu20.04 ENV DEBIAN_FRONTEND noninteractive # setup timezone RUN echo 'Etc...
<python><docker><shell><dockerfile>
2024-02-15 11:47:28
0
304
bhomaidan90
78,000,451
353,337
Construct all `r`-tuples with two nonzeros
<p>Given an int value <code>val</code> and a tuple length <code>r</code>, I need to create all <code>r</code>-tuples that have <code>d</code> of <code>{+val, -val}</code> and the rest filled up with zeros. With <code>d=2</code>, I can do</p> <pre class="lang-py prettyprint-override"><code>val = 7 r = 5 out = [] for i...
<python><permutation><python-itertools>
2024-02-15 11:35:49
2
59,565
Nico Schlömer
78,000,267
2,473,382
Mock `__setitem__ ` of a subclass of dict
<p>I am trying to subclass a dict, and making sure that <code>__setitem__</code> is called when a new item is added.</p> <p>I do know that <code>__setitem__</code> is called (if I add <code>1/0</code> I see it), but I cannot confirm it from my unit tests. I have this behaviour if I inherit from <code>dict</code> and <c...
<python><python-3.x><mocking><pytest>
2024-02-15 11:05:18
0
3,081
Guillaume
78,000,266
22,221,987
How to make a simple C server, which accept only one connection at the same time
<p>I'm trying to make a simple C server (for testing my python clients). The main rule is that server must accept only one connection at the same time. Server should work like the loop with <code>accept</code> function in it. Server should accept or reject clients. If client is accepted, server should continue listenin...
<python><c><python-3.x><sockets><tcp>
2024-02-15 11:05:11
0
309
Mika
78,000,249
1,908,482
Uni-modal vs Multi-modal models - how to pick best fit
<p>My goal is to create a model of a data distribution. I want to pick the best model however I am not sure how to compare the obtained models.</p> <p>For uni-modal distribution I used the Fitter library. For multi-modal I tried Gaussian Mixture Models. Both models output aic/bic.</p> <p>In Fitter the information crite...
<python><model-fitting><gaussian-mixture-model>
2024-02-15 11:01:45
1
2,390
Eugen
78,000,094
16,707,518
Combinations of all possible values from single columns
<p>I've tried to find this specific question answered but not had any luck. Suppose I have a pandas dataframe with the following columns:</p> <pre><code>A B C 1 2 3 4 5 6 </code></pre> <p>All I'm trying to achieve is a new dataframe that has all combinations of the unique values in the individual columns themselves, so...
<python><pandas><dataframe><combinations>
2024-02-15 10:38:52
1
341
Richard Dixon
77,999,955
893,254
The Python jsons library produces duplicated serialized output with underscores prepended to the field names. Can this be prevented?
<p>The original title of this question was going to be</p> <p><em><strong>Why does the Python <code>jsons</code> library produce serialized output with underscores prepended to the field names?</strong></em></p> <p>However while writing the question I realized why this is happening. Now the question has become more abo...
<python><json><python-jsons>
2024-02-15 10:17:58
1
18,579
user2138149
77,999,789
10,639,382
Finding standard deviation and mean for Normalize function from torchvision
<p>I am wondering how to find the mean and standard deviation for lets say 3 images. This is to be used as inputs to the <code>Normalize</code> function in Pytorch (<code>from torchvision.transforms import Normalize</code>).</p> <p>In the particular dataset I work, the 3 color channels are in separate tif files. As it ...
<python><pytorch><computer-vision><normalization>
2024-02-15 09:52:49
1
3,878
imantha
77,999,731
501,663
Keras/Tensorflow have slightly different outputs on different CPU architectures
<p>I know similar questions were asked in the past, for example <a href="https://stackoverflow.com/questions/69729241/is-it-normal-that-model-output-slightly-different-on-different-platforms">Is it normal that model output slightly different on different platforms?</a>, and there are more.</p> <p>I am fully aware to di...
<python><tensorflow><keras>
2024-02-15 09:43:43
2
9,665
Itamar Katz
77,999,455
391,161
Is it possible to wait for a key release and then consume the remainder of stdin in Python?
<p>My goal is to have a program that waits for a key to be released, and then consumes standard input so that the next program to run in a script does not pick up the input that was emitted by the key being held down.</p> <p>Currently, I've cobbled together a script based on a combination of these <a href="https://stac...
<python><linux>
2024-02-15 08:59:20
0
76,345
merlin2011
77,999,362
619,609
I'm unable to find a type for aws s3 event notifications in python
<p>I am working in python and have a code that receives s3 event notifications via an SQS. I'm trying to find existing type support (for type hints and parsing using pydantic) for events such as s3:ObjectCreated - I would assume something must exist in libraries such as types_aiobotocore_s3, but I'm unable to locate a ...
<python><amazon-web-services><amazon-s3><types><boto3>
2024-02-15 08:43:33
2
404
Anorflame
77,999,148
1,307,231
How can I make back/forward history navigation not care about cursor position in VS Code interactive windows?
<p>When working with Python Interactive windows in VS Code, I find the following behaviour irritating:</p> <p>When typing commands into the field at the bottom (where it says &quot;Type 'python' code here and press Enter to run), these commands are added to some sort of history. Using Cursor-Up and Cursor-Down I can go...
<python><visual-studio-code><keyboard-shortcuts>
2024-02-15 07:57:33
1
581
mcenno
77,999,061
17,501,206
Python mmap return Invalid argument
<p>I tried to use <code>mmap</code> in Python</p> <pre><code>import mmap import sys f = open(sys.argv[1]) off = int(sys.argv[2]) mm = mmap.mmap(f.fileno(),length=0,access=mmap.ACCESS_READ,offset=off ) </code></pre> <p>When off =0 that works fine .</p> <p>But when off equal to any number (100 for example) I got <code>OS...
<python><python-3.x><mmap>
2024-02-15 07:38:03
1
334
vtable
77,999,057
13,987,643
atexit registered function unable to access streamlit session state variable
<p>I have registered an atexit function like this:</p> <pre><code>import streamlit as st from azure.search.documents.indexes import SearchIndexClient from azure.core.credentials import AzureKeyCredential @atexit.register def delete_vector_index(): admin_client = SearchIndexClient(endpoint=st.session_state.vector...
<python><azure><function><streamlit><atexit>
2024-02-15 07:37:00
1
569
AnonymousMe
77,998,762
19,370,273
Returning as many complete concatenated rows as possible up to a length limit
<p>Suppose I have a dataframe with a single column (elements as strings) and a certain number of rows. The length of the string of each row can be variable.</p> <p>I want to concatenate the rows into a single string. Currently, I can do something like this (where <code>output</code> is the column with the strings I wan...
<python><pandas>
2024-02-15 06:26:03
1
391
Leaderboard
77,998,694
3,121,975
Replace pandas row in one dataframe with row(s) from another dataframe
<p>I have two pandas DataFrames defined like so:</p> <pre><code>left = pd.DataFrame({&quot;A&quot;: [1, 2], &quot;B&quot;: [&quot;a&quot;, &quot;b&quot;]}) left[&quot;C&quot;] = pd.Series(dtype=&quot;int64&quot;) right = pd.DataFrame({&quot;A&quot;: [1, 1], &quot;B&quot;: [&quot;a&quot;, &quot;a&quot;], &quot;C&quot;:...
<python><pandas>
2024-02-15 06:05:02
2
8,192
Woody1193
77,998,622
5,640,500
Do gca().lines and legend.get_lines() return the lines in the same order?
<p>Do <code>gca().lines</code> and <code>legend.get_lines()</code> return the lines in the same corresponding order?</p> <p>If not, is there a way to get corresponding legend lines from <code>gca().lines</code>?</p>
<python><matplotlib><legend>
2024-02-15 05:45:36
1
651
Tims
77,998,568
13,634,472
langchain : ModuleNotFoundError: No module named 'langchain_community'
<p>Trying to execute this code:</p> <p><code>from langchain_community.vectorstores import FAISS</code></p> <p>Error it is showing: <strong>ModuleNotFoundError: No module named 'langchain_community'</strong></p> <p>Thou I have executed the command:</p> <blockquote> <p><strong>pip install langchain-community</strong></p>...
<python><langchain>
2024-02-15 05:24:26
4
1,679
Nikita Malviya
77,998,496
12,149,817
How to build shell plots based on pandas dataframe?
<p>I have the following dataframe of numbers of interactions between ligand-receptor pairs:</p> <pre><code>d = {'ligand': ['B cells','CAFs','Malignant cells','T cells','TAMs','TAMs','TAMs','TAMs','TAMs','TAMs','TAMs','TECs','unclassified'], 'receptor': ['TAMs','TAMs','TAMs','TAMs','B cells','CAFs','Malignant cells...
<python><pandas><matplotlib><visualization>
2024-02-15 04:56:50
1
720
Yulia Kentieva
77,998,370
11,330,010
Plotly: Add both primary and secondary axis for same line
<p>I am working on a school project. I have created the following callback to update a graph. The graph simply plots :</p> <ol> <li>a line showing the values of the variable Wealth,</li> <li>a horizontal line at the starting value of Wealth,</li> <li>fills the area between the first and the second line.</li> </ol> <p>I...
<python><plotly><plotly-dash>
2024-02-15 03:59:30
1
407
NC520
77,998,349
1,437,138
Execute background process in python
<p>In python, I am trying to run a process (storing huge amount of data to db) as a background process and it should not wait to return the response of current executing function. I tried the below code. But its not working as my expectation. I will explain my real problem. If I get an alternate solution for my real pr...
<python><azure-functions><multiprocessing><azure-cosmosdb><python-asyncio>
2024-02-15 03:52:36
1
2,827
Smith Dwayne
77,998,316
9,582,542
Press button when class name changes using Selenium
<p>Using Selenium for Edge what would the proper syntax be to click the div below? the class names changes but the &quot;Run Job&quot; text remains the same. How can I click on this using the text instead of the class?</p> <pre><code>&lt;div class=&quot;x9f619 xjbqb8w x78zum5 x168nmei x13lgxp2 x5pf9jr xo71vjh x1n2onr6 ...
<python><selenium-webdriver>
2024-02-15 03:38:45
1
690
Leo Torres
77,998,295
5,896,591
python on Linux: os.pipe() with cumulative byte counter?
<p>Is it possible to get a cumulative count of bytes written to an <code>os.pipe()</code>? I tried <code>os.fdopen(...).tell()</code> but got <code>IOError: [Errno 29] Illegal seek</code>. Is there some other way to wrap the <code>fd</code> to get a cumulative byte count?</p>
<python><linux><pipe>
2024-02-15 03:28:59
1
4,630
personal_cloud
77,998,038
6,394,617
Python slice assignment should be sequence of same type?
<p>In the <a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow noreferrer">documentation</a>, it states &quot;If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object s...
<python><slice><variable-assignment>
2024-02-15 01:24:02
0
913
Joe
77,997,955
12,358,733
Using Google Application Default Credentials (ADC) with gcloud-aio Storage in Python
<p>I'm using <a href="https://github.com/talkiq/gcloud-aio/tree/master/storage" rel="nofollow noreferrer">gcloud-aio/storage</a> to access GCS buckets, with the authentication via service account key file (JSON file). Here's my working Python code:</p> <pre><code>from os import path from gcloud.aio.auth import Token f...
<python><google-cloud-platform><google-cloud-storage><google-oauth><aio>
2024-02-15 00:49:21
0
931
John Heyer
77,997,732
9,842,472
Decorate a decorator: how to assign functionality to adecorator programatically
<p>I'm building a class where I want some methods to be registered under a set of categories. To do so, I build a set of decorator functions, one for each category I want to then apply them kinda following <a href="https://stackoverflow.com/questions/3054372/auto-register-class-methods-using-decorator">this answer</a>....
<python><python-3.x>
2024-02-14 23:27:59
1
527
Puff
77,997,430
866,262
ImportError: cannot import name 'sync_playwright' from 'playwright.async_api'
<p>I initially did</p> <pre><code>pip3 install playwright playwright install </code></pre> <p>Then tried uninstalling and reinstalling <code>pip3 install pytest-playwright</code>. I looked at other StackOverflow questions and none of them worked for me.</p> <pre class="lang-none prettyprint-override"><code>Traceback (m...
<python><python-3.x><playwright><playwright-python>
2024-02-14 22:00:49
1
3,315
stumped
77,997,390
1,141,818
Sqlalchemy - Filtering parent and chidren objects at the same time
<p>I got this many-to-many design</p> <pre><code>class Parent(Base): __tablename__ = &quot;parent&quot; id = Column(Integer, primary_key=True) parent_number = Column(String) start_date = Column(DateTime, primary_key=True) end_date = Column(DateTime) children= relationship(&quot;Child&quot;, lazy...
<python><sqlalchemy>
2024-02-14 21:51:09
1
3,575
GuillaumeA
77,997,297
4,355,878
What does this mean? "Be aware, overflowing tokens are not returned for the setting you have chosen"
<p>I don't understand if this is an error or warning:</p> <blockquote> <p>Be aware, that overflowing tokens are not returned for the setting you have chosen, i.e. sequence pairs with the 'longest_first' truncation strategy. So the returned list will always be empty even if some tokens have been removed.</p> </blockquot...
<python><huggingface-transformers>
2024-02-14 21:24:29
0
1,533
j35t3r
77,997,127
12,178,630
Add padding to CubeSpline interpolation curve
<p>I have the a set of points and I pass a curve through them, using <code>scipy</code> <code>CubeSpline</code>, I really would like to know how can I add padding from outside, so that the curve is fitting the flow of the points but they are always inside it by some factor, as shown in this image, where what I have is ...
<python><scipy><spline><spatial-interpolation>
2024-02-14 20:44:29
0
314
Josh
77,997,083
4,159,833
Web scraping a website when page source doesn't contain what I see on browser
<p>Suppose I want to scrape the data (marathon running time) in this website: <a href="https://www.valenciaciudaddelrunning.com/en/marathon/2021-marathon-ranking/" rel="nofollow noreferrer">https://www.valenciaciudaddelrunning.com/en/marathon/2021-marathon-ranking/</a></p> <p>One Google chrome when I right-click and se...
<python><html><selenium-webdriver><web-scraping><beautifulsoup>
2024-02-14 20:33:26
2
3,068
Physicist
77,996,844
13,494,917
How to explode a pandas dataframe that has nulls in some rows, but populated in others
<p>So I have many dataframes coming in that need to be exploded. they look something like this:</p> <pre><code>df = pd.DataFrame({'A': [1, [11,22], [111,222]], 'B': [2, [33,44], float('nan')], 'C': [3, [55,66], [333,444]], 'D': [4, [77,88], float('nan')] ...
<python><pandas><dataframe>
2024-02-14 19:30:35
3
687
BlakeB9
77,996,792
10,940,989
Why does torch.compile need to use g++?
<p>I was trying to use the <code>compile</code> feature that was introduced with Pytorch 2 and had trouble getting it to work. After much debugging, I realised that the problem came from g++: it was using an incorrect version on my machine that didn't support C++17. Patching it by setting the <code>cpp.cxx</code> confi...
<python><c++><pytorch><g++>
2024-02-14 19:20:27
0
380
Anthony Poole
77,996,758
4,710,409
Django- getting the value of 'models.DateField(default=datetime.datetime.today)' in view
<p>I have this model:</p> <p><strong>models.py:</strong></p> <pre><code>class myModel(models.Model): a = models.ForeignKey(P,on_delete=models.CASCADE) ... **date = models.DateField(default=datetime.datetime.today)** </code></pre> <p>In the views.py, I get the data of &quot;date&quot; field:</p> <p><strong>...
<python><django><datetime><view><model>
2024-02-14 19:15:35
2
575
Mohammed Baashar
77,996,511
1,360,476
Writing in delta using Polars and adlfs
<p>According to <a href="https://stackoverflow.com/questions/75800596">How to you write polars data frames to Azure blob storage?</a>, we can write <em>parquet</em> using <code>polars</code> directly on <em>Azure Storage</em> such as basic storage containers.</p> <p>In my case I was required to write in <em>Delta</em> ...
<python><azure-storage><python-polars><fsspec>
2024-02-14 18:25:46
1
1,787
Michel Hua
77,996,468
595,305
QTableView won't display single line of text quite right
<p>Here's an MRE:</p> <pre><code>import sys, logging, datetime from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.Qt import QVBoxLayout class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.__class__.instance = self self.resize(1200, 1600) # w, h m...
<python><pyqt><qtableview>
2024-02-14 18:15:52
1
16,076
mike rodent
77,996,458
23,260,297
Find starting point to read csv data
<p>I am given a csv file everyday that contains data to be used for calculations. I want to use pandas to organize the data. My issue is that the data to be read does not start on the first line of the file. The data also does not start on the same exact line every time so I cannot use the skiprows parameter in read_cs...
<python><pandas><csv>
2024-02-14 18:13:08
2
2,185
iBeMeltin
77,996,271
5,790,653
how to print duplicate values of a list of dictionaries in python
<p>Suppose this list:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ {'id': 1, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 2, 'name': 'B', 'blob': 'blob', 'type': 'B'}, {'id': 3, 'name': 'A', 'blob': 'blob', 'type': 'A'}, {'id': 4, 'name': 'C', 'blob': 'blob', 'type': 'A'}, {'id': 5, 'name': 'E', '...
<python><dictionary>
2024-02-14 17:37:28
1
4,175
Saeed
77,996,196
22,466,650
How to duplicate rows based on the number of weeks between two dates?
<p>My input is this dataframe :</p> <pre><code>df = pd.DataFrame( { 'ID': ['ID001', 'ID002', 'ID003'], 'DATE': ['24/12/2023', '01/02/2024', '12/02/2024'], } ) df['DATE'] = pd.to_datetime(df['DATE'], dayfirst=True) print(df) ID DATE 0 ID001 2023-12-24 1 ID002 2024-02-01 2 ID003 ...
<python><pandas>
2024-02-14 17:25:06
1
1,085
VERBOSE
77,995,989
11,567,354
How to automatically update ORM object attributes with client-side values
<p>I'm using aws api gateway to create my rest api and I'm using lambda layers to define my sqlalchemy models. I'm using Mysql as my RDBMS I have a model defined as:</p> <pre><code>class Project(Base): __tablename__ = &quot;project&quot; name = Column(String(256)) created_by = Column(String(256)) update...
<python><sqlalchemy><aws-api-gateway>
2024-02-14 16:51:40
1
366
Wajih Katrou
77,995,937
3,200,552
Race Conditions with ModelViewset Requests
<p>I'm experiencing an issue with a Django Rest Framework ModelViewSet endpoint named <code>projects/</code>. I have a set of requests (PATCH, DELETE, then GET) that are causing unexpected behavior. The timeline of requests and responses is as follows:</p> <ol> <li>PATCH request at 14:45:09.420</li> <li>DELETE request ...
<python><django><django-rest-framework><race-condition>
2024-02-14 16:44:31
1
785
merhoo
77,995,812
353,337
Initialize pytest test objects in the test, not in the `parametrized`/collection phase
<p>I have a number of pytest tests that I run like</p> <pre class="lang-py prettyprint-override"><code>import pytest from mymodule import * @pytest.mark.parametrize( &quot;arg&quot;, [ fun1(), fun2(), ] + [ fun3(n) for n in range(10) ] + [ fun4(n, model) ...
<python><pytest>
2024-02-14 16:25:53
2
59,565
Nico Schlömer
77,995,669
5,168,463
pyspark schema mismatch issue
<p>I am trying to load a .csv file into spark using this code:</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * from pyspark.sql import Window spark = SparkSession.builder.appName('Demo').master('local').getOrCreate() pathData = '/home/data/depar...
<python><apache-spark><pyspark><schema>
2024-02-14 16:04:26
1
515
DumbCoder
77,995,602
9,069,109
Excel truncates function return when using PyXll
<p>We have a function in python that is called in Excel using PyXll Add-in. To do so, the function is called using this code:</p> <pre class="lang-py prettyprint-override"><code> import myfunction from pyxll import xl_func import pandas as pd @xl_func('float[][], float[]', auto_resize=True) def myfunction_xl( x: I...
<python><excel><excel-addins><pyxll>
2024-02-14 15:52:55
1
453
Aniss Chohra
77,995,419
92,516
Correct way to perform expensive per-worker setup
<p>What's the correct / best way to perform costly per-process initialisation when using multiple workers, ensuring the workers can correctly communicate with the master?</p> <p>As part of a custom <code>locustfile.py</code> I need to download a large dataset from a URL and load into memory to generate GET request para...
<python><load-testing><locust>
2024-02-14 15:28:07
1
9,708
DaveR
77,995,258
5,022,847
Django group by substring on a field
<p>I have a Django, PostgreSQL project. I want to perform a group by on substring from a field. Ex I have a model as <code>Model1</code> and its column as <code>name</code>. The value in the column can be:</p> <pre><code>ABC-w-JAIPUR-123 XYZ-x-JAIPUR-236 MNO-y-SURAT-23 DEF-q-SURAT-23 </code></pre> <p>From the above val...
<python><django><postgresql><django-models><django-model-field>
2024-02-14 15:04:26
1
1,430
TechSavy
77,995,227
1,754,307
How to remove data validation from selected cells in python using openpyxl
<p>I am opening a template file using openpyxl, which has data validation down to row 500 in about 5 columns. In my python script I am loading data into the left half of the spreadsheet from Oracle, with the data validation columns being on the right.</p> <p>If the data is only 50 rows I am inserting, I need to get ri...
<python><openpyxl>
2024-02-14 14:58:46
1
3,082
smackenzie
77,995,211
16,420,204
Polars: Manipulation on columns by 'dtype' creating multiple new columns
<p>With the given code I want to create new columns for every column selected by <code>pl.DATETIME_DTYPES</code> with the extracted year.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data = {&quot;col1&quot;: ['2020/01/01', '2020/02/01'], &quot;col2&quot;: ['2020/01/01', '2020/02/01']} df =...
<python><dataframe><datetime><python-polars>
2024-02-14 14:56:58
1
1,029
OliverHennhoefer
77,994,983
13,086,128
Difference between [ ] and Expression API?
<p>What is the difference between using square brackets <code>[ ]</code> and using <a href="https://docs.pola.rs/py-polars/html/reference/expressions/index.html" rel="nofollow noreferrer"><strong>Expression APIs</strong></a> like <code>select</code>, <code>filter</code>, etc. when trying to access data from a polars Da...
<python><python-polars>
2024-02-14 14:21:17
3
30,560
Talha Tayyab
77,994,888
10,570,372
Can we provide an example and motivation on when to use covariant and contravariant?
<p>I have some troubles finding real use cases of covariant/contravariant. I would like a concrete motivation and example on when covariant/contravariant is used, in particular, I would appreciate the example to be such that if covariant/contravariant is not applied, then the application would be buggy/not type safe.</...
<python><pytorch><python-typing><liskov-substitution-principle>
2024-02-14 14:07:02
1
1,043
ilovewt
77,994,872
7,662,164
Specify an arbitrary argument in addition to *args in python
<p>For a function with multiple arguments like this:</p> <pre><code>def f(a, b, c): return a + b + c </code></pre> <p>it is straightforward to define a new function as follows:</p> <pre><code>def g(a, *args): return f(a, *args) </code></pre> <p>here, <code>a</code> is the first argument of <code>f()</code>. Wha...
<python><function><arguments><positional-argument>
2024-02-14 14:04:29
2
335
Jingyang Wang
77,994,776
16,525,263
Join two dataframes to get data into another dataframe and create a new column in pyspark
<p>I have a pyspark dataframe</p> <pre><code>mail_id e_no aaa@ven.com 111 bbb@ven.com 222 ccc@ven.com 333 </code></pre> <p>I have another dataframe</p> <pre><code>email emp_no aaa@ven.com 111 222 333 </code></pre> <p>I need to fill the emp_no from second...
<python><pyspark>
2024-02-14 13:49:14
1
434
user175025
77,994,714
10,452,700
How can retrieve numbers of records above and under mean\median over time data with respect to time resolution in python?
<p>Let's say I have the following time <a href="https://github.com/amcs1729/Predicting-cloud-CPU-usage-on-Azure-data/blob/master/azure.csv" rel="nofollow noreferrer">data</a> for 1 month or (31 days) in January:</p> <pre class="lang-py prettyprint-override"><code>import os, holoviews as hv os.environ['HV_DOC_HTML'] = '...
<python><pandas><time-series><bokeh>
2024-02-14 13:41:00
2
2,056
Mario
77,994,707
14,860,526
Python unittest/pytest tests priority
<p>i have many unittests in my project each independent from another, however i would like to run the tests in parallel on several cores and in order to get the most out of it, it's necessary that the longest tests run as early as possible. Is it possible to give a priority order to the tests? something like</p> <pre><...
<python><unit-testing><testing><pytest>
2024-02-14 13:39:45
1
642
Alberto B
77,994,610
15,803,668
LlamaIndex library not respecting LLAMA_INDEX_CACHE_DIR environment variable
<p>I'm using the <code>LlamaIndex</code> library in my Python project to handle some data processing tasks. According to the documentation <a href="https://docs.llamaindex.ai/en/stable/getting_started/installation.html#quickstart-installation-from-pip" rel="nofollow noreferrer">(Link)</a>, I can control the location wh...
<python><llama-index>
2024-02-14 13:22:03
1
453
Mazze
77,994,599
800,457
What are all the known serialization formats of (unix) epoch time?
<p>So, the <a href="https://en.wikipedia.org/wiki/Unix_time" rel="nofollow noreferrer">basic definition</a> of epoch time (similar to 'unix time', but not exactly: see below) and what it means is clear. However, nowhere on the wikipedia page or on any other resource I can find is it mentioned that <strong>epoch time ca...
<javascript><python><datetime><unix-timestamp><epoch>
2024-02-14 13:20:06
1
19,537
XML
77,994,578
3,050,852
Python subprocess will not run command
<p>For some reason I have a subprocess command line that is not running the subprocess command line underneath it and doing the processing it should be.</p> <pre><code> import subprocess import os os.chdir('/home/linux/Trial/') a = open('Attempts.txt', 'r') b = a.readlines() a.close() for c in range(0, len(b)-1)...
<python><ffmpeg><subprocess>
2024-02-14 13:14:49
1
1,341
confused
77,994,378
12,194,774
Pandas 'isin' or 'merge' function with multiple columns and dataframes conditions
<p>I have 2 dataframes:</p> <pre><code>d1={'A':[1,3,5,7,8,4,6],'B':[6,4,3,8,1,7,4], 'C':[2,5,8,9,8,4,7]} df1=pd.DataFrame(data=d1) d2={'a':[2,8,6,5,7],'b':[6,4,9,3,2]} df2=pd.DataFrame(data=d2) </code></pre> <p>Now, I would like to see which &quot;a&quot; and &quot;b&quot; values of df2 are the same as &quot;A&quot;...
<python><pandas><dataframe>
2024-02-14 12:39:42
3
337
HungryMolecule
77,994,342
18,178,867
How to calculate the computational complexity of machine learning algorithms
<p>I have used five machine learning algorithms, including the artificial neural network (ANN), random forest, CatBoost, SVM, and K-nearest neighbors (KNN) for a multiclass classification. How can I compute the computational complexity of these models?</p> <p>I have also utilized the Power-Law Committee Machine (PLCM) ...
<python><machine-learning><scikit-learn>
2024-02-14 12:34:47
1
443
Reza
77,994,163
7,566,673
composite score for denoising 1D signal
<p>I am suing different methods such as wavelet(different parameters) , FFT to denoise 1 D single . I using <code>skimage.metrics</code> to evaluate denoising as shown in snippet below. (here <code>signal</code> is original noisy signal)</p> <pre><code>import skimage.metrics as M def get_denoise_metrics(signal, clean_s...
<python><signal-processing><fft><scikit-image><pywavelets>
2024-02-14 12:04:36
1
1,219
Bharat Sharma
77,994,041
10,327,984
Memory Error while Generating User-Movie Combinations for Content-Based Recommender
<p>I'm working with the MovieLens dataset and aiming to build a content-based recommender using a machine learning algorithm to predict ratings. To achieve this, I need to generate all combinations of users and movies and assign actual ratings for users who have already rated a movie or assign 0 for users who haven't w...
<python><pandas><dataframe><recommendation-engine>
2024-02-14 11:44:31
0
622
Mohamed Amine
77,993,956
19,672,778
keras.models.load_model() fails to load model from .keras file
<p>Hello so i am trying to load model from .keras zip file but it fails to do so. it gives me this error. how can i fix it?</p> <pre class="lang-py prettyprint-override"><code>modelvggNew = keras.models.load_model('/kaggle/working/vgg15.keras') </code></pre> <pre><code>--------------------------------------------------...
<python><tensorflow><keras>
2024-02-14 11:29:37
4
319
NikoMolecule
77,993,932
709,439
How to get detailed status from flask background runner?
<p>I have to implement a very long (many minutes, perhaps hours) method in my Python Flask API.</p> <p>I was planning to use flask_executor. My code is something like this:</p> <pre><code>from flask import Flask, request, jsonify from flask_executor import Executor import uuid import time app = Flask(__name__) execut...
<python><python-3.x><flask>
2024-02-14 11:25:34
0
17,761
MarcoS
77,993,912
4,575,197
cuML UserWarning: Scoring failed. The score on this train-test partition for these parameters will be set to nan
<p>i am trying to train a RF regression using <code>gridsearchcv</code>. I change all file types to float32 and i still get these warnings that i'm not sure how to solve.</p> <p>my code:</p> <pre><code>combined_df=cpd.concat([train_df,evaluate_df]) combined_df = combined_df.astype({ 'Mcap_w': 'float32', 'consta...
<python><typeerror><rapids><cuml><user-warning>
2024-02-14 11:22:29
1
10,490
Mostafa Bouzari
77,993,894
3,828,463
Error in Python trying to create a list of a certain length after a call to Fortran to get the length
<p>I have a piece of Python code which needs to call Fortran to get the length of a list Python needs to create (so that it can pass that list of the correct size back to Fortran later).</p> <p>Here is the code:</p> <pre><code># get size of x n = ct.c_int(0) fs(ct.byref(n)) # fs is a Fortran subroutine which returns th...
<python><fortran>
2024-02-14 11:19:13
1
335
Adrian