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
⌀
77,532,591
8,854,526
Is it possible to optimize a function with discrete variables in `mealpy`?
<p>I have been working with the <a href="https://pypi.org/project/mealpy/" rel="nofollow noreferrer"><code>mealpy</code> Python library</a> for quite some time-- the repository of around 200 metaheuristic algorithms including GA, DE, ACO, PSO, ...authored by <a href="https://github.com/thieu1995" rel="nofollow norefer...
<python><optimization><genetic-algorithm><discrete-optimization>
2023-11-22 19:17:53
1
326
Partha D.
77,532,463
10,859,585
Collecting data from nested lists and dictionaries without so many for/if statements
<p>I've been working a lot with monday.com's API lately. Once I receive queried data, I retrieve specific pieces to check them with other values, manipulate them, etc. Due to the complexity of the query, I often find myself having to iterate through nested lists of dictionaries with values of more nested lists of dicti...
<python><list><dictionary>
2023-11-22 18:50:49
2
414
Binx
77,532,451
9,251,158
Authenticated request to a RESTful API gives 404
<p>I want to use the BeyondWords RESTful API, with documentation <a href="https://api.beyondwords.io/docs" rel="nofollow noreferrer">here</a>:</p> <pre><code>POST /projects/{project_id}/content (Create) </code></pre> <p>Unfortunately, they don't provide sample code, so I use their request body and these threads (<a hre...
<python><rest>
2023-11-22 18:49:04
0
4,642
ginjaemocoes
77,532,284
3,963,478
Python module setup.py dependency updates by Renovate combined with GitLab Package Registry
<p>We have Python modules, which were referencing other Python modules from an internal GitLab Package Registry. The <code>setup.py</code> looks like the following:</p> <pre class="lang-py prettyprint-override"><code>import setuptools setuptools.setup( name=&quot;dummy-module&quot;, version=&quot;0.1.0&quot;, ...
<python><gitlab><setup.py><renovate>
2023-11-22 18:14:51
1
2,228
Patrick
77,531,932
10,985,257
interpretion of branch coverage
<p>This is kind of an followup question to <a href="https://stackoverflow.com/questions/37304078/how-do-i-interpret-python-coverage-py-branch-coverage-results">How do I interpret Python coverage.py branch coverage results?</a></p> <p>I have a different situation where I check a variable <code>perr</code> which has in d...
<python><coverage.py>
2023-11-22 17:12:53
1
1,066
MaKaNu
77,531,821
2,473,382
Typing/completion in a generic container
<p>Imagine this setup, where I define a generic container, with as goal to make it easy to search inside:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, Generic, Self, TypeVar from pydantic import BaseModel T = TypeVar(&quot;T&quot;) class Container(Generic[T]): def __init__(self, valu...
<python><python-typing><pydantic>
2023-11-22 16:53:09
1
3,081
Guillaume
77,531,793
13,874,745
The Loss can’t back propagate to model’s parameters with my customized loss function
<p>I designed a customized loss:</p> <pre><code>class CustomIndicesEdgeAccuracyLoss(torch.nn.Module): def __init__(self, num_classes: int, selected_indices: list): super(CustomIndicesEdgeAccuracyLoss, self).__init__() self.num_classes = num_classes self.selected_indices = selected_indices ...
<python><pytorch><loss-function>
2023-11-22 16:48:55
1
451
theabc50111
77,531,749
2,749,397
The computation had not completed because of the undecidable set membership is found in every candidates
<p>Using Sympy from IPython, I receive an error that I cannot understand.</p> <p>The <code>Y1</code> function below is a polynomial in <em>x</em>, that has a maximum in [0,1] (see the plot, <em>please notice that the <em>y</em> axis is inverted!</em>), and I've checked that using simpler polynomials works, e.g. <code>m...
<python><sympy>
2023-11-22 16:43:25
1
25,436
gboffi
77,531,574
16,707,518
Reduce value of maximum value in multiple columns by one in pandas dataframe by group
<p>Apologies - this is very similar to a query I had earlier but I was unable to delete as I'd made a mistake within it.</p> <p>I simply want to find the maximum value <strong>by group</strong> in some of the columns (not all of them) in a dataframe - and reduce this grouped maximum value by one. It will be a single ro...
<python><pandas>
2023-11-22 16:17:15
2
341
Richard Dixon
77,531,410
9,443,671
How can I take the difference of two overlapping byte streams in Python?
<p>I have an audio stream coming in from an API call which generated text-to-speech; I am currently generating overlapping chunks of consecutive texts and want to only write the difference between a stream chunk and the one preceding it (excluding the overlap), how can I do that when what I'm dealing with are byte stre...
<python><audio><stream><byte><botocore>
2023-11-22 15:55:50
0
687
skidjoe
77,531,227
540,665
Filtering Pandas Dataframe Records, based on "key:value" match in a list of dictionaries as 2nd field of the Dataframe
<p>I have a dataset like below in a pandas dataframe. What I want is to check the values in second column, which look like a list of dictionaries, and keep only those full records for which <code>platform</code> is <code>Windows</code> and <code>script_type</code> is <code>PowerShell</code></p> <p>Is there a way to do ...
<python><pandas><dataframe>
2023-11-22 15:29:26
1
2,398
dig_123
77,531,208
536,262
Python 3.12 SyntaxWarning: invalid escape sequence on triple-quoted string, `\d` must be `\\d`
<p>After updating to Python 3.12, I get warnings about invalid escape sequence on some triple-quotes comments.</p> <p>Is this a new restriction? I have the habit of documenting code using triple-quoted string, but this has never been a problem prior to Python 3.12.</p> <pre><code>python3 --version Python 3.12.0 $ ./so...
<python><warnings><string-literals><quoting><python-3.12>
2023-11-22 15:25:57
2
3,731
MortenB
77,531,190
4,340,985
How to read a CSV file with a date and time with milliseconds? ('DD.MM.YYY hh:mm:ss:mmm')
<p>I have a CSV file with timestamps that have (empty) milliseconds in them (<code>01.01.1901 00:00:00:000</code>) and pandas ´read_csv´ can't seem to parse them:</p> <p>test.csv:</p> <pre><code>date,value 18.03.2019 00:00:00:000,3.97 19.06.2019 00:00:00:000,4.22 10.09.2019 00:00:00:000,4.4 16.12.2019 00:00:00:000,5.6 ...
<python><pandas><datetime><time>
2023-11-22 15:23:12
0
2,668
JC_CL
77,531,042
18,237,126
Images with Tkinter
<p>I am having quite some problems trying to implement images in my game. I want to put each image in the frames I created for the different stages of the game, however, this seems impossible. I can only get it to work if I place the image in the window (and thus I can't change the background). What would be the best w...
<python><image><tkinter><background><python-imaging-library>
2023-11-22 15:03:20
0
314
António Rebelo
77,530,731
546,465
Thread & Process PoolExecutor with workers that keep state
<p>For a FTP download problem at scale I'd like to use Python's <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow noreferrer">concurrent futures</a> to get multiple FTP connections and have each download multiple files.</p> <p>My question is how can I make workers that can keep their sta...
<python><multithreading><multiprocessing>
2023-11-22 14:20:59
1
4,712
Bastiaan
77,530,677
2,123,706
How to parse xml to pandas dataframe using beatiful soup
<p>I have:</p> <pre><code>xml_data = &quot;&quot;&quot;&lt;address_details sequence_number=&quot;1&quot; match_indicator=&quot;L&quot;&gt; &lt;address_input id=&quot;ADI&quot; address_details=&quot;street address and postcode&quot; /&gt; &lt;address_matched id=&quot;ADO&quot; address_key=&quot;123&quot; house_n...
<python><pandas><xml><beautifulsoup>
2023-11-22 14:13:57
3
3,810
frank
77,530,583
7,233,155
PyO3 "`From<&PyCell<mod::struct>>` is not implemented for `f64`"
<p>I am trying to expose a Rust struct to Python class.</p> <pre class="lang-rust prettyprint-override"><code>use pyo3::prelude::*; use std::sync::Arc; use indexmap::set::IndexSet; use ndarray::{Array1, Array}; #[pyclass] #[derive(Clone, Debug)] pub struct Dual { real : f64, vars : Arc&lt;IndexSet&lt;String&gt...
<python><rust><pyo3>
2023-11-22 14:01:16
0
4,801
Attack68
77,530,570
2,947,077
How to find a 10x10x3 numpy array within a 1000x1000x3 numpy array (fast)?
<p>I am wondering the following:</p> <p>I have a 10x10x3 and a 1000x1000x3 numpy array. I want to check if the smaller array can be found within the bigger array (and where). This is pretty easy with 2 for loops, but that solution is <em>very</em> slow:</p> <pre class="lang-py prettyprint-override"><code>H, W, _ = big....
<python><numpy>
2023-11-22 13:59:41
2
545
dljve
77,530,451
3,114,229
Terminal prompts for Jupyter Notebook for Python in VScode
<p>I'm having trouble running a batch file from a Jupyter Notebook in VScode. The prompts from the batch file are not showing up in the terminal when I run the script. Is there a way to print the prompts in the terminal instead of between cells? I've looked at a <a href="https://stackoverflow.com/questions/38616077/liv...
<python><visual-studio-code><jupyter-notebook>
2023-11-22 13:42:52
1
419
Martin
77,530,412
9,422,346
Python Arrow datetime function returns a timestamp with seconds field value more than 60
<p>I have a function in my code for taking a UTC time argument like - <code>2023-11-06T20:53:39.062Z</code>, convert it to EST time and then return in a format as 'MM-DD-YYYY HH:MM:SS'.</p> <pre><code>def date_conv(time): est = zoneinfo.ZoneInfo('America/Toronto') est_time = arrow.get(time).astimezone(est) ...
<python><datetime><utc><python-arrow>
2023-11-22 13:37:25
1
407
mrin9san
77,530,306
13,371,166
Convert Python curl response.content bytes object to readable format (json, xml)
<p>I fetch some data from an api with below code</p> <pre class="lang-py prettyprint-override"><code>headers = { 'Authorization': &quot;Basic XXXXXXXXX&quot;, 'Accept': 'application/xml', } resp = requests.get('https://api_request', headers=headers) </code></pre> <p>I receive a correct response from the API (c...
<python><xml>
2023-11-22 13:23:37
1
542
kenshuri
77,530,281
16,707,518
Reduce maximum value in multiple columns by one in pandas dataframe
<p>Bit of a niche one here that I've not been able to find equivalent code for anywhere. I simply want to find the maximum value in some of the columns (not all of them) and reduce this maximum value by one. It will be a single row, not multiple rows that have the maximum value.</p> <p>So let's say I have a table with ...
<python><pandas><dataframe><max>
2023-11-22 13:19:53
2
341
Richard Dixon
77,530,232
2,063,900
How I can add button to the variants tab in the products screen in Odoo
<p>I try to add a button in the products screen but I can't find the correct path, and I do not know the problem.</p> <p>this is my code</p> <pre><code> &lt;xpath expr=&quot;//page[@name='variants']&quot; position=&quot;inside&quot;&gt; &lt;button string=&quot;Custom Button&quot; type=&quot;object&qu...
<python><xml><odoo><odoo-16>
2023-11-22 13:11:33
1
361
ahmed mohamady
77,530,111
8,324,480
Pandas DF eval failing if it's not explicit
<p>I have a dataframe column named <code>foo</code> contianing booleans, True or False, and I want to understand why:</p> <pre><code>df.eval(&quot;foo&quot;) -&gt; fails with ValueError: unknown type object df.eval(&quot;foo == True&quot;) -&gt; works </code></pre> <p>It seems like this first line should select the <...
<python><pandas>
2023-11-22 12:54:05
2
5,826
Mathieu
77,530,069
1,609,428
missing labels in matplotlib chart created with pandas
<p>Consider the following example</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt ddd = pd.DataFrame({'time': [1,2,3,4], 'var1': [1,4,6,3], 'var2': [4,3,2,1]}) fig, ax = plt.subplots() for col in ['var1', 'var2']: ddd.set_index('time')[col].plot(label =...
<python><pandas><matplotlib>
2023-11-22 12:47:58
1
19,485
ℕʘʘḆḽḘ
77,530,056
10,962,766
Improving performance when looping through country codes in App Store Scraper
<p>I am using the <a href="https://pypi.org/project/app-store-scraper/" rel="nofollow noreferrer">App Store Scraper</a> to get podcast reviews from the Apple Store. One thing students and I realised is that, naturally, popular international podcasts get reviews from several countries, and when we want to catch them all...
<python><web-scraping><podcast>
2023-11-22 12:45:45
1
498
OnceUponATime
77,529,961
16,844,801
How to sort and query jsonb data from postgresql query
<p>I have a similarity matrix dataframe. The dataframe has two columns: movie_id and similar_movies. The column similar movies is a jsonb object showing cosine similarity to other movies. Example row 3 (movie_id = 3) in dict:</p> <pre><code>{'movie_id': '3', 'similar_movies': '{&quot;0&quot;: 0.014912461842819367, &q...
<python><postgresql>
2023-11-22 12:31:34
1
434
Baraa Zaid
77,529,913
3,752,185
Pydantic model_validate with generic abstract classes
<p>I have a generic response class</p> <pre><code>RESP = TypeVar(&quot;RESP&quot;, bound=BaseModel) class TestResponse(BaseModel, Generic[RESP]): status: str data: RESP </code></pre> <p>And an example model class</p> <pre><code>class Example(BaseModel): description: str ExampleResponse = RootModel[list[...
<python><mypy><pydantic>
2023-11-22 12:23:16
0
2,711
Janar
77,529,835
14,374,599
Passing arguments to a nested function in Python
<p>I have two functions, called <code>update_y_with_x</code> and <code>update_x</code>, which are as follows:</p> <p><em>update_y_with_x</em></p> <pre><code>def update_y_with_x(chosen_tissue): for i, trace in enumerate(f.data): if trace.type == &quot;scatter&quot;: # reset all line width ...
<python><nested><plotly>
2023-11-22 12:10:08
0
497
KLM117
77,529,638
14,408,656
How to correctly read .exr files in python?
<p>like the title says I want to read .exr image files which encode depth.</p> <p>Sample image - displayed using openexr-viewer<a href="https://i.sstatic.net/Fu2jr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Fu2jr.png" alt="" /></a> (Source: <a href="https://synscapes.on.liu.se/" rel="nofollow norefe...
<python><image><opencv><image-processing><openexr>
2023-11-22 11:43:12
1
484
Chris
77,529,079
21,034,926
Extract informations from excel file if a certain column is not empty
<p>I'm trying to extract some informations from an excel file using python and openpyxl. I'm learning it so I don't know at all the language. I've writed this code that will extract data from the excel file and will print it to the console.</p> <pre class="lang-py prettyprint-override"><code># Importing openpyxl import...
<python><excel><openpyxl>
2023-11-22 10:22:27
0
501
OHICT
77,529,042
859,141
How to mask an int with bitfields
<p>I have a series of 25 flags represented by Bitfields and a session integer which represents any flags set at this time. I want to mask the integer e.g. 268698112 and see what flags are set.</p> <pre class="lang-py prettyprint-override"><code>class Flags: flaga = 0x0001 flagi = 0x0100 flagp = 0x8000 f...
<python><bit-fields>
2023-11-22 10:17:11
1
1,184
Byte Insight
77,528,844
521,347
Getting asyncio.run() cannot be called from a running event loop
<p>I have a python application which is running inside a uvicorn server. I have created a Pub/sub subscriber and trying to enable it from my main.py. I am using a streaming-pull subscription. Now, my requirement is that once the subscriber is created, control should come back to main.py instead of getting blocked in th...
<python><async-await><python-asyncio><google-cloud-pubsub><publish-subscribe>
2023-11-22 09:45:04
1
1,780
Sumit Desai
77,528,736
14,471,688
How to unpack bits from packbits results?
<p>I am not familial with np.packbits and I want to perform a huge XOR operation by using it.</p> <p>Here is my toy example:</p> <pre><code>import numpy as np # Example arrays u_values = np.array([[True, True, True, True, True, True, False, True, True, True], [True, True, True, True, True, True, T...
<python><numpy><bit-manipulation>
2023-11-22 09:29:08
1
381
Erwin
77,528,673
8,318,946
Celery Task ECS Termination Issue - Need Help Updating Decorator for Handling ProtectionEnabled State Changes
<p><strong>Explanation:</strong></p> <p>I have a Django application where I am running multiple Celery tasks on AWS Elastic Container Service (ECS), using SQS as the broker. I am encountering an issue where the Celery tasks are being started in an existing ECS task once the previous one is completed. The issue arises b...
<python><django><celery><amazon-ecs>
2023-11-22 09:19:48
1
917
Adrian
77,528,663
726,730
Why QMenu shortcuts didn't triggered from modal QDialog?
<p>For this question, i have two windows: one QMainWindow with a QMenu and one QPushButton, and one QDialog window with just a QLabel.</p> <p>When the user hits the QMenu action, a console message is appeared in the screen. This action has a shortcut key (F10).</p> <p>When the user clicks the button one modal QDialog i...
<python><pyqt5><shortcut>
2023-11-22 09:18:29
1
2,427
Chris P
77,528,563
4,555,249
Serial communication logging with data transfer
<p>I am trying to develop a communication script for a device that is connected through serial port in python. I am sending and receiving data from/to the device using functions. Now what I would like to do is keep a full communication log. If I am sending and receiving data that I initiate this is trivial. However the...
<python><python-3.x><logging><serial-port><serial-communication>
2023-11-22 09:00:14
0
3,689
Gábor Erdős
77,528,429
21,034,926
ModuleNotFoundError: No module Openpyxl found
<p>I'm learning python and I want to create a simple script to analyze some data from an excel file. I'm reading <a href="https://www.datacamp.com/tutorial/python-excel-tutorial" rel="nofollow noreferrer">this tutorial</a> and it suggest to install the openpyxl library using the command <code>pip install openpyxl</cod...
<python><openpyxl>
2023-11-22 08:40:07
3
501
OHICT
77,528,415
9,974,205
How to join two dataframes for which column values are within a certain range and some values do not match?
<p>I have been reading <a href="https://stackoverflow.com/questions/46525786/how-to-join-two-dataframes-for-which-column-values-are-within-a-certain-range">this other post</a>, since I am dealing with a similar situation.</p> <p>However, I have a problem. In my version of <code>df_1</code>, I have timestamps which are ...
<python><pandas><dataframe><datetime><intervals>
2023-11-22 08:38:34
3
503
slow_learner
77,528,356
16,703,301
'gpiod' is not a package
<p>I'm trying to use libgpiod in python on my orangepi model 4B. I installed it with:</p> <pre><code>sudo apt install libgpiod-dev python3-libgpiod </code></pre> <p>Now I try to use it:</p> <pre><code>from gpiod.line import Direction, Value </code></pre> <p>But I get an error:</p> <pre><code>ModuleNotFoundError: No mod...
<python><python-3.x><orange-pi><libgpiod>
2023-11-22 08:30:06
1
336
Dmitry
77,528,329
12,603,110
How to splat Powershell arguments in the same manner that Python *args, **kwargs work
<p>Both python and powershell support a form of splatting array and named arguments as function inputs, a very useful feature.</p> <p>However powershell seem to be internally inconsistent somewhat. I am trying to reproduce powershell code that behaves similarly to the following python code:</p> <pre class="lang-py pret...
<python><powershell><arguments><keyword-argument><parameter-splatting>
2023-11-22 08:25:25
1
812
Yorai Levi
77,528,014
1,068,879
How to run Huey consumer on Windows IIS
<p>I am working on a Django application which is deployed on a Windows Server using IIS. I want to use <code>Huey</code> to be able to run background tasks e.g. sending of emails and report generation. <code>Celery</code> does not support Windows hence my decision to use <code>Huey</code>.</p> <p>According to the <a hr...
<python><django><iis><windows-server><python-huey>
2023-11-22 07:26:03
0
41,075
Frankline
77,527,951
9,586,338
How to cancel tasks in anyio.TaskGroup context?
<p>I write a script to find out the fastest one in a list of cdn hosts:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3.11 import time from contextlib import contextmanager from enum import StrEnum import anyio import httpx @contextmanager def timeit(msg: str): start = time.time() ...
<python><httpx><anyio>
2023-11-22 07:12:35
2
6,549
Waket Zheng
77,527,947
6,643,219
How to check email validation using regex in Django
<p>I'm trying to create a registration form for my Django project. I want to check if the user's email address is correct. I used built-in email validator, but it just check the domain. I need to prevent user to enter emails like this: john#doe@gmail.com etc. here is my models.py</p> <pre><code>class Profile(models.Mod...
<python><django>
2023-11-22 07:11:00
1
457
Shima Erfan
77,527,847
7,067,333
Jax vmap limit memory
<p>I'm wondering if there is a good way to limit the memory usage for Jax's VMAP function? Equivalently, to vmap in batches at a time if that makes sense?</p> <p>In my specific use case, I have a set of images and I'd like to calculate the affinity between each pair of images; so ~order((num_imgs)^2 * (img shape)) byte...
<python><jax>
2023-11-22 06:52:02
1
620
Evan Mata
77,527,741
12,522,881
Replace pandas column with list values from another panadas dataframe
<p>I'm trying to modify the <code>main_df</code> dataframe by replacing its <strong>Product</strong> list values with corresponding Model list values from the <code>mapping_df</code>, but only if they are found in the lookup list <code>to_replace_values</code>.</p> <p>For example, the first <strong>Product</strong> ...
<python><pandas><dataframe>
2023-11-22 06:32:20
2
473
Ibrahim Ayoup
77,527,647
435,563
How can I best type a python function returning a named tuple type
<p>In python 3.11 (mypy 1.7.0) I have a function that constructs a dynamic NamedTuple type. It returns the type constructed - not an instance. I first tried typing it with <code>Type[NamedTuple]</code>, but that causes python to expect the named tuple constructor itself, not a subclass.</p> <p>I tried a protocol such a...
<python><mypy>
2023-11-22 06:09:27
1
5,661
shaunc
77,527,407
11,790,637
python in conda uses packages in the user directory instead of those in virtual environments
<p>I am on ubuntu 20.04 and using anaconda 22.9.0. I installed two versions of pytorch in my user directory and the conda virtual environment, respectively. Despite <code>which python</code> and <code>which pip</code> showing:</p> <pre class="lang-bash prettyprint-override"><code>(openmmlab) user@hostname:~/Application...
<python><anaconda><conda>
2023-11-22 04:54:36
0
2,337
ihdv
77,527,302
13,881,506
Are there a C# equivalents of Python's iter() and next() functions?
<p>Python's <a href="https://docs.python.org/3.9/library/functions.html?highlight=iter#iter" rel="nofollow noreferrer"><code>iter(.)</code></a> and <a href="https://docs.python.org/3.9/library/functions.html?highlight=iter#next" rel="nofollow noreferrer"><code>next(.)</code></a> built-in functions allow iterating a lis...
<python><c#><iterator><ienumerator>
2023-11-22 04:18:53
2
1,013
joseville
77,526,956
2,056,201
Could not build wheels for Numpy when installing MlAgents
<p>All my code is below,</p> <p>I am trying to install ml agents with the simple anaconda commands using Windows 10,</p> <pre><code>conda create --name mlagents python==3.10.8 conda activate mlagents cd ml-agents pip install -e ./ml-agents </code></pre> <p>How do I fix this wheels error?</p> <pre><code>(base) c:\Code\u...
<python><numpy><pytorch><conda><ml-agent>
2023-11-22 02:07:21
1
3,706
Mich
77,526,928
11,237,476
How Does NumPy Internally Handle Matrix Multiplication with Non-continuous Slices?
<p>Hello Stack Overflow community,</p> <p>I'm working with NumPy for matrix operations and I have a question regarding how NumPy handles matrix multiplication, especially when dealing with non-continuous slices of matrices.</p> <p>Consider a scenario where we have a large matrix, say of size [1000, 1000], and we need t...
<python><numpy><blas>
2023-11-22 01:55:11
1
1,337
musako
77,526,909
20,122,390
Is it more efficient to use del or dictionary comprehension in python?
<p>Suppose I have a python dictionary with the following structure:</p> <pre><code>data = { &quot;key_1&quot;: &quot;some value&quot;, &quot;key_2&quot;: &quot;some value&quot;, &quot;key_3&quot;: &quot;&quot;, &quot;key_4&quot;: &quot;&quot; } </code></pre> <p>So, I want to remove all key-values for which the value is...
<python><dictionary-comprehension>
2023-11-22 01:47:13
0
988
Diego L
77,526,899
7,930,118
Runnning NetLogo Mode from Python Throws RuntimeException
<p>I am trying to connect NetLogo from Python. I am following the official pyNetLogo documentation. Here is my code.</p> <pre><code>import pynetlogo netlogo = pynetlogo.NetLogoLink( gui=True, netlogo_home=&quot;/home/protik/NetLogo/&quot; ) netlogo.load_model(&quot;../Netlogo-model/ICS1023.nlogo&quot;) netlog...
<python><netlogo><pynetlogo>
2023-11-22 01:42:47
0
529
Protik Nag
77,526,134
4,628,504
Failure to authenticate with Artifactory using Python Poetry
<p>I'm using the Poetry package manager for Python for the first time. I have a private package stored on our enterprise Artifactory instance.</p> <p>I followed the very simple instructions for how to declare a package source and credentials for it.</p> <p>There are basically two ways to declare creds.</p> <ol> <li>Sto...
<python><authentication><python-poetry>
2023-11-21 21:53:14
1
2,140
John Carrell
77,526,110
1,228,532
How do I assign a generic return type to the method of a generic typed class?
<p>In the code below, <code>GameObjects.to_dict</code> needs to reflect the generic for a <code>TypeDict</code>, depending on the type that has been passed to <code>GameObjects</code>. In this specific example, mypy gives an error:</p> <p><code>line 37: error: List comprehension has incompatible type List[GameObjectDic...
<python><python-3.x><types><mypy>
2023-11-21 21:46:30
0
653
James N
77,525,969
4,382,391
How do you serve *all* files in a directory in flask? (Not just an individual file), accepting index.html as a default entrance?
<p>Say I have project structure:</p> <pre><code>- app.py // flask server - static/ - index.html - subfolder/ - index.html - main.js </code></pre> <p>In Flask I can go:</p> <pre class="lang-py prettyprint-override"><code>@app.route('/') def index(): return send_from_directory(os.getcwd() + &quot;/static&...
<javascript><python><flask>
2023-11-21 21:15:27
1
1,070
Null Salad
77,525,668
2,423,091
How do I define a class in Python to say that that class can have an instance of itself as a child
<p>How do I define a base class in Python, with type hinting, to say that that class can have an instance of itself as a attribute.</p> <p>For example.....</p> <pre><code>class Person(): first_name: str = None last_name: str = None parent: Person = None def __init__(self, first_name: str = None, last_n...
<python><python-typing>
2023-11-21 20:08:02
0
410
hfrog713
77,525,333
1,084,174
InvalidArgumentError: `predictions` contains negative values
<p>I was trying to run the Tensorflow Audio classification code following the <a href="https://www.tensorflow.org/tutorials/audio/simple_audio" rel="nofollow noreferrer">article</a> of tensorflow. When I ran the following python code after finishing all above cells orderly:</p> <p><strong>Code:</strong></p> <pre><code...
<python><tensorflow><classification><tensor><kaggle>
2023-11-21 18:59:31
1
40,671
Sazzad Hissain Khan
77,525,270
11,402,435
Filtering even columns in SAS
<p>I have a data set with financial data that has a particular structure:</p> <pre><code>|Date |price1 |Date |price2 |...|Date |priceN | |dd/mm/yy|numeric |dd/mm/yy|numeric |...|dd/mm/yy|numeric | |dd/mm/yy|numeric |dd/mm/yy|numeric |...|dd/mm/yy|numeric | |dd/mm/yy|numeric |dd/mm/yy|numeric |...|dd/mm/yy|n...
<python><sas>
2023-11-21 18:47:13
3
301
MARIO ANTONIO CASTILLO MACHUCA
77,525,271
4,621,513
How can mutable variables be treated as "volatile" for static type checking?
<p>Consider this class which has a variable <code>state</code> that is compared twice in the method <code>check_twice</code> and its value is changed in between the two checks by the method <code>work</code>:</p> <pre><code>import enum class State(enum.Enum): INIT = 0 DONE = 1 class Worker: def __init__...
<python><mypy><python-typing>
2023-11-21 18:47:12
1
24,148
mkrieger1
77,525,057
183,717
Selenium code to download a file from a link not working
<p>I have written the following code to download a file from the URL: <a href="https://www.nseindia.com/market-data/oi-spurts" rel="nofollow noreferrer">https://www.nseindia.com/market-data/oi-spurts</a> every 1 min. However, I have not been successful in getting it to work. I am seeing the Selenium is opening up a new...
<python><selenium-webdriver><automation>
2023-11-21 18:13:00
1
9,853
name_masked
77,524,976
2,954,547
Polars LazyFrame streaming directly to (partitioned) Parquet without collecting
<p>I am reading some data from AWS S3 with <code>polars.scan_pyarrow_dataset</code>. When I am finished with my data processing, I would like to write the results back to cloud storage, in partitioned Parquet files. However, I'd like to avoid collecting all results in memory. I believe this should be possible with the ...
<python><python-polars>
2023-11-21 17:57:54
2
14,083
shadowtalker
77,524,974
5,424,117
How to resolve error running pipdeptree with Python 3.11
<p>I'm following the instructions here for upgrading Django: <a href="https://www.youtube.com/watch?v=9i1VZQg8mFg" rel="nofollow noreferrer">Django Upgrade Video</a></p> <p>And I get a big error when trying to run the first command for deriving dependencies:</p> <pre><code>pipdeptree -f --warn silence | grep -E '^[a-zA...
<python><python-3.x><django><pip>
2023-11-21 17:57:32
2
2,474
jb62
77,524,958
18,904,265
Mypy shows error when using a function to return a type
<p>I have written a function <code>string_prompt</code> to return a type annotation which I have to reuse a lot in the context of <a href="https://typer.tiangolo.com/" rel="nofollow noreferrer">typer</a>. This is a working example (run with <code>python -m</code>):</p> <pre class="lang-py prettyprint-override"><code>fr...
<python><mypy><typer>
2023-11-21 17:55:55
1
465
Jan
77,524,726
608,294
Create a new package from an existing installed python package
<p>I made many changes to a library installed with pip (library not maintained anymore) and I want to create a new package that I can use for my own projects without each time to install the library using pip and then change the files I modified.</p> <p>Is there a way?</p>
<python>
2023-11-21 17:17:52
0
1,741
Andrea
77,524,700
17,487,457
Creating an ensemble of classifiers based on predefined feature subsets
<p>The following MWE creates an ensemble method from the features selected using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html" rel="nofollow noreferrer">SelectKBest</a> algorithm and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.Rand...
<python><machine-learning><scikit-learn><classification><ensemble-learning>
2023-11-21 17:12:25
2
305
Amina Umar
77,524,524
3,368,201
Tkinter Canvas - 2px internal padding appearing
<p>I noticed a strange behavior with the Tkinter Canvas implementation. Here is a small snippet to highlight this behavior.</p> <pre class="lang-py prettyprint-override"><code>shall_configure_innerframe = False shall_configure_periodically = False from tkinter import Tk, Canvas from tkinter.ttk import Style, Frame, L...
<python><tkinter><tkinter-canvas>
2023-11-21 16:42:11
1
2,880
frarugi87
77,524,506
5,374,234
Equivalent of Linux 'zip -FF' in Python
<p>I have a python application that works with .zip files. Occasionally this application will fail with error <code>BadZipFile: File is not a zip file</code></p> <p>In spot checking the failed files, I've found that a working zip file can be created using the <code>zip -FF</code> Linux command.</p> <p>The issue is that...
<python><zip>
2023-11-21 16:39:19
0
478
Chris Decker
77,524,430
17,744,230
Django optional, non-capturing string in URLs
<p>I am trying to add prefix parameter to our api url's for our application implemented in Python Django. It is currently like this</p> <pre><code>urlpatterns= [ path(&quot;api/&quot;, include( [ path(&quot;books/&quot;, include(books.urls)), path(&quot;events/&quot;, include(events.urls)), path...
<python><django><regex><rest>
2023-11-21 16:28:14
1
738
dense8
77,524,428
12,477,405
Problems with inheritance using SQLModel
<p>I want the role attribute from AppUser populated. When I declare it in AppUser class, it works as expected, joining the userrole table. But if I declare it in BaseUser class, it's not populating the field, ignoring the join. My question is, how can I make this inheritance model work? With the code below, you can vie...
<python><inheritance><sqlalchemy><orm><sqlmodel>
2023-11-21 16:27:59
1
454
Gabriel Macus
77,524,234
1,957,873
asyncio: how to handle exceptions
<p>I'm using <code>asyncio.gather()</code> to run concurrently two coroutines. They should run forever, so if one of them returns (correctly or with an exception) I'd like to know.</p> <p>If I use <code>try/except</code> for <code>asyncio.gather()</code>, I can correctly catch the exceptions of coroutines.</p> <p>The p...
<python><python-asyncio>
2023-11-21 16:01:21
2
846
pozzugno
77,523,991
5,594,008
Poetry, keyring backends error on creating
<p>After installing poetry using pipx, I got such error</p> <pre><code>&quot;/Users/my_user/.local/pipx/venvs/poetry/lib/python3.12/site-packages/keyring/backend.py&quot;, line 199, in _load_plugins entry_points = metadata.entry_points()['keyring.backends'] ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^...
<python><python-poetry>
2023-11-21 15:25:21
0
2,352
Headmaster
77,523,657
17,194,313
How do you "condense" long recursive Polars expressions?
<p>The Polars expression language is amazing, but it very occasionally can cause issues when the expression definition becomes extremely large.</p> <p>In my experience this only happens with recursion - for example:</p> <pre class="lang-py prettyprint-override"><code>def diffuse(c:pl.Expr, n_time_steps=1, conductivity:...
<python><python-polars>
2023-11-21 14:33:44
1
3,075
MYK
77,523,623
3,129,604
Is there a way to take screenshot from a window that is not currently active through a Python script?
<p>I have seen ways to take screenshots easily for the active window in Windows OS.</p> <p>I would like to know if there is a way and how to take screenshots from windows that are minimized in Windows OS, through a Python script.</p> <p>The reason is because I am building a bot app for a game that will run for multiple...
<python><windows><screenshot>
2023-11-21 14:28:18
0
2,753
Matteus Barbosa
77,523,527
1,328,355
numpy Polynomial to vector
<p>How do I extract the coefficient vector from a <code>numpy</code> polynomial?</p> <p>In Python, when using the <code>numpy</code> package to construct a polynomial, how do I extract the coefficients of this polynomial as a vector?</p>
<python><numpy><polynomials>
2023-11-21 14:14:17
1
3,681
Bastiaan Quast
77,523,524
183,054
Create view that shows all objects relating to current user's department
<p>I have the following Django model:</p> <pre class="lang-py prettyprint-override"><code>from django.conf import settings from django.db import models class Appeal(models.Model): DEPARTMENTS = [ (&quot;a&quot;, &quot;DeptA&quot;), (&quot;b&quot;, &quot;DeptB&quot;), (&quot;c&quot;, &quot;...
<python><django><django-views>
2023-11-21 14:14:05
1
1,536
RafG
77,523,522
15,915,737
ImportError: cannot import name 'SecretField' from 'pydantic'
<p>I'm using prefect on a gitlab CI and it was working fine until now when it had this error:</p> <pre><code>from pydantic import BaseModel, Field, SecretField ImportError: cannot import name 'SecretField' from 'pydantic' (/usr/local/lib/python3.8/site-packages/pydantic/__init__.py) </code></pre> <p>I tought it was com...
<python><package><pydantic><prefect>
2023-11-21 14:13:45
2
418
user15915737
77,523,409
1,216,183
Python slower inside docker container
<p>I'm experiencing a slower python when running from inside of a docker container than the one of my system. I can't explain this difference.</p> <p>I've found a lot of content about this on the Internet, but the solutions I've tried don't work.</p> <h3>Test</h3> <p>Host system Up-to-date <em>Arch linux</em></p> <pre>...
<python><docker><performance>
2023-11-21 14:00:37
0
2,213
fabien-michel
77,523,265
3,932,908
struggling to get unique values in large dataset
<p>I have a large dataset that can't fit in memory with fields &quot;function_name&quot; and &quot;trace&quot; (and a couple of others). The traces are very long strings, and what I want to do is for each function_name, ensure there are no duplicate traces without running out of memory. I have tried the following:</p> ...
<python><python-polars>
2023-11-21 13:36:39
0
399
Henry
77,523,119
2,002,076
Python 2.7 to Python 3 upgrade
<p>I am working on updating a series of python 2.7 plugins to python 3.10 that get loaded into the software individually. Below is an example of how the python 2.7 plugin is organized.</p> <p>ProjectDir</p> <ul> <li>Plugin1 <ul> <li><code>__init__.py</code></li> </ul> </li> <li>Plugin2 <ul> <li><code>__init__.py</code>...
<python><python-3.x><python-2.7>
2023-11-21 13:13:36
2
1,352
Travis Pettry
77,523,055
833,300
_MissingDynamic: `license` defined outside of `pyproject.toml` is ignored
<p>For the last 24 hours or so I'm seeing the below error messages when I try to install either of sexpdata 1.0.1 or segno 1.5.3 in python.</p> <p>I should perhaps note that these installs usually happen via github code runners (automated tests), which is what alerted me to the issue. I can reproduce locally.</p> <p>M...
<python><python-3.x><pip>
2023-11-21 13:04:53
2
3,799
jma
77,523,045
4,255,096
Failure to partition a dataframe to write to DeltaLake
<p>I'm getting an <code>IllegalArgumentException</code> while attempting to write to Delta.</p> <pre><code>E pyspark.sql.utils.IllegalArgumentException: requirement failed: The provided partitioning does not match of the table. E - provided: identity(class_name) E - table: </...
<python><apache-spark><pyspark><delta-lake>
2023-11-21 13:02:30
0
375
Geosphere
77,523,017
8,302,849
How to toggle swap camera view between 2 cameras on live feed frame?
<p>I have only 2 USB cameras that are connected to my PC (Note: highly confident that I won't use more than 2 cameras now and in future) . My aim of this program is to capture front and rear view concurrently. And I have successfully have the working prototype of the program which allowed to view 2 live feed video at t...
<python><tkinter>
2023-11-21 12:59:06
2
423
Alan Koh W.T
77,522,801
1,581,090
How to create a rotating animation of a Scatter3D plot with plotly and save it as gif?
<p>With plotly in jupyter I am creating a Scatter3D plot as follows:</p> <pre><code># Configure the trace. trace = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker=dict(color=colors, size=1) ) # Configure the layout. layout = go.Layout( margin={'l': 0, 'r': 0, 'b': 0, 't': 0}, height = 1...
<python><animation><3d><plotly><jupyter>
2023-11-21 12:24:12
2
45,023
Alex
77,522,771
110,451
How can I get python to get exactly the bytes written to the standard output when running with subprocess.run?
<p>The problem I have is the following: in a subprocess (on Windows), someone is writing something as:</p> <p><code>print(&quot;line1\r\nline2\r\nline3\n&quot;)</code></p> <p>and for some reason additional <code>\r</code> chars end up in the stream being written.</p> <p>I'm running in binary mode (<code>text=False</cod...
<python><windows>
2023-11-21 12:20:25
1
25,390
Fabio Zadrozny
77,522,743
8,547,163
How to create straight edges at specific corners using graphviz
<p>I have the below code to create a simple flow using graphviz to be visualized in jupyter notebook</p> <pre><code># Create Digraph object dot = Digraph() # Add nodes dot.node('1', shape='box') dot.node('2', shape='rectangle') dot.node('3', shape='parallelogram') dot.node('4', shape='diamond') dot.node('5', shape='b...
<python><jupyter-notebook><graphviz>
2023-11-21 12:16:43
2
559
newstudent
77,522,726
1,850,978
Populating text on a grid does not place text in the grid cell nor do the cells appear
<p>I have the following Python code:</p> <pre><code>import json import sys import matplotlib.pyplot as plt import numpy as np if len(sys.argv) != 2: print(&quot;Usage: python script_name.py &lt;path_to_input_json&gt;&quot;) sys.exit(1) filename = sys.argv[1] with open(filename) as f: data = json.load(f) # ...
<python><matplotlib>
2023-11-21 12:14:00
1
5,853
David Faizulaev
77,522,673
5,506,400
Google Calendar API Understanding of token.json
<p>I am working with the Google calendar API, the python quickstart in particular, but the language does not matter.</p> <p>The example from <a href="https://developers.google.com/calendar/api/quickstart/python" rel="nofollow noreferrer">https://developers.google.com/calendar/api/quickstart/python</a> has:</p> <pre><co...
<python><google-oauth><google-calendar-api><google-api-python-client>
2023-11-21 12:04:57
1
2,550
run_the_race
77,522,575
13,674,431
Python Selenium Choose date from a Datepicker Calendar
<p>I want to select a date (dd/mm/yyyy) from a Datepicker calendar</p> <p><a href="https://i.sstatic.net/lgDE4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lgDE4.png" alt="enter image description here" /></a></p> <p>So I used the following code, which doesn't display an error but doesn't work on the b...
<python><selenium-webdriver><selenium-chromedriver><webdriver>
2023-11-21 11:48:29
1
315
Ruser-lab9
77,522,478
7,841,952
Why does xgboost prediction have lower AUC than evaluation of same data in eval_set?
<p>I am training a binary classifier and I want to know the AUC value for its performance on a test set. I thought there were 2 similar ways to do this: 1) I enter the test set into parameter <code>eval_set</code>, and then I receive corresponding AUC values for each boosting round in <code>model.evals_result()</code>;...
<python><xgboost>
2023-11-21 11:32:40
1
436
j45612
77,522,454
21,691,539
importlib.import_module loading the wrong module in custom plugin system
<p>I'm trying to implement a plugin system in Python.<br> Each plugin exposes exactly the same function and I want to call one or another, for instance with a simple Id.<br> For instance, the plugins can be image loader, each plugin handling a different format (<em>jpeg</em>,<em>bmp</em>,...).<br> Plugins are all insid...
<python><python-import>
2023-11-21 11:29:08
0
3,479
Oersted
77,522,434
4,667,839
LLM SQL Agents and few shot learning
<p>I want to use sql Agent together with few shot examples. I followed this example: <a href="https://python.langchain.com/docs/use_cases/qa_structured/sql#extending-the-sql-toolkit" rel="nofollow noreferrer">https://python.langchain.com/docs/use_cases/qa_structured/sql#extending-the-sql-toolkit</a></p> <p>However, I w...
<python><langchain><large-language-model><py-langchain>
2023-11-21 11:25:13
1
399
Userrrrrrrr
77,522,380
2,725,810
Some invocations of a Lambda function take much longer despite a warm start (not a duplicate)
<p><strong>Note:</strong> the question has been previously mistakenly marked as a duplicate of <a href="https://stackoverflow.com/questions/1685221/accurately-measure-time-python-function-takes">this one</a>. Please note that my question is about AWS Lambda and the issue is not how to measure execution time (my code me...
<python><amazon-web-services><aws-lambda><huggingface-transformers>
2023-11-21 11:16:37
0
8,211
AlwaysLearning
77,522,301
2,749,397
How to change sympy plot properties in Jupyter with matplotlib methods
<p>The following code in a script works as expected,</p> <pre><code>from sympy import * x = symbols('x') p = plot(x, x*(1-x), (x, 0, 1)) ax = p._backend.ax[0] ax.set_yticks((0, .05, .25)) p._backend.fig.savefig('Figure_1.png') </code></pre> <p><a href="https://i.sstatic.net/1zg1x.png" rel="nofollow noreferrer"><img src...
<python><matplotlib><jupyter-notebook><sympy><jupyter-lab>
2023-11-21 11:07:24
2
25,436
gboffi
77,522,268
5,539,782
creates a new pandas column named "list_of_all_next_high" and populates it with lists of all next high values for each row
<p>I have a dataframe for stock prices:</p> <pre><code> dt open close high low 0 2023-09-15 07:51:00 1.06521 1.06521 1.06525 1.06521 1 2023-09-15 07:52:00 1.06521 1.06520 1.06522 1.06520 2 2023-09-15 07:53:00 1.06520 1.06523 1.06524 1.06520 3 2023-09-15 07:54:00 1.06521 1.06532 1.065...
<python><pandas><dataframe>
2023-11-21 11:03:01
2
547
Khaled Koubaa
77,522,191
1,581,090
How to create a 3D scatter plot with plotly with all markers individually colored?
<p>Following the suggestion <a href="https://community.plotly.com/t/specifying-a-color-for-each-point-in-a-3d-scatter-plot/12652" rel="nofollow noreferrer">HERE</a> I have tried the following code to create a Scatter3D plot with plotly in a jupyter notebook so each marker is colored individually, like you can do with m...
<python><plotly><scatter3d>
2023-11-21 10:49:45
0
45,023
Alex
77,522,184
3,575,623
Scale colour over multiple graphs
<p>I have this function that plots data along two axes, and colours them according to their distance to the diagonal:</p> <pre><code>def scatter_diagdistance(x, y) : z = abs(y-x) fig, ax = plt.subplots(dpi=200) ax2 = ax.twinx() ##Create secondary axis ax2.set_yticks([]) ##No ticks for the secondary axis...
<python><matplotlib><colors><colorbar>
2023-11-21 10:48:00
1
507
Whitehot
77,522,054
16,405,935
Count unique value with prioritize value in pandas
<p>I have a simple data frame as below:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'CUS_NO': ['900636229', '900636229', '900636080', '900636080', '900636052', '900636052', '900636053', '900636054', '900636055', '900636056'], 'indicator': [...
<python><pandas><pivot>
2023-11-21 10:26:48
1
1,793
hoa tran
77,521,745
13,518,907
Map_Reduce prompt with RetrievalQA Chain
<p>in the code below you see how I built my RAG model with the ParentDocumentRetriever from Langchain with Memory. At the moment I am using the RetrievalQA-Chain with the default chain_type=&quot;stuff&quot;. However I want to try different chain types like &quot;map_reduce&quot;. But when replacing chain_type=&quot;ma...
<python><information-retrieval><langchain><nlp-question-answering>
2023-11-21 09:40:33
2
565
Maxl Gemeinderat
77,521,686
22,466,650
How to make overlapping windows of weeks based on the nearest available dates in both sides?
<p>Sorry guys for the title but it is really what I'm trying to do.</p> <p>Here is a table to explain that more. The bold lines makes the years and the the thin ones makes the weeks.</p> <p><a href="https://i.sstatic.net/dhO22.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dhO22.png" alt="enter image de...
<python><pandas><dataframe>
2023-11-21 09:30:38
2
1,085
VERBOSE