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,033,804
12,178,630
How to separate two touching blobs?
<p>I have written the following code in order to detect the blobs based on their <code>HSV</code> values, everything works fine, except that when the two blobs intersect(touch) the are detected as one instead of two. I have read <a href="https://stackoverflow.com/questions/19916765/opencv-blob-detection-separate-close-...
<python><opencv><image-processing><scikit-image><canny-operator>
2024-02-21 11:56:23
1
314
Josh
78,033,500
4,093,755
I have an excel sheet which has four columns in which each cell of the column is related to the next columns cell in a cascaded manner
<p>I have an excel sheet which has four columns in which each cell of the column is related to the next columns cell in a cascaded manner.</p> <p>The excel sheet looks like below:-</p> <pre><code> Base Version OS Package Name Description Version 0 A NaN NaN NaN ...
<python><pandas><dataframe>
2024-02-21 11:02:21
2
349
Biplab
78,033,462
1,711,271
Compute the ratio between the number of rows where A=True, to the number of rows where A=False
<p>I have a Polars dataframe:</p> <pre><code>df = pl.DataFrame( { &quot;nrs&quot;: [1, 2, 3, None, 5], &quot;names&quot;: [&quot;foo&quot;, &quot;ham&quot;, &quot;spam&quot;, &quot;egg&quot;, None], &quot;random&quot;: np.random.rand(5), &quot;A&quot;: [True, True, False, False, Fals...
<python><python-3.x><dataframe><count><python-polars>
2024-02-21 10:56:12
2
5,726
DeltaIV
78,033,441
512,183
Poetry: [Errno 2] No such file or directory: 'python'
<p>OSX 14.2.1 on M1, Python 3.11.4, Poetry 1.7.1 I set config virtualenvs.in-project = true</p> <p>If I run &quot;poetry install&quot; or &quot;poetry env info&quot; I get the error:</p> <blockquote> <p>[Errno 2] No such file or directory: 'python'</p> </blockquote> <p>If I run a &quot;poetry check&quot; I get:</p> <bl...
<python><python-poetry>
2024-02-21 10:52:30
1
1,574
eriq
78,033,431
7,414,939
Python Linter to catch user shadowed function names
<p>Assume the following scenario:</p> <pre><code>def my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): # Code return wrapper def f(): # function code return f = my_decorator(f) </code></pre> <p><code>f = my_decorator(f)</code> shadows the function <code>f</code> and that ...
<python><mypy><pylint><linter><ruff>
2024-02-21 10:50:32
0
23,254
John Moutafis
78,033,347
11,561,992
Communicate with python process
<p>I have a python prog which does something like that:</p> <pre class="lang-python prettyprint-override"><code>while (true) { Number1 = input(&quot;What's your first number?&quot;) Number2 = input(&quot;What's your second number?&quot;) print(&quot;Your numbers are: &quot;,Number 1, Number 2) Sum= inpu...
<python><linux><bash><input><output>
2024-02-21 10:39:34
0
305
Ablia
78,033,145
2,386,113
How to get immediate neighbors using a kd-tree irrespective of the spacing?
<p>I want to find the immediate neighbours around a given point in a multidimensional space (up to 7 dimensions).</p> <p><strong>Important facts about the space:</strong></p> <ul> <li><strong>non-linear spacing</strong> among points within a single dimension. As shown in the screenshot below, the distance between the p...
<python><scikit-learn><sklearn-pandas><nearest-neighbor>
2024-02-21 10:08:59
1
5,777
skm
78,033,119
11,584,327
How to interactively control the amplitude and frequency of a signal with two scale sliders using Tkinter
<p>Just starting out with python, I want to model a triangular signal and be able to control its amplitude and frequency in an interactive way using scale/sliders widgets, and <code>Tkinter</code> as possible.</p> <p>Inappropriately, my (updated) code below generate two signals (amplitude and frequency) which are contr...
<python><tkinter><widget><waveform>
2024-02-21 10:05:01
1
902
denis
78,032,524
10,686,345
Airflow - NameError: name 'ti' is not defined
<p>I am trying to execute a Airflow script that consists of a couple of functions. I want to pass the value of 'program_no' as an argument in spark submit request which I am getting in my DAG from an api call via context in get_conf method. I am trying to pass like {ti.xcom_pull(task_ids='parameterized_task')} but I am...
<python><airflow><spark-submit>
2024-02-21 08:29:39
2
457
Ayush Goyal
78,032,313
3,099,733
How to create a TypeGuard to ensure value not None in python?
<p>Given the following code</p> <pre class="lang-py prettyprint-override"><code>val = object.data assert val, 'data should not be None' </code></pre> <p>It use a lot in my project to ensure <code>Optional[T]</code> data type is not None.</p> <p>I create the following method to make the code DRY.</p> <pre class="lang-py...
<python><python-typing>
2024-02-21 07:44:47
1
1,959
link89
78,032,224
11,840,002
PySpark and Databricks addFile and SparkFiles.get Exception java.io.FileNotFoundException
<p>I am trying to:</p> <ol> <li>Load an SSL certification from S3 to a cluster.</li> <li><code>addFile</code> so all nodes see the file.</li> <li>Create a connection URL to IBM db2 with JDBC.</li> </ol> <p>Step 1 and Step 2 are working successfully. I can open the file with <code>with open(cert_filepath, &quot;r&quot;)...
<python><apache-spark><amazon-s3><pyspark><databricks>
2024-02-21 07:26:19
1
1,658
eemilk
78,032,156
13,613,776
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <User at 0x197950dead0> is not bound to a Session;
<p>Hey I am trying to print all stocks which users have</p> <pre><code>class User(Base, TableNameMixin): user_id: int = Column(BIGINT, primary_key=True, autoincrement=False) stocks: Mapped[List[&quot;Stock&quot;]] = relationship(back_populates=&quot;user&quot;) class Stock(Base, TableNameMixin): stock_id: ...
<python><sqlalchemy>
2024-02-21 07:12:19
0
448
Rishu Pandey
78,032,069
188,331
Free up Python script-driven Selenium WebDriver's cache in Ubuntu?
<p>I am using Selenium WebDriver to scrap website data 24-hour non-stop. I found out that the cache size is increasing non-stop.</p> <pre><code>4879M /tmp/snap-private-tmp/snap.chromium/tmp </code></pre> <p>My Python script <strong>scrap.py</strong> is as follow:</p> <pre><code>from selenium import webdriver from sel...
<python><selenium-webdriver>
2024-02-21 06:54:06
0
54,395
Raptor
78,031,873
1,029,902
Keeping macros when writing to .xlsm using Python on Ubuntu
<p>I have a fairly straightforward script. It is supposed to replace all the data in one sheet of an <code>.xlsm</code> workbook. The workbook contains macros which I would like to keep. Unfortunately, <strong>I cannot find a way to do this on UBUNTU</strong>, not Windows</p> <p>I cannot use <code>xlwings</code> becaus...
<python><pandas><excel><linux><openpyxl>
2024-02-21 06:12:55
0
557
Tendekai Muchenje
78,031,665
8,589,908
Reading and Writing numpy Float Complex 128
<p>I have a block of code given to me that generates a file containing numpy Float Complex 128 array from streamed data from a SDR. Another part of this same program can read in the file containing numpy Float Complex 128 using <code>np.load</code></p> <p>When I try to generate my own Float Complex 128 array by writing...
<python><numpy>
2024-02-21 05:03:39
0
499
Radika Moonesinghe
78,031,540
21,323,912
"Compiled regex exceeds size limit of 10485760 bytes." error when defining the pattern property in a Pydantic Field
<h1>Original question</h1> <p>I'm trying to define a Pydantic model with a string field that matches the following regex pattern: <code>^(\/[\w-]{1,255}){1,64}\/?$</code>, which should be used to validate expressions that match the form: <code>/alphanumeric-slugs-no-longer-than-255-chars/separated-by-slashes/no-more-th...
<python><regex><pydantic>
2024-02-21 04:21:23
1
556
amoralesc
78,031,403
5,782,416
How to static type check dicts for standard API Response types?
<p>I am looking to learn how to make a more robust API in Python using pythonic methods. My goal is to achieve a more strict API response, to reduce the amount of parsing errors on our frontend and increase standardisation for response types (error states, etc).</p> <p>For the sake of argument, I am using Python 3.11 a...
<python><flask><python-typing>
2024-02-21 03:23:52
1
1,664
Jack Hales
78,031,380
12,314,521
How to vectorize this 2 loops in Pytorch (Difficult)
<p>How to vectorize this:</p> <pre><code>vocab_size = 20 batch_size = 2 input_len = 5 output_len = 10 input_ids = torch.randint(0, vocab_size, (batch_size, input_len)) output_ids = torch.randint(0, vocab_size, (batch_size, output_len)) print(input_ids) print(output_ids) tensor([[ 0, 8, 7, 12, 8], [14, 15, ...
<python><pytorch><vectorization>
2024-02-21 03:16:17
1
351
jupyter
78,031,374
10,567,465
Trigger a property setter when an attribute of an injected class changes in python
<p>I have this python problem (simplified here for the sake of the example) where I have 2 classes: One child class (to be injected) and one parent class. In the parent class, I have an attribute that stores an instance of the child class (via dependency injection). This attribute has a getter and a setter.</p> <p>What...
<python><dependency-injection><properties><getter-setter>
2024-02-21 03:12:57
1
365
TheNomad
78,031,336
2,707,864
Sympy: Extract the two functions solutions of a homogeneous second order linear ODE
<p>I have a homogeneous second-order ODE, whose general solution is <code>ur(r) = C1*u1(r) + C2*u2(r)</code>.</p> <p>How can I get <code>u1(r)</code> and <code>u2(r)</code> as separate functions by setting <code>(C1=1, C2=0)</code> and <code>(C1=0, C2=1)</code>, respectively?</p> <p>This is what I tried (and other vari...
<python><sympy><differential-equations>
2024-02-21 02:59:10
1
15,820
sancho.s ReinstateMonicaCellio
78,031,001
2,681,662
django if any of many to many has filed with value of False
<p>Say I have a model of a library and I want to hide some books if either the book is marked as hidden or any of authors is marked as hidden or any of categories is marked as hidden.</p> <pre><code>class Category(CustomModel): name = models.CharField(max_length=32, unique=True, null=False, blank=False) ... ...
<python><django>
2024-02-21 00:34:23
1
2,629
niaei
78,030,969
8,010,921
Type declaration for dynamically created properties (setattr)
<p>I am writing a class which dynamically sets its attributes according to a <code>dict</code> passed to the constructor:</p> <pre class="lang-py prettyprint-override"><code>class Test: def __init__(self, track_data:dict[Any,Any]) -&gt; None: valid_attributes = [member.value for member in fields] ...
<python><python-typing>
2024-02-21 00:23:53
1
327
ddgg
78,030,967
5,769,814
EditorCamera's look_at method ruins the zoom-in/zoom-out commands
<p>I have an <code>EditorCamera</code> in my code and I was trying to set its initial rotation in a certain direction. I couldn't get it to work using <code>.rotation</code>, so I used the <code>look_at</code> method instead:</p> <pre><code>import ursina as ur app = ur.Ursina(title=&quot;Cube&quot;) ground = ur.Entity...
<python><python-3.x><ursina>
2024-02-21 00:23:14
1
1,324
Mate de Vita
78,030,853
1,767,106
JAX jax.grad on simple function that takes an array: `ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected`
<p>I'm trying to implement this function and use JAX to automatically build the gradient function:</p> <pre><code>$f(x) = \sum\limits_{k=1}^{n-1} [100 (x_{k+1} - x_k^2)^2 + (1 - x_k)^2]$ </code></pre> <p>(sorry, I don't know how to format math on stackoverflow. Some sister sites allow TeX, but apparently this site does...
<python><numpy><jax><autograd>
2024-02-20 23:41:28
1
20,816
clay
78,030,813
7,265,114
Fill between areas with gradient color in matplotlib
<p>I try to plot the following plot with gradient color ramp using matplotlib fill_between. I can manage to get the color below the horizontal line correctly, but I had difficult time to do the same for above horizontal line. The idea is to keep color above and below the horizontal line up to y values boundary, and the...
<python><matplotlib>
2024-02-20 23:24:47
1
1,141
Tuyen
78,030,679
11,462,274
Keep the token active by updating its expiration date to not receive the error Token has been expired or revoke
<p>Based on <a href="https://developers.google.com/drive/api/quickstart/python?hl=pt-br" rel="nofollow noreferrer">Google's documentation</a> I tried to use this code to keep my token active:</p> <pre class="lang-python prettyprint-override"><code> from google.auth.transport.requests import Request from google.o...
<python><oauth-2.0><google-oauth>
2024-02-20 22:45:50
1
2,222
Digital Farmer
78,030,469
3,534,782
Multiprocessing pool, whether using map or async, hangs on last couple processes
<p>I have a function that I am applying to hundreds of chunks of my larger dataset -- each individual job only takes a minute or two, and outputs a file if it is successful. This holds true for the first ~740 out of my ~750 individual jobs, but then the last several jobs, especially the very last one, seems to take inc...
<python><multiprocessing><freeze><lag><pool>
2024-02-20 21:47:54
0
419
ekofman
78,030,364
3,750,694
Applying CLAHE on RGB images
<p>I applied CLAHE to improve the image visibility (original image). However, it looks like after applying the CLAHE, the visibility of imagery is not improved in the shadow areas (CLAHE image). Please suggest me how to improve quality of my imagery. Below are my script:</p> <pre><code># Input and output folder paths i...
<python><image-processing>
2024-02-20 21:17:50
0
703
user30985
78,030,332
7,578,588
VSCode Python debugger runs but nothing happens
<p>I have recently bought a new laptop and set up VSCode and Python so I can continue coding. Everything looks fine, took a bit of messing around to get virtual environments working, but apart from that no problem EXCEPT my code does not run.</p> <p>To be specific, when I open my code and click &quot;Run | Start Debugg...
<python><visual-studio-code><vscode-debugger>
2024-02-20 21:09:45
2
2,130
Mark Kortink
78,030,103
901,426
Python split() fails when using delimiter
<p>i'm trying to parse a feedback string from a device. i'm just trying to run a simple <code>split()</code> but it throws this error: <code>ValueError: not enough values to unpack (expected 2, got 1)</code>. this makes no sense to me.</p> <pre class="lang-py prettyprint-override"><code> workingResult = &quot;SIMSta...
<python><split>
2024-02-20 20:20:45
1
867
WhiteRau
78,030,097
8,120,585
Is there a way in Python GitHub library to check if the branch for which a PR has been raised is out-of-date from it's base branch or not?
<ul> <li>My python script is getting a list of PRs and then it needs to run a check if the branches being used in those PRs are out-of-date from their base branch or not.</li> <li>I need to perform this action remotely i.e without cloning the repo to my local machine.</li> </ul> <p><a href="https://i.sstatic.net/obTSP....
<python><github><github-api><pygithub>
2024-02-20 20:18:18
1
438
Syed Faraz Umar
78,029,940
17,040,989
legend in bokeh UMAP shows only one entry
<p>Hi there I just managed to get this plot done in <code>bokeh</code>, so I imagine there are many things that could be improved. Nonetheless, what bothers me the most is that I cannot figure out how to have all entries for my eight populations in the UMAP plot...<br /> Right now it shows only one entry which I don't ...
<python><legend><bokeh><legend-properties><runumap>
2024-02-20 19:43:54
2
403
Matteo
78,029,932
5,710,525
How to interrupt Linux kernel module without terminating the interfacing userspace process
<p>I've written a kernel module implementing a device driver that uses <code>down_interruptible</code> to handle access to shared resources. I have a userspace application that communicates with the kernel module. I'd like to be able to interrupt the kernel module without terminating the userspace application (this wil...
<python><linux><linux-kernel><linux-device-driver><interrupt>
2024-02-20 19:42:36
0
464
MattHusz
78,029,856
243,031
Mysql execute many wont work when add on duplicate
<p>I have mysql table and I want to run the <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html" rel="nofollow noreferrer"><code>executemany</code></a> for that table. I want to make sure, if there is duplicate entry, then it should be updated. I wrote query as below...
<python><mysql><pymysql><executemany>
2024-02-20 19:23:09
1
21,411
NPatel
78,029,820
1,852,526
Write two strings into one column using pandas
<p>I want to write 2 strings into one column within an xlsx file using pandas like</p> <blockquote> <p><a href="https://www.nuget.org/packages/Newtonsoft.Json/" rel="nofollow noreferrer">https://www.nuget.org/packages/Newtonsoft.Json/</a> - release notes tab</p> </blockquote> <p>where the part of the hyperlink is click...
<python><pandas><xlsx>
2024-02-20 19:16:28
1
1,774
nikhil
78,029,817
6,462,301
How to type hint a subset of values from a known set in python
<p>Consider the following set:</p> <p><code>s = set([&quot;x&quot;, &quot;y&quot;, &quot;z&quot;])</code></p> <p>How do I create a type hint for a variable that is any subset of the elements in s (short of explicitly creating a Union of every possible subset)?</p>
<python><set><python-typing>
2024-02-20 19:16:02
1
1,162
rhz
78,029,628
7,344,164
Adding nested lists to shared dict in Multiprocessing Pool and saving to JSON after the context
<p>I'm trying to run a process in multiprocesses Pool as:</p> <pre><code>from multiprocessing.pool import Pool from multiprocessing import Manager manager = Manager() lock = manager.Lock() data_dict = manager.dict({data_subset: {}}) with Pool(processes=cpu_count()-2) as p: with tqdm(total=len(paths)) as pbar: ...
<python><json><multiprocessing><python-multiprocessing>
2024-02-20 18:34:07
1
14,299
DevLoverUmar
78,029,515
17,580,381
Managed dictionary does not behave as expected in multiprocessing
<p>From what I've managed to figure out so far, this may only be a problem in macOS.</p> <p>Here's my MRE:</p> <pre><code>from multiprocessing import Pool, Manager from functools import partial def foo(d, n): d.setdefault(&quot;X&quot;, []).append(n) def main(): with Manager() as manager: d = manager....
<python><multiprocessing>
2024-02-20 18:08:59
1
28,997
Ramrab
78,029,447
1,485,926
Release of references in PyObject when that object is a dictionary, list or text string
<p>I have a code in <a href="https://docs.python.org/3/c-api/index.html" rel="nofollow noreferrer">Python C API</a> like this:</p> <pre><code>PyObject* result = PyObject_CallMethod(/* some function with some arguments */); // Do something with result Py_XDECREF(result); </code></pre> <p>I'm almost sure this code is fin...
<python><python-c-api>
2024-02-20 17:56:03
0
12,442
fgalan
78,029,445
250,540
Pythonic optimization of per-pixel image processing
<p>I am processing an image in Python where I need to calculate an image metric on &quot;how much is happening on an image&quot;. Metric calculates stripes of non-0 values, calculates sum of values inside the stripes, and calculate sum of squares of these sums.</p> <p>Naive implementation which is processing every pixe...
<python><numpy><opencv>
2024-02-20 17:55:40
1
6,601
BarsMonster
78,029,336
1,111,886
Qt event for focus changed with tab key
<p>I have a UI that I would like to implement a form of auto-fill for. I have implemented this by using an event filter to populate the QLineEdit when it's given focus based on the previously focused QLineEdit.</p> <p>The issue is that I only want this autofill to occur only when the user is using the tab key to cycle ...
<python><pyqt5>
2024-02-20 17:35:31
1
4,367
Fr33dan
78,029,324
1,485,926
How can I create lambda PyObject from its Python code in a C string?
<p>I have the following code in Python, which uses <a href="https://pypi.org/project/pyjexl" rel="nofollow noreferrer"><code>pyjexl</code> module</a>:</p> <pre><code>import pyjexl jexl = pyjexl.JEXL() jexl.add_transform(&quot;lowercase&quot;, lambda x: str(x).lower()) </code></pre> <p>I want to do the same using <a hr...
<python><python-c-api>
2024-02-20 17:34:03
1
12,442
fgalan
78,029,273
2,791,346
Code standards check before commit in PyCharm
<p>I would like to have some analysis done on Python code before I commit, to gently “enforce” the standards.</p> <p>I would like to have a check such as:</p> <ul> <li>no print in new code</li> <li>No methods longer than 50 lines</li> <li>No more than 4 arguments in methods</li> <li>…</li> </ul> <p>( inside the team we...
<python><git><pycharm><code-standards>
2024-02-20 17:27:17
1
8,760
Marko Zadravec
78,029,128
2,015,734
readthedocs build fails with `Sphinx version error`
<p>readthedocs started to throw an error <code>Sphinx version error</code> during build, although there were no changes to the readthedocs configuration and dependencies are all pinned.</p> <p>Here's the <a href="https://github.com/dask/dask-image" rel="nofollow noreferrer">repository</a> and a specific [PR] <a href="h...
<python><continuous-integration><python-sphinx><read-the-docs>
2024-02-20 16:56:26
0
358
malbert
78,029,050
2,778,860
Installing gst-python in macOS
<p>I installed GStreamer 1.22.10 on macOS (Sonoma) using the <a href="https://gstreamer.freedesktop.org/download/#macos" rel="nofollow noreferrer">official binaries</a>. I realized that gst-python is not automatically installed, so I cloned the GStreamer Gitlab repository and followed the <a href="https://gitlab.freede...
<python><macos><gstreamer><pygobject>
2024-02-20 16:45:10
1
1,715
chronosynclastic
78,029,020
640,916
PIL's Image.rotate gives me 90 degrees instead of 270 degrees
<p>Python 3.11.8 PIL 10.2.0</p> <p>I'm trying to rotate this image by 270 degrees:</p> <p><a href="https://i.sstatic.net/X6jhX.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/X6jhX.jpg" alt="enter image description here" /></a></p> <p>My code:</p> <pre><code>from PIL import Image image = Image.open(&quo...
<python><image-processing><python-imaging-library>
2024-02-20 16:38:36
1
7,819
djangonaut
78,028,992
8,385,813
TypeError: len() of unsized object in pyclustering library
<p>I am using the pyclustering library to perform K-means. The datasets I am using are being read in CSV format as shown in the code below. I have tried passing X_scaled as a numpy array, as a list using to_list(). However, I constantly get this error:</p> <pre><code>TypeError: len() of unsized object </code></pre> <p>...
<python><cluster-analysis><k-means><unsupervised-learning>
2024-02-20 16:34:56
1
340
Arnab Sinha
78,028,664
2,459,855
Setting File Type for Emailed Attachments
<p>A Python script for sending email with attachments is working, but all attachments, if any, are arriving as .eml files rather than as jpg, pdf, txt, etc. They do open correctly, but I would prefer that they bear their actual name and type. Although I made a minor change for Python 3 ( <em>attach( changed to add_atta...
<python><email><attachment><email-attachments><mime>
2024-02-20 15:49:50
1
1,127
JAC
78,028,444
1,501,700
Different current folders in Debug and Run modes
<p>I have python code in Visual Studio Code :</p> <pre><code>current_working_directory = os.getcwd() print (current_working_directory) </code></pre> <p>It prints my Windows home directory when I run it. In case I do debug it prints folder where code file is located. Why? How to make the same behavior in both cases?</p>...
<python><visual-studio-code>
2024-02-20 15:17:42
0
18,481
vico
78,028,390
4,527,660
Whitelisting of IP in GCP using cloud function not working
<p>I am writing a cloud function which gets trigger from slack with an IP and then we whitelist the IP in GCP firewall. because GCP firewall dont appeand so we have to get the IP and then appear a new IP to and then update it .</p> <p>I am facing below error</p> <p><code>Error updating firewall rule: FirewallsClient.up...
<python><google-cloud-platform><google-cloud-functions><google-compute-api>
2024-02-20 15:07:54
1
303
Waseem Mir
78,028,104
15,176,150
How can you colour a matplotlib plot to show point density?
<p>I'm plotting some partial dependency plots using matplotlib. I have 1,000 samples which I produce regression predictions for. These predictions are plotted on the y-axis. To get an overview of partial dependency for the whole dataset I'm fixing all variables in my samples bar one. The un-fixed variable is shown on t...
<python><matplotlib><plot>
2024-02-20 14:24:00
2
1,146
Connor
78,028,090
836,723
Regex is not working in Python Playwright page.wait_for_url()?
<p>I found a strange difference in Python VS JavaScript regex implementation of <code>page.waitForURL()</code> / <code>page.wait_for_url()</code>.</p> <p>In python version this code doesn't work:</p> <pre class="lang-py prettyprint-override"><code>from playwright.sync_api import sync_playwright with sync_playwright() ...
<python><playwright><playwright-python>
2024-02-20 14:21:59
2
1,818
Maksim Shamihulau
78,028,035
6,498,753
Basemap with joint histograms plot
<p>Here is the code returning the figure below:</p> <pre><code>import seaborn as sns plt.figure(figsize=(8, 8)) gs = plt.GridSpec(3, 3) ax_main = plt.subplot(gs[1:3, :2]) ax_lon = plt.subplot(gs[0, :2]) ax_lat = plt.subplot(gs[1:3, 2]) m = Basemap(projection='merc', resolution='i', llcrnrlon=llcrnrlon, llcrnrlat=llcr...
<python><matplotlib><plot><histogram><matplotlib-basemap>
2024-02-20 14:14:00
1
461
Roland
78,028,014
11,659,631
pick a specific contour level in seaborn/matplotlib
<p>I have a dataset with x and y variables. I plotted them in a regular plot:<a href="https://i.sstatic.net/wDtCv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wDtCv.png" alt="enter image description here" /></a></p> <p>Now I want to plot the contour level of the density probability contour level eg: 5...
<python><matplotlib><seaborn><contour>
2024-02-20 14:10:45
1
338
Apinorr
78,027,998
15,313,661
Reading a .shp and .shx file from an Azure Data Lake/Blob Container
<p>I am using our Azure Data Factory to load a ZIP from a public api. I then unpack that ZIP using a copy activity, resulting in a bunch of .shp/.shx files.</p> <p>From a Python Script, I then want to use the geopandas package to read the data into a variable. To achieve that I use the following packages:</p> <p>azure-...
<python><encoding><azure-blob-storage><geopandas><shapefile>
2024-02-20 14:08:38
1
536
James
78,027,996
6,760,756
prevent windows popingup when exe run from python
<p>I’m using python to batch run a scientific application (DNDC) compiled for OS Windows using the <code>subprocess.run()</code> function:</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.run(r'root_path_to_dndc/exe/console/DNDC95.exe -s path_to_input.txt -output path_to_output -root ro...
<python><subprocess><exe>
2024-02-20 14:08:10
1
718
Rami
78,027,881
6,803,114
Efficient way to replace parts of a word in a document where the replacement words are defined in a excel
<p>I have a .txt file which is huge I have read it using <code>readlines()</code> in python</p> <p>Sample:</p> <p><code>lines = [&quot;XX_A_Name, A_Bad_Joke = '67' , \n&quot;, &quot;A quick Black.Jack fox JJ_Value over XX_A_Name a.lazy.dog\n&quot;]</code></p> <p>Replacements are defined in excel file:</p> <pre><code>Ol...
<python><python-3.x><replace>
2024-02-20 13:51:16
3
7,676
Shubham R
78,027,676
2,409,868
Mock fails to block expensive resources
<p>In the following minimal code samples I show what should be two identical classes. Both versions work correctly in the original source from which this extract has been drawn.</p> <p>The problem is a normally valid tkinter error message that appears to be wrongly generated. Please note there are many SO questions abo...
<python><mocking><python-dataclasses>
2024-02-20 13:21:24
1
1,380
lemi57ssss
78,027,669
5,368,083
Download multiple files concurrently
<p>I'm using fsspec to interact with remote filesystems, in my case its GCS, but I believe the solution would be general.</p> <p>For a single file, I'm using the following code (if you need the helper function code, it's <a href="https://gist.github.com/eliorc/4edcd45cd20a513aea7682e5142a0824" rel="nofollow noreferrer"...
<python><fsspec>
2024-02-20 13:20:10
1
12,767
bluesummers
78,027,629
6,783,015
Can jax.vmap() do a hstack()?
<p>As the title says, I currently manually <code>hstack()</code> the first axis of a 3D array returned by <code>jax.vmap()</code>. In my code, the copy operation in <code>hstack()</code> is a currently a speed bottleneck. Can I avoid this by instructing <code>jax.vmap()</code> to do this directly?</p> <p>Here is a simp...
<python><arrays><jax><google-jax>
2024-02-20 13:15:23
1
1,172
marnix
78,027,613
14,114,654
Create a column based on similarity to other rows
<p>I have a df with guests, sorted by family. The number of members in a family is not fixed. Two different families may have the same familyhead name (e.g. &quot;abba&quot;).</p> <pre><code> family fam_head name meeting1 meeting2 meeting3 meeting4 0 1 True abba 1 1 1 1 ...
<python><pandas><group-by>
2024-02-20 13:12:52
1
1,309
asd
78,027,549
5,553,963
How to reconnect to RabbitMQ after the RMQ goes down
<p>I have a python code that connects to RMQ and consumes messages. I just noticed that when the RMQ goes down my code just hangs at the close connection (inside aioamqp library) and stuck there and the only solution is to restart my code.</p> <p>I added different exceptions but non solved my problem.</p> <p>My code:</...
<python><rabbitmq><amqp>
2024-02-20 13:02:35
0
5,315
AVarf
78,027,325
17,575,465
Stable baselines 3 throws ValueError when episode is truncated
<p>So I'm trying to train an agent on my custom <code>gymnasium</code> environment trough <code>stablebaselines3</code> and it kept crashing seemingly random and throwing the following <code>ValueError</code>:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\bo112\PycharmProjects\ecocharge\code\S...
<python><reinforcement-learning><openai-gym><stable-baselines>
2024-02-20 12:29:06
1
369
maxxel_
78,027,324
4,858,640
pydantic: JSON dictionary type?
<p>I want to use <code>pydantic</code> to validate that some incoming data is a valid JSON dictionary. There is already the predefined <code>pydantic.Json</code> type but this seems to be only for validating Json strings. Then of course I could use <code>Dict[str, Any]</code> but that allows values that are not valid i...
<python><pydantic>
2024-02-20 12:29:05
1
3,242
Peter
78,027,259
1,219,317
Can ARIMA take input sequence in Python?
<p>In Python, when you train LSTM model you can train the model on part of the data. Then at inference you can give it whatever input you like for example 10 recent timesteps that is not part of the training set. It will produce the output. Now can ARIMA operate in the same way? Can we give it input sequence ? Or does ...
<python><machine-learning><time-series><statsmodels><arima>
2024-02-20 12:16:51
2
2,281
Travelling Salesman
78,027,110
10,167,486
I have a websocket server. It works connecting with postman, but in my react proyect doesnt
<p>So i have a websocket server built with python, which is deployed in a EC2 container. Connecting through postman works perfectly, but when connecting via Websocket in React, it throws always this error:</p> <p>WebSocket connection to 'wss://xxx:3500/' failed:</p> <p>with no further description.</p> <pre class="lang-...
<python><reactjs><next.js><websocket><server>
2024-02-20 11:51:01
2
365
Juan Pedro Pont Vergés
78,027,086
1,668,622
Is it possible to check for a given python file whether it's pyc file is valid and up to date?
<p>For a project which gets deployed to a RO filesystem I want to also deploy pre-compiled <code>.pyc</code> files for all of the Python source.</p> <p>Thanks to the <code>compileall</code> module this already works, but due to whatever reasons caused by a complex build machinery, those <code>.pyc</code> files <em>can<...
<python><python-3.x><bytecode><precompile><pyc>
2024-02-20 11:47:13
1
9,958
frans
78,027,044
11,167,163
Django IIS Deployment - HTTP Error 404.0 - Not Found
<p>I need explanation on how to deploy Django Application on Windows IIS Server.</p> <p>I am struggling to follow the following <a href="https://blog.nonstopio.com/deploy-django-application-on-windows-iis-server-93aee2864c41" rel="nofollow noreferrer">tutorial</a></p> <p>I have a project which looks like this :</p> <pr...
<python><django><iis>
2024-02-20 11:41:51
1
4,464
TourEiffel
78,026,990
8,515,825
How can I uninstall Jupyter Notebook if I don't know the package manager?
<p>I am having troubles with running Jupyter Notebook and want to reinstall it.</p> <p>When I run <code>which jupyter</code>, I get <code>/opt/homebrew/bin/jupyter</code>.</p> <p>However, trying to run <code>brew uninstall jupyter</code> yields <code>Error: No such keg: /opt/homebrew/Cellar/jupyter</code>.</p> <p>Indee...
<python><jupyter-notebook><homebrew><uninstallation><package-managers>
2024-02-20 11:34:13
0
455
chickenNinja123
78,026,989
12,439,683
Narrow down type-hint of return value to child class if function only hints to parent class
<p>I have an external function that works like a factory and returns instances of different classes with a common parent type: e.g.</p> <pre class="lang-py prettyprint-override"><code>class Printer: def make(self, blueprint:str) -&gt; Blueprint: ... class PrintA(Blueprint): def a_specific(self) -&gt; int: .....
<python><mypy><python-typing><pyright>
2024-02-20 11:34:09
3
5,101
Daraan
78,026,944
5,506,167
IronPython garbage collection - How does it provides compatibility with C-extensions?
<p>In this part of the talk on GIL by Larry Hastings, there is an explanation about how <a href="https://code.google.com/archive/p/ironclad/" rel="nofollow noreferrer">ironclad</a> provides C-extension compatibility with IronPython. This is the interesting <a href="https://youtu.be/4zeHStBowEk?list=LL&amp;t=1444" rel="...
<python><garbage-collection><ironpython><python-c-api><reference-counting>
2024-02-20 11:25:59
2
1,962
Saleh
78,026,859
10,595,871
VScode can't find python unittest
<p>I've set up a test in VScode, if I normally run it in the powershell it works fine, but I'm struggling in finding how to properly set it as a test in vscode.</p> <p>I've already tried all of the thing I found so:</p> <ul> <li>addedd an <code>__init__.py</code> file in the test directory</li> <li>in the command palet...
<python><unit-testing><visual-studio-code>
2024-02-20 11:12:40
1
691
Federicofkt
78,026,771
1,606,657
python - handle exceptions with curses wrapper
<p>I'm following the documentation <a href="https://docs.python.org/3/howto/curses.html" rel="nofollow noreferrer">https://docs.python.org/3/howto/curses.html</a> to setup a <code>curses</code> app in Python. According to the documentation it is recommended to use the <code>wrapper</code> as it auto initializes everyth...
<python><curses>
2024-02-20 11:01:32
1
6,352
wasp256
78,026,674
16,627,522
Pybind11/Nanobind: How to return class object and use methods from Python. How can I cast the C++ object to something whose methods I can use in Py
<p>I'm not sure why I can't find any good discussion of this, I have been searching since yesterday.</p> <p>How do you return a class object from C++ binding and use its methods in Python i.e.:</p> <pre><code>class A { ... void foo() { py::print(&quot;Hello world&quot;); } } class B { ... A...
<python><c++><boost-python><pybind11><nanobind>
2024-02-20 10:44:50
1
634
Tommy Wolfheart
78,026,618
237,105
Cannot connect slot to pqtgraph InfiniteLine signal with connectSlotsByName
<p>I'm using the following code to call a function whenever the infinite line is dragged. It does not call the function.</p> <pre class="lang-py prettyprint-override"><code> import sys import pyqtgraph as pg from PyQt5.QtCore import pyqtSlot as Slot, Qt, QMetaObject from PyQt5.QtWidgets import * ...
<python><pyqt><signals><signals-slots><pyqtgraph>
2024-02-20 10:37:46
1
34,425
Antony Hatchkins
78,026,604
4,269,851
Python break loop with one line of code without using enumerate()
<p>If I want to add a break to my <code>for</code> or <code>while</code> loop at certain iteration can it be done without adding counter?</p> <pre><code> i=1 for line in zip(*input): print(format_row.format(*line)) if i &gt; 3: break i += 1 </code></pre> <p>also without <code>enumerate()<...
<python><loops><break>
2024-02-20 10:35:00
1
829
Roman Toasov
78,026,487
412,137
SpecTree - is there a way to hide an endpoint from swagger
<p>I am currently working on a Flask project and using Spectree version 1.2.8 for API validation. For certain endpoints, I want to restrict their visibility on the Swagger UI documentation generated by Spectree to keep them private or for internal use only.</p> <p>Could anyone guide me on whether it's possible to exclu...
<python><flask>
2024-02-20 10:19:19
1
2,767
Nadav
78,026,458
127,508
How to convert binary Postgres data to text with Polars?
<p>I am extracting data from POstgres with Polars.</p> <p>The table looks like this:</p> <pre><code> | Column | Type | |----------------+--------------------------+ | seq_id | bigint | | id | uuid | | version | integer ...
<python><postgresql><python-polars>
2024-02-20 10:15:17
1
8,822
Istvan
78,026,404
3,650,983
list of supported backbones models
<p>I'm running the following example:</p> <pre><code>from transformers import TimmBackboneConfig, TimmBackbone # Initializing a timm backbone configuration = TimmBackboneConfig(&quot;resnet50&quot;) # Initializing a model from the configuration model = TimmBackbone(configuration) # Accessing the model configuration ...
<python><machine-learning><pytorch><huggingface-transformers><huggingface>
2024-02-20 10:07:59
1
4,119
ChaosPredictor
78,026,392
8,832,641
Get Azure Application ID from Enterprise Application Name in python
<p>I have an Azure Application name and I would like to know if there is a way to get the application ID of the enterprise application in python.</p> <p>I am able to authenticate myself by passing in the clientID/ApplicationID and secret. But, I would like to know if there is a way to fetch client id/application ID usi...
<python><azure>
2024-02-20 10:06:01
1
1,117
Padfoot123
78,026,316
11,861,874
Excel Data to be updated using python in a loop
<p>I have below table to update in excel using python. I tried groupby and also loop or iterrow method but failed to populate values.</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>AGE</th> <th>INCOME</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>32</td> <td>50,000</td> <td></td> </tr...
<python><excel>
2024-02-20 09:55:57
1
645
Add
78,026,306
532,054
Django Rest Framework basic set of APIs around authentication
<p>I'm a django newby and I'm looking to expose basic services like: forgotten password, password change.</p> <p>I would expect to have those services for free but looking here and there it looks like we have to do them by hand, is that correct?</p> <p>Is there any explanation for that?</p>
<python><django><authentication><django-rest-framework>
2024-02-20 09:54:15
1
1,771
lorenzo
78,026,256
12,304,000
filter out dagster assets based on group_name
<p>In my assets file, I have 3 groups but they are differentiated based on their <strong>group_name</strong>*</p> <p><strong>assets/my_assets.py:</strong></p> <pre><code>@asset( group_name=&quot;group1&quot; ) def group1_data(context: AssetExecutionContext): x = 1 + 3 @asset( group_name=&quot;group1&q...
<python><assets><jobs><directed-acyclic-graphs><dagster>
2024-02-20 09:47:36
1
3,522
x89
78,026,226
1,613,983
"Incorrect number of bindings supplied" when inserting into SQLite DB
<p>I'm trying to check whether a row exists and contains some expected values, but I keep getting this error:</p> <blockquote> <p>Incorrect number of bindings supplied. The current statement uses 1, and there are 5 supplied.</p> </blockquote> <p>Here's a minimal reproduction of the error:</p> <pre><code>import sqlite3 ...
<python><sqlite>
2024-02-20 09:44:17
1
23,470
quant
78,026,207
15,136,864
Stream connection lost: RxEndOfFile(-1, 'End of input stream (EOF)' when connecting from Lambda to Amazon MQ using Python + AMQP
<p>My goal is to create a client responsible for sending messages from AWS Lambda to Amazon MQ (ActiveMQ Classic) through AMQP protocol. I've done everything according to the <a href="https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/amazon-mq-rabbitmq-pika.html" rel="nofollow noreferrer">documentation</a>.<...
<python><amazon-web-services><ssl><amazon-mq>
2024-02-20 09:41:22
1
310
Sevy
78,026,120
1,493,192
Merge two dataframe in pandas with different size
<p>I want to find a method to join two dataframes in pandas in an elegant way without doing grafted loops. The first dataframe appears with the following structure and a &quot;week_of_year&quot; column</p> <p><a href="https://i.sstatic.net/yPrGa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yPrGa.png" ...
<python><pandas><dataframe>
2024-02-20 09:29:58
1
8,048
Gianni Spear
78,025,987
21,049,944
polars - what does "fortran-like indexing" mean and how to enforce it?
<p>I am trying to use <code>to_numpy(allow_copy=False)</code> on my polars dataframe, but I am getting:</p> <p><code>RuntimeError: copy not allowed: only numeric data without nulls in Fortran-like order can be converted without copy</code></p> <p>Since I checked that <code>df.select(pl.all().is_null().sum())</code> giv...
<python><numpy><python-polars><zero-copy>
2024-02-20 09:09:18
0
388
Galedon
78,025,976
5,868,293
Create a column for cumulative sum for each string value in a column pandas
<p>I have the following pandas dataframe</p> <pre><code>import pandas as pd import random random.seed(42) pd.DataFrame({'index': list(range(0,10)), 'cluster': [random.choice(['S', 'C', ]) for l in range(0,10)]}) index cluster 0 0 S 1 1 S 2 2 C 3 3 S 4 4 S 5 5 S 6 6 S 7 ...
<python><pandas>
2024-02-20 09:07:53
3
4,512
quant
78,025,970
12,314,521
How to asign a tensor of value to another tensor of value by a tensor of indices (Pytorch)
<p>Given:</p> <ul> <li>a tensor A of zeroes has shape: (batch_size, vocab_size), lets say (16, 10000)</li> <li>a tensor B is tensor of indices has shape: (batch_size, seq_len), lets say (16, 20)</li> <li>a tensor C is tensor of value has shape: (batch_size, seq_len), -&gt; (16, 20)</li> </ul> <ol> <li><p>Now I want to ...
<python><pytorch><tensor>
2024-02-20 09:07:19
1
351
jupyter
78,025,938
769,405
Are DBT Python models with Snowflake but without Snowpark possible?
<p>A significant chunk of one of my pipelines utilises DBT Python models that write to Snowflake. Originally these were workbooks in Databricks. We have moved everything to Snowflake recently. The code originally generated asynchronous inserts to the DB in a loop. However, Snowpark Session library is not threadsafe, so...
<python><snowflake-cloud-data-platform><dbt>
2024-02-20 09:00:54
0
1,074
mikelus
78,025,925
4,521,319
PySpark Error - SparkContext can only be used on the driver, not in code that it run on workers
<p>I have a PySpark job that reads data into a dataframe and tokenizes a column as a part of the transformations. I have the follwoing:</p> <p><code>Main.py</code> - reads configs and creates sparkSession</p> <p><code>Extractor.py</code> - reads the data from source and returns the dataframe to <code>main.py</code></p>...
<python><apache-spark><pyspark><apache-spark-sql>
2024-02-20 08:58:59
0
925
Hemanth Annavarapu
78,025,817
16,436,095
Too fast checking local ports with python socket
<p>This code example is given in the book &quot;CPython Internals&quot;.</p> <pre class="lang-py prettyprint-override"><code>from queue import Queue import socket import time timeout = 1.0 def check_port(host: str, port: int, results: Queue): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settim...
<python><sockets><python-sockets>
2024-02-20 08:38:50
1
370
maskalev
78,025,739
815,859
Call a function on Raspberry Pi Pico from PC using pyserial
<p>I have a small python file in Raspberry Pi Pico that can control servos via PCA9685 servo controller:</p> <pre><code>import time from adafruit_servokit import ServoKit import busio import board import time kit = ServoKit(channels=16, i2c=(busio.I2C(board.GP1, board.GP0))) def rotateservo(): kit.servo[0].angle =...
<python><pyserial><raspberry-pi-pico>
2024-02-20 08:22:18
1
795
Monty Swanson
78,025,726
714,564
Selenium printing with chrome, keeps showing a save popup
<p>I need some automated script that will print a page. This script has to run on Chrome, as FF does not give me a decent output for this printing task. I tried several things, but for some reason it still requeires a filename, and it ignores what I use for both savefile.default_directory and download.default_directory...
<python><selenium-webdriver><selenium-chromedriver>
2024-02-20 08:19:39
2
671
GuruYaya
78,025,589
13,320,357
Scheduled cron job not getting executed
<p>I have a cron job scheduled as follows inside an EC2 instance operating on Amazon Linux OS:</p> <pre><code>51 7 * * * /usr/bin/python3 /home/ec2-user/set_access_token.py &gt; /home/ec2-user/access_token_logs.txt </code></pre> <p>The job is not getting executed despite providing the native path of python3 and specify...
<python><python-3.x><amazon-web-services><amazon-ec2><cron>
2024-02-20 07:55:17
1
415
Anuj Panchal
78,025,330
11,267,783
Python link between properties
<p>I wanted to know if there is an easy way to link properties in a object. This is my code :</p> <pre class="lang-py prettyprint-override"><code>import numpy as np obj = {} obj[&quot;data&quot;] = np.linspace(1,10) obj[&quot;first&quot;] = obj[&quot;data&quot;][0] # obj[&quot;first&quot;] = 1 obj[&quot;last&quot;] = ...
<python>
2024-02-20 07:04:32
1
322
Mo0nKizz
78,025,039
11,098,908
Matplotlib: ValueError: 'steps' is not a valid value for ls
<p>The following code came from the <a href="https://www.packtpub.com/en-au/product/matplotlib-30-cookbook-9781789135718?type=print&amp;gad_source=1&amp;gclid=CjwKCAiAlcyuBhBnEiwAOGZ2S5AG1tIdmdDusS18Q4CYS6Cv8c3TLClPdVPEMOz85nEEyw5kpOYxmRoCJLoQAvD_BwE" rel="nofollow noreferrer">Matplotlib 3.0 Cookbook</a></p> <pre><code...
<python><matplotlib>
2024-02-20 05:51:08
1
1,306
Nemo
78,025,006
1,453,157
How to open content in a new tab using Python + Selenium
<p>I am using Python + Selenium.</p> <p>Browsing this page</p> <p><a href="https://rovo.co/explore/activities" rel="nofollow noreferrer">https://rovo.co/explore/activities</a></p> <p>you will see many activities.</p> <p>Using Python + Selenium, how can I open each activity in a new tab, and switch to the new tab?</p> <...
<python><selenium-webdriver>
2024-02-20 05:42:50
3
503
J K
78,024,843
9,997,385
multipart POST with python requests unsupported media type
<p>Trying to recreate the following cURL with Python requests. I see <a href="https://stackoverflow.com/questions/17415084/multipart-data-post-using-python-requests-no-multipart-boundary-was-found">here</a> that I &quot;should NEVER set <code>&quot;content-type&quot;: 'multipart/form-data'</code>&quot; header. Instead,...
<python>
2024-02-20 04:43:33
0
643
A. Gardner
78,024,426
9,614,610
How to make two mouseMoveEvents work together
<p>I have a QGraphicsEllipseItem and a QGraphicsScene, both of which have custom mouseMoveEvent and mousePressEvent functions. However, for some reason, the mouseMoveEvent only seems to work for the QGraphicsScene. My guess is that the QGraphicsScene event is overriding the QGraphicsEllipseItem event. But, the mousePre...
<python><pyqt><pyqt5>
2024-02-20 02:03:27
1
417
Vlad