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,577,545
3,466,818
How can I access a buffer or sequence in an unusual order?
<p>I have a block of memory representing RGB values for a 8 row x 32 column matrix. When writing into this block of memory, it would be convenient to treat it as properly ordered. When reading from the memory (and pushing into a peripheral), due to the way the electronics are wired, every other column is reversed.</p...
<python><list><slice><sequence><memoryview>
2024-06-04 20:14:30
1
706
Helpful
78,577,362
10,727,283
Should a Protocol with @property change runtime behavior in Python?
<p>I thought python <code>Protocol</code> was only useful for type-hints, without any impact on the runtime behavior (except when using <code>@runtime_checkable</code> or default method implementation).</p> <p>But see this example:</p> <pre class="lang-py prettyprint-override"><code>from typing import Protocol class P...
<python><protocols><python-typing><mypy>
2024-06-04 19:27:02
1
1,004
Noam-N
78,577,145
4,865,723
How to extract glm() results from R objects using Pythons rpy2?
<p>I use <em>Python</em> <code>rpy2</code> to run <code>glm()</code> (regression model) in <em>R</em>. My problem is to get a result back that I can handle. The best would be a nice data structure (dict, dataframe, ...) but I also would be satisfied with a human readable multi-line string.</p> <p>Using <code>glm()</cod...
<python><rpy2>
2024-06-04 18:32:01
1
12,450
buhtz
78,577,010
13,721,819
How to suppress stdout within a specific python thread?
<p>I want to be able to suppress any print to stdout within a specific thread. Here is what I have tried:</p> <pre><code>import sys, io, time from threading import Thread def do_thread_action(): # Disable stdout sys.stdout = io.StringIO() print(&quot;don't print this 1&quot;) time.sleep(1) print(...
<python><stdout><python-multithreading>
2024-06-04 17:56:39
1
612
Wilson
78,576,942
11,402,025
Pydantic model : add case insensitive field
<p>I have a confirm field that accepts yes ( case insensitive ) input from the user. This is how I am implementing it :</p> <pre><code>class ConfirmEnum(str, Enum): yes = &quot;yes&quot; Yes = &quot;Yes&quot; YES = &quot;YES&quot; </code></pre> <pre><code>class OtherFields(CamelModel): data: int con...
<python><enums><model><fastapi><pydantic>
2024-06-04 17:37:41
1
1,712
Tanu
78,576,803
5,568,409
Title is bold, but label is not. What to do?
<p>I made a small reproducible program, where you will see the <code>title</code> in bold font, but the <code>label</code> in normal font:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np observed = np.array([28, 15, 21, 23, 17, 22, 19, 19, 24, 27, 20, 21, 25, 25, 16, 20, 23]) f...
<python><matplotlib><fonts>
2024-06-04 17:01:28
1
1,216
Andrew
78,576,526
237,225
PyTorch Startup High Memory Consumption Without Import
<p>I have a docker container running a Python (3.10) Flask app. The app had high baseline memory usage (1 GB+) when loading/idle. The app was formerly dependent on these 17 <code>requirements</code> dependencies. I removed two dependencies: <code>angle-emb</code> and <code>sentence-transformers</code>. <code>torch 2.3....
<python><python-3.x><memory><pytorch>
2024-06-04 15:58:08
0
3,719
JJ Zabkar
78,576,521
3,124,181
How to run commands from Python console with the same config as Pycharm Terminal
<p>Is there a quick/practical way to run commands from the Pycharm Python console with exactly the same configurations as Pycharm Terminal?</p> <p>I.e. I am able to run certain software like <code>wget</code> from Pycharm's terminal but not from the python console <code>os.system(&quot;wget&quot;)</code> which gives me...
<python><terminal><pycharm>
2024-06-04 15:57:16
0
903
user3124181
78,576,403
8,964,393
Open html file and insert a plot in Python
<p>I have an html file called <code>output.html</code> (see the html code at the bottom of this message).</p> <p>The html file contains the following table.</p> <p><a href="https://i.sstatic.net/zZNBto5n.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zZNBto5n.png" alt="enter image description here" /></...
<python><html><file><html-table><format>
2024-06-04 15:32:46
0
1,762
Giampaolo Levorato
78,576,317
6,930,340
Python hypothesis dataframe assume column not exclusively consisting of NaN values
<p>I am producing a <code>pd.DataFrame</code> using the <code>hypothesis</code> library like so:</p> <pre><code>import datetime from hypothesis import strategies as st from hypothesis.extra.pandas import columns as cols from hypothesis.extra.pandas import data_frames, indexes data_frames( columns=cols( [&q...
<python><pandas><python-hypothesis>
2024-06-04 15:19:15
1
5,167
Andi
78,576,288
5,558,497
expand based on a dictionary
<p>Considering I have the following Python dictionary:</p> <pre><code>d = {'A': ['a', 'b', 'c], 'B': ['d', 'e', 'f']} </code></pre> <p>Considering the keys in <code>d</code>, I would like to produce a plot with the following pattern <code>f&quot;{key}/plot/{d[key]}&quot;</code>, for every element in <code>d[key]</...
<python><snakemake>
2024-06-04 15:12:58
1
2,249
BCArg
78,576,233
1,417,735
How do you get 'additional' combinations when adding items to a list that I have already gotten all combinations for?
<p>Using python I would like to calculate all combinations of 3 from a list.</p> <p>For example, list = [a,b,c,d] and combinations would be - [a,b,c], [a,b,d], [a,c,d], [b,c,d].</p> <p>And then I would like to add some items to the original list and get only the additional combinations of 3.</p> <p>For example, adding ...
<python><combinations>
2024-06-04 15:01:42
1
1,287
shawn.mek
78,576,088
10,633,596
How to create Pandas data frame with dynamic values within a for loop
<p>I'm literally new to data engineering where I'm using Python, PySpark and Pandas to create a data frame and I'm since a very long time I'm blocked and could not put my head around it. It is a simple problem but I'm stuck here.</p> <p>Here is my code snippet which works fine (assuming there is only 1 primary key) wit...
<python><pandas><pyspark>
2024-06-04 14:37:11
1
1,574
vinod827
78,575,906
6,195,489
How to use a dask cluster as a scheduler for dask.compute
<p>I have a class that has something like the following context manager to create a dask client &amp; cluster:</p> <pre><code>class some_class(): def __init__(self,engine_kwargs: dict = None): self.distributed = engine_kwargs.get(&quot;distributed&quot;, False) self.dask_client = None ...
<python><dask><dask-delayed>
2024-06-04 14:02:21
1
849
abinitio
78,575,791
14,282,714
Submit results to fill a dataframe in streamlit
<p>I would like to build a streamlit app where the user gives some inputs and every time it uses the <code>form_submit_button</code> button, it will fill a dataframe row by row to collect user data. Currently I have the following app:</p> <pre><code>import streamlit as st import pandas as pd import numpy as np # page ...
<python><streamlit>
2024-06-04 13:41:41
1
42,724
Quinten
78,575,696
293,420
Firebase admin authentication works in interpreter but fails in production
<p>I'm interfacing with the resources of a firebase project.</p> <p>From a VM in GCP I am using python to get information from the database and files from the bucket. The VM has gcloud installed and the VM is authenticated using the firebase service account which should have all privileges for the firebase app.</p> <p>...
<python><firebase><firebase-authentication><gcloud><firebase-admin>
2024-06-04 13:23:54
0
3,654
lesolorzanov
78,575,692
13,946,204
How to use structlog with logfmt formatted logs in python?
<p>I want to print out root logs in <code>logfmt</code> format. <code>structlog</code> also should print logs in the same format. I tried <a href="https://www.structlog.org/en/stable/standard-library.html#rendering-using-logging-based-formatters" rel="nofollow noreferrer">this example</a> for JSON format and looks like...
<python><logging><structlog>
2024-06-04 13:23:10
1
9,834
rzlvmp
78,575,645
25,413,271
Python re, extract path from text
<p>I receive a text like:</p> <pre><code>`D:\Programming\sit\bin\MyLab.json` </code></pre> <p>It may contain different kind of quotes or may not contain them. Quotes if present are placed strictly at the beggining and at the end of the text, wrapping the path. But the text definately contains absolute windows path of a...
<python><python-re>
2024-06-04 13:17:25
3
439
IzaeDA
78,575,463
17,672,187
Fitting outer edge of a rough rectangle with rounded corners
<p><a href="https://i.sstatic.net/8Wa66uTK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8Wa66uTK.png" alt="enter image description here" /></a></p> <p>I have detected edges of an image with openCV (shown with green points) as</p> <pre><code> edges = cv2.Canny(gray, canny_0, canny_1) ker...
<python><opencv><image-processing><scikit-image>
2024-06-04 12:40:39
1
691
Loma Harshana
78,575,343
2,749,397
How to set a distinct label for each plotted curve?
<p><a href="https://i.sstatic.net/lUcCFk9F.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lUcCFk9F.png" alt="enter image description here" /></a></p> <pre><code>In [9]: %matplotlib qt ...: from sympy import * ...: ...: x = symbols('x') ...: plot(4-x**3/2, x*x, (x, 0, 2), legend=1) </code></...
<python><plot><sympy>
2024-06-04 12:12:55
0
25,436
gboffi
78,575,313
6,929,467
Need Help Reducing OpenAI API [Python] Costs: Here's My Code
<p>I then call like 500 times the <code>get_category_and_subcategory</code> function.. It cost me like 60$ which is too much for this type of job. Am I doing something wrong and what could be improved?</p> <p>It seems my problem is that the category_and_subcategory is huge, that seems to be causing the biggest cost, co...
<python><openai-api><chatgpt-api><cost-management>
2024-06-04 12:08:55
1
2,720
innicoder
78,575,261
896,451
What's the significance of `SyntaxError: 'break' outside loop` v. `SyntaxError: 'continue' not properly in loop`?
<p>I accept that, due to Python language limitation, <code>continue</code> must be within a loop &quot;properly&quot; i.e. <a href="https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement" rel="nofollow noreferrer">&quot;not nested in a function or class definition within that loop.&quot;</a></p> <...
<python>
2024-06-04 11:56:28
2
2,312
ChrisJJ
78,575,177
10,396,491
Reading PETSc binary matrix in Python
<p>I am trying to read a sparse PETSc matrix saved from a Fortran code into a binary file like so:</p> <pre><code>CALL PetscViewerBinaryOpen(PETSC_COMM_SELF, TRIM(ADJUSTL(filename)), FILE_MODE_WRITE, viewer2, ier) CALL MatView(aa_symmetric, viewer2, ier) CALL PetscViewerDestroy(viewer2, ier) </code></pre> <p>When I run...
<python><fortran><petsc>
2024-06-04 11:43:09
1
457
Artur
78,575,142
11,751,799
`matplotlib` figure border and text disagree about the figure limits
<p>I find the behavior of the following image to be surprising.</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.text(1.3, 1.3, &quot;ABC&quot;, color = 'red') # Add blue border # fig.patch.set_linewidth(3) fig.patch.set_edgecolor(&quot;blue&quot;) fig.text(0, 1, &quot;DEF&quot;, color = ...
<python><matplotlib><plot><graph>
2024-06-04 11:37:22
0
500
Dave
78,574,926
351,410
Python: concise float format without losing order of magnitude
<p>For easy comparison at a glance, statistical results in my project are usually best formatted as <code>0.3f</code>, except (a) where decimal places are useless, or (b) where there is a small fraction such that the first 3 places are all zero. As of Python 3.11.8, there doesn't seem to be a built-in format that alway...
<python><floating-point><format><precision>
2024-06-04 10:52:17
2
2,715
Byron Hawkins
78,574,898
5,306,861
How to find Base-line of Curved Text?
<p>Attached is a picture with curved lines, how can you find the <strong>Baseline</strong> of the text?</p> <p><a href="https://i.sstatic.net/269aSnEM.jpg" rel="noreferrer"><img src="https://i.sstatic.net/269aSnEM.jpg" alt="enter image description here" /></a></p> <p>The goal is to get lines like I drew by hand in the ...
<python><algorithm><opencv><image-processing><ocr>
2024-06-04 10:46:09
2
1,839
codeDom
78,574,847
227,860
DST aware shift in polars
<p>I'm working with a dataset that is dependent on local dates and times. I want to add a lag so a row has access to the values from the previous <code>n</code> days. The challenge here comes from the DST transitions. Sometimes there are too few or too many records in one of the previous days. For example, when changin...
<python><python-polars>
2024-06-04 10:36:59
1
852
kvaruni
78,574,826
6,997,665
Indexing from a 3D numpy array using another 3D numpy array
<p>I have a 3D array, say <code>a</code>. I want to create another array <code>b</code> which has <code>0</code>s at least and second least absolute values in <code>a</code>. My approach is as follows</p> <pre><code>import numpy as np a = np.random.randn(100, 4, 4) c = np.argsort(np.abs(a), axis=2)[..., :2] b = np.one...
<python><arrays><numpy>
2024-06-04 10:32:31
1
3,502
learner
78,574,815
3,929,481
Obtain type annotation of a function argument
<p>Since Python 3.5 type aliases are available (with a simplified syntax since 3.12),</p> <pre><code>type T = int # introduces type alias T t: T = 1 # annotates t as type T </code></pre> <p>The type annotation of variable <code>t</code> can be found in the <code>__annotations__</code> dict</p> <pre><code>&gt;&gt;&g...
<python><python-typing>
2024-06-04 10:29:10
1
2,053
mcmayer
78,574,458
6,941,400
How can I automate the connection to an On Prem Windows VM that uses Azure AAD for authentication?
<p>My requirement is to automate the transfer of files, and running commands on the Windows VM, which is currently a manual process where I log in to the VM via RDP (and it prompts me for my username/password of my account).</p> <p>I have been doing a bit of digging on this, as I am able to automate the same thing for ...
<python><windows><ssh><automation><azure-active-directory>
2024-06-04 09:23:52
0
576
Anshuman Kumar
78,574,396
1,658,080
How to extract nested text while keeping line breaks?
<p>I want to extract text from an extremely nested website without any obvious pattern nor classes I can use.</p> <p>That's why I need to write a logic which is quite &quot;generic&quot; and works in multiple scenarios. That's where I need some support.</p> <p>If we have for example:</p> <pre><code>&lt;div&gt;&lt;span&...
<python><web-scraping><beautifulsoup>
2024-06-04 09:10:22
2
725
Clms
78,574,392
10,517,777
Create a log file only when there were logs
<p>Python version: 3.11.8</p> <p>Hi everyone,</p> <p>I am using the package logging to log of the execution. I am using <code>logging.basicConfig</code> to output the logs in a log file. I added it at the beginning of my python script. I realised a file was created when invoking <code>logging.basicConfi</code>g. Howeve...
<python><logging><python-logging>
2024-06-04 09:09:17
1
364
sergioMoreno
78,574,357
19,130,803
Given argument of list[int] | list[str], can't I be sure that the list is list[int] if element [0] is int, and vice versa?
<p>I have a <code>python</code> script and trying to add type hints to the code, Following is the sample code (without type hints the code works) using <code>mypy</code>.</p> <pre><code>values_int: list[int] = [1, 2, 3, 4] values_str: list[str] = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;] def bar(*, ...
<python><mypy><python-typing>
2024-06-04 09:00:05
1
962
winter
78,574,168
2,398,430
pytest - collect information about test together with parameters
<p>I am using pytest. I would like to query the framework to get a list of all the tests that would be scheduled to run, together with the parameters for each test.</p> <p>By query, I mean an action to acquire that info.</p> <p>When I execute <code>pytest -s --co</code>, I get some info but not all the info. The issue ...
<python><pytest>
2024-06-04 08:20:51
1
366
stackQA
78,574,071
8,869,003
Prevent django from writing e-mail information to stdout
<p>I'm using django 2.2. with python 3.6. In some cases my server stores stdout into a log used by managers.</p> <p>For some reason django started to write to stdout at send-mail some time ago. The managers do not like it because it looks like en error case for them.</p> <p>So the following sends the e-mail, but also w...
<python><django><smtp>
2024-06-04 07:58:20
0
310
Jaana
78,574,047
5,786,649
Python setattr and getattr: best practice with flexible, mutable object variables
<p>I have a class that holds an unspecified number of dicts as variables. I want to provide methods that allow the user to easily append to any of the dicts while naming the corresponding variable, without having to check whether the variable was already created. Example for my goal:</p> <pre class="lang-py prettyprint...
<python><dictionary>
2024-06-04 07:55:43
1
543
Lukas
78,574,035
11,562,537
Tkinter - How can I disable the "undo" option for a default message saved in a text widget?
<p>I have a text widget with the &quot;undo&quot; option activated and a default message already inserted. In this case, how can I avoid affecting the default message using <kbd>Ctrl+Z</kbd>? In my mind it should work only for the new text inserted by the user but it always deletes all the text. How can I solve this is...
<python><tkinter><text><tkinter-text>
2024-06-04 07:52:48
1
918
TurboC
78,573,979
2,604,247
Does Ray Offer any Functional/Declarative Interface to Map a Remote Function to an Iterator/Iterable?
<h4>My present Code</h4> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # encoding: utf-8 &quot;&quot;&quot;Demonstration of Ray parallelism&quot;&quot;&quot; import ray from typing import Iterator ray.init() @ray.remote def square(n:int)-&gt;int: return n*n references: Iterator[ray.ObjectR...
<python><concurrency><functional-programming><ray>
2024-06-04 07:41:42
2
1,720
Della
78,573,962
8,163,773
Getting google oauth tokens using "code" with python
<p>I want to create an auth flow using react + python Here is an <a href="https://github.com/MomenSherif/react-oauth/issues/12#issuecomment-1131408898" rel="nofollow noreferrer">example</a> of how to do it with react + node.js:</p> <pre><code>const { tokens } = await oAuth2Client.getToken(req.body.code); </code></pre> ...
<python><google-oauth>
2024-06-04 07:38:04
1
9,359
Arseniy-II
78,573,789
8,964,393
Export multiple pandas crosstabs into one html file with table of contents
<p>I have created a pandas dataframe as follows:</p> <pre><code>import pandas as pd import numpy as np ds = {'col1' : [1,1,2,3,4], 'col2' : [1,1,3,4,5], 'col3': [3,3,3,3,3]} df = pd.DataFrame(data=ds) </code></pre> <p>The dataframe looks like this:</p> <pre><code>print(df) col1 col2 col3 0 1 1 3 1 ...
<python><html><templates><format>
2024-06-04 06:57:37
0
1,762
Giampaolo Levorato
78,573,661
893,254
Calculating a rolling mean window with Pandas with data which is non-periodic
<p>I have some existing Pandas code which calculates the mean of some timeseries data on a month period.</p> <pre><code> df .groupby( pandas.Grouper( key='transaction_date', freq='M', ) ) .aggregate( { 'transaction_date': 'first', 'price': 'mean' } ) </code></pre> <p>The ...
<python><pandas>
2024-06-04 06:26:55
0
18,579
user2138149
78,573,638
1,082,349
Reindex to expand and fill value only across one level of multi-index
<p>I have a dataframe with an index of (month, A, B):</p> <pre><code> foo N month A B 1983-03-01 3 9 0 1 1983-06-01 3 9 0 1 1983-09-01 3 9 0 1 1983-11-01 4 5 0 1 1984-05-01 4 5 0 1 1984-06-01 3 9 0 1 1984-09-01 ...
<python><pandas>
2024-06-04 06:19:19
2
16,698
FooBar
78,573,164
5,273,594
Value from F expression in Django ORM is not a decimal and Objects has to field named
<p>I have the following classes/models and I'm trying to do bulk update thousands of Recipt objects to have an Item JSON object in the details section</p> <pre><code>from django.db import models from schematics import models as schema_models class Recipt(models.Model): id = UUID() is_red = models.BooleanField(...
<python><json><django><django-models><orm>
2024-06-04 02:46:33
0
2,073
Fredy
78,573,014
9,279,753
Forward slash being changed to "%2F" when deploying Azure Function
<p>I have an Azure Function that connects to an Azure File Storage account.</p> <p>The File Storage Account is structure like the following:</p> <pre><code>ShareName ShareName/folder_1 ShareName/folder_1/subfolder_1 ShareName/folder_1/subfolder_1/other_folder ShareName/folder_1/subfolder_1/another_folder ShareName/fold...
<python><azure><azure-functions><azure-file-share>
2024-06-04 01:13:37
1
599
Jose Vega
78,572,954
3,610,310
Using CloudLinux to create a Python app getting error Specified directory already used by '/path/to/application'
<p>I am using cloudlinux through DirectAdmin (this shouldn't matter) and I am trying to create a new Django application using the &quot;Setup Python App&quot; create application option. I have uploaded my django files properly and I am certain that the correct permissions are set to the applications folder (i.e. <code>...
<python><node.js><django><directadmin>
2024-06-04 00:39:37
1
3,475
jAC
78,572,945
14,673,832
× Encountered error while trying to install package. ╰─> typed-ast
<p>I have a django project which I cloned into my local but I am not being able to start backend coding because of the requirements not being installed. Everytime I try to install the requirements.txt, it gives me the following error.</p> <pre><code>note: This error originates from a subprocess, and is likely not a pro...
<python><django><pip><requirements.txt><typed>
2024-06-04 00:35:05
1
1,074
Reactoo
78,572,914
896,451
On this Conditional Expression, what the syntax error about?
<p>I get:</p> <pre><code> return r.group() if r := re.match(rx,l) else None ^ </code></pre> <p>SyntaxError: invalid syntax</p> <p>whereas</p> <pre><code> return r.group() if (r := re.match(rx,l)) else None </code></pre> <p>is accepted.</p> <p>What is invalid about the first's syntax? And w...
<python><python-3.x><conditional-operator><python-assignment-expression>
2024-06-04 00:14:35
1
2,312
ChrisJJ
78,572,908
1,593,783
Python initializes method parameters instead of using default values
<p>I have created a class:</p> <pre><code>class PolicyJSON: def __init__(this, path:str=&quot;&quot;, values:dict={}, children:list=[], parent=None): this.path = path this.values = values this.children = children this.parent = parent this.path = this.getfullpath() </code></p...
<python>
2024-06-04 00:11:21
1
10,128
ojek
78,572,746
5,042,280
How to use Python Click's `ctx.with_resource` to capture tracebacks in (sub-)commands/groups
<p>In Click, <code>Context.with_resource</code>'s <a href="https://click.palletsprojects.com/en/8.1.x/api/#click.Context.with_resource" rel="nofollow noreferrer">documentation</a> states it can be used to:</p> <blockquote> <p>[r]egister a resource as if it were used in a <code>with</code> statement. The resource will b...
<python><python-click>
2024-06-03 22:47:04
1
506
Adam
78,572,702
1,718,989
How to Slice Multi Dimensional Array?
<p>Dipping my toes into multi dimensional array slicing in Python and am hitting a wall of confusion with the following code</p> <pre><code># Example 2D array matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Basic slicing result = matrix[0:2][1:2] print(result) </code></pre> <p>So when I read this example wit...
<python><arrays><multidimensional-array><slice>
2024-06-03 22:29:16
1
311
chilly8063
78,572,653
6,666,008
Automating pdf to pdf/A-2b conversion using ghostscript. How to overcome icc color profiling error?
<p>I'm trying to figure out how to convert pdf's to pdfa2b format for archiving. The batch process only takes in 600-800 files at a time, and we have over half a million files. It would take an eternity if we do it one by one (probably 20 months at this rate). Any help is appreciated. Is there a way within Adobe to ach...
<python><adobe><ghostscript><pdfa>
2024-06-03 22:09:22
1
682
ss301
78,572,444
2,153,235
Python regular expression adorns string with visible delimiters, yields extra delmiter
<p>I am fairly new to Python and pandas. In my data cleaning, I would like to see the I performed previous cleaning steps correctly on a string column. In particular, I want to see where the strings begin and end, regardless of whether they have leading/trailing white space.</p> <p>The following is meant to bookend e...
<python><pandas><regex>
2024-06-03 20:41:02
0
1,265
user2153235
78,572,415
10,994,166
Create a Sparse vector from Pyspark dataframe maintaing the index
<p>I have pyspark df like this:</p> <pre><code>+--------------------+-------+----------+----------+----------+----------+--------+ | user_id|game_id|3mon_views|3mon_carts|3mon_trans|3mon_views| dt| +--------------------+-------+----------+----------+----------+----------+--------+ |0006e38c8968431f8......
<python><dataframe><pyspark><apache-spark-sql><sparse-matrix>
2024-06-03 20:33:50
0
923
Chris_007
78,572,370
2,115,971
Difference between accuracy during training and accuracy during testing
<p>In the model below the accuracy reported at the end of the final validation stage is 0.46, but when reported during the manual testing the value is 0.53. What can account for this discrepancy?</p> <pre class="lang-py prettyprint-override"><code>import torch from torch import nn import torchvision.models as models im...
<python><machine-learning><pytorch><pytorch-lightning>
2024-06-03 20:17:59
1
5,244
richbai90
78,572,233
23,260,297
Rename all files in a directory with specific format
<p>I have 100s of files in a directory that are all in the same format like this:</p> <pre><code>Recon-2024Jun03.xlsx Recon-2024Jun02.xlsx Recon-2024Jun01.xlsx etc... </code></pre> <p>I need to rename them all with a new format like this:</p> <pre><code>Recon-240603.xlsx Recon-240602.xlsx Recon-240601.xlsx etc... </cod...
<python><regex>
2024-06-03 19:34:49
1
2,185
iBeMeltin
78,572,163
832,230
Python threading lock with cooldown period for rate-limiting
<p>I am using Python 3.12 or newer. I need a threading lock, blocking only, with a cooldown feature that serves as a simple rate limiter. This will help me to avoid hammering a resource excessively.</p> <p>Expected features:</p> <ol> <li>It must have the typical mutual exclusion feature of a threading lock.</li> <li>It...
<python><multithreading><locking><rate-limiting>
2024-06-03 19:14:25
1
64,534
Asclepius
78,572,051
4,663,429
How to create custom Pydantic type for Python's "ElementTree"
<p>I want to create a custom Pydantic type for Python's <code>ElementTree</code>. It should accept string as input and type to parse the XML string via <code>ElementTree.fromstring</code> and raise appropriate error is invalid XML is found.</p> <p>I tried creating a custom type using pydantic <code>Annotated</code> met...
<python><pydantic><pydantic-v2>
2024-06-03 18:45:55
1
361
rishabhc32
78,572,006
982,402
AutoIt library not clicking dropdown of windows print pop-up using robot framework
<p>I am trying to select the <code>Save as PDF</code> option fron the print pop-up of windows. For which I have used <code>AutoItLibrary</code> along with <code>Robot Framework</code>. My code is as below but I am unable to click the <code>Destination</code> dropdown of the print pop-up. Please help me what can be wron...
<python><robotframework><ui-automation><autoit>
2024-06-03 18:34:56
1
1,719
Anna
78,571,748
14,073,111
Encrypt message body using kerberos
<p>How, we would encrypt me message body of the request using kerberos? I have kerberos ticket active.</p> <p>My main goal is to send first request as authentication part and it is ok, i get 200 from the WEC. This is the code i am using:</p> <pre><code>import requests import kerberos def get_kerberos_token(service): ...
<python><encryption><http-post><kerberos>
2024-06-03 17:28:23
1
631
user14073111
78,571,618
12,415,855
Selenium / How to select a value form a select-box?
<p>I try to select the option &quot;Psychatrie&quot; on a website using the following code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webd...
<python><selenium-webdriver>
2024-06-03 16:52:09
1
1,515
Rapid1898
78,571,464
6,376,297
How to pass a list of strings as a python sys.argv in a script, when the script command must be executed from a string
<p>Suppose you have a <code>script.py</code> that takes various input arguments, so you can run it by a command line like:</p> <pre><code>python script.py arg1 arg2 </code></pre> <p><code>sys.argv</code> can be used <em>inside</em> <code>script.py</code> to read those arguments:</p> <pre><code>sys.argv[1] # gives you s...
<python>
2024-06-03 16:14:10
2
657
user6376297
78,571,410
11,233,365
Creating optional argparse arguments, and ones that takes either None or a str as input
<p>I'm writing <code>argparse</code> arguments for a command line function where:</p> <ol> <li>More than one of the functions are optional, and</li> <li>One of the functions defaults to <code>None</code> if no file path string is provided</li> </ol> <p>The code is as follows, and I would like to know if I've done both ...
<python><argparse>
2024-06-03 16:03:25
0
301
TheEponymousProgrammer
78,571,372
2,977,256
Spatial data structures with efficient dynamic updates
<p>I am looking for a python library which does approximate (or exact, no problem with that) nearest neighbor search which has fast dynamic updates. (it seems that the scipy.spatial ones, like KDTree or BallTree do not. It would be even better if this were GPU compatible, but we should not be too greedy.</p>
<python><spatial><knn>
2024-06-03 15:54:55
1
4,872
Igor Rivin
78,571,287
5,924,264
How to ensure subprocess sees mock patched variable?
<p>I have unit tests that look like the following:</p> <pre><code>with patch('my_module.file_in_module.SOME_GLOBAL_VARIABLE', new=mocked_var): subprocess.check_call([ # CLI omitted ]) </code></pre> <p>If I print <code>my_module.file_in_module.SOME_GLOBAL_VARIABLE</code> right before the <code>subprocess</...
<python><mocking><subprocess>
2024-06-03 15:36:17
1
2,502
roulette01
78,571,286
6,622,697
Could not translate host name "jdbc:postgresql" in Django and Python
<p>I've successfully created a Django project in Pycharm to talk to the default Sqlite3. But now I'd like to switch to Postgress. I have the following in <code>settings.py</code></p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER'...
<python><django><postgresql><pycharm>
2024-06-03 15:36:09
2
1,348
Peter Kronenberg
78,571,230
2,522,673
FineTune llama3 model with torch tune gives error
<p>Im trying to fine tune the llama3 model with torch tune.</p> <p>these are the steps that ive already done :</p> <pre><code>1.pip install torch 2.pip install torchtune 3.tune download meta-llama/Meta-Llama-3-8B --output-dir llama3 --hf-token ***(my token)*** 4.tune run lora_finetune_single_device --config llama3/8B_l...
<python><pytorch><torchtune><llama3>
2024-06-03 15:25:27
1
1,718
Ahad Porkar
78,571,212
1,188,758
Implement WCF service in Python
<p>I have an existing web app developed in ASP.NET Frameword 4.7.2 using C#, and it's very large. Because most NLP libraries (i.e. Spacy) are implemented using Python, I have the idea to define a WCF service interface to be called by the web app, but <strong>implement the WCF service in Python</strong> so I can use the...
<python><c#><wcf>
2024-06-03 15:21:50
0
543
jtsoftware
78,571,193
2,973,447
Avoiding iteration in pandas when I want to update the value in a column x when a condition is true where x is given by another column
<p>I have the following pandas dataframe:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>key1</th> <th>key2</th> <th>col_name</th> <th>bool</th> <th>col_1</th> <th>col_2</th> <th>col_3</th> </tr> </thead> <tbody> <tr> <td>a1</td> <td>a2</td> <td>col_1</td> <td>0</td> <td>5</td> <td>10</td> ...
<python><pandas>
2024-06-03 15:18:33
1
381
user2973447
78,571,071
5,985,921
Altair Show Axis Tick Labels As Percentage Point
<p>I would like to format axis tick labels as percentage point.</p> <pre class="lang-py prettyprint-override"><code>import altair as alt from vega_datasets import data source = data.jobs.url alt.Chart(source).mark_line().encode( alt.X('year:O'), alt.Y('perc:Q').axis(format='%'), alt.Color('sex:N') ).trans...
<python><formatting><altair>
2024-06-03 14:57:16
1
1,651
clog14
78,570,966
6,037,956
Given a pandas DataFrame with several columns containing NaNs, the goal is to efficiently find the last non-null value for each row
<p>Given a pandas DataFrame with several columns containing potentially missing values (NaN), the goal is to efficiently find the last non-null value for each row. A similar question using polars DataFrame and solution is here: <a href="https://stackoverflow.com/q/77401947/6037956">Fill null values with the closest no...
<python><pandas><numpy>
2024-06-03 14:36:30
2
2,072
Soudipta Dutta
78,570,944
2,545,680
Is it possible to execute package wrapped into archive as module
<p>This is the structure:</p> <pre><code>__init__.py __main__.py server.py </code></pre> <p>Inside <code>__main__.py</code> I use relative imports:</p> <pre><code>from .server import app </code></pre> <p>When I zip the directory:</p> <pre><code>python -m zipapp app_builder </code></pre> <p>And then try to run it like t...
<python>
2024-06-03 14:32:31
1
106,269
Max Koretskyi
78,570,938
5,349,291
Pandas aggregated groupby has incorrect size
<p>I have a puzzling situation with pandas groupby objects. I'm in a situation where I have a dataset with ids, features, and targets for training a machine learning model. In some cases, there are groups of features with differing target values, and since that doesn't make sense, I would like to compute the mean of ta...
<python><pandas><group-by>
2024-06-03 14:31:54
1
2,074
mchristos
78,570,901
10,734,452
How to get the number of explicit arguments in the __init__ of a class?
<p>I have a class A that is inherited by classes A0,A1...An, some of which are inherited by classes A0a, A0b, A0c, A1a, A2a,...</p> <pre><code>class A(): def __init__(self,att_1=12,att_2=&quot;Blue&quot;,att3=False,att4=None) class A0_end(A): def __init__(self) super().__init__(self,att_1=13) class A...
<python>
2024-06-03 14:25:14
2
2,378
Guillaume D
78,570,866
6,751,456
cron log shows the job is running but actually the job is failing
<p>I have a cron job in <code>aws ec2 instance</code> defined as:</p> <pre><code>0 2 * * * /home/ec2-user/scripts/backup.sh 0 3 * * 0 /home/ec2-user/scripts/cleanup.sh 0 * * * * /home/ec2-user/scripts/health_check.sh </code></pre> <p>I checked whether the jobs are running by :</p> <pre><code>$ tail -f /var/log/cron Jun...
<python><linux><bash><amazon-ec2><cron>
2024-06-03 14:19:47
1
4,161
Azima
78,570,861
179,014
Smarter way to create diff between two pandas dataframes?
<p>I have two pandas dataframes which represent a directory structure with file hashes like</p> <pre><code>import pandas as pd dir_old = pd.DataFrame([ {&quot;Filepath&quot;: &quot;dir1/file1&quot;, &quot;Hash&quot;: &quot;hash1&quot;}, {&quot;Filepath&quot;: &quot;dir1/file2&quot;, &quot;Hash&quot;: &quot;has...
<python><pandas><dataframe><diff>
2024-06-03 14:18:53
3
11,858
asmaier
78,570,731
6,829,655
Build distribution package for different platform architecture
<p>We have Jenkins pipeline that runs on X86 architecture and invokes following command:</p> <pre><code>python setup.py sdist bdist_wheel </code></pre> <p>I would like to build a package for ARM-based architecture. Is it possible by adding some additional configuration to setup.py?</p>
<python><jenkins><jenkins-pipeline><setup.py>
2024-06-03 13:55:19
1
651
datahack
78,570,583
5,662,005
Store methods in class in order they are written
<p>This might be a two part question. First is the context if better alternatives can be suggested. Second part is the (probably) XY problem for my solution.</p> <p>xy - Have a method in the class which returns a list of all functions in the class in order they were written/typed.</p> <p>My projects typically involve l...
<python>
2024-06-03 13:30:08
5
3,899
Error_2646
78,570,412
7,389,168
How does the Python Interpreter check thread duration?
<p>My understanding is that historically, the python Interpreter counted lines of code executed and switched threads after a fixed amount. This was then changed to being time dependent.</p> <p>What I am trying to figure out is how is the time checked for the current threads running duration? Does time duration get call...
<python><python-3.x><python-internals>
2024-06-03 12:59:15
0
601
FourierFlux
78,570,189
20,301,996
Is there an easier way to run async functions in Celery tasks in one event loop?
<p>I have some async code and I need to run it inside the Celery task.</p> <p>I tried the approach with using <code>asgiref.sync.async_to_sync()</code>, but it turned out that it creates new event loop every time. And it brakes my code since I use SQLAlchemy session pool and there are restrictions about using sessions ...
<python><celery><python-asyncio>
2024-06-03 12:13:23
0
2,593
Yurii Motov
78,570,167
9,703,655
Error when update with Python Tortoise ORM
<p>I use <code>Tortoise ORM</code> for my Postgresql databse. I have two models. They are related via <code>OneToOneField</code>.</p> <pre class="lang-py prettyprint-override"><code>class User(Model): class Meta: table = &quot;users&quot; id = fields.UUIDField(primary_key=True) internal_id = fields...
<python><postgresql><tortoise-orm>
2024-06-03 12:07:09
1
463
picKit
78,570,103
11,760,835
How to test Flask SQLAlchemy database with different data
<p>I am pretty newbie in web testing. I would like to test my Flask web and API which uses SQLAlchemy using pytest.</p> <p>I would like to test the behaviour of the Flask server when the database is empty and when the database is full.</p> <p>Having the database empty and filling it with values on each test is not effi...
<python><flask><pytest><flask-sqlalchemy>
2024-06-03 11:53:02
2
394
Jaime02
78,569,948
19,363,912
Vectorize processing of log table to determine the latest availability
<p>I have a log table which contains changes. Sign + means addition, sign - means deletion.</p> <pre><code>import pandas as pd history = pd.DataFrame({ &quot;First&quot;: [&quot;X&quot;,&quot;X&quot;, &quot;Y&quot;, &quot;Y&quot;, &quot;X&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;], &quot;Last...
<python><pandas><performance><vectorization>
2024-06-03 11:17:21
1
447
aeiou
78,569,898
205,147
What is the fastest way to drop consecutive duplicates a List[int] column?
<p>I have a Polars DataFrame which has a column containing a variable length list of numbers in each row. For each row I need to drop consecutive duplicates from the list.</p> <p>So for example:</p> <pre><code>[5, 5, 5, 4, 4, 5, 5, 6, 6, 7] =&gt; [5, 4, 5, 6, 7] [3, 4, 4, 5, 6] =&gt; [3, 4, 5, 6] [2, 2] =&gt; [2] ...
<python><python-polars>
2024-06-03 11:07:12
2
2,229
Hendrik Wiese
78,569,897
10,794,986
Survey data many periods: transformation to current and previous period (wide to long format)
<p>I have a data frame (survey data) called <code>df</code> that looks like this (this is sample data):</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>respondent_id</th> <th>r1age</th> <th>r2age</th> <th>r3age</th> <th>r4age</th> <th>r1smoke</th> <th>r2smoke</th> <th>r3smoke</th> <th>r4smok...
<python><pandas><dataframe><performance><optimization>
2024-06-03 11:06:53
4
410
caproki
78,569,761
14,882,395
Type hint for an object that can be used as a type hint itself
<p>I have following code</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Type, overload T = TypeVar('T') @overload def foo(bar: Type[T]) -&gt; T: ... @overload def foo(bar: Type[T] | None) -&gt; T | None: ... def foo(bar: Type[T] | None) -&gt; T | None: # implementation...
<python><mypy><python-typing>
2024-06-03 10:38:38
1
2,213
sudden_appearance
78,569,602
9,827,719
Python receive txt/xml logs from Palo Alto HTTP
<p>I have a flask application that should receive txt/xml logs from a Palo Alto Firewall. How can I receive the traffic logs?</p> <p><strong>My Python Script: main.py</strong></p> <pre><code>import flask from flask import request # For development! app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST'])...
<python><request>
2024-06-03 10:04:30
1
1,400
Europa
78,569,532
2,242,012
Symmetry of Best Fit Straight Line on Inverting Axes
<p>I have a set of data that I have created a scatter plot from. On top of this I overlay the best fit straight line. Everything was fine until I realised that because of the nature of the data, it made more conceptual sense if the y-axis data was plotted on the x-axis. So I inverted the axes</p> <p>Say a1 and b1 are t...
<python><numpy><scipy>
2024-06-03 09:48:27
1
460
sil
78,569,342
1,422,096
Import a script from a parent's subdir, with a filename and dirname starting with digits
<p>I know the usual Python import system, packages, <code>__init__.py</code>, the <code>__import__</code> function (see <a href="https://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number">In python, how to import filename starts with a number</a>), etc. I know the classic <a href...
<python><import><python-import><python-importlib>
2024-06-03 09:06:14
2
47,388
Basj
78,569,244
17,795,398
numpy.histogram is there a way to get a binning so there is at least one count per bin?
<p>I'm using <code>numpy.histogram</code> on my data and then I want to perform a fit to some curve where the number of occurrences in each bin is dividing, so it cannot be zero. So I need the bins to contain at least one count. Is there anyway to do that with <code>numpy.histogram</code> or <code>numpy.histogram_bin_e...
<python><numpy><histogram><divide-by-zero>
2024-06-03 08:44:49
0
472
Abel Gutiérrez
78,569,237
6,837,132
FastAPI App using Zoom Webhook runs locally but not in Docker where Zoom Signature Rejected
<p>I built a FastAPI App that receives meeting/recordings events from Zoom API through Zoom Webhook. I use ngrok for the webhook URL. Everything works perfectly when running it locally.</p> <p>However, I built an image for the app in Docker, and when I try to run it, I get &quot;signature rejected&quot;. I verified tha...
<python><docker><fastapi><ngrok><zoom-sdk>
2024-06-03 08:43:26
0
849
SarahData
78,569,097
424,957
How to plot mutltiple geometries in correct projection by geoplot?
<p>I use code as below to plot multiple geometries:</p> <pre><code>newGdf = gpd.read_file(os.path.abspath(newFile), driver='KML') oldGdf = gpd.read_file(os.path.abspath(oldFile), driver='KML') lonMean, LagMean = newGdf.centroid.get_coordinates().mean() proj = geoplot.crs.Orthographic(central_longitude=lonMean, central...
<python><matplotlib><map-projections><geoplot>
2024-06-03 08:08:00
1
2,509
mikezang
78,569,067
567,797
How to avoid the entire app refresh on streamlit chat input
<p>I have the following piece of code</p> <pre><code>def ask_q_n_a(data): question = streamlit.chat_input(&quot;Ask any question&quot;) if question: streamlit.write(ask_f(data, question)) </code></pre> <p>the problem is as soon as the user enters the question the page refreshes and the entire app reloa...
<python><streamlit>
2024-06-03 07:59:23
0
7,145
station
78,568,527
8,995,555
How to send large videos to Gemini AI API 1.5 Pro for inference?
<p>I'm currently working with the Gemini AI API 1.5 Pro (latest version) and need to send large video files for inference. These videos are several hundred megabytes each (~700MB) but are within the API's constraints (e.g., less than 1 hour in length). I want to upload them once and perform inference without re-uploadi...
<python><server><openai-api><google-gemini>
2024-06-03 05:27:01
1
1,014
RukshanJS
78,568,499
828,647
Passing named arguments to test template in Robot framework
<p>I am using the following code in Robot framework in Python</p> <pre><code>*** Settings *** Library SeleniumLibrary Test Template Create New Guest of Specified Type *** Test Cases *** Verify creation of new guest of type Today guest_details = &amp;{TodayGuestDetails} schedule_type = Today guest_type...
<python><selenium-webdriver><robotframework>
2024-06-03 05:20:17
1
515
user828647
78,568,483
22,912,974
FastAPI request with base64 image body takes too long to get response
<p>Below api took too long to respond(more than 1 minute) in swagger, but the print statement <code>print(len(doc))</code> prints instantly.</p> <pre><code># pip install fastapi # fastapi dev main.py from fastapi import FastAPI from typing import Any, Dict app = FastAPI() @app.post(&quot;/fast&quot;) async def root(da...
<python><swagger><base64><fastapi>
2024-06-03 05:13:06
1
1,804
christopher johnson mccandless
78,568,303
13,176,726
Stripe Checkout Session: No session_id Provided in Request After Successful Payment in Django
<p>I'm working on a Django project where users can purchase subscriptions to various packages using Stripe Checkout. However, after a successful payment, I'm encountering an issue where the session_id is not being provided in the request when redirected to the payment_success view.</p> <p><strong>here are the models.py...
<python><django><stripe-payments>
2024-06-03 03:50:23
1
982
A_K
78,568,094
5,210,052
How to better include the optional filtering conditions for URL of API calls
<p>When working with API calls, we need to edit the URL. We typically can add many options for filtering in the URL.</p> <p>For example, if I have two optional filtering conditions (lane_id and workflow_id), then I can stupidly write the following for all the possible combinations:</p> <pre><code>def get_cards(board_id...
<python><url>
2024-06-03 01:36:03
2
1,828
John
78,568,011
2,016,632
How to compute the derivative of a spline in scipy, including the edges
<p>I'm having trouble with the derivative of spline computed with <code>LSQUnivariateSpine</code>. Specifically that it is generating garbage at the edges.... My example is a bit wierd because I want to specify the knot location rather than letting the algorithm choose (like <code>splrep</code>) but the that should be ...
<python><scipy><interpolation><spline><derivative>
2024-06-03 00:21:06
2
619
Tunneller
78,567,764
5,171,169
how to stop a thread? Is it possible to tie a thread to a global variable? the thread2 in this script is not visible to elife statment event
<pre><code>import PySimpleGUI as sg from my_scripts import * from my_constants import * import sys import glob import yt_dlp import threading import time global thread2 sg.LOOK_AND_FEEL_TABLE['MyCreatedTheme'] = {'BACKGROUND': '#000066', 'TEXT': '#ffebbf', ...
<python><pysimplegui>
2024-06-02 21:41:27
2
5,696
LetzerWille
78,567,601
15,433,308
Effect of python interpreter and environment on wheel creation
<p>I wrote a python package that I want to publish. I created a setup.py file for it and managed to create a wheel file by running <code>python setup.py sdist bdist_wheel</code>.</p> <p>My question is whether the python interpreter that I run the command with affects the created wheel and its compatibilities somehow, f...
<python><setuptools>
2024-06-02 20:25:57
2
492
krezno