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,903,338
893,159
How to combine async functions with callbacks in python?
<p>If I have an async view in Django, can I have it await a callback?</p> <p>Pseudocode:</p> <pre class="lang-py prettyprint-override"><code>async def my_view(request): # Use external services that eventually send data to /callback/ do_something() # Wait for the callback result = await callback_executed...
<python><django><django-rest-framework><async-await><callback>
2024-08-22 20:02:30
1
4,297
allo
78,903,264
19,039,483
Layout gaps dash dbc components
<p>I am trying to build a dashboard. The problem is even if I specify className=&quot;g-0&quot; and justify=&quot;start&quot;. My elements are spread out across the screen with huge gaps. I need them to be concentrated on the left side of screen without any gaps.</p> <p>The versions:</p> <ul> <li>dash-bootstrap-compone...
<python><python-3.x><plotly-dash><dash-bootstrap-components>
2024-08-22 19:42:46
1
315
Thoughtful_monkey
78,903,133
15,452,898
Counting repetitons in Pyspark
<p>Currently I'm working with a large dataframe and faced with an issue.</p> <p>I want to return a number of time (count) each value is repeated in a table.</p> <p>For example: number 10 is repeated twice, so I want to get number 2 and so on...</p> <p>My code is:</p> <pre><code>from pyspark.sql.types import StructType,...
<python><pyspark><data-manipulation><repeat>
2024-08-22 19:04:44
1
333
lenpyspanacb
78,903,094
12,255,379
Display waveform with ability to zoom on both axes preferably without rendering whole waveform in python
<p>I'm looking for a library or tool to setup an oscilloscope-like interface in my python program. Ideally I want a hassle-free solution with the matplotlib level of engagement as this would only serve to check the waveform in human friendly way for sanity's sake. I looked through the matplotlib's pyplot documentation ...
<python><visualization>
2024-08-22 18:53:17
0
769
Nikolai Savulkin
78,902,924
4,577,467
How to force SWIG to see DECLSPEC preprocessor macro when included from another file?
<p>I am using SWIG version 4.0.2 in a Windows Subsystem for Linux (WSL) Ubuntu distribution. I am attempting to create a Python extension module that wraps a C++ library. The C++ library is intended to used in both Windows and Linux environments, and thus its classes and external functions are decorated with a <code>...
<python><c++><linux><swig>
2024-08-22 18:02:19
0
927
Mike Finch
78,902,913
13,102,622
How to bypass Cloudflare using Playwright
<p>I'm creating a webscraping program in Python that bypasses Cloudflare authentication like the checkbox. Problem is that the program is unable to search for the <code>&lt;iframe&gt;</code> where the checkbox resides</p> <pre><code>async def run(playwright: Playwright): args = [] #disable navigator.webdriver:...
<python><python-3.x><web-scraping>
2024-08-22 18:00:39
1
415
Elijah Leis
78,902,899
10,038,696
Why is in-place assignment slower than creating a new array in NumPy?
<p>I am trying to optimize a code, which has allocations inside a function that is repeatedly called in a loop. I ran some performance tests using jupyter and results were counterintuitive for me. As a minimal example, see the following.</p> <p>Given arrays <code>A</code>, <code>B</code>, I will perform matrix multipli...
<python><numpy><variable-assignment><pre-allocation>
2024-08-22 17:56:53
1
377
cap
78,902,884
95,048
Optimize reading of a very wide dataset (100k columns) in polars and pandas
<p>I have a dataset that contains a very large number of columns, about 500k.</p> <p>The same data is stored in parquet and as a CSV.</p> <p>I've noticed the following:</p> <ul> <li>Reading the CSV file is very fast in polars, but crashes in pandas.</li> <li>Reading the parquet file is very fast in pandas (about 30 sec...
<python><pandas><python-polars>
2024-08-22 17:54:00
1
8,960
dalloliogm
78,902,791
2,201,603
ReportLab is not sending PDF file to path directory
<p>My colleagues and I are using ReportLab and two of us can successfully generate a simple PDF document using the below script. Both of us that receive a successful ReportLab PDF file have ReportLab version 4.2.0. Our other team member ran the same script, but the PDF isn't showing up in the directory as expected. Whe...
<python><reportlab>
2024-08-22 17:25:06
0
7,460
Dave
78,902,565
250,962
How do I install Python dev-dependencies using uv?
<p>I'm trying out <a href="https://github.com/astral-sh/uv" rel="noreferrer">uv</a> to manage my Python project's dependencies and virtualenv, but I can't see how to install <em>all</em> my dependencies for local development, including the development dependencies.</p> <p>In my <em>pyproject.toml</em> file, I have this...
<python><uv>
2024-08-22 16:20:22
6
15,166
Phil Gyford
78,902,557
7,265,057
How to properly configure Python to use system-level Certificates (windows) behind a Forced VPN (zscaler)?
<p>I've recently started working within a large organization that requires all computers to be behind a forced VPN (zscaler). This setup has caused several issues when using multiple Python libraries and even when installing packages from remote sources, such as PyTorch with CUDA.</p> <p>Here are the main issues we're ...
<python><ssl><vpn>
2024-08-22 16:17:34
0
343
wrong1man
78,902,450
741,262
AWS Sagemaker Notebook + Panel Tabulator: on_edit not working
<p>I am trying to get some basic example of <a href="https://panel.holoviz.org/reference/widgets/Tabulator.html" rel="nofollow noreferrer">Panel Tabulator</a> with <code>on_edit</code> working in an AWS SageMaker notebook (Jupyter Lab).<br /> My understanding is that <code>edit_table.on_edit(lambda e: print(e.column, e...
<python><amazon-sagemaker><jupyter-lab><tabulator><holoviz-panel>
2024-08-22 15:50:27
0
1,291
Reini
78,902,320
8,410,477
Compile, install X-13ARIMA-SEAT on macOS Apple Silicon (ARM64) and use it in sm.tsa.x13_arima_analysis()
<p>I am struggling to compile and use <strong>X-13ARIMA-SEAT</strong> on a Mac with an m3 chip, and called it using <code>sm.tsa.x13_arima_analysis(s, x12path='/usr/local/bin/x13as')</code> in <strong>statsmodels</strong>. Finally, I succeeded and now share the method step by step.</p> <p>In addition, I would like to k...
<python><macos><statsmodels><seasonal-adjustment><x13>
2024-08-22 15:14:37
1
10,141
ah bon
78,902,034
1,914,781
Use one regex to extract information from two patterns
<p>I would like to simplify below regex logic with one regex statement. Then it's easier to understand the logic.</p> <pre class="lang-python prettyprint-override"><code>import re content = &quot;&quot;&quot; [ 1.765989] initcall init_module.cfi_jt+0x0/0x8 [altmode_glink] returned 0 after 379 usecs [ 0.001873] i...
<python><regex>
2024-08-22 14:15:00
2
9,011
lucky1928
78,901,940
13,840,270
Can I subset an Iterator and keep it an Iterator?
<p>I have a use case where I need the permutations of boolean. However I do not need them when they are reversed. So I can do something like this:</p> <pre class="lang-py prettyprint-override"><code>import itertools [ p for p in itertools.product([True,False],repeat=4) if p!=p[::-1] ] </code></pre> <p>Thi...
<python><iterator>
2024-08-22 13:55:21
2
3,215
DuesserBaest
78,901,762
893,254
How to build a module for logging in Python?
<p>I want to write a library (a module) in Python for logging. The logger instance should be unique per process and global per process. (Meaning that it <em>should not</em> be passed around as an argument to different functions.)</p> <p>I am having a bit of a mental block trying to design something sensible.</p> <p>Let...
<python><logging><design-patterns><module><software-design>
2024-08-22 13:14:33
2
18,579
user2138149
78,901,682
13,663,100
Python Polars SQL Interface asof Join
<p>Is there a SQL interface equivalent for the asof join in polars? I use <code>by</code> and <code>on</code> arguments often with these joins.</p> <p>The methodology that I am using in the meantime is the one provided for Snowflake before the asof join was introduced in the SQL interface: <a href="https://stackoverflo...
<python><sql><python-polars>
2024-08-22 12:52:39
0
1,365
Chris du Plessis
78,901,681
9,313,033
Exporting only dev dependencies
<p>Is there a command for <a href="https://github.com/astral-sh/uv" rel="nofollow noreferrer">uv</a> that exports/extracts just the dependencies declared as dev dependencies from the <code>pyproject.toml</code> file, for example to pass test dependencies to tox?</p> <pre class="lang-bash prettyprint-override"><code>uv ...
<python><uv>
2024-08-22 12:52:30
3
2,941
CoffeeBasedLifeform
78,901,597
17,040,989
snakemake: MissingOutputException in rule hifiasm in file /home/usr/path/to/Snakefile, line 13
<p>Hi there I was working on a very basic Snakemake file to run <code>hifiasm</code>; it seems to work well but, for some reason, at the end of the run I was prompted with the following:</p> <blockquote> <p>Waiting at most 5 seconds for missing files. MissingOutputException in rule hifiasm in file /home/usr/path/to/Sna...
<python><pipeline><bioinformatics><snakemake>
2024-08-22 12:32:41
1
403
Matteo
78,901,594
7,227,146
Find text inside top-level brackets when they're nested
<p>I have a file with nested brackets. I need to parse the text within the top-level brackets with Python regex.</p> <pre><code>import re string = '{a {b} c} {d}' # desired output: ['a {b} c', 'd'] # non-greedy pattern_1 = r'(?&lt;={).*?(?=})' print(re.findall(pattern_1, string)) # actual output: ['a {b', 'd'] # gr...
<python><regex><python-re>
2024-08-22 12:32:22
0
679
zest16
78,901,476
1,203,670
How can we efficiently determine in a table with items whether the orders contain only our products / third party or mixed?
<p>I have a dataset in Python, in which we have OrderNumbers, IsOurs, whether a product is ours or not and we have the amount that the product costs. We would like to classify every order, whether it only contains our product, whether it contains a mix of products or only contains products from others. We can generate ...
<python><pandas><dataframe>
2024-08-22 12:06:12
2
3,099
Snowflake
78,901,386
5,615,873
How can I center a trimesh window on screen?
<p>I have started to work with Python's <code>trimesh</code> package and the first thing I want to do is to set the size of the graphics window and its position on the screen.</p> <p>I figured out how to resize the graphics window, as the simple code below (from <a href="https://github.com/mikedh/trimesh/blob/main/exam...
<python><pyglet><trimesh>
2024-08-22 11:44:49
3
3,537
Apostolos
78,901,385
5,878,986
How to Perform Pagination with Sorting on DynamoDB Using CreatedAt Attribute in Python?
<p>I'm working with AWS DynamoDB using Python, and I have a table defined as follows using AWS SAM:</p> <pre><code>RecommendedTalesNewTable: Type: 'AWS::DynamoDB::Table' Properties: TableName: 'RecommendedTalesNew' # New table name AttributeDefinitions: - AttributeName: 'Id' AttributeType: 'S...
<python><amazon-web-services><amazon-dynamodb><boto3>
2024-08-22 11:44:48
1
1,166
Bertug
78,901,362
7,256,443
Why are `dict_keys`, `dict_values`, and `dict_items` not subscriptable?
<p>Referring to an item of a <code>dict_keys</code>, <code>dict_values</code>, or <code>dict_items</code> object by index raises a type error. For example:</p> <pre class="lang-py prettyprint-override"><code>&gt; my_dict = {&quot;foo&quot;: 0, &quot;bar&quot;: 1, &quot;baz&quot;: 2} &gt; my_dict.items()[0] ------------...
<python><python-3.x><dictview>
2024-08-22 11:39:41
1
1,033
Ben Jeffrey
78,901,337
1,560,414
py2exe: how to include additional resource files from dependancy
<p>I'm trying to build a project that has a dependency on <code>jsonschema</code>. On building and running the project with <code>py2exe</code> I get this error at runtime:</p> <pre><code>INFO:runtime:Analyzing the code INFO:runtime:Found 527 modules, 27 are missing, 0 may be missing 27 missing Modules -----------...
<python><py2exe>
2024-08-22 11:33:37
1
1,667
freebie
78,901,146
1,613,983
Why does recurse=True cause dill not to respect globals in functions?
<p>If I pickle a function with <code>dill</code> that contains a global, somehow that global state isn't respected when the function is loaded again. I don't understand enough about <code>dill</code> to be anymore specific, but take this working code for example:</p> <pre><code>import multiprocessing import dill def i...
<python><dill>
2024-08-22 10:51:28
1
23,470
quant
78,901,041
10,207,281
Why is it so slowly while transferring files from windows through WinRM by using python?
<p>I'm using <code>python + winrm</code> to get files from a windows server. The code runs fine but slowly. It can only get about 10GB per day by this way.<br /> If I copy files through remote desktop(<code>mstsc.exe</code> or Other remote clients) manually, I can get a file of 140GB just at one night.</p> <p>I want to...
<python><remote-access><file-transfer><winrm>
2024-08-22 10:25:40
0
920
vassiliev
78,900,776
1,658,617
Convert xml.etree.ElementTree.Element to lxml.Element
<p>I'm developing a package that can be used by both users of lxml and the default xml package. ATM I have a small try:except for the lxml import, but sometimes the user uses functions like <code>dump()</code> from the default <code>xml.etree</code> which don't support the <code>lxml.Element</code>.</p> <p>How can I co...
<python><xml><lxml><elementtree>
2024-08-22 09:27:14
1
27,490
Bharel
78,900,629
1,627,466
Erroneous pandas rolling results with time window in grouped by dataframe imported from BigQuery
<p>I would like to preface this by apologizing for the lack of reproducibility of my question because if I convert my dataframe to a dictionary and turn that into a dataframe again I am not getting the issue.</p> <p>Nevertheless, this is the query I am using on BigQuery:</p> <pre class="lang-sql prettyprint-override"><...
<python><pandas><dataframe><google-bigquery>
2024-08-22 08:53:33
1
423
user1627466
78,900,584
101,152
pip3 tries to write to /var/log even with venv and failing
<p>I follow these steps, and they always fail.</p> <pre><code>mkdir python-mess cd python-mess echo toml &gt; requirements.txt which python3 # /usr/bin/python3 which pip3 # /usr/bin/pip3 python3 -m venv .venv source .venv/bin/activate # (.venv is added to prompt) which pip3 # /home/karel.bilek/python-mess/.venv/bin/pip...
<python><python-3.x><pip>
2024-08-22 08:44:02
1
38,046
Karel BΓ­lek
78,900,482
5,269,892
Pandas replace multiple substring patterns via dictionary
<p>Suppose we want to replace multiple substrings via <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.replace.html" rel="nofollow noreferrer">pd.Series.replace</a> or <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">pd.DataFrame.replace</...
<python><pandas><replace>
2024-08-22 08:21:00
1
1,314
silence_of_the_lambdas
78,900,439
16,611,809
How to show two outputs of the same function without running it twice?
<p>I have this function that iterates over my data and generates two outputs (in the example, the function <code>check()</code>. Now I want to show both outputs on different cards. AFAIK the card ID has to be the same as the function that generates the output. In my example, the function <code>check()</code> is run twi...
<python><py-shiny>
2024-08-22 08:10:30
1
627
gernophil
78,900,424
12,945,785
How to calculate the last 3 month, 6 month...performance from price?
<p><strong>Disclaimer.</strong> I am new to polars.</p> <p>I have a dataframe that is generated with something like this with polars:</p> <pre><code>import polars as pl import numpy as np from datetime import datetime # CrΓ©er une plage de dates date_ranges = pl.date_range(start=datetime(2000, 1, 1), end=datetime(2025,...
<python><dataframe><python-polars>
2024-08-22 08:06:15
4
315
Jacques Tebeka
78,900,274
17,580,381
scipy 1.14.1 breaks statsmodels 0.14.2
<p>After installation of scipy 1.14.1 a previously viable Python program now fails.</p> <p>The original program is more complex so here's a MRE:</p> <pre><code>import pandas as pd import plotly.express as px if __name__ == &quot;__main__&quot;: data = { &quot;Date&quot;: [0, 7, 14, 21, 28], &quot;V...
<python><macos><scipy>
2024-08-22 07:32:27
2
28,997
Ramrab
78,900,270
21,040,543
This is a question about tkinter's <Configure> binding
<p>I am a Windows 11 user. I wrote this code with the idea of ​​a canvas that changes size responsively when the window size changes. However, when the program started, the window and canvas kept growing together. I think it's because of some relationship between tkinter's window creation process and , but I'm curious ...
<python><tkinter>
2024-08-22 07:31:03
1
344
kimhyunju
78,899,693
736,662
Unix timestamp +1 hour replacement
<p>I defined two helper methods in Python for setting start-time and end-time and want it converted into unix timestamp (epoch):</p> <pre><code>def set_epoch_start(): unix_epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc) now = datetime.now(tz=timezone.utc) new_time = now.replace(hour=17, mi...
<python><epoch><timedelta>
2024-08-22 03:31:34
1
1,003
Magnus Jensen
78,899,132
375,432
Use Ibis to return aggregates of every numeric column in a table
<p>I want to use <a href="https://ibis-project.org" rel="nofollow noreferrer">Ibis</a> to return the mean and standard deviation of each floating point numeric column in a table. How do I do that?</p>
<python><ibis>
2024-08-21 21:59:22
1
763
ianmcook
78,898,865
13,135,901
Updating object attribute from database in Django
<p>Let's say I have a model representing a task:</p> <pre><code>class Task(models.Model): on_status = models.BooleanField() def run(self): if self.on_status: # do stuff </code></pre> <p>I run this task with Celery Beat and I have a dashboard running on Gunicorn both using the same database....
<python><django><celery>
2024-08-21 20:20:19
1
491
Viktor
78,898,805
11,159,734
docker-compose -e flag does not override default value
<p>I have created the following docker-compose.yml:</p> <pre><code>version: &quot;3.8&quot; services: app: image: my-image build: context: . dockerfile: Dockerfile working_dir: /src command: python ${SCRIPT} environment: - .env app-dev: extends: service: app vol...
<python><docker>
2024-08-21 20:01:41
4
1,025
Daniel
78,898,776
145,504
How can a Python enum accept any value without raising ValueError
<p>Suppose I am implementing a network service that receives commands. I want to have an enumeration of these commands, so I can write something like:</p> <pre class="lang-py prettyprint-override"><code>class Command(enum.Enum): ECHO = 0x01 LOGIN = 0x02 SEND_FILE = 0x03 def handle_packet(p: bytes): com...
<python><enums>
2024-08-21 19:50:51
3
4,458
rgov
78,898,497
769,933
Create Categorical series from physical values
<p>I want to create a categorical column, where each category has a descriptive name for self-documentation. I have a list of integers equivalent to the physical values in the categorical column, and I want to make the categorical column without creating an intermediate list of strings to pass to <code>pl.Series</code>...
<python><python-polars>
2024-08-21 18:20:47
2
2,396
gggg
78,898,466
758,836
PyTorch Lightning Distributed Training Timeout error with NCCL Backend
<p>I'm using Pytorch Lightning to run a distributed training Python script using the <a href="https://lightning.ai/docs/pytorch/stable/accelerators/gpu_intermediate.html#distributed-data-parallel" rel="nofollow noreferrer">DDP</a>. I'm using a <code>DDPStrategy</code> to define the backend, a custom timeout and a custo...
<python><pytorch><nvidia><pytorch-lightning><nccl>
2024-08-21 18:08:32
0
16,321
loretoparisi
78,898,460
1,549,983
Make type checker accept multiple types for a field as valid but have pydantic always coerce to one type
<p>I'm building a wrapper for another program I'm using that takes integer-valued flags as input for setting various options. To make the interface a bit more intuitive, I'd like to have a way to automatically validate either a keyword string or the integer flag value and associate it with any other data that might be ...
<python><python-typing><pydantic>
2024-08-21 18:06:44
0
391
Beezum
78,898,299
375,666
Converting Reality Capture Transormation matrix into another coordinate system
<p>I'm using reality capture and I have expoerted a set of 20 cameras in the scene into XMP and I have the list of coordinate systems.</p> <p>I have a reference coordinate system that I want to match the reality capture/convert to it's coordinate system.</p> <p>I have tried everything so that I can match the two system...
<python><3d><computer-vision><camera>
2024-08-21 17:27:23
1
1,919
Andre Ahmed
78,898,176
8,467,078
How to use PRAGMA with sqlite3's new autocommit attribute in Python?
<p>Python's <code>sqlite3</code> module recently introduced the <code>autocommit</code> attribute, which <a href="https://docs.python.org/3/library/sqlite3.html#sqlite3-transaction-control-autocommit" rel="noreferrer">the docs recommend</a> setting to <code>False</code>. I'd like to use this recommended setting for a n...
<python><sqlite>
2024-08-21 16:56:22
0
345
VY_CMa
78,898,081
7,321,700
Groupby index and keep the max column value given a single column
<p><strong>Scenario:</strong> With a dataframe with duplicated indices, I want to groupby while keeping the max value. I found the solution to this in <a href="https://stackoverflow.com/questions/43486226/drop-duplicates-by-index-keeping-max-for-each-column-across-duplicates">Drop duplicates by index, keeping max for e...
<python><pandas><dataframe><group-by>
2024-08-21 16:32:22
1
1,711
DGMS89
78,897,975
4,648,809
Python idiom `if __name__ == '__main__':` in uwsgi?
<p>What is Python idiom in uwsgi for</p> <pre><code>if __name__ == '__main__': main() </code></pre> <p>I found here a long string in uwsgi instead of <code>__main__</code> <a href="https://stackoverflow.com/questions/34129354/what-name-string-does-uwsgi-use">What __name__ string does uwsgi use?</a>. But it looks lik...
<python><uwsgi>
2024-08-21 16:08:57
1
1,031
Alex
78,897,914
3,486,684
Polars: What are the downsides of joining on null?
<p><a href="https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.join.html" rel="nofollow noreferrer"><code>join_nulls</code> is <code>False</code></a> by default in <code>polars</code>.</p> <p>Suppose I were to always call <code>join</code> with <code>join_nulls</code> set to <code>True</cod...
<python><dataframe><python-polars>
2024-08-21 15:53:50
1
4,654
bzm3r
78,897,803
5,213,451
Can I easily parse datetimes independently of my machine?
<p>In python I like the <code>datetime</code> module of the standard library to parse timestamps. However, some of the <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes" rel="nofollow noreferrer">format codes</a> depend on the locale set for the machine where it's run, which ma...
<python><datetime><locale><python-datetime>
2024-08-21 15:28:55
0
1,000
Thrastylon
78,897,764
10,425,150
Create "Pass/Fail/Caution" status in pandas dataframe based another columns without "SettingWithCopy" warning
<p>I wrote code where:</p> <ol> <li>All values above 3 are marked as &quot;Fail&quot;.</li> <li>Values between 1 and 3 marked as &quot;Caution&quot;.</li> </ol> <p>However I have the following warning: <code>A value is trying to be set on a copy of a slice from a DataFrame</code>. And I'm not sure how I could avoid thi...
<python><pandas><dataframe>
2024-08-21 15:20:28
3
1,051
GΠΎΠΎd_MΠ°n
78,897,744
342,546
PunktSentenceTokenizer with specific language and complex abbreviations
<p>I've tried to adapt the solution from <a href="https://stackoverflow.com/q/69734355/342546">Configure PunktSentenceTokenizer and specify language</a> for abbreviations containing dots (e.g. &quot;i.d.F.&quot;). Thus, I've expected the following to work:</p> <pre><code>import nltk additional_abbreviations = [&quot;z...
<python><nltk><tokenize>
2024-08-21 15:17:48
1
13,736
tohuwawohu
78,897,635
3,061,305
Unable to unit test Azure Durable Function in Python v2 Programming Model
<p>I'm really struggling to write unit tests for an Azure Durable Function in Python.</p> <p>This is the code:</p> <pre><code>@bp.timer_trigger(schedule=&quot;0 0 12 * * *&quot;, arg_name=&quot;timer&quot;) @bp.durable_client_input(client_name=&quot;client&quot;) async def my_func(timer: func.TimerRequest, client: df.D...
<python><pytest><azure-durable-functions>
2024-08-21 14:50:47
2
7,331
Jan Swart
78,897,605
1,406,168
Azure Function App Python - Accessing Storage Account
<p>I have created a function app on a linux host. I deploy via a pipeline and everythings works as expected. Until I start importing azure libraries, then the functions are just not deployed. No errors.</p> <pre><code>#When adding below functions fails to show in the azure portal. from azure.identity import DefaultAzu...
<python><azure><azure-functions>
2024-08-21 14:43:55
1
5,363
Thomas Segato
78,897,579
2,456,863
How to create numpy records array with numerical entries without dtype name
<p>I am trying to create a numpy records array to match data that I am reading from an HDF5 file. The dtype of the HDF5 dataset (<code>dataset</code>) has a dtype of <code>np.dtype(('u1', (3,)))</code>. The dtype of <code>dataset[0]</code> is <code>dtype('uint8')</code>. I am trying to write an HDF5 to match this as sh...
<python><numpy><hdf5><h5py>
2024-08-21 14:38:28
1
680
Stephen Hartzell
78,897,164
9,476,917
Matplotlib Chart bring xticks lables to the front
<p>I found a wonderful example to plot a radar chart in python's matplotlib from this <a href="https://stackoverflow.com/a/78122416/9476917">answer</a>.</p> <p>My xtick labels are quite long and reach into the radar chart. The label text is thus covered by the lines of the radar chart as shown in the screenshot below. ...
<python><matplotlib><axis-labels>
2024-08-21 13:14:20
0
755
Maeaex1
78,896,938
7,483,211
How to get exact exit code that a snakemake job exited with?
<p>When a snakemake job errors with a non-zero exit code, snakemake prints:</p> <pre><code>(one of the commands exited with non-zero exit code; note that snakemake uses bash strict mode!) Exiting because a job execution failed. Look above for error message </code></pre> <p>How can I find out what the <em>exact</em> ex...
<python><logging><snakemake><exit-code>
2024-08-21 12:24:11
1
10,272
Cornelius Roemer
78,896,889
7,483,211
How to see the logs of failed snakemake jobs immediately in stderr - instead of log file
<p>I'm running snakemake inside kubernetes with argocd. When a job errors, snakemake says that the logs of the failed job are in a log file. Now I can't easily look this logfile up because argocd doesn't allow this.</p> <p>I want the failed job logs to be shown in the normal log output. How can I do this?</p>
<python><logging><snakemake><logfile>
2024-08-21 12:14:30
1
10,272
Cornelius Roemer
78,896,818
8,188,120
expo-go development app not communicating with flask API
<h2>Problem details</h2> <p>I am running an Android Expo Go app in development mode which appears to be available at these locations:</p> <blockquote> <p>β€Ί Choose an app to open your project at <a href="http://192.168.0.49:8081/_expo/loading" rel="nofollow noreferrer">http://192.168.0.49:8081/_expo/loading</a> β€Ί Metro ...
<python><react-native><flask><expo><ip-address>
2024-08-21 11:59:19
1
925
user8188120
78,896,815
265,683
pyautogui locateCenterOnScreen is not finding my source image or 'needle'
<p>I am searching in an area of 543 pixels wide and 378 pixels height from the top left corner of my screen for the following 'needle'</p> <p><a href="https://i.sstatic.net/76rX3peK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/76rX3peK.png" alt="enter image description here" /></a></p> <p>You may reco...
<python><python-3.x><macos><ui-automation><pyautogui>
2024-08-21 11:58:08
1
5,690
RenegadeAndy
78,896,677
2,177,047
Migration of Workflow from Spyder IDE to PyCharm: Code snippet execution and variable explorer
<p>I currently use the Spyder IDE and have often thought about migrating to PyCharm but there is one feature I often use which makes it impossible for me to switch.</p> <p>I very often use Spyders Code Snippet execution by marking lines of code and executing them with F9. After that I inspect the outcome of the executi...
<python><debugging><pycharm><workflow><spyder>
2024-08-21 11:23:58
1
2,136
Ohumeronen
78,896,645
11,829,398
What do pydantic's field_validator modes do?
<p>I want to apply field validation to my Pydantic v2 model but don't understand what the <code>mode</code> kwarg does.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from typing import Optional from pydantic import BaseModel, field_validator, Field class MyModel(BaseModel): gross: Option...
<python><pydantic><pydantic-v2>
2024-08-21 11:14:39
1
1,438
codeananda
78,896,486
926,918
Spurious zero printed in seaborn barplot while plotting pandas dataframe
<p>The following is the minimal code. A spurious zero is printed between second and third bars that I am unable to get rid of in the plot. Please help me fix the code. A minimal working example is below:</p> <p><a href="https://i.sstatic.net/kZeNQUfb.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kZeNQU...
<python><pandas><seaborn>
2024-08-21 10:39:25
2
1,196
Quiescent
78,896,474
8,964,393
How to get coefficients from glm model in python
<p>I have trained the following glm model in Python:</p> <pre><code>fitGlm = smf.glm( listOfInModelFeatures, family=sm.families.Binomial(),data=train, freq_weights = train['model_weight']).fit() </code></pre> <p>I have then produced the summary of the trained model:</p> <pre><code> print(fitGlm.summary...
<python><list><glm><coefficients>
2024-08-21 10:35:55
1
1,762
Giampaolo Levorato
78,896,438
2,753,095
Copying a class object in Python
<p>Suppose I have a complicated class with lots of methods. In particular it is callable via a <code>__call__</code> member. I would like to have an object from the exact same class, but not callable and not with <code>__call__</code> at all in fact, because some introspection tool would detect it and this is not wante...
<python><metaprogramming>
2024-08-21 10:29:49
2
7,998
mguijarr
78,896,435
4,451,315
Function takes `Foo` subclass and wraps it in `Bar`, else returns type unaltered
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Any, Generic class Foo: ... class Bar(Generic[FooT]): def __init__(self, foo: FooT): self._foo = foo FooT = TypeVar('FooT', bound=Foo) T = TypeVar('T') def func(a: FooT | T) -&gt; Bar[Foo...
<python><python-typing><mypy>
2024-08-21 10:29:20
2
11,062
ignoring_gravity
78,896,317
11,022,199
Unpivoting a dataframe by splitting column names
<p>I have the following dataframe:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>volume_brand1</th> <th>volume_productX_brand1</th> <th>amount_brand1</th> <th>amount_productX_brand1</th> <th>volume_productX_brand2</th> <th>amount_productX_brand2</th> </tr> </thead> <tbody> <tr> <td>1000</t...
<python><pandas>
2024-08-21 10:03:52
3
794
borisvanax
78,896,313
2,641,187
Bound TypeVar resolution of arguments to multiplication
<p>I am struggling with a problem of bound TypeVar resolution of function/method arguments.</p> <p>Suppose I have a base class <code>Base</code> and a couple of derived classes. Also suppose I have a TypeVar <code>T</code> that is bound to <code>Base</code>. I want to define a generic container class that represents or...
<python><python-typing>
2024-08-21 10:02:11
0
931
Darkdragon84
78,896,251
1,753,640
docx2pdf set permissions on docx fie
<p>I am calling an api to download a docx file which I save locally. I then want convert it to PDF. When I run docx2pdf on the file, I get a pop-up stating that MS Word needs permissions. What can I do to automate this step and remove the popup so a user is not involved? Should I set appropriate permissions on the file...
<python><macos><ms-word><permissions><docx2pdf>
2024-08-21 09:47:05
1
385
user1753640
78,896,210
1,021,819
How do I use python to zero pad an integer substring (not a whole string) within another string?
<p>Say I have strings like (outputted from running <code>glob.glob()</code> on output from someone else's code):</p> <pre><code>image-0.png image-1.png image-2.png image-3.png image-4.png image-5.png image-6.png image-7.png image-8.png image-9.png image-10.png image-11.png </code></pre> <p>How do I left zero pad the in...
<python><string><substring><zero-padding>
2024-08-21 09:39:25
1
8,527
jtlz2
78,895,938
1,224,456
Incremental parsing of LLM output
<p>I'm working on a service that calls a Large Language Model, parse the output, and sends the parsed output to a client, message by message. When aggregated, the stream of text coming back from the LLM looks somewhat like this:</p> <p><code>This is a reference [r1] and here's an image of a cat &lt;image&gt;a black cat...
<python><parsing><large-language-model>
2024-08-21 08:36:57
1
2,880
Nagasaki45
78,895,893
26,843,912
AttributeError: 'function' object has no attribute 'submit'
<p>I am using fastapi and uvicorn as my python server and whenever a user visits a route, I want to start a subprocess in the background. I used asyncio.create_task and <code>loop.run_in_excutor</code> in order to properly handle the subprocess code.</p> <p>PYTHON VERSION :- 3.11.3 OPERATING SYSTEM :- Windows x64</p> <...
<python><multithreading><asynchronous><python-asyncio><fastapi>
2024-08-21 08:22:33
1
323
Zaid
78,895,733
9,860,033
Pythonic way to create a singleton class that requires an async method to setup?
<p>I'm writing a Python package that implements a class which should be a singleton.<br /> The class is responsible for sending async http requests. Thus the class needs to have access to an <code>aiohttp.ClientSession</code>.<br /> The catch is that I wish to support two types of instantiation:</p> <ol> <li>The user c...
<python><class><design-patterns><singleton><python-packaging>
2024-08-21 07:45:01
0
1,134
waykiki
78,895,508
3,067,485
Cannot make inline formset working with class based view in Django 5.1
<p>I have the following Django structure. I use the latest Django version <code>5.1</code>. I have also checked in version <code>4.2.15</code> the issue is still present.</p> <p>I aim to get <code>Formset</code> working with Class Based View. Anyway, whatever I tried my formset is never valid. I can see raw data in <co...
<python><django><django-forms><inline-formset>
2024-08-21 06:49:22
1
11,564
jlandercy
78,895,421
6,907,424
How to prevent Playwright to load non-textual contents?
<p>I am trying to implement a crawler which will be responsible to crawl the given page. Here I <strong>don't</strong> want to crawl any non-textual items, not even want the headless browser to load it, as it is simply wasteful and unnecessarily increases the crawling time. To achieve this, I have added rules which sho...
<python><web-scraping><scrapy><playwright>
2024-08-21 06:26:42
1
2,916
hafiz031
78,895,386
1,408,347
Why can't I run `from algorithm import foo` in `lambda_function.py` inside a docker container for AWS lambda function?
<p>I'm following <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-image.html#python-image-instructions" rel="nofollow noreferrer">this tutorial</a> to build a Docker image for an AWS lambda function that runs python 3.11.</p> <p>When I run <code>python lambda_function.py</code> locally, it can successfully ...
<python><docker><aws-lambda><aws-lambda-containers>
2024-08-21 06:14:29
1
13,773
Brian
78,895,383
188,331
How to use apply() on DataFrame using a custom function?
<p>I have the following Pandas DataFrame:</p> <pre><code>import pandas as pd from collections import Counter print(sentences) </code></pre> <p>the output is (yes, the column name is <code>0</code>):</p> <pre><code> 0 0 A 1 B 2 C 3 D 4 EEE ... ...
<python><pandas>
2024-08-21 06:12:35
2
54,395
Raptor
78,895,244
3,523,406
Can Docker in the terminal display Python library versions like Docker Desktop?
<p>I'm using Docker Desktop, which provides a GUI feature to easily view the versions of installed Python libraries within a container. This feature is quite handy for managing dependencies and ensuring consistency across environments.</p> <p>However, I often work in the terminal and want to achieve the same outcome th...
<python><docker><pip><docker-desktop>
2024-08-21 05:22:56
1
645
user3523406
78,895,109
1,125,062
Is it possible to run autograd backward one node at a time?
<p>Let say I have a complex model with many many layers.</p> <p>When I obtain the output of the model I calculate the loss.</p> <p>Now when I run loss.backward() it would calculate gradients for all layers at once.</p> <p>But is it possible to run backward() one layer at a time?</p> <p>So what I'm trying to do is to ob...
<python><python-3.x><pytorch><torch><autograd>
2024-08-21 04:09:45
2
4,641
Anonymous
78,895,025
9,769,454
fill_value='extrapolate', bounds_error=False in interp1d still raise ValueError
<p>I have set the <em><strong>fill_value='extrapolate</strong>'</em>, <em><strong>bounds_error=False</strong></em> for using interp1d.</p> <pre><code>f_ca = interp1d(df_Ca['Cap_x'], df_Ca['V'], kind='linear', fill_value='extrapolate', bounds_error=False) </code></pre> <p>However when I run the code there is still error...
<python><scipy><interpolation>
2024-08-21 03:23:20
0
553
Roy Dai
78,894,984
26,438,560
Why can hexadecimal python integers access properties but not regular ints?
<p>Decimal (i.e. non-prefixed) integers in Python seem to have fewer features than prefixed integers.</p> <p>If I do <code>1.real</code> I get a <code>SyntaxError: invalid decimal literal</code>. However, if I do <code>0x1.real</code>, then I get no error and <code>1</code> is the result. (Same for <code>0b1.real</code...
<python><syntax><integer>
2024-08-21 02:57:44
1
413
Sir Nate
78,894,954
6,312,979
Polars Dataframe via Django Query
<p>I am exploring a change from pandas to polars. I like what I see.</p> <p>Currently, it is simple to get the data into Pandas.</p> <pre class="lang-py prettyprint-override"><code>cf = Cashflow.objects.filter(acct=acct).values() df = pd.DataFrame(cf) </code></pre> <p>So I figured it would be a simple change - but this...
<python><django><pandas><python-polars>
2024-08-21 02:42:41
1
2,181
diogenes
78,894,926
5,044,463
LP Solver; Setting up model constraints for large number of chained dependency variables is slow
<p>Creating the model is too slow. Solving it is not the problem here.</p> <p>I have looked at a few similar questions before, but they don't have the problem from the size that I am giving it.</p> <p>The constraint that is very slow to add to the model looks something like this:</p> <pre><code>x out of {0, 1} (binary)...
<python><linear-algebra><linear-programming><solver><pulp>
2024-08-21 02:28:03
2
737
GRASBOCK
78,894,917
8,929,698
Time per process increases with number of processes when reading JSON in Python. Why?
<p>I am trying to parallelize the processing of some JSON files using Python's multiprocess module. The amount of time required to process a fixed number of files within a subprocess seems to depend on the overall number of files. My expectation was that this should be constant.</p> <p>In the example below, I compare...
<python><multiprocess>
2024-08-21 02:24:07
0
1,044
broken.eggshell
78,894,891
2,662,302
polars, combining sales and purchases, FIFO method
<p>I have two dataframes:</p> <p>One with buys</p> <pre class="lang-py prettyprint-override"><code>df_buy = pl.DataFrame( { &quot;BuyId&quot;: [1, 2], &quot;Item&quot;: [&quot;A&quot;, &quot;A&quot;], &quot;BuyDate&quot;: [date.fromisoformat(&quot;2023-01-01&quot;), date.fromisoformat(&quot;...
<python><dataframe><python-polars><asof-join>
2024-08-21 02:08:25
1
505
rlartiga
78,894,887
243,755
How to change the working directory in pycharm globally?
<p>When I run a pytest script, the working directory is always the folder where this pytest script is in. But what I want is to make the project root folder as the working directory. Although I can change it in the Run configuraiton, but it only applied in for the single pytest, which means I need to do this change for...
<python><pycharm>
2024-08-21 02:04:48
1
29,674
zjffdu
78,894,807
6,137,760
How to time an aiohttp request
<p>I have an async script that looks partially like:</p> <pre class="lang-py prettyprint-override"><code>def main(endpoints): loop = asyncio.get_event_loop() loop.run_until_complete(_main(endpoints, loop)) loop.close() async def _main(endpoints, loop): connector = aiohttp.TCPConnector(limit=3) asyn...
<python><python-asyncio><aiohttp>
2024-08-21 01:09:25
1
1,673
Mike S
78,894,794
4,423,300
regex to match starting numbering or alphabet bullets like (a)
<p>I am trying to find whether string(sentence) starts with numbering or alphabet bullets followed by dot(.) or space. I have regex like:</p> <pre><code>r'^(\(\d|\[a-z]\))\s +' </code></pre> <p>and</p> <pre><code>r&quot;^(?:\(\d+\)|\\[a-z]\.)\s*&quot; </code></pre> <p>I tried it on example strings:</p> <pre class="lang...
<python><regex>
2024-08-21 01:00:15
2
637
SheCodes
78,894,720
998,619
Tile according to a pattern in pytorch (or numpy)?
<p>I have a 2-d tensor pattern I'd like to repeat/tile with a particular sparsity. I suspect there is a function (or two-line approach using gather, fold/unfold, or similar) to do this in Pytorch.</p> <p>These two approaches each get the result I want but are inefficient and/or confusing:</p> <pre><code># inputs mask =...
<python><numpy><pytorch>
2024-08-20 23:54:10
2
341
RussH
78,894,598
268,581
Downloading 1D OHLC data using thetadata
<h1>Program</h1> <p>Here's a simple Python program which uses the thetadata <a href="https://http-docs.thetadata.us/docs/theta-data-rest-api-v2/vt7qa2ms85ulr-ohlc" rel="nofollow noreferrer">/hist/stock/ohlc</a> endpoint to retrieve 1D candles for AAPL over a given date range.</p> <pre><code>import io import time import...
<python>
2024-08-20 22:37:03
2
9,709
dharmatech
78,894,323
4,934,344
Custom Threading Timer Kill Function Python
<p>I have a queue with threading setup. I need it to kill the process if it runs longer than 2900s which works fine. I'm wanting to write out information if it has to kill the process because it ran to long. Is there a way to write a custom function for this line:</p> <pre><code>timer = Timer(2900, recover.kill) </code...
<python><multithreading><timer><kill>
2024-08-20 20:41:17
1
611
Rankinstudio
78,894,207
275,669
Preventing exceptions in Python due to print/string format errors?
<p>Is there a way in Python to avoid having <code>print()</code>/string formatting errors throw an exception, without wrapping every <code>print()</code> in a <code>try-except</code> block? Specifically, to avoid premature termination of long-running jobs due to trivial string formatting mistakes?</p> <p>I was develop...
<python><exception><printing>
2024-08-20 19:56:43
0
992
Matt
78,894,195
2,774,885
python vscode venv - launches in "wrong" directory only on the initial launch
<p>I've got a python project set up with a standard virtual environment (.venv).</p> <p>When I launch the project in VSCode's debugger for the FIRST time, it detects that the venv has not been activated, and does the source call to the activate script.</p> <p>However, somewhere it does NOT call the <code>cwd/cd</code> ...
<python><visual-studio-code><python-venv>
2024-08-20 19:53:29
0
1,028
ljwobker
78,894,096
19,315,471
Python http server REMOTE_ADDR returns another local ip (Linux)
<p>(I use Linux)</p> <p>The local IP of my PC is <code>172.16.1.2</code><br /> <code>ip a</code> command returns <code>172.16.1.2</code></p> <p>Then I can add another IP to the same network interface:</p> <pre><code>ip addr add 192.168.1.10 dev eth0 </code></pre> <p>now <code>ip a</code> command returns 2 IPs</p> <pre>...
<python><linux><ip><http.server>
2024-08-20 19:13:32
1
707
user19315471
78,894,085
5,109,125
symmetric_difference() multiple sets in python
<p>I have three sets and I want to get the symmetric_difference.</p> <pre><code>primes = {1, 2, 3, 5, 7, 11} odds = {1, 3, 5, 7, 9, 11} threes =. {1, 3, 6, 9, 12} </code></pre> <p>Using the regular way</p> <p>set(primes) ^ set(odds) ^ set(threes)</p> <pre><code>result a : {2, 3, 6, 12) </code></pre> <p>HOWEVER I saw th...
<python><python-3.x><math><set>
2024-08-20 19:10:35
2
597
punsoca
78,894,080
585,419
Syncing matplotlib imshow coordinates
<p>I'm trying to create an image using networkx, save that image to use later, and then overlay a plot over top of it later. However, when I try to load the image in and make new points, the scale seems off. I've tried everything I can find to make them sync, and I'm not sure what else to try at this point. Here's a...
<python><matplotlib><networkx><imshow>
2024-08-20 19:08:05
1
464
Amanda
78,894,010
1,337,007
Parallelism in AWS Glue
<p>I am reading a large file from <code>S3</code> in a <code>Glue</code> job. Its a <code>.txt</code> file which I convert to <code>.csv</code> and read all the values in a particular column.</p> <p>I want to leverage <code>parallelism</code> of <code>Glue</code> over here where the reading part can be taken as a task ...
<python><apache-spark><pyspark><aws-glue>
2024-08-20 18:48:01
1
2,258
ghostrider
78,893,923
503,157
Polars: set missing value from another row
<p>The following data frame represents basic flatten tree structure, as shown below, where pairs <code>(id, sub-id)</code> and <code>(sub-id, key)</code> are always unique and <code>key</code> always represents the same thing under the same <code>id</code></p> <pre><code>id1 └─┬─ sub-id β”‚ β”‚ └─── key1 β”‚ β”‚ └───...
<python><dataframe><python-polars>
2024-08-20 18:24:55
2
1,617
Eir Nym
78,893,765
11,001,493
How to add values to dataframe based on jump through columns based on a specific number?
<p>I have a dataframe like df:</p> <pre><code>df = pd.DataFrame({'Months': [4, 3], 'Type': ['A', 'B'], 1: [0, 1], 2: [0, 1], 3: [2, 1], 4: [2, 0], 5: [0, 0], 6: [0, 0], 7: [0, 0], 8: [0, 0], 9: [0, 0]}) </code></pre> <pre><code> Months Type 1 2 3 4 5 6 7 8 9 0 4 A 0 0 2 2 0 0 0 0 0 1 ...
<python><pandas>
2024-08-20 17:37:35
1
702
user026
78,893,764
1,071,179
Wierd chart layout with pandas/matplotlib line chart
<p>I am new to Data Science and Python/NumPy/Pandas world in general. I have a dataset which is an order/order line item/product dataset. I am trying to plot a basic line chart with pandas:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('display.max_columns', 500)...
<python><pandas><matplotlib><data-science>
2024-08-20 17:37:33
1
1,119
Mahesh
78,893,734
4,372,237
sklearn.metrics.accuracy_score is very slow
<p>I need to measure accuracy of my model's prediction for binary classification (0 and 1 outputs). I am testing my model with many different values of threshold, and my testing dataset is quite big (50-100 million of examples), so I need a fast way to compute model's accuracy. I was optimizing my code and noticed that...
<python><performance><scikit-learn>
2024-08-20 17:27:36
2
3,470
Mikhail Genkin