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,949,007
5,269,892
Pandas operations between non-float types and NaN
<p>What are the reasons behind pandas allowing operations between sets / strings / other non-float types and NaN (yielding NaN), whereas pure Python does not?</p> <pre><code>import pandas as pd import numpy as np pd.Series([np.nan]) - pd.Series([{5}]) # yields a NaN-series pd.Series([np.nan]) - set([5]) # throws error ...
<python><pandas>
2024-09-04 13:47:40
1
1,314
silence_of_the_lambdas
78,948,870
1,942,555
How to debug Qt Creator's debugging helpers
<p>Debugging in Qt Creator can be extended with custom debugging helpers:<br /> <a href="https://doc.qt.io/qtcreator/creator-debugging-helpers.html" rel="nofollow noreferrer">https://doc.qt.io/qtcreator/creator-debugging-helpers.html</a></p> <p>How can I debug the debugging helpers? E.g. is there a python snippet, whic...
<python><debugging><gdb><qt-creator><lldb>
2024-09-04 13:17:05
0
658
elsamuko
78,948,830
4,412,929
Efficient way to subtract yearly mean data from monthly data in Xarray?
<p>Suppose I have the following Xarray dataarray:</p> <pre><code>&gt;&gt;&gt; da &lt;xarray.DataArray 'precip' (time: 521, lat: 72, lon: 144)&gt; Size: 22MB [5401728 values with dtype=float32] Coordinates: * lat (lat) float32 288B 88.75 86.25 83.75 81.25 ... -83.75 -86.25 -88.75 * lon (lon) float32 576B 1...
<python><python-xarray><weather>
2024-09-04 13:11:22
1
363
RogUE
78,948,777
15,587,034
Ruff formater lengthens the string, how to make sure that it does not change strings that are already less than the length specified in the settings
<p>The problem is that this is the line:</p> <pre><code>__all__ = ( &quot;Base&quot;, &quot;TimestampMixin&quot;, &quot;BaseUser&quot;, &quot;User&quot;, &quot;Locale&quot;, &quot;DBBot&quot; ) </code></pre> <p>It turns you into such a</p> <pre><code>__all__ = (&quot;Base&quot;, &quot;TimestampM...
<python><python-3.x><formatter><linter><ruff>
2024-09-04 13:00:13
1
360
Charls Ken
78,948,402
8,849,071
How does MyPy work when considering MagicMock
<p>I was thinking about enabling the same <code>mypy</code> rules in my tests as in my production code. I started doing some tinkering in <code>mypy</code> playground and found some things I do not quite understand about how <code>mypy</code> and <code>MagicMock</code> play together. Let's say I have the following clas...
<python><unit-testing><python-typing><mypy><magicmock>
2024-09-04 11:28:53
1
2,163
Antonio Gamiz Delgado
78,948,398
6,689,867
Pandas style.to_latex: how to add a \cmidrule in the header?
<p>I have <code>mycsv.csv</code>:</p> <pre><code>Nr,A,B,C 1,a,b,g 2,c,d,h 3,e,f,i </code></pre> <p>With this Phyton code:</p> <pre><code>import pandas as pd testo = pd.read_csv(&quot;mycsv.csv&quot;) columns = [ ('','Something'), ('Multicolumn','A'), ('Multicolumn','B'), ('Something else',''), ] ...
<python><pandas><csv><latex>
2024-09-04 11:28:40
1
305
CarLaTeX
78,948,296
2,243,490
pytest nested parameterization
<p>Code</p> <pre><code>@pytest.mark.parametrize(&quot;arg1&quot;, [1,2]) @pytest.mark.parametrize(&quot;arg2&quot;, [[&quot;A1&quot;, &quot;A2&quot;], [&quot;B1&quot;, &quot;B2&quot;, &quot;B3&quot;]]) def test_stackoverflow(arg1, arg2): print(arg1, arg2) </code></pre> <p>Current output</p> <pre><code>1 [A1, A2] 2 ...
<python><python-3.x><pytest>
2024-09-04 11:07:00
2
1,886
Dinesh
78,948,247
4,483,043
Gradio How to add user avatar in chat interface
<p>I have a very basic code for Gradio chat interface, how can i add user avatar in Gradio chat interface</p> <pre><code>import gradio as gr import random import time with gr.Blocks(theme=gr.themes.Soft()) as demo: chatbot = gr.Chatbot() msg = gr.Textbox() clear = gr.ClearButton([msg, chatbot]) def re...
<python><chatbot><large-language-model><gradio>
2024-09-04 10:54:41
2
437
Farooq Zaman
78,948,116
854,101
Django error on forms when running makemigrations
<p>I'm getting the following error when trying to make migrations for my models. This is against a clean DB so it is trying to generate the initial migrations.</p> <pre><code>File &quot;/Users/luketimothy/Library/Mobile Documents/com~apple~CloudDocs/LifePlanner/LifePlanner/LifePlanner/urls.py&quot;, line 20, in &lt;mod...
<python><django>
2024-09-04 10:22:51
1
2,496
Luke
78,947,991
891,959
How do I get sqlalchemy subqueries to retain their ORM type?
<p>I have a query with subquery. It partitions based on ID and selects the newest of each one in the partitions. It works fine:</p> <pre><code>subquery = db.query( func.rank() .over( order_by=Table.CreatedAt.desc(), partition_by=[Table.ID], ) .label(&quot;rank&quot;), Table, ).subque...
<python><sqlalchemy><orm>
2024-09-04 09:51:35
1
321
InformationEntropy
78,947,680
110,963
Type annotations for parameters of Luigi tasks
<p>I'm using <a href="https://luigi.readthedocs.io/en/stable/" rel="nofollow noreferrer">Luigi</a> in my Python project, so I have classes that look like this:</p> <pre><code>class MyTask(luigi.Task): my_attribute = luigi.IntParameter() </code></pre> <p>I would like to add a type annotation to <code>my_attribute</c...
<python><python-typing><mypy><luigi>
2024-09-04 08:41:47
1
15,684
Achim
78,947,551
10,240,072
Python package and conda environnement
<p>I have encountered a behavior relative to package versions in different conda environment that I don’t understand and seems illogical. There is probably something fundamental that I do not understand in the behavior. Basically :</p> <ol> <li>I have a conda environment 'env' with pandas version 2.0.3</li> <li>I clone...
<python><conda><environment>
2024-09-04 08:18:12
0
313
Fred Dujardin
78,947,384
5,704,198
What does this code mean: "assert result == repeat, (result, repeat)"?
<p>From <a href="https://hypothesis.readthedocs.io/en/latest/ghostwriter.html#hypothesis.extra.ghostwriter.idempotent" rel="nofollow noreferrer">here</a>:</p> <pre><code>from hypothesis import given, strategies as st @given(seq=st.one_of(st.binary(), st.binary().map(bytearray), st.lists(st.integers()))) def test_idemp...
<python><assert>
2024-09-04 07:41:58
1
1,385
fabio
78,947,382
3,540,161
Inconsistent Python import behaviour with subdirectories
<p>When splitting my python code into simple modules and putting them in a subdirectory, I see seemingly inconsistent behaviour that I was not able to solve by adding an <code>__init__.py</code> file in the module. I am also unable to understand why things not seem to work consistently. Please explain or point to docum...
<python><python-3.x><python-import>
2024-09-04 07:41:25
2
7,308
Rolf
78,947,332
1,866,775
How to install torch without nvidia?
<p>While trying to reduce the size of a Docker image, I noticed <code>pip install torch</code> adds a few GB. A big chunk of this comes from <code>[...]/site-packages/nvidia</code>. Since I'm not using a GPU, I'd like to not install the <code>nvidia</code> things.</p> <p>Here is a minimal example:</p> <pre><code>FROM p...
<python><pytorch><pip><dockerfile><torch>
2024-09-04 07:27:02
1
11,227
Tobias Hermann
78,947,142
4,483,043
how to change favicon in Gradio python
<p>I have a very basic code for Gradio chat interface, how can i change favicon in Gradio chat interface</p> <pre><code>import time import gradio as gr def slow_echo(message, history): for i in range(len(message)): time.sleep(0.3) yield &quot;You typed: &quot; + message[: i+1] gr.ChatInterface(slow_echo...
<python><chatbot><large-language-model><gradio>
2024-09-04 06:33:45
1
437
Farooq Zaman
78,946,789
7,471,830
Python Asyncio source code analysis: Why does `_get_running_loop` in Python execute the C implementation instead of the Python one?
<p>I've been exploring the <code>async</code> source code and noticed that the function <code>_get_running_loop()</code> is defined both in Python and has a note stating it's implemented in C (in <code>_asynciomodule.c</code>).</p> <pre class="lang-py prettyprint-override"><code># python3.11/asyncio/events.py def get_r...
<python><python-asyncio><cpython><event-loop>
2024-09-04 04:16:28
1
831
OOD Waterball
78,946,628
10,778,476
Python imaplib: Is there a consistent way to authenticate/login to Outlook via IMAP?
<p>I'm literally junior to Python programming after years of C++ and C programming, and am trying to work in using Python to save all messages &amp; attachments from Outlook, specifically <code>imaplib</code>.</p> <p>My experiments so far led me to understand that imaplib module could succeessly connect to an email ser...
<python><outlook><imaplib>
2024-09-04 02:43:42
2
884
Shelton Liu
78,946,545
736,662
Getting nested JSON value using a for-loop
<p>I make the use of a function in my Python script to get a certain value. The value I want is the so-called 'parentComponentId' using the condition 'name' equal to 'Vinje'. Here is the function:</p> <pre><code>def get_parentcomponentid(data, name): return next( element[&quot;parentComponentId&quot;] for eleme...
<python>
2024-09-04 01:45:24
1
1,003
Magnus Jensen
78,946,519
1,862,823
How to convert query string parameters from Datatables.js, like columns[0][name] into an object in Python/Django?
<p>I'm using DataTables.js and trying to hook up server-side processing. I'm using Django on the server.</p> <p>Currently, the data to Django looks like:</p> <pre><code>{'draw': '1', 'columns[0][data]': '0', 'columns[0][name]': 'Brand', 'columns[0][searchable]': 'true', 'columns[0][orderable]': 'true', 'columns[0]...
<python><django><dictionary><datatables>
2024-09-04 01:28:49
1
2,353
NeomerArcana
78,946,450
11,638,153
Python how to fit value, weight using different distributions
<p>I have tabular data in form of <code>values, weight</code> and would like to fit different distributions like normal, lognormal, etc. and get sum squared error of fitting. I tried normal distribution so far using <code>scipy.stats.norm.fit()</code> but it does not give any indication of error. Is there built-in way ...
<python><pandas><numpy><scipy>
2024-09-04 00:40:16
1
441
ewr3243
78,946,447
391,161
Is it possible to change the index URL for fetching `rules_python` itself in bazel?
<p>I am currently attempting to do a custom build of <code>envoy</code> on a machine that does not have access to PyPi. My company's security team requires us to use a corporate proxy with a different URL to access the PyPi repos.</p> <p>When I try to run <code>bazel build ...</code>, I get the following error:</p> <pr...
<python><bazel><pypi>
2024-09-04 00:39:09
1
76,345
merlin2011
78,946,446
484,944
Forward-over-reverse mode Hessian-vector product in Jax: how smart is jax.jvp at re-using computations?
<p>How smart is <a href="https://jax.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">Jax</a> at re-using intermediate computations when computing Hessian-vector products via forward-over-reverse mode automatic differentiation via <a href="https://jax.readthedocs.io/en/latest/_autosummary/jax.jvp.html" re...
<python><jax><automatic-differentiation>
2024-09-04 00:37:23
0
1,114
Nick Alger
78,946,237
825,227
Python groupby rank in two different directions
<p>I have a dataframe, <code>d</code>:</p> <pre><code> Position Operation Side Price Size 9 9 0 1 0.7289 -16 8 8 0 1 0.729 -427 7 7 0 1 0.7291 -267 6 6 0 1 0.7292 -15 5 5 0 1 0.7293 -16 4 4 0 1 0.7294 -16 3 3 0 1 0.7295 -426 2 2 0 1 0....
<python><pandas><dataframe><group-by>
2024-09-03 22:17:34
3
1,702
Chris
78,946,135
127,682
Convert a list of strings to conversion functions
<p>Currently I can create a list of conversion functions like the following:</p> <pre class="lang-py prettyprint-override"><code>casts = [float, float, int, str, int, str, str] </code></pre> <p>but I would like to do it in the following manner:</p> <pre class="lang-py prettyprint-override"><code>casts = input(&quot;Ent...
<python><list>
2024-09-03 21:33:04
3
465
capnhud
78,946,027
986,612
Change console icon on taskbar
<p>I don't want to change the shortcut icon:</p> <p><a href="https://stackoverflow.com/questions/16782047/how-to-add-an-icon-of-my-own-to-a-python-program">How To Add An Icon Of My Own To A Python Program</a></p> <p>I want to change the console (cmd) icon that runs a python script:</p> <p><a href="https://stackoverflow...
<python><windows>
2024-09-03 20:51:44
1
779
Zohar Levi
78,945,969
610,569
How to set max_memory pool of pyarrow to just use max available on the instance?
<p>I've a machine with 80GB RAM but whenever it does the <a href="https://arrow.apache.org/docs/python/generated/pyarrow.concat_tables.html" rel="nofollow noreferrer">pa.concat_tables</a> operation, it goes out of memory.</p> <p>I've tried doing the following to set the default memory pool but it's showing the <code>to...
<python><pyarrow><memory-pool>
2024-09-03 20:34:07
0
123,325
alvas
78,945,955
13,557,319
Spotify API 403 Forbidden Error When Adding Tracks to Playlist Despite Correct Token and Scopes
<p>I'm experiencing a 403 Forbidden error when trying to add a track to a Spotify playlist using the Spotify Web API. Despite having a correctly configured token and permissions, I’m still facing this issue.</p> <p>Details:</p> <ul> <li>Spotify Client ID: My client ID</li> <li>Spotify Client Secret: Client Secrete</li>...
<python><django><oauth-2.0><cron><spotipy>
2024-09-03 20:26:45
0
342
Linear Data Structure
78,945,806
4,748,483
Creating a standalone python executable with pywin32 and missed required module
<p><br/>I'm going to create a standalone python executable that rely on a python interpreter on windows (I don't want to create an exe file). <br/>So, I'm used this helpful article: <br/><a href="https://n8henrie.com/2022/08/easily-create-almost-standalone-python-executables-with-the-builtin-zipapp-module/#google_vigne...
<python><pywin32><python-standalone>
2024-09-03 19:29:38
1
1,463
Parsa Saei
78,945,659
2,893,712
Check if Series has Values in Range
<p>I have a Pandas dataframe that has user information and also has a column for their permissions:</p> <pre><code>UserName Permissions John Doe 02 John Doe 11 Example 09 Example 08 User3 11 </code></pre> <p>I am trying to create a new column called <c...
<python><pandas>
2024-09-03 18:32:34
5
8,806
Bijan
78,945,511
20,302,906
Mock instantiated class in class attribute
<p>I'm working on a project that uses a class called <code>Deck</code> to fetch data from an API. This class is instantiated inside another class called <code>Game Manager</code> through its <code>__init__</code> (it's a blackjack game btw) like this:</p> <p><em>server/game_manager.py</em></p> <pre><code>import .deck i...
<python><unit-testing><mocking>
2024-09-03 17:42:44
1
367
wavesinaroom
78,945,487
2,726,900
How to read and write large amounts of data to Cassandra DB?
<p>I have a client application that connects to two or more Cassandra DB servers -- and has to copy some tables from one server to another.</p> <p>What is the best way to copy big amounts of Cassandra data, especially using Python?</p>
<python><cassandra>
2024-09-03 17:35:07
1
3,669
Felix
78,945,462
1,700,890
Import module from subfolder - invalid syntax
<p>Here is my Python project folder structure.</p> <pre><code>project\ main_code.py code\ __init__.py s_utils.py data\ </code></pre> <p>in <code>main_code.py</code> I tried:</p> <pre><code>import os os.chdir('absolute path to project folder') from .code import s_utils </code></pre> <p>Th...
<python><import><subdirectory><relative-path>
2024-09-03 17:25:54
1
7,802
user1700890
78,945,437
2,386,113
How to arrange figures in a grid?
<p>I have six pairs of vertically stacked figures. I want to arrange the figures into a 3x2 grid. However, I don't find a way to do it. Since I will receive the required figures from an existing function (here as a dummy, it's <code>stacked_lineplots()</code>), the organization of the figures into the grid MUST be done...
<python><matplotlib><figure>
2024-09-03 17:18:54
1
5,777
skm
78,945,394
4,746,081
Matplotlib imshow and dna_features_viewer: Align X axis
<p>I can't find a solution to align on the X-axis a matplotlib imshow with a <a href="https://edinburgh-genome-foundry.github.io/DnaFeaturesViewer/" rel="nofollow noreferrer">dna features viewer</a> plot.</p> <p>The python3 code I used is:</p> <pre class="lang-py prettyprint-override"><code>from dna_features_viewer imp...
<python><matplotlib>
2024-09-03 17:07:55
1
341
Mesmer
78,945,294
7,519,700
Elasticsearch search query returning "empty" response using elasticsearch python API
<p>I am using <a href="https://github.com/elastic/elasticsearch-py" rel="nofollow noreferrer">elasticsearch py client</a> in my real time application.</p> <p>The application performs search query aggregations like &quot;sum of field settledAmount in last 10 days&quot;.</p> <p>Most of queries work without problems. Howe...
<python><elasticsearch>
2024-09-03 16:34:38
1
1,033
room13
78,945,268
1,088,979
Efficient Conversion of Timezone-Aware Timestamps to datetime64[m] in Pandas
<p>I have the following code that creates a DataFrame representing the data I have in my system:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = { &quot;date&quot;: [ &quot;2021-03-12 19:50:00-05:00&quot;, &quot;2021-03-12 19:51:00-05:00&quot;, &quot;2021-03-12 19:52:00-05:00...
<python><pandas><datetime><time-series>
2024-09-03 16:25:13
1
9,584
Allan Xu
78,945,163
1,632,519
argparse parse arbitary number groups of arguments
<p>I have this snippet for illustrative purpose that doesn't work at all.</p> <pre><code>#!/usr/bin/env python3 import argparse parser = argparse.ArgumentParser() parser.add_argument(&quot;--action&quot;, nargs=&quot;+&quot;) parser.add_argument(&quot;--number&quot;, nargs=&quot;+&quot;, default=1) parser.add_argume...
<python><argparse>
2024-09-03 15:52:28
1
2,126
Philippe
78,945,099
5,904,690
Reading lines in certain interval from a file in python: alternatives to readline()
<p>I realize that how to read lines from a file in interval [start, stop] is a common question, however many of the standard answers don't work well for my data set.</p> <p>Specifically, I have data files with 500K lines and 100K columns. Each block of 50 rows is a separate data set which I need to read as a block, ana...
<python>
2024-09-03 15:38:28
2
789
Max
78,944,749
2,287,458
Explode Polars rows on multiple columns but with different logic
<p>I have this code, which splits a <code>product</code> column into a list, and then uses <code>explode</code> to expand it:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import datetime as dt from dateutil.relativedelta import relativedelta def get_3_month_splits(product: str) -&gt; list[st...
<python><dataframe><python-polars>
2024-09-03 14:07:15
2
3,591
Phil-ZXX
78,944,702
39,590
Convert log(x)/log(2) to log_2(x) in sympy
<p>I received a sympy equation from a library. It makes extensive use of log2, but the output was converted to <code>log(x)/log(2)</code>. This makes reading the results messy.</p> <p>I would like to have sympy simplify this equation again with a focus on using log2 directly where possible.</p> <p>How could this be don...
<python><sympy>
2024-09-03 13:52:27
1
33,018
mafu
78,944,602
1,028,133
How can I override the default behavior of `list(MyEnum)`?
<p>I have a custom <code>enum</code>, <code>MyEnum</code>, with some elements that have different names but the same value.</p> <pre><code>from enum import Enum class MyEnum(Enum): A = 1 B = 2 C = 3 D = 1 # Same value as A </code></pre> <p>Consequently, <code>list(MyEnum)</code> returns only the name...
<python><enums>
2024-09-03 13:29:49
1
744
the.real.gruycho
78,944,123
13,806,869
How to change the value of a column based on a condition and an inner join?
<p>I have two Pandas dataframes; let's call them df_a and df_b.</p> <p>df_a looks like this:</p> <pre><code>account | threshold | standardised_threshold --------|-----------|----------------------- A | 39.5 | 40 B | 42.6 | 45 C | 47.4 | 45 D | 53.5 | 50 </code></pre> <p>df_b ...
<python><pandas><dataframe>
2024-09-03 11:31:52
3
521
SRJCoding
78,944,113
5,379,182
How to recover from a closed channel
<p>I am using <a href="https://aio-pika.readthedocs.io/en/latest/" rel="nofollow noreferrer">aio-pika</a> for my RabbitMQ workers. I ran into a <code>ChannelInvalidStateError</code> exception when the worker wanted to ack the message at the end of its processing but the channel was already closed.</p> <p>What are the b...
<python><rabbitmq>
2024-09-03 11:27:15
0
3,003
tenticon
78,943,949
243,031
flask babel not able to load the translated files
<p>I am trying to translate my current flask project and I follow the step mentioned in <a href="https://python-babel.github.io/flask-babel/#module-flask_babel" rel="nofollow noreferrer"><code>flask-babel</code></a>.</p> <p>First I tried with new <a href="https://flask-restx.readthedocs.io/en/latest/" rel="nofollow nor...
<python><flask><translation><python-babel><flask-restx>
2024-09-03 10:46:53
0
21,411
NPatel
78,943,716
270,043
Pairwise comparison of multiple fields in Pyspark dataframes
<p>I have a pyspark dataframe that looks like the one below.</p> <pre><code>key_field fieldA fieldB fieldC ddd A1 B1 C1 ddd A2 B2 C2 ddd A2 B2 C2 eee A1 B1 C1 eee A3 B3 C3 </code></pre> <p>The goal is to group by <...
<python><pyspark>
2024-09-03 09:53:49
0
15,187
Rayne
78,943,401
3,745,149
Fine-tuning a Pretrained Model with Quantization and AMP: Scaler Error "Attempting to Unscale FP16 Gradients"
<p>I am trying to fine-tune a pretrained model with limited VRAM. To achieve this, I am using quantization and automatic mixed precision (AMP). However, I am encountering an issue that I can't seem to resolve. Could you please help me identify the problem?</p> <p>Here is a minimal example:</p> <pre class="lang-none pre...
<python><pytorch><nlp><huggingface-transformers><fine-tuning>
2024-09-03 08:38:23
1
770
landings
78,943,385
8,458,083
How to configure Visual Studio Code to recognize external stub files for Python development?
<p>I'm developing a Python plugin that uses a specific external library. I have the following setup:</p> <ul> <li>I'm using Visual Studio Code as my IDE</li> <li>I have access to the stub files (<code>.pyi</code>) for the library I'm using</li> <li>The library is not installed in my development environment, as it will ...
<python><visual-studio-code>
2024-09-03 08:34:18
1
2,017
Pierre-olivier Gendraud
78,942,969
8,849,755
Python dominate do not escape characters
<p>I am using <a href="https://github.com/Knio/dominate" rel="nofollow noreferrer">dominate</a> to create an HTML document in Python. In one part of my workflow there is an already hardcoded HTML code in a string which I want to insert inside a tag similarly as <code>innerHTML</code> would do in JavaScript. However, I ...
<python><html><dominate>
2024-09-03 06:43:48
1
3,245
user171780
78,942,907
341,840
How to get the y values from Bokeh RangeTool selection pan?
<p>I'm working in an app which will show the temperatures recorded by meteorological stations.</p> <p>I'm using Bokeh 3.5.1 with two figures: one is the main graph, and the other one holds a RangeTool to get a view of the data.</p> <p>What I want is to get the y values (maximum, minimum and mean temperatures) in the se...
<python><bokeh><bokehjs>
2024-09-03 06:15:10
1
1,075
quimm2003
78,942,885
13,447,006
Logging configuration does not take effect
<pre><code> logging.basicConfig( filename=f&quot;{output_location}/log.txt&quot;, format=&quot;{asctime} - {levelname} - {filename}: {message}&quot;, datefmt = &quot;%d %b %H:%M&quot;, style=&quot;{&quot;, level=logging.INFO ) </code></pre> <p>This is my code and it used t...
<python><logging><python-logging>
2024-09-03 06:09:14
1
565
AlphabetsAlphabets
78,942,791
12,035,739
Why won't Matplotlib's imshow plot 0.5 as grey?
<p>I remember this working. Zero meant fully dark and one meant fully lit up and in-between meant some shade of grey for plotting with <code>pyplot.imshow</code>. I remember plotting the MNIST data of handwritten digits like that. I wrote the following,</p> <pre class="lang-py prettyprint-override"><code>import nump...
<python><matplotlib>
2024-09-03 05:27:10
1
886
scribe
78,942,768
20,762,114
Faster Sequential Joins
<p>In a regular Polars join where there are duplicates, the result is the cartesian product of the matched rows.</p> <p>However, I would like to join the dataframes such that if there are duplicates, the rows are matched in a sequential manner.</p> <p>Example below:</p> <pre class="lang-py prettyprint-override"><code>d...
<python><dataframe><python-polars>
2024-09-03 05:13:47
3
317
T.H Rice
78,942,542
4,500,749
Typing for tuple or list of tuples in recursive function
<p>Here is an example I wrote.</p> <pre class="lang-py prettyprint-override"><code>from typing import Tuple, List def performances( pt: Tuple[float, float] | List[Tuple[float, float]] ) -&gt; float | list[float]: if isinstance(pt, list): output = [] for pt_i in pt: output.append(pe...
<python><recursion><python-typing>
2024-09-03 02:57:21
1
326
Romn
78,942,488
127,320
Resolve no validator found for <class '__main__.Resume'>, see `arbitrary_types_allowed` in Config
<p>Getting the <code>no validator found</code> error with the following code. Here are the Library versions:</p> <pre><code>LangChain version: 0.0.284 Pydantic version: 2.8.2 </code></pre> <p>Code:</p> <pre><code>from typing import Optional from pydantic import BaseModel, Field, ValidationError from config import set_e...
<python><pydantic><langchain><py-langchain>
2024-09-03 02:21:38
1
80,467
Aravind Yarram
78,942,459
1,457,380
Bar chart with slanted lines instead of horizontal lines
<p>I wish to display a barchart over a time series canvas, where the bars have width that match the duration and where the edges connect the first value with the last value. In other words, how could I have slanted bars at the top to match the data?</p> <p>I know how to make barcharts using either the last value (examp...
<python><matplotlib><bar-chart>
2024-09-03 02:06:16
2
10,646
PatrickT
78,942,406
2,382,483
How to "smooth" a discrete/stepped signal in a vectorized way with numpy/scipy?
<p>I have a signal like the orange one in the following plot that can only have integer values: <a href="https://i.sstatic.net/2h9odqM6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2h9odqM6.png" alt="enter image description here" /></a></p> <p>As you can see, the orange signal in a bit noisy and &quot...
<python><numpy><scipy>
2024-09-03 01:38:50
1
3,557
Rob Allsopp
78,942,402
8,997,728
Python: all items that have a higher than average price in array
<p>As part of a Python course I´m taking I wonder whether anyone can help me with the following question: given a list of food names along with their calories and prices information in the format of [name, calories, price] I want to create a function in Python that returns all items in a new array that have a higher th...
<python><arrays><list>
2024-09-03 01:34:23
1
309
Estrobelai
78,942,254
647,002
How to "borrow" an instance property type in Python type annotations?
<p>In Python type annotations, is there some way to declare that a property has the same type as a property of another class? To &quot;borrow&quot; or copy the type from the other class?</p> <p>For example, in this code, how could you say that <code>bar</code> should have the same type as the <code>foo</code> property ...
<python><python-typing><mypy>
2024-09-02 23:33:04
0
6,291
medmunds
78,942,252
11,154,841
How can I get TSQL from easy MS Access SQL with little to no handiwork?
<p>I have 500+ queries in a bunch of MS Access databases. The queries are rather easy.</p> <ul> <li>(1.) I read them out with VBA into an Excel file as columns <code>A</code> to <code>H</code>, with the columns &quot;ID, Datenbank, Objektname, LastUpdated, Objekttyp, Objektart, SourceTableName, Abfrage_SQL&quot;, with ...
<python><excel><t-sql><ms-access>
2024-09-02 23:32:08
1
9,916
questionto42
78,942,124
6,907,703
How to install langchain-openai that is compatible with existing openai installation?
<p>I am migrating to <code>langchain</code> version 0.2 in my project, which now requires installing LLM models separately. I attempted to install <code>langchain-openai</code> using:</p> <pre class="lang-bash prettyprint-override"><code>pipenv install langchain-openai </code></pre> <p>However, this conflicts with anot...
<python><openai-api><langchain><pipenv><py-langchain>
2024-09-02 21:55:28
1
1,281
Muhammad Mubashirullah Durrani
78,942,113
13,792,730
SymPy having trouble plotting Bessel functions - cannot recognize ```besselj``` within its own namespace
<p>It seems like SymPy is having some issues plotting a Bessel function. This is the working example:</p> <pre><code>import sympy as sp x = sp.symbols('x') sp.plot(sp.besselj(4,x), (x,1,2)) </code></pre> <p>When I try running the block above, I get the following stack trace:</p> <pre><code>File &quot;/Users/..../test...
<python><plot><sympy><bessel-functions>
2024-09-02 21:49:51
0
321
laplacian_07
78,941,843
5,134,817
Several derived instances of an abstract base class throwing mypy error
<p>I cannot figure out the correct way to get <code>mypy</code> to not complain about the type hinting when using abstract base classes, specifically a container of several of these (more than 2).</p> <p>As an example:</p> <pre class="lang-py prettyprint-override"><code>mapping_1 = {type(i()).__name__: i() for i in [A,...
<python><python-typing><mypy>
2024-09-02 19:31:57
0
1,987
oliversm
78,941,736
1,277,488
I'm getting a 400 error and the endpoint isn't even entered. Why?
<p>I've encountered a situation with my Django Rest Framework (DRF) app in which a client mobile app is calling one of my endpoints and is getting a 400 error, but I can't debug what's going wrong. This is what appears in the log:</p> <pre><code>Sep 02 11:11:29 myapp heroku/router at=info method=POST path=&quot;/users/...
<python><django><django-rest-framework><request><http-status-code-400>
2024-09-02 18:47:40
2
2,385
Dylan
78,941,620
1,116,354
TemplateSyntaxError jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'result1'
<p>I am trying to implement an application for comparison. There is a method as you can see below in the method. <code>get_site_analysis</code></p> <pre><code>@app.route('/comparison/&lt;site_id1&gt;/&lt;site_id2&gt;', methods=['GET']) def comparison(site_id1, site_id2): arable = ArableData() site1_result, site...
<python><jinja2>
2024-09-02 17:54:52
1
6,877
Vinay
78,941,537
7,475,143
OpenCV not able to detect aruco marker within image created with opencv
<p>I encountered an issue while trying out a simple example of creating and detecting aruco-images. In the following code-snippet, I generate aruco images, save them to a file and then load one of these files for detection:</p> <pre><code>import cv2 aruco_dict= cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_ARUCO_OR...
<python><opencv><image-processing><augmented-reality><aruco>
2024-09-02 17:29:33
1
563
Bobipuegi
78,941,483
243,031
Want to use COALESCE on related fields on django model
<p>I have model structure as below.</p> <pre><code>from django.db import models class Switch(models.Model): fqdn = models.CharField(unique=True) class Meta: db_table = 'Switch' class Colo(models.Model): name = models.CharField() class Meta: db_table = 'Colo' class Clstr(models.Model...
<python><django><orm><coalesce>
2024-09-02 17:09:41
0
21,411
NPatel
78,941,367
7,326,981
Binance - Spot Market Profit Calculator
<p>I have a Python method that calculates the profit after taking into account the commission structure. However, it fails to replicate the exact values from Binance trade history. For example I bought <code>ETH/USDT</code> using <code>LIMIT</code> order at a price of <code>2595</code> with a buy amount of <code>57.609...
<python><trading><binance>
2024-09-02 16:25:03
2
1,298
Furqan Hashim
78,941,273
685,984
Python requests: No module named 'werkzeug.wrappers.json'
<p>I'm trying to use the requests library in Python, but when I do so, I get an error</p> <pre><code> from werkzeug.wrappers.json import JSONMixin ModuleNotFoundError: No module named 'werkzeug.wrappers.json' </code></pre> <p>Below is an example (using a repo I forked specially for this, and a very fine grained acce...
<python><python-requests>
2024-09-02 15:55:09
1
2,949
crobar
78,941,136
1,714,385
Can requests-aws4auth.AWS4Auth accept three arguments?
<p>I'm trying to connect to AWS via a script. The script works on my colleague's machine, but doesn't on mine, even if I install all of his python packages via pip freeze. I can't even run the example from the <a href="https://pypi.org/project/requests-aws4auth/" rel="nofollow noreferrer"><code>requests-aws4auth</code>...
<python>
2024-09-02 15:11:56
2
4,417
Ferdinando Randisi
78,941,054
3,033,634
error message using multiple %s string substitutions
<p>I haven't been able to find another example of string substitution like in this error message where %s%s is doubled up as it is here: <a href="https://github.com/django/django/blob/387475c5b2f1aa32103dbe21cb281d3b35165a0c/django/contrib/gis/utils/layermapping.py#L260" rel="nofollow noreferrer">https://github.com/dja...
<python><string>
2024-09-02 14:49:54
1
1,050
Hugh_Kelley
78,940,790
13,023,224
Pandas order column with lists by pairs
<p>Here is the dataframe:</p> <pre><code>df1 = pd.DataFrame( {'st': {0: 1, 1: 0, 2: 2, 3: 0, 4: 1, 5: 5, 6: 0, 7: 7, 8: 19, 9: 0, 10: 0, 11: 0, 12: 3, 13: 0}, 'gen': {0: 'B1', 1: 'A0,B0', 2: 'A1,B1', 3: 'A0,B0', 4: 'B109', 5: 'B4,A1', 6: 'A0,B0', 7: 'A4,B3', 8: 'B15,A4', 9: 'A0,B0', 10: 'A0,B0', 11: 'A0,B0', 12: 'A123'...
<python><pandas><list><sorting>
2024-09-02 13:48:18
1
571
josepmaria
78,940,757
13,606,345
How to annotate after group by and order_by in django?
<p>I have a DB table which has a field &quot;created_at&quot;. This is a auto_now_add=True field.</p> <p>This table is inserted data once everyday. What I want to do is filter data that corresponds to the last day of each month of each year.</p> <p>I have a query as follows:</p> <pre class="lang-py prettyprint-override...
<python><django><django-orm>
2024-09-02 13:39:14
1
323
Burakhan Aksoy
78,940,747
5,089,311
Python Tkinter Treeview display checkbox as a value
<p>I need display checkbox as a value for entries in my TreeView.<br /> Basically this:<br /> <a href="https://i.sstatic.net/31xi5tlD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/31xi5tlD.png" alt="enter image description here" /></a></p> <p>In the example on the screenshot I use UTF-8 symbols ✅ and ☐...
<python><tkinter>
2024-09-02 13:37:09
1
408
Noob
78,940,177
12,439,683
ValueError: Space not allowed in string format specifier
<p>I was modernizing some old <code>%</code> formatted string via regex substitution to change:</p> <pre class="lang-py prettyprint-override"><code># Old: 'Map: % 20s' % name # to New: 'Map: {: 20s}'.format(name) </code></pre> <p>and was surprised a</p> <ul> <li><code>ValueError: Space not allowed in string for...
<python><string><format><string-formatting>
2024-09-02 11:20:43
1
5,101
Daraan
78,940,132
12,466,687
How to extract only unique values from string using regex in Python?
<p>I have this piece of String <code>&quot;Desirable: &lt; 200 Borderline HIgh: 200 - 240 High: &gt; 240&quot;</code> where I want to extract only unique Number or decimal values.</p> <p>To extract <code>Number,Decimal,-</code> I was using this regex code <code>r'[^0-9.-]+'</code> but it doesn't return unique values:<...
<python><regex>
2024-09-02 11:10:08
1
2,357
ViSa
78,940,125
17,721,722
How to Perform SQL-like Update Operations on a PySpark DataFrame Using SQL Queries?
<p>I am trying to perform in-memory updates on a very large PySpark DataFrame instead of making disk-based updates in a PostgreSQL database. I chose PySpark for its speed and scalability over direct database updates.</p> <p><strong>Here's what I'm doing:</strong></p> <ol> <li>I have a <code>.csv</code> file named <code...
<python><sql><apache-spark><pyspark><apache-spark-sql>
2024-09-02 11:09:09
0
501
Purushottam Nawale
78,940,118
11,154,841
In a standard MS Access SQL query output that does not have any aliases, how do I replace the full names by their "first-letters" aliases?
<p>I have a lot of queries from a bunch of MS Access databases. I read them out and split them into their SQL-blocks by the standard SQL keywords with:</p> <ul> <li><a href="https://superuser.com/questions/1840186/how-do-i-get-the-full-sql-code-for-all-queries-in-all-ms-access-databases-of-a-f">How do I get the full sq...
<python><sql><excel><ms-access>
2024-09-02 11:07:43
1
9,916
questionto42
78,939,932
4,451,521
Why gradio image resizes the image in one environment?
<p>I am running the same gradio script in two different computers.</p> <p>It uses</p> <pre><code>image_display = gr.Image(label=&quot;Image Display&quot;, interactive=False) </code></pre> <p>however in one PC it shows the image occupying all the width of the Image element, and in the other, the image appears smaller</p...
<python><gradio>
2024-09-02 10:11:52
0
10,576
KansaiRobot
78,939,900
10,595,871
Exploding multiple column list in pandas
<p>I've already tried everything posted here but nothing is working, so please don't mark this as duplicate because I think the problem is different.</p> <p>I have a json like this:</p> <pre><code>[{'Id': 1, 'Design': [&quot;09&quot;, '10', '13' ], 'Research': ['Eng', 'Math'] }] </code></pre> <p>Plus o...
<python><pandas>
2024-09-02 10:00:43
2
691
Federicofkt
78,939,798
9,159,407
Greenhouse harvest API pagination doesn't work as expected
<p>I'm working with greenhouse API and tried to work with some API and their pagination mechanism.</p> <p>Most of their APIs worked as documented, but the &quot;User Permissions&quot; API pagination didn't work for me.</p> <p>Does anyone familiar with that issue and have a soltution?</p> <p>Reference: <a href="https://...
<python><pagination>
2024-09-02 09:35:14
0
386
omer blechman
78,939,671
2,293,659
Format a SELECT query that avoids SQL injection taking multiple parameters
<p>I'm using Python 3 and SQLAlchemy to create dynamically a query that selects all the products that fulfill the conditions and avoids SQL injection issues.</p> <p>I get the following error: &quot;List argument must consist only of tuples or dictionaries&quot;</p> <p>The code is something like this</p> <pre><code>data...
<python><sqlalchemy><sql-injection>
2024-09-02 09:03:20
1
820
PepeVelez
78,939,607
158,049
Generic `NamedTuple`
<p>I work with a set of <code>NamedTuple</code> which share two common attributes (<code>key</code> and <code>value</code>), such as:</p> <pre class="lang-py prettyprint-override"><code>CompanyIdentifier = NamedTuple(&quot;CompanyIdentifier&quot;, [ (&quot;key&quot;, str), (&quot;value&quot;: str), (&quot;some&quot...
<python><python-typing><mypy><namedtuple><pyright>
2024-09-02 08:43:18
1
2,547
NewbiZ
78,939,142
1,993,709
How to connect to existing logged in chrome instance in Playwright on MacOs?
<p>My goal is to automate a task on a website that requires login. So I want to login once manually and let the automation run from there. I tried using CRD but when my code runs, it opens a new window where my account is not logged in. Here is an example code I am running:</p> <pre class="lang-py prettyprint-override"...
<python><playwright><playwright-python>
2024-09-02 06:18:33
1
4,238
Adi
78,938,961
6,309,590
What does it mean if a model acts normal on a training set but is abnormal on validation set
<p>I am trying to classify either an image of 25x25 px stacked together as 50x25 px is the same(1) or different(0). I am using keras to create the NN layers. The Keras sequential layers are shown below:</p> <pre><code>layers.Input((2*imsize,imsize,3)), # shape of input with 3 channels layers.Reshape((2,imsiz...
<python><machine-learning><keras><deep-learning><evaluation>
2024-09-02 04:51:20
2
447
Squish
78,938,875
865,220
Fix wrong spelling after a run of correct spellings in a sorted dataframe in pandas
<p>I have a dataframe like this:</p> <pre><code>Bevonce,2008,296853 Beyonce,2007,1210744 Beyonce,2007,1222003 Beyonce,2007,1222003 Beyonce,2007,1222007 Beyoncel,2007,1222002 Nicki Mina,2015,2717068 Nicki Minaj,2015,2741567 Nicki Minaj,2015,2741567 Nicki Minaj,2015,2743565 Nicki Minajl,2015,2744974 Nicki Minal,2015,2741...
<python><pandas><dataframe><spelling>
2024-09-02 04:02:56
6
18,382
ishandutta2007
78,938,799
4,057,790
How to read responses from request in Robot Selenium
<p>I am looking for similar to <code>cypress.intercept()</code> in Robot framework where we read API responses for get and post requests already happening for API testing from UI without additional calls. I've not found any suitable docs. Is it doable from Robot or any helper library?</p> <pre><code>cy.intercept('POST'...
<python><selenium-webdriver><automation><robotframework><ui-automation>
2024-09-02 03:12:21
2
3,653
Mithun Shreevatsa
78,938,754
260,345
Set x-axis scale for Altair bar chart
<p>I am using Python's Altair and Streamlit to create a bar chart. I'd like to have the x-axis represent time, and the y-axis be a list of people. Start and end times are plotted on the chart for each person. The problem is, I am unable to figure out how to set the scale of the x-axis. <strong>I would like the scale to...
<python><streamlit><altair>
2024-09-02 02:38:43
1
2,982
Dylan Klomparens
78,938,725
7,228,093
How to include C libraries in cibuildwheel Github Action for Cython module?
<p>I'm trying to separate a few libraries from my Python project, into a C++ submodule, that should improve the performance, using Cython. Now, I've managed to make the module an compile it, but now I want to make possible for it to be used in more platforms, not just my computer, and that's when I found that Github pr...
<python><github-actions><cython>
2024-09-02 02:18:36
2
515
Efraín
78,938,722
200,783
What are valid assignment targets in Python?
<p>In Python, obviously it's possible to assign to names, e.g. <code>a = 1</code>. It's also valid to assign to attributes (<code>a.b = 1</code> - AFAIK this corresponds to the <code>__setattr__</code> special method) and indexing operations (<code>a[b] = 1</code>, which corresponds to <code>__setitem__</code>).</p> <p...
<python><lua><variable-assignment>
2024-09-02 02:13:41
0
14,493
user200783
78,938,424
3,995,472
Why the Airflow dag is not getting triggered?
<p><a href="https://i.sstatic.net/FyMNxccV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FyMNxccV.png" alt="Attached the screenshot of Schedules shown on Airflow UI" /></a>I have attached the code. It's 1st Sept 2024, Sunday, 21:45 UTC. Dag should have triggered. What's the problem with it ? I had to m...
<python><python-3.x><airflow>
2024-09-01 21:51:32
0
501
learner57
78,938,395
1,267,833
Matplotlib broke after Ubuntu update
<p>I just updated Ubuntu to 24.04.1 LTS and I'm having some trouble with Matplotlib in my Anaconda Python setup. Most of the other scientific libraries I use appear to be fine.</p> <p>I'll try to run</p> <pre><code>import matplotlib.pyplot as plt import numpy as np plt.hist(np.random.normal(10)) </code></pre> <p>and I...
<python><matplotlib><ubuntu-24.04>
2024-09-01 21:20:03
0
2,157
Taylor
78,938,260
9,655,667
Passing Exception type and type hinting
<p>I have the following python code:</p> <pre><code>from pathlib import Path def ffind_overview_ex(base_dir: Path, exc: Exception = FileNotFoundError) -&gt; Path: try: # do something except Exception as err: raise exc(&quot;hello&quot;) from err ## do some more if some_extraordinary_c...
<python><exception><python-typing><mypy>
2024-09-01 19:57:47
1
455
Rick Manix
78,938,211
6,930,340
Computing cross-sectional rankings using a tidy polars dataframe
<p>I need to compute cross-sectional rankings across a number of trading securities. Consider the following <code>pl.DataFrame</code> in long (tidy) format. It comprises three different symbols with respective prices, where each symbol also has a dedicated (i.e. local) trading calendar.</p> <pre class="lang-py prettypr...
<python><dataframe><python-polars>
2024-09-01 19:28:42
1
5,167
Andi
78,938,115
4,699,441
Python (pyparsing): parsing legacy curly braces file format
<p>I have to parse with Python (pyparse) a legacy file format that is not well defined.</p> <p>It is of the curly brace family (im fact, having to parse arbitrary curly brace formats is a recurring issue because people are always like &quot;XML is too verbose, let's invent our own format&quot;).</p> <p>So I have things...
<python><parsing><text-parsing><curly-braces>
2024-09-01 18:39:16
1
1,078
user66554
78,938,085
14,944,414
Making a user-friendly input for subdividing a square into coordinates
<p>I am working on a program (in Python) that involves cutting a square(s) into smaller pieces. The user has to enter a 'code', which the program will automatically convert into the coordinates for each individual rectangle. Each rectangle also has a value associated with it.</p> <p>So far, I came up with the following...
<python><python-3.x><tkinter><cjk><kanji>
2024-09-01 18:23:14
1
307
Leo
78,938,073
12,016,688
Why doesn't the "repeated" number go up in the traceback as I increase the recursion limit?
<p>When I run a recursive function and it exceeds the recursion depth limit, the below error is displayed:</p> <pre class="lang-py prettyprint-override"><code>Python 3.12.4+ (heads/3.12:99bc8589f0, Jul 27 2024, 11:20:07) [GCC 12.2.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;li...
<python><recursion><traceback>
2024-09-01 18:12:17
1
2,470
Amir reza Riahi
78,937,921
6,357,916
Unable to convert cuda:0 device type tensor to numpy
<p>I have <code>y_hat</code> variable of type <code>list</code>. I am unable to convert it to numpy array. It gives following error:</p> <pre><code>TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. </code></pre> <p>Also I cannot call <code>.cpu()</cod...
<python><python-3.x><pytorch>
2024-09-01 17:10:19
1
3,029
MsA
78,937,912
2,774,885
is there a better (?) way to maintain a bidirectional mapping of strings
<p>I've got a use case for what I'll call an &quot;invertible dictionary&quot; -- because I don't know a better term for it. I've got a set of data where the values for some properties are repeated all over the place... think about a database where there are a million records but they share maybe a few dozen unique va...
<python><data-structures>
2024-09-01 17:06:50
1
1,028
ljwobker
78,937,897
1,332,263
Confirm if Python script process is running
<p>I want to check if a specific Python script is running. The script is &quot;EXIF_GUI_EXPERIMENT.py&quot;. Running the script below returns nothing.</p> <p>If I run <code>ps -fA</code> in the terminal I see the script is running as process &quot;python3 /home/pi/scripts/tkinter/EXIF/EXIF_GUI_EXPERIMENT.py. What is th...
<python><python-3.x>
2024-09-01 16:55:46
1
417
bob_the_bob