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,937,759
1,317,018
Pytorch `DataSet.__getitem__()` called with `index` bigger than `__len__()`
<p>I have following torch dataset (I have replaced actual code to read data from files with random number generation to make it minimal reproducible):</p> <pre><code>from torch.utils.data import Dataset import torch class TempDataset(Dataset): def __init__(self, window_size=200): self.window = wi...
<python><python-3.x><machine-learning><deep-learning><pytorch>
2024-09-01 15:52:18
1
25,281
Mahesha999
78,937,753
2,093,469
How to define a channel-wise finite-differencing kernel in tensorflow
<p>I want to implement spatial finite differences using a tensorflow conv2d layer with a fixed kernel.</p> <p>My input data X is of size (nbatch,nx,ny,nchannel) and the output Y must be of the same shape with</p> <pre><code>Y[batch, i, j, channel] == 0.5 * (X[batch, i, j+1, channel] - X[batch, i, j-1, chan...
<python><tensorflow>
2024-09-01 15:47:18
1
9,167
sieste
78,937,366
595,305
Search for a specific tuple in a list of tuples sorted by their first element?
<p>Say I have a list of tuples like this, where the int is the &quot;id&quot; for this purpose:</p> <pre><code>records_by_id = [(10, 'bubble1'), (5, 'bubble2'), (4, 'bubble3'), (0, 'bubble4'), (3, 'bubble5'),] </code></pre> <p>... and I sort this by the first element of the tuple:</p> <pre><code>records_by_id.sort(key ...
<python><list><search><bisect>
2024-09-01 12:46:15
4
16,076
mike rodent
78,937,235
5,790,653
How to break the loop if iteration is between two members of a list
<p>I have a list like this:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ 'some', 'thing', 'is', 'here', 'dont', 'care', 'them', 'The process completed', 'process id: p1', 'process id: p2', 'Regards', 'some', 'thing', 'is', 'here', 'dont', ...
<python>
2024-09-01 11:44:52
6
4,175
Saeed
78,936,857
16,363,897
Count NaNs in window size and min_periods of rolling Pandas function
<p>We have the following pandas dataframe:</p> <pre><code> U date 1990-02-28 NaN 1990-03-01 NaN 1990-03-02 -0.068554 1990-03-05 -0.056425 1990-03-06 -0.022294 1990-03-07 -0.038996 1990-03-08 -0.026863 </code></pre> <p>I want to compute the rolling mean of column 'U', with a...
<python><pandas><numpy>
2024-09-01 08:12:54
1
842
younggotti
78,936,816
4,987,648
Python: how to run the equivalent of the entry_point `foo.bar:baz` during development?
<p>I have in my <code>setup.py</code>:</p> <pre><code> entry_points={ 'console_scripts': [ # Error at runtime: module planning_web does not exists 'foobaz = foo.bar:baz', ], }, </code></pre> <p>so that when I install it, it creates automatically a script <code>foobaz</co...
<python><module>
2024-09-01 07:44:06
0
2,584
tobiasBora
78,936,755
779,130
How do I fix broken pip installation
<p>I'm not sure what has happened to my Ubuntu server. I just migrated from an old Ununtu 20.04 to 24.04, and most things seem to now by working all right.</p> <p>However, if I run <code>pip</code> I get:</p> <pre><code>svend@localhost:~$ pip -bash: /home/svend/.local/bin/pip: cannot execute: required file not found </...
<python><ubuntu><pip>
2024-09-01 06:57:07
0
3,343
Svend Hansen
78,936,530
372,172
Can cython detects if certain C header exists and compile conditionally?
<p>I have a new C function in my library that doesn't exists in previous editions:</p> <pre class="lang-c prettyprint-override"><code>#define MYLIB_VERSION &quot;dev&quot; const char *mylib_version(void) { return MYLIB_VERSION; } </code></pre> <p>Now, I can do this with my new Cython code:</p> <pre><code>cdef extern f...
<python><c><cython>
2024-09-01 04:06:01
1
7,998
Koala Yeung
78,936,509
10,589,070
Deltakernel FFI Error while DuckDb Reading Delta
<p>Getting an FFI error while trying to read a detla table with Duckdb. The delta table is on a network connected drive via SMB. I just wrote the delta table from the same machine, just prior, using the same python kernel. I wrote the delta table using Polars and wanted to query it using SQL in Duckdb.</p> <p>The err...
<python><delta-lake><duckdb>
2024-09-01 03:37:55
1
446
krewsayder
78,936,478
11,244,192
Python Subprocess Catch STDIN Input and Wait
<p>I'm creating an online python compiler using Django.</p> <p>I have this code for executing the code</p> <pre class="lang-py prettyprint-override"><code>def stream_response(): try: process = subprocess.Popen(['python', temp_code_file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, s...
<python><subprocess>
2024-09-01 02:53:32
1
482
Winmari Manzano
78,936,276
3,486,684
DuckDB: importing a Polars dataframe containing an `Enum` column turns it into a `VARCHAR` column in DuckDB?
<pre class="lang-py prettyprint-override"><code>import polars as pl values = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] df = pl.DataFrame(pl.Series(&quot;x&quot;, values, dtype=pl.Enum(values))) print(df) </code></pre> <pre><code>shape: (3, 1) β”Œβ”€β”€β”€β”€β”€β”€β” β”‚ x β”‚ β”‚ --- β”‚ β”‚ enum β”‚ β•žβ•β•β•β•β•β•β•‘ β”‚ a β”‚ β”‚ b β”‚ β”‚ c β”‚ ...
<python><python-polars><duckdb>
2024-08-31 22:58:54
1
4,654
bzm3r
78,936,155
1,471,828
Is there no autocompletion for interop objects in VS Code?
<p>Using this code:</p> <pre><code>import win32com.client as win32 xl_ens = win32.gencache.EnsureDispatch('Excel.Application') </code></pre> <p>When I type <code>xl_ens.</code>, I do not get auto-completion for the Excel properties and methods, just built in Python stuff</p> <p>I somehow expected it to pick up on the E...
<python><visual-studio-code>
2024-08-31 21:35:06
1
905
Rno
78,936,118
1,236,694
VS Code Python unittest not finding tests to run
<p>VS Code latest version.</p> <p>I have a file <code>test_whatever.py</code></p> <pre><code>import unittest class Test_TestWhatever(unittest.TestCase): def test_whatever(self): self.assertEqual(1, 1) if __name__= '__main__': unittest.main() </code></pre> <p>In Explorer if I right-click this file a...
<python><visual-studio-code><python-unittest>
2024-08-31 21:07:29
1
9,151
BaltoStar
78,935,980
7,775,166
Django: Use widgets in Form's init method?
<p>Why the widget for the field defined as a class attribute is working, but it is not for the instance attribute inside the <code>__init__</code> method? (I need the init method)</p> <pre><code>class CropForm(forms.ModelForm): class Meta: model = CropModel fields = ['name', 'label'] label = f...
<python><django><forms><widget>
2024-08-31 19:47:17
1
732
girdeux
78,935,848
2,571,805
Python comprehension with different number of elements
<h1>The general problem</h1> <p>I have a case where I'm generating an element comprehension with a different cardinality to the input source. This cardinality should not be a multiple of the original (data-driven), but rather guided by conditions. Some elements in the original source could translate to one element in t...
<python><list><dictionary><functional-programming><list-comprehension>
2024-08-31 18:30:34
3
869
Ricardo
78,935,739
2,986,153
how to set accuracy within mizani.labels.percent()
<p>Can I use <code>mizani.label.percent</code> or another mizani formatter to present the geom_label with one decimal place? The code below works but rounds to an integer.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl from plotnine import * import mizani.labels as ml df = pl.DataFrame({ &q...
<python><plotnine>
2024-08-31 17:31:19
1
3,836
Joe
78,935,707
20,591,261
Apply Scaler() on each ID on polars dataframe
<p>I have a dataset with multiple columns and an ID column. Each ID can have different magnitudes and varying sizes across these columns. I want to normalize the columns for each ID separately.</p> <pre><code>import polars as pl from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() df = pl.DataFrame(...
<python><scikit-learn><python-polars>
2024-08-31 17:09:38
1
1,195
Simon
78,935,686
2,779,130
'asyncpg.pgproto.pgproto.UUID' object has no attribute 'replace'
<p>I'm building a fastAPI application. I have a Psotgres DB where i write and read data from. I'm using SQLAlchemy to interact with my Postgres Database. Here is my model:</p> <pre><code>import uuid from db.database import Base from sqlalchemy import Column, String, Boolean, DateTime, func from sqlalchemy.dialects.post...
<python><postgresql><sqlalchemy><asyncpg>
2024-08-31 16:55:35
1
804
Rashid
78,935,532
12,415,855
Change some input-fields in a PDF?
<p>i try to change some input-fields in a pdf using the following code:</p> <pre><code>from fillpdf import fillpdfs erg = fillpdfs.get_form_fields(&quot;template.pdf&quot;) erg[&quot;ΓΎΓΏ\x00f\x002\x00_\x000\x001\x00[\x000\x00]&quot;] = &quot;TEST1&quot; erg[&quot;ΓΎΓΏ\x00f\x002\x00_\x000\x002\x00[\x000\x00]&quot;] = &qu...
<python><pdf>
2024-08-31 15:43:41
1
1,515
Rapid1898
78,934,919
6,447,399
FastAPI - passing an input to a LangGraph model and getting an output in JSON/HTML
<p>I have the following LangGraph code. I can't seem to integrate it with FastAPI correctly. I want to send to the graph an input which is defined in the <code>inp</code> function, pass it through a langgraph workflow and then return the output in FastAPI.</p> <p>I can go to the playground and input some text: <a href=...
<python><fastapi><langgraph>
2024-08-31 11:13:00
1
7,189
user113156
78,934,877
19,048,626
How do I formalize a repeated relationship among disjoint groups of classes in python?
<p>I have Python code that has the following shape to it:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass @dataclass class Foo_Data: foo: int class Foo_Processor: def process(self, data: Foo_Data): ... class Foo_Loader: def load(self, file_path: str) -&gt; Foo_Dat...
<python><python-typing>
2024-08-31 10:46:47
1
611
Alex Duchnowski
78,934,698
10,200,497
Why doesn't fillna work as expected in pandas version 2.1.4?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': ['long', 'long', 'short', 'long', 'short', 'short', 'short'], 'b': [1, -1, 1, 1, -1, -1, 1], } ) </code></pre> <p>Expected output is creating column <code>a_1</code>:</p> <pre><code> a b a_1 0 ...
<python><pandas><dataframe>
2024-08-31 08:49:26
2
2,679
AmirX
78,934,548
12,466,687
How to extract date from a column in Pandas?
<p>I am trying to <strong>extract</strong> only <strong>dates</strong> from a <code>column(Result)</code> of a <code>dataframe</code>. Dates will only start from year 2000 and beyond but the format of date could be any including datetime.</p> <p>What I want is just date.</p> <p>Is there a simple way of doing it with so...
<python><pandas><date><datetime>
2024-08-31 07:18:15
1
2,357
ViSa
78,934,371
72,437
Wildcard rule for @storage_fn.on_object_finalized?
<p>Currently, this Firebase function works fine</p> <pre><code>@storage_fn.on_object_finalized( bucket='XXX.appspot.com', timeout_sec=540, memory=options.MemoryOption.GB_32 ) def process_audio_file(event: storage_fn.CloudEvent[storage_fn.StorageObjectData]): </code></pre> <p>However, it is not efficient b...
<python><google-cloud-storage>
2024-08-31 05:36:12
0
42,256
Cheok Yan Cheng
78,934,312
1,231,714
How to plot a cumulative sum based on a certain columns
<p>Below is sample data from my dataframe. I am trying to plot the cumulative sales by date (X-axis is date that is sorted, Y-axis is cumulative sum of sales_USD). Each item code needs to have its own curve. How do I do this using pandas?</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Date<...
<python><pandas><plot>
2024-08-31 04:28:09
1
1,390
SEU
78,934,295
219,153
Can these two Python functions be replaced by a single generic one taking either a list or a tuple argument?
<p>Can these two Python functions:</p> <pre><code>def negativeList(a): return [-e for e in a] def negativeTuple(a): return tuple(-e for e in a) </code></pre> <p>be replaced by an equvalent single generic function <code>negative(a)</code>?</p>
<python><arrays><function><tuples>
2024-08-31 04:13:26
4
8,585
Paul Jurczak
78,933,843
548,123
How install own python package to be used as a command system wide after PEP-668?
<p>I have a utility written in Python that I used to use and need to use it again.</p> <p>It's done as a package I install and an executable script with shebang that will be imported and called the main function.</p> <p>The usage is just like any other utility as in other languages. Just call the executable that wraps ...
<python><pip><python-packaging>
2024-08-30 21:54:52
2
515
Allan Deamon
78,933,840
8,850,850
How to properly shear a line in a 2D image using interpolation in Python?
<p>I'm trying to apply a shearing transformation to a simple 2D line filter (represented as a binary image) using interpolation methods in Python. However, the resulting image after applying the shear transformation looks almost identical to the input filter, with no visible shearing effect.</p> <p>When I apply the sam...
<python><numpy><matplotlib><scipy>
2024-08-30 21:54:02
1
427
tag
78,933,681
210,559
Airflow Task Group Execution Order
<p>I am trying to understand when airflow tasks will be run. I do not understand why task_3a is running immediately when running this example.</p> <p>How do I make this sample dag run in this order:</p> <ul> <li>Task 1</li> <li>Task 2 if instructed to run</li> <li>Task 3</li> <li>Task 3a and Task 3b (great if these run...
<python><python-3.x><airflow>
2024-08-30 20:37:41
1
9,488
Scott
78,933,569
3,045,351
Python py7zr extracting .7z archive differently to Linux command line 7zip
<p>I have created a .7z archive using the usual basic Windows UI. It is my understanding this defaults to relative paths for any archives created. When looking in the archive post creation, all I see is a directory called 'autocfg'. When I experimented with absolute paths this changed (as expected).</p> <p>When unzippi...
<python><python-3.x><linux><7zip>
2024-08-30 19:52:02
0
4,190
gdogg371
78,933,467
3,156,085
How can access the pointer values passed to and returned by C functions from Python?
<p>Can my python code have access to the actual pointer values received and returned by C functions called through <code>ctypes</code>?</p> <p>If yes, how could I achieve that ?</p> <hr /> <p>I'd like to test the pointer values passed to and returned from a shared library function to test an assignment with pytest (her...
<python><ctypes>
2024-08-30 19:20:11
1
15,848
vmonteco
78,933,243
5,305,512
Python package installed, but getting import error in Jupyter notebook
<p>Fresh install of Python 3.12.5 on Mac OS.</p> <p>Getting import error in Jupyter notebook:</p> <p><a href="https://i.sstatic.net/J85zwz2C.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/J85zwz2C.png" alt="enter image description here" /></a></p> <p>But works fine in terminal:</p> <p><a href="https://i...
<python><jupyter-notebook><python-import><importerror>
2024-08-30 17:52:28
1
3,764
Kristada673
78,933,232
20,591,261
Keep training pytorch model on new data
<p>I'm working on a text classification task and have decided to use a PyTorch model for this purpose. The process mainly involves the following steps:</p> <ol> <li>Load and process the text.</li> <li>Use a TF-IDF Vectorizer.</li> <li>Build the neural network and save the TF-IDF Vectorizer and model to predict new data...
<python><scikit-learn><pytorch><nlp><python-polars>
2024-08-30 17:47:59
1
1,195
Simon
78,933,210
1,275,942
Is string slice-by-copy a CPython implementation detail or part of spec?
<p>Python does slice-by-copy on strings: <a href="https://stackoverflow.com/questions/5722006/does-python-do-slice-by-reference-on-strings/">Does Python do slice-by-reference on strings?</a></p> <p>Is this something that all implementations of Python need to respect, or is it just a detail of the CPython implementation...
<python><specifications><cpython>
2024-08-30 17:41:40
1
899
Kaia
78,933,132
1,275,942
Type-hinting a generator: send_type Any or None?
<p>I have a generator that does not use <code>send()</code> values. Should I type its <code>send_value</code> as <code>Any</code> or <code>None</code>?</p> <pre><code>import typing as t def pi_generator() -&gt; t.Generator[int, ???, None]: pi = &quot;3141592&quot; for digit in pi: yield int(digit) pi_...
<python><generator><python-typing>
2024-08-30 17:15:22
1
899
Kaia
78,933,115
12,415,855
File not printed using os.startfile?
<p>i try to print a document on windows using the following code</p> <pre><code>import os import sys os.startfile(r&quot;D:/DEV/Python-Diverses/os/testb.png&quot;, &quot;print&quot;) </code></pre> <p>But nothing happens at all - the programs runs trough but no printing.</p> <p>When i just open the file with</p> <pr...
<python><windows><python-os>
2024-08-30 17:10:55
1
1,515
Rapid1898
78,933,101
5,625,497
define multiple methods for comparison at once using the same principle
<p>I am building a binary tree in python defining the node as a class. I wanted the node to have a value and be comparable to other nodes in order to, for example, sort a list of them.</p> <p>I wanted to know if there is a more elegant way to avoid explicitly defining all comparison methods (<code>__le__</code>, <code>...
<python><oop><inheritance>
2024-08-30 17:04:36
1
4,353
Tarifazo
78,932,994
4,875,641
JSON interpretation of chunked data
<p>I need to locate the parameters for a specific object returned from a remote server in JSON format. But the number of objects on the server is always increasing so the JSON responses get larger and larger. I anticipate when there are hundreds of thousands of objects, the JSON response will exceed the memory capacity...
<python><json><list><stream><chunks>
2024-08-30 16:29:44
0
377
Jay Mosk
78,932,929
7,713,770
How to Resolve the Issue: Django with Visual Studio Code Changing Template Without Effect?
<p>I have a Django app, and I am using Visual Studio Code as my editor. I have implemented functionality for recovering passwords via an email template. I edited the template to see what effect it would have on the email, but the changes had no effect. I even deleted the email template, but I still received the old ema...
<python><django><visual-studio-code><django-templates>
2024-08-30 16:12:57
1
3,991
mightycode Newton
78,932,922
390,897
How to add padding to matplotlib plot when aspect is "equal"?
<p>Whenever I make plots with plt.gca().set_aspect(&quot;equal&quot;), the plot can become scrunched to the point where it appears collapse. How can I add some extra padding or retain padding while maintaining the aspect ratio?</p> <p>A few examples:</p> <pre><code># A Line plt.plot([0, 0], [0, 100]) ax = plt.gca() ax....
<python><matplotlib>
2024-08-30 16:11:25
2
33,893
fny
78,932,725
8,849,755
Pandas sort one column by custom order and the other naturally
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>import pandas import numpy strs = ['custom','sort']*5 df = pandas.DataFrame( { 'string': strs, 'number': numpy.random.randn(len(strs)), } ) sort_string_like_this = {'sort': 0, 'custom': 1} print(df.sort_values(...
<python><pandas><sorting>
2024-08-30 15:15:36
3
3,245
user171780
78,932,657
1,914,781
plotly - replace first and last yticks with min and max value
<p>I would like to mark max/min value as yticks like below:</p> <pre><code>import plotly.graph_objects as go import pandas as pd import plotly.express as px def save_fig(fig,pngname): fig.write_image(pngname,format=&quot;png&quot;,width=800,height=500, scale=1) print(&quot;[[%s]]&quot;%pngname) #fig.show()...
<python><plotly><xticks><yticks>
2024-08-30 14:57:55
0
9,011
lucky1928
78,932,535
1,560,414
Python Async Thread-safe Semaphore
<p>I'm looking for a thread-safe implementation of a Semaphore I can use in Python.</p> <p>The standard libraries <a href="https://docs.python.org/3/library/asyncio-sync.html#asyncio.Semaphore" rel="nofollow noreferrer">asyncio.Semaphore</a> isn't thread-safe.</p> <p>The standard libraries <a href="https://docs.python....
<python><multithreading><python-asyncio>
2024-08-30 14:30:59
2
1,667
freebie
78,932,526
4,435,175
Add X days to a Datetime Series
<p>I have a Datetime Series that always contains the datetime of yesterday like:</p> <pre><code>Series: '' [datetime[ns]] [ 2024-08-29 00:00:00 ] </code></pre> <p>How can I add 2 days to that Datetime Series so that I can add the datetime from 2 days and 3 days ago?</p> <p>End result should be:</p> <pre><code>Serie...
<python><datetime><python-polars>
2024-08-30 14:28:55
2
2,980
Vega
78,932,341
403,875
Why does 2x - x == x in IEEE floating point precision?
<p>I would expect this to only hold when the last bit of the mantissa is <code>0</code>. Otherwise, in order to subtract them (since their exponents differ by 1), <code>x</code> would lose a bit of precision first and the result would either end up being rounded up or down.</p> <p>But a quick experiment shows that it s...
<python><precision><ieee-754>
2024-08-30 13:47:03
3
5,604
dspyz
78,932,161
13,336,872
How to calculate second derivative using gpu and PyTorch
<p>I have a python code segment related to a deep RL algorithm where it calculates the second order optimization and second derivative with Hessian matrix and fisher information matrix. Normally I run the whole code on GPU (cuda), but since I got a computational issue to calculate second derivative in cuda,</p> <pre><c...
<python><pytorch><gpu><reinforcement-learning><cudnn>
2024-08-30 13:07:44
1
832
Damika
78,932,072
13,294,364
Efficiently recalculating dependent values in real-time data streams using NumPy in Python
<p>I'm currently working on a real-time data processing system for financial securities, where I need to perform calculations as soon as new data comes in. Each financial security has multiple data points (about 10-20) being fed into the system in real-time, and I have around 200 different securities.</p> <p>I am using...
<python><arrays><numpy><performance><real-time-data>
2024-08-30 12:49:09
1
305
Harry Spratt
78,932,041
7,169,710
Update or access Pandas DataFrame via API extension register_dataframe_accessor
<p>I would like to edit a dataframe through the <a href="https://pandas.pydata.org/docs/reference/api/pandas.api.extensions.register_dataframe_accessor.html" rel="nofollow noreferrer">`register_dataframe_extension`</a> available in the pandas API.</p> <p>For example, I would like that that, provided the following code:...
<python><python-3.x><pandas><dataframe>
2024-08-30 12:42:26
1
405
Pietro D'Antuono
78,932,035
6,930,340
Filter or join a polars dataframe by columns from another dataframe
<p>I have two <code>pl.DataFrame</code>s:</p> <pre><code>from datetime import date import polars as pl df1 = pl.DataFrame( { &quot;symbol&quot;: [ &quot;sec1&quot;, &quot;sec1&quot;, &quot;sec1&quot;, &quot;sec1&quot;, &quot;sec1&quot;, &quot;sec1&quot;, &quot;sec2&quot;, &quot;sec...
<python><dataframe><join><python-polars>
2024-08-30 12:39:57
1
5,167
Andi
78,932,018
4,417,769
Assert that two files have been written correctly
<p>How would I assert that this function wrote to those files in tests?</p> <pre class="lang-py prettyprint-override"><code>def write() -&gt; None: with open('./foo', 'w') as f: f.write('fooo') with open('./bar', 'w') as f: f.write('baar') </code></pre> <pre class="lang-py prettyprint-override">...
<python><mocking><python-unittest><python-unittest.mock>
2024-08-30 12:36:50
2
1,228
sezanzeb
78,931,932
9,684,951
Is the generator expression stored anywhere semantically intact?
<p>If I set a generator</p> <pre><code>myra = (x + 100 for x in range(5)) </code></pre> <p>and then later do something with it, like</p> <pre><code>for i in myra: print(i) </code></pre> <p>the generator has run its course, cannot be iterated over again, got that.</p> <p>But is there a way, before, during, or after ...
<python><generator>
2024-08-30 12:15:56
2
308
bukwyrm
78,931,861
1,741,868
How to deploy a Python Azure Function app from a mono-repo?
<p>Following on from <a href="https://stackoverflow.com/questions/78928280/deploying-a-python-function-app-where-the-source-is-in-a-subdirectory/78931022#78931022">this question</a>, I've got a mono-repo containing a Flask API and the first of what will be several Azure Function apps. I'm trying to deploy the app to Az...
<python><python-3.x><azure-devops><azure-functions><azure-pipelines>
2024-08-30 11:57:01
1
14,935
Greg B
78,931,843
608,041
In Python unittest log testname, expected value and actual value into a separate file
<p>I have used the standard python unittest framework to create a testsuite for my hardware that read values from sensors. A test might look like below (a bit simplified)</p> <pre><code>def test_temperature1(self): self.assertAlmostEqual(self.temp_sensor1.get_value(),25.0, delta=1) </code></pre> <p>I would be able t...
<python><unit-testing>
2024-08-30 11:52:14
1
534
kungjohan
78,931,736
865,169
Why can I unpack a Python set when sets are unordered?
<p>I am quite used to unpacking sequences in Python like:</p> <pre class="lang-py prettyprint-override"><code>my_tuple = (1, 2, 3) a, b, c = my_tuple </code></pre> <p>I have noticed that I can also do it with sets:</p> <pre class="lang-py prettyprint-override"><code>my_set = set((1, 2, 3)) a, b, c = my_set </code></p...
<python><set><iterable-unpacking>
2024-08-30 11:23:24
4
1,372
Thomas Arildsen
78,931,521
13,946,204
How to pass argument into schedule_task for Locust?
<p>Let's say that my test case is to get list of articles at news site and make a comment for the articles.</p> <p>Here is how my code may look:</p> <pre class="lang-py prettyprint-override"><code>class MyTasks(TaskSet): def post_comment(self. article_id: int): self.client.post( f&quot;/{article_id}/comment...
<python><locust>
2024-08-30 10:26:11
2
9,834
rzlvmp
78,931,345
1,930,011
Python function app how to terminate after a timer without harming other functions
<p>I have inherited a collection of Python functions that are capable of deadlocking(this can happen at several places in the code), when that happens they seize all function time out on the Function app in Azure. This process then kills all other running function apps.</p> <p>Obviously the deadlocking shouldn't be hap...
<python><azure><azure-functions>
2024-08-30 09:36:50
1
2,633
Thijser
78,931,299
13,392,257
NameError: name 'process' is not defined
<p>I have a base64 string with python function. I want to run this python code</p> <p>My code:</p> <pre><code>import base64 def apply_script(custom_script: str, spark_df=None): script_encoded = base64.b64decode(custom_script).decode('utf-8') print(script_encoded) exec(script_encoded) print(&quot;EXECU...
<python>
2024-08-30 09:25:20
1
1,708
mascai
78,931,121
12,550,791
Pytest assert the original exception raised using `raise AnyException from MyExceptionToAssert`
<p>I wrote a suit of tests that asserts exception (following what was said here <a href="https://stackoverflow.com/questions/23337471/how-do-i-properly-assert-that-an-exception-gets-raised-in-pytest">How do I properly assert that an exception gets raised in pytest?</a> and in the doc). However, there is one instance of...
<python><exception><pytest>
2024-08-30 08:31:26
3
391
Marco Bresson
78,931,082
1,111,652
Abstract base class function pointer python
<p>I'd like to make an abstraction of one of my api classes to resolve the following problem. Let's say I have a base class like:</p> <pre><code>class AbstractAPI(ABC): @abstractmethod def create(self): pass @abstractmethod def delete(self): pass </code></pre> <p>And a concrete class:</...
<python><inheritance>
2024-08-30 08:20:56
2
1,168
hasdrubal
78,930,856
219,153
What is an equivalent of in operator for 2D Numpy array?
<p>Using Python lists:</p> <pre><code>a = [[0, 1], [3, 4]] b = [0, 2] print(b in a) </code></pre> <p>I'm getting <code>False</code> as an output, but with Numpy arrays:</p> <pre><code>a = np.array([[0, 1], [3, 4]]) b = np.array([0, 2]) print(b in a) </code></pre> <p>I'm getting <code>True</code> as an output. What is a...
<python><arrays><numpy-ndarray>
2024-08-30 07:18:44
5
8,585
Paul Jurczak
78,930,100
1,492,613
how to effeciently write chunks to partitioned dataset?
<p>I have multiple level of index in my data, for example</p> <pre><code>schema = pa.schema( [ ('level1', pa.dictionary(pa.int64(), pa.utf8())), ('level2', pa.binary(16)), ('level3', pa.int64()), ('doc', pa.string()) ] ) </code></pre> <p>usually I have 10-100 level2 for each leve...
<python><pyarrow>
2024-08-30 00:58:10
1
8,402
Wang
78,930,091
5,328,289
Why http.server does not deliver the data to the CGI script in this basic example?
<p>I am testing the legacy CGI functionality of python http.server module by implementing a &quot;hello world&quot; alike example that sends data from a fictional &quot;add customer&quot; form from the web front end to the backend. The data is processed by a CGI script which just writes the text received into a file.</...
<javascript><python><cgi><http.server>
2024-08-30 00:45:59
1
5,635
M.E.
78,929,964
1,401,640
UTF-16 as sequence of code units in python
<p>I have the string <code>'abΓ§'</code> which in UTF-8 is <code>b'ab\xc3\xa7'</code>.</p> <p>I want it in UTF-16, but not this way:</p> <pre><code>b'ab\xc3\xa7'.decode('utf-8').encode('utf-16-be') </code></pre> <p>which gives me:</p> <p><code>b'\x00a\x00b\x00\xe7'</code></p> <p>The answer I want is the UTF-16 code unit...
<python><unicode><utf-8><utf-16>
2024-08-29 23:26:29
3
465
Andy Jewell
78,929,867
4,476,484
In python, how do you assert the type of a variable after checking it?
<h2>Overview</h2> <p>There is a general pattern in programming that goes like this</p> <pre class="lang-none prettyprint-override"><code>if (something is not initialized) { initialize the thing } do something with the initialized thing </code></pre> <p>In python, I have an object that's of type <code>A | B</code>. ...
<python><python-typing><type-assertion>
2024-08-29 22:47:48
0
2,737
nullromo
78,929,802
10,022,961
Plone REST API - Filtering search results using a value inside an object
<p>I am trying to use <code>@search</code> or <code>@querystring-search</code> endpoints to limit the response to include only items with <code>priority.token</code> = 1.</p> <p>An item includes a <code>priority</code> object as follows:</p> <pre><code>&quot;priority&quot;: { &quot;title&quot;: &quot;1 Important&qu...
<python><plone>
2024-08-29 22:18:51
1
466
Abdallah El-Yaddak
78,929,762
9,158,985
Is it possible in polars to give the full schema of a LazyFrame/DataFrame in a function argument, and get type errors?
<p>There are occasions when I know ahead of time the full schema of a table I'm working with. In those scenarios, it would be nice to be able to specify the full schema (call it a <code>FullyDefinedFrame</code>). Then the type system could help me out with things like:</p> <ol> <li>error when accessing a column that do...
<python><python-polars><rust-polars>
2024-08-29 22:00:21
1
880
natemcintosh
78,929,742
160,245
Claude/Sonnet Python API - more tokens freezes, less tokens truncates
<p>My prompt was to create a blog with 5 sections covering 5 different individuals in an industry niche.</p> <p>When I had max_tokens= 300 (and then 1000), it ran quickly, but the result was not complete.</p> <p>When I tried max_tokens=1500 (or 3000), then the program freezes, and doesn't come back after even about 5 m...
<python><claude>
2024-08-29 21:49:04
0
18,467
NealWalters
78,929,674
10,319,707
How can I dramatically increase the logging from running pandas.DataFrame.to_csv with an S3 target?
<p>There are many closed bugs claiming that <code>pandas.DataFrame.to_csv</code> fails silently when saving to S3 if it has problems on the S3 side. I think that I have another, but the number of sources claiming that these bugs are closed makes me uneasy. I want to submit a good bug report. How can I get as much loggi...
<python><pandas><amazon-s3><logging><export-to-csv>
2024-08-29 21:18:03
0
1,746
J. Mini
78,929,522
2,986,153
How to format geom_label() values within plotnine
<p>When I am using plotnine, I can use mizani.labels to format the axis labels as percent strings. Is there a similar method to formate geom_label values? I cannot use <code>label = ml.percent(&quot;rate&quot;)</code> as this will trigger an error.</p> <pre><code>import polars as pl from plotnine import * import mizan...
<python><plotnine>
2024-08-29 20:22:09
1
3,836
Joe
78,929,497
2,893,712
Pandas Export to Excel with MultiIndex Column with Formatting
<p>I have a dataframe in Pandas which groups shift attendance for specific days</p> <pre><code>DAYS = ['26-Aug','27-Aug','28-Aug'] SHIFTS = ['S1','S2','S3'] EMPLOYEES = ['John Doe','Jane Doe'] # Create Column Index of shifts for each day idx = pd.MultiIndex.from_product([DAYS, SHIFTS], names=['Days','Shifts']) # Creat...
<python><excel><pandas>
2024-08-29 20:14:15
1
8,806
Bijan
78,929,356
614,443
Sphinx autodoc - Skipping members with automethod set
<p>I'm using sphinx and a few of the files have the directive <code>.. automethod::</code> set. I need a way to have sphinx show all <code>__init__</code> methods, without removing the <code>.. automethod::</code> directive and without any warnings. I tried to look through stack, but didn't see anything like this. Here...
<python><python-sphinx><autodoc>
2024-08-29 19:23:02
0
2,551
Aram Papazian
78,929,322
7,200,174
Pandas groupby and concat multiple rows
<p><strong>CONTEXT</strong></p> <p>I want to group by both a rule_id and calc_id and transform multiple columns into one row where each variable is concatenated with a &quot;,'</p> <p><strong>DATA EXAMPLE</strong></p> <pre><code>Calc_ID Rule_ID Name Tracked? 100 Rule1 Y 100 ...
<python><pandas><dataframe><group-by>
2024-08-29 19:12:21
1
331
KL_
78,929,301
3,798,035
Parallel performance with xarray and dask
<p>I am trying to perform operations in parallel on a very large array using <code>xarray</code>. My current approach is roughly as follows:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import xarray as xr # Read dataset (netCDF4). Holds data variable 'p2(time, distance)' data = xr.open_datas...
<python><python-xarray><dask-dataframe>
2024-08-29 19:05:48
0
652
TMueller83
78,929,276
243,158
Creating a pylint coverage report
<p>We have a lot of legacy python code in our github repo that has the very useful type and pylint checks disabled:</p> <pre><code># type: ignore # pylint: skip-file </code></pre> <p>In some files where this is not the case, there are whole sections with no pylint coverage.</p> <p>We'd like to create a pylint coverage ...
<python><code-coverage><pylint>
2024-08-29 18:56:05
1
1,725
Ido Cohn
78,929,240
8,521,346
Memory Leak When Using Django Bulk Create
<p>I have the following code that constantly checks an API endpoint and then if needed, adds the data to my Postgres database.</p> <p>Every iteration of this loop is leaking memory in the <code>postgresql\operations.py</code> file.</p> <p>Im not sure what data is still being referenced and isnt clearing, so realistical...
<python><django>
2024-08-29 18:39:43
0
2,198
Bigbob556677
78,929,001
1,330,734
Flask WebSocket Messages not emitted
<p>I want to use a WebSocket to stream dummy data (a random 4-char string) to a div on a HTML page, using Python with the Flask webserver. The source for both Python and HTML follows.</p> <p>main7.py</p> <pre><code>from flask import Flask, render_template from flask_socketio import SocketIO import random import string ...
<python><flask><websocket>
2024-08-29 17:23:04
1
490
user1330734
78,928,919
8,308,617
Issue with Updating Entries in Asset_Insert Array
<p>Note: This specific code is being executed on ignition perspective platform, but the problem I am having is more related to logic than platform.</p> <p><strong>Problem Description:</strong></p> <p>I'm encountering a problem with updating entries in an array named <code>Asset_Insert</code> within an Ignition Perspect...
<python><datatable><logic>
2024-08-29 16:59:37
0
462
Uniquedesign
78,928,866
4,648,809
Python multiprocessing manager does not work in uwsgi for spawn method
<p>Python multiprocessing manager does not work in uwsgi for spawn method in Linux. Code:</p> <pre><code>from torch.multiprocessing import Manager import torch.multiprocessing as mp ...
<python><linux><uwsgi>
2024-08-29 16:42:09
0
1,031
Alex
78,928,846
6,231,539
Kafka partioning key difference between Python and Nestjs
<p>In my infrastructure I have multiple microservices with multiple language communicating over Kafka. In my Kafka I have multiple partitions and to keep consistency I use a key when I push messages so that messages with the same key go to the same partition.</p> <p>It works well when different Nestjs microservices com...
<python><apache-kafka><nestjs><confluent-kafka-python>
2024-08-29 16:36:14
1
1,922
Antoine Grenard
78,928,797
1,087,370
How to wait for a confirmation dialog in Flet?
<p>I press a button, a confirmation popup should appear and based on the option you picked(ex: yes or no) to decide what to do next.</p> <p>Using <code>flet==0.22.*</code></p>
<python><flet>
2024-08-29 16:20:18
2
5,934
Alex
78,928,639
897,272
Is it possible to have python workers use different global context?
<p>We have a singleton object we use for our program that refers to an ugly god-object that I wish would die - we inherited the code from a team that had already implemented it this way. Unfortunately stripping the singleton out is a non-trivial task at this point.</p> <p>We want to have a rest endpoint, using django ...
<python><django-rest-framework><singleton>
2024-08-29 15:41:25
1
6,521
dsollen
78,928,619
494,134
Two if statements in a list comprehension
<p>Looking at <a href="https://stackoverflow.com/q/77893051/494134">another question</a>, I saw what I assumed was a simple typo or misunderstanding of list comprehension syntax -- but it actually worked!</p> <p>This is a simplified version of the code in that question:</p> <pre><code>message = &quot;ABCABCABCABC&quot;...
<python><list-comprehension>
2024-08-29 15:37:50
0
33,765
John Gordon
78,928,608
8,758,459
How to fix mixed content error when embedding a FastAPI app as iframe
<p>I'm deploying a web application using NiceGUI (fastAPI) on Google Cloud Run. The main application is served over HTTPS, but I’m embedding a sub-application (Chainlit) as an iframe within the main app. The Chainlit app is mounted as a FastAPI subapp.</p> <p>When I load the main app (served locally or remotely), I get...
<python><fastapi><google-cloud-run><nicegui><chainlit>
2024-08-29 15:34:27
0
395
John Szatmari
78,928,486
2,715,498
How to deduce whether a classmethod is called on an instance or on a class
<p>I'm writing a logger decorator that can be applied to, among others, classmethods (and theoretically any kind of function or method). My problem is that their parametrization changes according to whether a function is</p> <ul> <li>a standalone_function(*args)</li> <li>a member_method(self, *args) or</li> <li>a class...
<python><python-decorators>
2024-08-29 15:04:35
1
3,372
Gyula SΓ‘muel Karli
78,928,344
495,786
Tool to extract functions used from specific package in Python
<p>Does anyone know a tool to copy all the functions used in a project comming from a specific package? A possible use case would be something like the following:</p> <p>Project A is a Python application that uses several functions from Package B as a dependency. Let's say that Package B is a private project, if we dis...
<python><dependencies>
2024-08-29 14:33:19
1
1,987
skd
78,928,280
1,741,868
Deploying a python Function App where the source is in a subdirectory
<p>I've got a mono-repo with a python project that I'm deploying to Azure. There's an API being deployed as a container and I'm trying to add a function app.</p> <p>My python code is structured in a few folders underneath a /backend folder, like</p> <pre><code>./backend ./backend/domain/ - contains domain logic .py fil...
<python><python-3.x><azure-functions>
2024-08-29 14:15:25
1
14,935
Greg B
78,928,259
1,325,861
scrape link for jwplayer calculated with JS using python
<p>I'm trying to scrape video link (m3u8) from this website: <a href="https://deaddrive.xyz/embed/fa31e" rel="nofollow noreferrer">https://deaddrive.xyz/embed/fa31e</a></p> <p>While inspecting the page, I realized that the link is calculated on the fly using JS in the function:</p> <p><div class="snippet" data-lang="js...
<javascript><python><selenium-webdriver><web-scraping>
2024-08-29 14:10:32
0
535
Gaurav Suman
78,927,980
2,832,011
Hiding facet row axis in Altair chart
<p>I'm using a faceted chart in Altair in order to split a lengthy timeline into multiple rows.</p> <p>My initial dataset is a pandas dataframe with &quot;Start&quot; and &quot;End&quot; timestamp columns and a &quot;Product&quot; string column.</p> <p>I bin the dataset into roughly equal rows by evenly dividing the ti...
<python><pandas><facet><altair>
2024-08-29 13:12:11
1
4,709
Christoph Burschka
78,927,977
8,703,313
update dictionaries in the list comprehension
<p>There is a dictionary:</p> <pre class="lang-py prettyprint-override"><code>d = [{&quot;a&quot;:1, &quot;b&quot;:2},{&quot;a&quot;:3, &quot;b&quot;:4},{&quot;a&quot;:5, &quot;b&quot;:6}] </code></pre> <p>I'd like to update values of keys <code>b</code>.</p> <pre class="lang-py prettyprint-override"><code>d = [{**m}.u...
<python><list-comprehension>
2024-08-29 13:11:59
3
310
Honza S.
78,927,891
16,958,410
what is Password-based authentication in the UserCreationForm in Django?
<p>I creat a signup form in django using django forms and when i run my code there is field i didnt expect <strong>Password-based authentication</strong> i did not use it and i have no idea what it is so anyone can tell me what it is and how i can remove it from user signup form? <a href="https://i.sstatic.net/Z9aQLmSb...
<python><django><django-forms>
2024-08-29 12:52:52
2
596
mehdi_ahmadi
78,927,863
1,614,809
removing a label on a jira issue using python
<p>I can add a label like this</p> <pre><code>issue.fields.labels.append(&quot;MYNEWLABEL&quot;) </code></pre> <p>but I have searched the docs and duckduckgo'd until my hair has gone greyer but I have not figured out how to remove a label. I tried the method I used to remove a component but it didn't work</p> <pre><cod...
<python><jira><python-jira>
2024-08-29 12:45:50
1
320
Paul M
78,927,743
4,049,658
How to debug a running python program?
<p>I'm a programmer but don't know much about python. The program in question is the a1111 stable diffusion webui and due to hardware quirks I'm running it in an anaconda environment with unsupported library versions. Every now and then, the back end seemingly just hangs when inferencing in a certain way and since I ha...
<python><debugging>
2024-08-29 12:17:05
0
6,683
user81993
78,927,692
16,187,613
How to get all Styling parameter configurable by `ttk.Style().configure()` for a widget from Themed Tkinter?
<p>I have been searching the answer for this question from a long time but with no success had to ask it here. I am able to get the styling parameter for from the <a href="https://tcl.tk/man/tcl8.6/TkCmd/contents.htm" rel="nofollow noreferrer">tcl documentation</a>, but my question is how can I achieve the same result ...
<python><tkinter><ttk>
2024-08-29 12:05:32
1
1,200
Faraaz Kurawle
78,927,686
8,683,461
Scrapy perform action on all retrieved items
<p>I'm a noob on scrapy. I found lots of info about pipelines, but it seems to only treat items individually. I wish to perform some actions - let's say ordering items - on a complete set, after it's been scraped. Is there a scrapy wau to do that ?</p> <p>Thanks</p>
<python><scrapy><scrapy-pipeline>
2024-08-29 12:03:34
1
534
MarvinLeRouge
78,927,654
19,369,310
Pandas Dataframe groupby count number of rows quickly
<p>I have a dataframe that looks like</p> <pre><code>Class_ID Student_ID feature 1 4 31 1 4 86 1 4 2 1 2 11 1 2 0 5 3 2 5 9 3 5 9 2 </code></pre> <p>and I would like to count...
<python><pandas><dataframe><group-by>
2024-08-29 11:56:20
2
449
Apook
78,927,503
12,466,687
Python Regex to only include/extract numbers, decimals and Hyphen (-)
<p>I am not good at <strong>regex</strong> and have been trying &amp; failing to <strong>extract only</strong> <code>numbers, decimals and -</code> from a column in python.</p> <p>Even better if spaces can also be removed but if not even then it is still manageable.</p> <p>I have tested <code>^(\d.+)|[-]</code> and <co...
<python><regex>
2024-08-29 11:17:09
2
2,357
ViSa
78,927,337
3,405,291
ModuleNotFoundError: No module named 'mononphm'
<p>I have followed the instructions here:</p> <p><a href="https://github.com/SimonGiebenhain/MonoNPHM?tab=readme-ov-file#31-demo" rel="nofollow noreferrer">https://github.com/SimonGiebenhain/MonoNPHM?tab=readme-ov-file#31-demo</a></p> <p>To run the model by:</p> <pre class="lang-bash prettyprint-override"><code>python ...
<python><python-3.x><package><python-import><relative-import>
2024-08-29 10:31:04
1
8,185
Megidd
78,927,330
18,769,241
dlib's load_rgb_image() couldn't be found
<p>So I have successfully installed <code>dlib</code> version <code>18.17.0</code> that's compatible with <code>Python 2</code>. Classes such as <code>simple_object_detector</code> could be instantiated and returned and instance of the object. But a function called <code>load_rgb_image</code> couldn't be identified and...
<python><python-2.x><attributeerror><dlib>
2024-08-29 10:28:55
1
571
Sam
78,927,079
14,860,526
Compare excel files in python
<p>I want to compare to excel files generated by Pandas. What I want is that they are exactly the same, not just the content but the formatting as well. If I use filecmp however I get that they are different:</p> <pre><code>import pandas as pd df1 = pd.DataFrame( [['a', 'b'], ['c', 'd']], index=['row 1', 'row 2...
<python><excel>
2024-08-29 09:30:41
1
642
Alberto B
78,926,673
1,981,797
bin data after filtering
<p>I have an experimental dataset in which I could see a feature when plotting a 2D histogram: <a href="https://i.sstatic.net/6iuJ48BM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6iuJ48BM.png" alt="enter image description here" /></a></p> <p>As it can be noticed, there is something appearing in the r...
<python><python-polars>
2024-08-29 07:43:57
0
641
Maxwell's Daemon