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
79,046,426
1,838,659
Ruamel preserving backslashes to indicate a line break
<p>Does ruamel have an option to preserve backslash line breaks? Consider the following example.</p> <ul> <li>the text was exported using SnakeYaml and included carriage returns.</li> <li>the wrapping and text length was such that the <code>\r\n</code> was split as part of the wrapping</li> </ul> <pre class="lang-yaml ...
<python><yaml><ruamel.yaml>
2024-10-02 11:05:53
1
738
Steve-B
79,046,349
5,790,653
How to show difference between two list of dictionaries
<p>I have these two lists:</p> <pre class="lang-py prettyprint-override"><code>list1 = [ {'name': 'one', 'email': 'one@gmail.com', 'phone': '111'}, {'name': 'two', 'email': 'two@gmail.com', 'phone': '111'}, {'name': 'three', 'email': 'three@gmail.com', 'phone': '333'}, {'name': 'four', 'email': 'four@gm...
<python>
2024-10-02 10:44:06
3
4,175
Saeed
79,046,036
1,251,549
How output single quote in dbt post hook macros with jinja?
<p>Here is post hook for dbt model:</p> <pre><code>{{ config( post_hook=[ '{{ execute_if_exists(&quot;delete from &quot; ~ this ~ &quot; where day = date('' &quot; ~ var(&quot;mydatevar&quot;) ~ &quot; '')&quot;) }}', ] ) }} </code></pre> <p>Please note the <code>''</code> in the string. Next:</p> <p...
<python><jinja2><dbt>
2024-10-02 08:57:43
1
33,944
Cherry
79,045,596
1,641,112
How can I tame pytest's separators in the output without losing progress updates?
<p>pytest output has lots of headers that span the width of the terminal:</p> <pre><code>========================================= FAILURES ========================================= </code></pre> <pre><code>____________________________________ test_advanced_fail ____________________________________ </code></pre> <p>If ...
<python><pytest>
2024-10-02 06:37:10
0
7,553
StevieD
79,045,569
195,787
NumPy Typing of Array (Vector, Matrix) of Floats
<p>What's the proper way to add type hints to a function with NumPy arrays?<br /> Specifically hint the types are vectors / matrices of any supported float.</p> <pre class="lang-py prettyprint-override"><code>def MyFun( myVectorFloat: &lt;Typing&gt;, myMatrixFloat: &lt;Typing&gt; ): some code... </code></pre> <p>So I...
<python><numpy><python-typing>
2024-10-02 06:25:39
0
5,123
Royi
79,045,488
1,609,710
What is the best way to access immutable part when subclassing immutable type?
<p>Suppose that you want to create a new subclass for <code>float</code>, using the following code:</p> <pre><code>class MyFloat(float): def __new__(cls,number,extra): return super().__new__(cls,number) def __init__(self,number,extra): float.__init__(number) self.extra = extra </code></...
<python><subclassing>
2024-10-02 05:48:59
0
733
Glen O
79,045,268
19,090,490
Generate all possible Boolean cases from n Boolean Values
<p>If two fields exist, the corresponding fields are Boolean values.</p> <ul> <li>x_field(bool value)</li> <li>y_field(bool value)</li> </ul> <p>I want to generate all cases that can be represented as a combination of multiple Boolean values.</p> <p>For example, there are a total of 4 combinations that can be expressed...
<python><math><combinatorics>
2024-10-02 03:33:05
4
571
Antoliny Lee
79,045,133
22,860,226
Download Instagram reel audio only with Instaloader/Python or any way
<p>I am trying to download the audio in the following format <a href="https://www.instagram.com/reels/audio/1997779980583970/" rel="nofollow noreferrer">https://www.instagram.com/reels/audio/1997779980583970/</a>. Below code is returning &quot;Fetching metadata failed&quot;. I am able to download the reels but not sepa...
<python><instagram><instaloader>
2024-10-02 01:37:22
2
411
JTX
79,045,092
3,334,721
python class and numba jitclass for codes with numba functions
<p>At some point in my code, I call a Numba function and all subsequent computations are made with Numba jitted functions until post-processing steps.</p> <p>Over the past days, I have been looking for an efficient way to send to the Numba part of the code all the variables (booleans, integers, floats, and float arrays...
<python><class><numba>
2024-10-02 01:03:42
1
403
Alain
79,044,863
4,388,451
Implement a server and client communicating via sockets in Python
<p>I need to implement a server and client communicating via sockets in Python. I decided to implement the server with <code>asyncio.start_server</code>. Clients connect to the server with socket connections. The server generates some messages at random moments and immediately pushes those messages to the client. All c...
<python><sockets><asynchronous><python-asyncio>
2024-10-01 22:02:02
2
1,636
Andriy
79,044,831
8,500,958
How to override __len__ return type in python?
<p>I am trying to implement a class <code>Foo</code> that when we call <code>len(foo)</code> will return an instance of another class <code>MyCoolIntType</code> instead of an <code>int</code>. Something like the following:</p> <pre><code>class Foo(object): def __len__(self) -&gt; MyCoolIntType: return MyCoolIntTy...
<python><magic-function>
2024-10-01 21:46:57
0
932
Icaro Mota
79,044,764
210,867
How do I call async code from `__iter__` method?
<p>New to async.</p> <p>I had a class called PGServer that you could iterate to get a list of database names:</p> <pre class="lang-py prettyprint-override"><code>class PGServer: # ...connection code omitted... def _databases( self ): curr = self.connection().cursor() curr.execute( &quot;SELECT d...
<python><python-asyncio><asyncpg>
2024-10-01 21:15:56
1
8,548
odigity
79,044,650
3,903,479
Print playwright browser in pytest terminal header
<p>I have pytest set up with playwright and can run it with a docker compose command:</p> <pre class="lang-bash prettyprint-override"><code>docker compose run test pytest /tests --browser-channel chrome </code></pre> <p>Which outputs:</p> <pre><code>============================ test session starts =====================...
<python><pytest><playwright>
2024-10-01 20:26:54
1
1,942
GammaGames
79,044,503
4,727,280
Can Pyright/MyPy deduce the type of an entry of an ndarray?
<p>How can I annotate an <code>ndarray</code> so that Pyright/Mypy Intellisense can deduce the type of an entry? What can I fill in for <code>???</code> in</p> <pre><code>x: ??? = np.array([1, 2, 3], dtype=int) </code></pre> <p>so that</p> <pre><code>y = x[0] </code></pre> <p>is identified as an integer as rather than ...
<python><numpy><python-typing><mypy><pyright>
2024-10-01 19:32:55
2
945
fmg
79,044,359
7,746,472
How to return results from COPY INTO from scripting block in Snowflake
<p>How can I make a Snowflake / Snowpark scripting block return the resonse of a COPY INTO statment?</p> <p>In our ELT pipeline I use Snowpark to copy data from an S3 stage into a table on a daily basis, like this:</p> <pre><code>sql_copy_into = f&quot;&quot;&quot; COPY INTO {target_table} FROM {stage_file_...
<python><snowflake-cloud-data-platform>
2024-10-01 18:40:42
1
1,191
Sebastian
79,044,322
11,278,044
Conditionally slice a pandas multiindex on specific level
<p>For my given multi-indexed DataFrame:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( np.random.randn(12), index=[ [1,1,2,3,4,4,5,5,6,6,7,8], [1,2,1,1,1,2,1,2,1,2,2,2], ] ) </code></pre> <pre class="lang-none prettyprint-override"><code> 0 1 1 1.667692 ...
<python><pandas><multi-index>
2024-10-01 18:29:55
4
376
Kyle Carow
79,044,153
13,562,186
How to best solve partial differential equations in Python accurately but quickly
<p>I am trying to reproduce 4.1.3 Emission from Solid Materials as per this PDF.</p> <p><a href="https://www.rivm.nl/bibliotheek/rapporten/2017-0197.pdf" rel="nofollow noreferrer">https://www.rivm.nl/bibliotheek/rapporten/2017-0197.pdf</a></p> <p>Produced this version of the model and this is the best I have gotten.</p...
<python><ode><pde>
2024-10-01 17:31:20
1
927
Nick
79,044,145
12,439,683
What do ** (double star/asterisk) and * (star/asterisk) inside square brakets mean for class and function declarations in Python 3.12+?
<p>What does <code>T, *Ts, **P</code> mean when they are used in square brackets directly after a class or function name or with the <code>type</code> keyword?</p> <pre class="lang-py prettyprint-override"><code>class ChildClass[T, *Ts, **P]: ... def foo[T, *Ts, **P](arg: T) -&gt; Callable[P, tuple[T, *Ts]]: type vat...
<python><generics><python-typing><type-parameter>
2024-10-01 17:29:52
1
5,101
Daraan
79,044,131
6,738,917
Unable to properly install Python 3.7.0 on a Ubuntu 22.04 LTS VBox machine
<p>I am preparing a VirtualBox machine (Ubuntu 22.04) to work on a project with a friend and it needs to use Python 3.7.0. In order to install this python version, I am using the following command:</p> <pre><code>pyenv install 3.7.0 </code></pre> <p>However, I get the following error message which I don't get when ins...
<python><python-3.x><pyenv>
2024-10-01 17:21:27
1
576
Jonalca
79,043,974
9,670,009
Raspberry Pi not decoding base 64 encoded data sent over BLE using Nordic UART service from a React Native app
<p>I'm using a react native app to write to and read from a .ini file on a Raspberry Pi, which I call a hub, which runs a GATT server using the Nordic UART service (NUS).</p> <p>I'm able to connect to the RPi and send a string, &quot;retrieveHubConfig&quot;, which is supposed to read the current .ini file contents and ...
<python><react-native><base64><bluetooth-lowenergy>
2024-10-01 16:22:50
1
537
Tirna
79,043,944
4,769,503
Why is SQLAlchemy / Pydantic auto-loading relations only sometimes and not always?
<p>I have a weird issue in my FastAPI-based application using <strong>SQLAlchemy</strong> and <strong>Pydantic</strong> with a Postgres-Database.</p> <p>A User-Model contains two different 1-to-Many-relationships. For unknown reasons, the first relationship is always automatically loaded although it shouldn't. The seco...
<python><sqlalchemy><fastapi><pydantic>
2024-10-01 16:12:03
1
19,350
delete
79,043,862
6,260,154
Need help in fixing regex pattern to find strings which contains invalid escape sequence but not defined as raw string
<p>I'm attempting to create a regex pattern that can iterate over every content of the file and look for strings that Flake8 has a labelled as W605 which contains that indicate include an <code>invalid escape sequence</code>.</p> <p>In other words, my goal is to locate certain strings and turn them into raw strings by ...
<python><regex>
2024-10-01 15:45:51
0
1,016
Tony Montana
79,043,777
4,636,579
How to extract arguments from call with ast python
<p>I am working on a function to convert function calls, therefore I need the calls and parameters. I fiddled with AST, and I am able to extract the specific nodes, but somehow I can't distinguish the nodes by their type.</p> <p>For example, I want to get the call and the parameters to do my make into a new syntax.</p>...
<python><abstract-syntax-tree>
2024-10-01 15:21:08
0
681
Coliban
79,043,588
6,511,990
Using Haystack and Ollama . ModuleNotFoundError: No module named 'ollama'
<p>I'm running an example from the haystack website <a href="https://haystack.deepset.ai/integrations/ollama#installation" rel="nofollow noreferrer">here</a></p> <p>I have used poetry to add ollama-haystack</p> <p>I am running the following code using Python 3.12.3 on WSL2 ubuntu 24.04</p> <pre><code>from haystack_inte...
<python><python-3.x><pip><ollama><haystack>
2024-10-01 14:27:46
1
2,769
dorriz
79,043,331
142,976
Fill a field inside dialog after return of method call
<p>I want to fill the <em>Conclusion</em> field after I click on <em>Copy Notes</em> button. How to do this in Odoo? I tried using the value property in the returned data but nothing happened.</p> <pre><code>@api.multi def copy_notes(self): notes = &quot;&quot; if self.uuid_v4 == 'e3d2e0c7-ba64-4522-abf3-9befcf...
<python><odoo><odoo-8>
2024-10-01 13:19:09
0
4,224
strike_noir
79,042,915
4,451,315
collect duckdb query into two dataframes?
<p>Say I have a csv file with</p> <pre><code>date,value 2020-01-01,1 2020-01-02,4 2020-01-03,5 2020-01-04,9 2020-01-05,2 </code></pre> <p>I would like to read it with duckdb, do some preprocessing, and ultimately end up with a train and validation set as Polars dataframes</p> <p>I <em>could</em> do:</p> <pre class="lan...
<python><duckdb>
2024-10-01 11:21:08
1
11,062
ignoring_gravity
79,042,837
4,444,546
automatically add fields_validators based on hint type with pydantic
<p>I'd like to define once for all fields_validators function in a BaseModel class, and inherit this class in my model, and the validators should apply to the updated class attributes.</p> <p>MWE</p> <pre class="lang-py prettyprint-override"><code>def to_int(v: Union[str, int]) -&gt; int: if isinstance(v, str): ...
<python><field><pydantic>
2024-10-01 11:04:44
1
5,394
ClementWalter
79,042,577
5,746,740
Getting Google site reviews with Python
<p>I need to be able to get Google site reviews by their API do put them in our data warehouse.</p> <p>I tried with the following code:</p> <pre><code>from googleapiclient.discovery import build API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx' service = build('**mybusiness**', 'v4', developerKey=API_KEY) location_id = 'locations...
<python><google-api-client><google-api-python-client><google-my-business-api><google-reviews>
2024-10-01 09:45:50
1
302
André Pletschette
79,042,426
10,855,529
Pure polars version of safe ast literal eval
<p>I have data like this,</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({'a': [&quot;['b', 'c', 'd']&quot;]}) </code></pre> <p>I want to convert the string to a list I use,</p> <pre class="lang-py prettyprint-override"><code>df = df.with_columns(a=pl.col('a').str.json_decode()) </code></pre> <p>...
<python><python-polars>
2024-10-01 09:11:24
2
3,833
apostofes
79,042,253
16,611,809
How do I speed up querying my >600Mio rows?
<p>My database has about 600Mio entries that I want to query (<a href="https://stackoverflow.com/questions/79033777/how-to-query-a-large-file-using-pandas-or-an-alternative">Pandas is too slow</a>). This local dbSNP only contains rsIDs and genomic positions. I used:</p> <pre><code>import sqlite3 import gzip import csv ...
<python><sql><sqlite><query-optimization>
2024-10-01 08:18:00
2
627
gernophil
79,042,189
1,183,071
How to debug asyncio warning in base_events.py:1931?
<p>I've written a chat app that uses Quart, socketio, and uvicorn, along with some external frameworks like firestore. My dev environment is Replit. In some parts of my app, I get vague warning messages that I interpret as meaning that something is blocking an async function:</p> <pre><code>WARNING Executing &lt;Task p...
<python><asynchronous><python-asyncio>
2024-10-01 07:58:50
0
8,092
GoldenJoe
79,042,155
1,801,588
How to call a Python script using several modules from a Bash script?
<p>Based on an <a href="https://stackoverflow.com/a/66491776/1801588">answer</a>, I've made a Bash script to install the requirements and run a Python script working with a MariaDB database. In WSL, the Python script runs well, but when I run the Bash script from Windows 11 command line, I get following error:</p> <pre...
<python><python-3.x><bash><mariadb><importerror>
2024-10-01 07:48:45
4
2,860
Pavel V.
79,041,361
1,676,880
How can I find lengths of all elements of the dataframe?
<p>I tried this:</p> <pre class="lang-py prettyprint-override"><code>df_work.with_columns( pl.all().str.len_chars() ) </code></pre> <p>But I got an error</p> <blockquote> <p><code>polars.exceptions.SchemaError</code>: invalid series dtype: expected <code>String</code>, got <code>i64</code></p> </blockquote>
<python><python-polars>
2024-10-01 00:57:31
1
601
Yaiba
79,041,358
897,968
When (and why) did Python2's built-in `file()` get deprecated?
<p>I recently had to port some ancient Python2 code to Python3 and bumped into the use of the <a href="https://docs.python.org/2.7/library/functions.html#file" rel="nofollow noreferrer"><code>file</code></a> built-in function instead of <a href="https://docs.python.org/2.7/library/functions.html#open" rel="nofollow nor...
<python><python-3.x><deprecated>
2024-10-01 00:55:27
0
3,089
FriendFX
79,041,221
725,932
Finding imports of a function globally
<p>I am working on a test fixture for the slash framework which needs to modify the behavior of <code>time.sleep</code>. For <em>reasons</em> I cannot use pytest, so I am trying to roll my own basic monkeypatching support.</p> <p>I am able to replace <code>time.sleep</code> easily enough for things that just <code>impo...
<python><reflection>
2024-09-30 23:00:47
1
3,258
superstator
79,041,199
495,990
networkx: identify instances where a node is both an ancestor and descendant of another node
<p>I'm not sure if specific terminology exists for this, but I'm looking to identify paths in a directed network in which case the directionality goes both ways. I'm building a network with a bunch of provided data and by accident stumbled on some artifacts where nodes A and B are both parents/children of each other.</...
<python><networkx><digraphs>
2024-09-30 22:43:10
1
10,621
Hendy
79,041,106
13,968,392
Get lorenz curve and gini coefficient in pandas
<p>How can I get lorenz curve and gini coefficient with the pandas python package? Similar posts on the gini coefficient and lorenz curve mostly concern numpy or R.</p>
<python><pandas><plot><charts><gini>
2024-09-30 21:44:13
1
2,117
mouwsy
79,040,904
9,665,272
Python annotate adding class members in __get__
<p>I want to create a decorator that adds a member to the decorated class<br /> that is instance of outer class.</p> <p>In this case, decorator <code>memberclass</code> adds attribute <code>self</code> to the instance of <code>class y</code> that is of type <code>X</code></p> <pre class="lang-py prettyprint-override"><...
<python><python-typing><python-decorators><python-descriptors>
2024-09-30 20:11:08
1
885
Superior
79,040,746
2,288,506
Having trouble displaying an image in an Adw.AboutDialog in python
<p>I have the following file structure:</p> <pre class="lang-bash prettyprint-override"><code>. ├── resources.gresource ├── resources.xml ├── texty.py └── texty.svg </code></pre> <p>The resources.xml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &...
<python><python-3.x><gtk4>
2024-09-30 19:09:51
1
512
CraigFoote
79,040,679
3,048,453
Module not found when using UV, py-shiny and external dependency
<p>I want to create a shiny app (using py-shiny) where I manage the dependencies using <code>uv</code>.</p> <p>So far I have used the following code</p> <pre class="lang-bash prettyprint-override"><code>uv init shiny-tester cd shiny-tester uv add shiny vim app.py # see below uvx shiny run # works as expected </code></p...
<python><py-shiny><uv>
2024-09-30 18:41:57
1
10,533
David
79,040,667
249,199
In free-threaded Python without the GIL or other locks, can mutating an integer field on an object break the interpreter?
<p>As of CPython 3.13, the <a href="https://peps.python.org/pep-0703/" rel="nofollow noreferrer">Global Interpreter Lock can now be disabled</a>.</p> <p>When running without the GIL, I'm curious about what operations are safe, where &quot;safe&quot; means &quot;does not crash or corrupt the interpreter&quot;.</p> <p>Sp...
<python><multithreading><python-multithreading><race-condition><gil>
2024-09-30 18:38:16
0
4,292
Zac B
79,040,567
11,457,006
Container based AWS python Lambda function cold start time
<p>I've converted a python and R containerized lambda to a multistage build which reduced the size of the container in ECR from 477 MB to 160 MB, but the cold start time is about the same for both (in fact a bit slower for the smaller package (from 2.3 -&gt; 2.97s)</p> <p>GIVEN my Dockerfile looks like this:</p> <pre><...
<python><docker><aws-lambda>
2024-09-30 18:07:31
0
3,875
Jesse McMullen-Crummey
79,040,530
825,227
Optimal data structure for assembling data in Python
<p>I'm doing a calculation over 1M+ records, that's not individually intensive (ie, &lt;&lt;1s to complete a single calc) but in aggregate, is quite sluggish (only ~1000 data points produced per second). I'm wondering if the use of a list/append statement to create the output time series could be improved here (or, pe...
<python>
2024-09-30 17:56:32
0
1,702
Chris
79,040,327
13,142,245
Asynchronous S3 downloads in FastAPI
<p>I'm trying to add some functionality to my FastAPI application, which will asynchronously update an ML model (pulled from an S3 bucket.) The idea is to update this model once hourly without blocking the API's ability to respond to CPU-bound tasks, such as model inference requests.</p> <pre><code># Global model varia...
<python><amazon-s3><async-await><fastapi>
2024-09-30 16:57:03
1
1,238
jbuddy_13
79,040,264
2,313,889
Python `multiprocessing.Queue` hanging process
<p>For whatever reason, when using <code>Process</code> with <code>Queue</code> <code>from multiprocessing</code> the process hangs when the queue is too big. I haven't investigated yet how big the queue needs to be in order to cause this.</p> <p>My initial assumption is that the reason for the process to be hanging wa...
<python><multithreading><queue>
2024-09-30 16:37:39
1
2,031
Eduardo Reis
79,040,165
3,912,693
`pipenv install` does not properly install mysqlclient while `pip install` does
<pre class="lang-bash prettyprint-override"><code>brew install mysql-client mkdir foo &amp;&amp; cd foo export PKG_CONFIG_PATH=&quot;/opt/homebrew/opt/mysql-client/lib/pkgconfig&quot; pipenv install mysqlclient pipenv run python -c 'import MySQLdb' </code></pre> <p>exits with an error:</p> <pre><code>Traceback (most re...
<python><macos><pipenv>
2024-09-30 16:04:44
2
333
Jinux
79,040,085
9,097,114
Page refresh at incremental intervals
<p>I have hard-coded <code>if</code> conditions with multiple lines of code to refresh a webpage at every 300th iteration in <code>for</code> loop.<br /> My code is as below</p> <pre><code>if counter == 300: driver.refresh() time.sleep(20) if counter == 600: driver.refresh() time.sleep(20) if counter ==...
<python>
2024-09-30 15:42:03
1
523
san1
79,040,042
5,278,205
How can I group a spark dataframe into rows no more than 50,000 and no more than 90mb in size
<p>How can I group a spark dataframe into rows no more than 50,000 and no more than 90mb in size.</p> <p>I've tried the following but some how occasionally I get partitions greater than 90mb.</p> <pre><code>from pyspark.sql.window import Window from pyspark.sql.functions import expr, length, sum as sql_sum, row_number,...
<python><apache-spark><pyspark><apache-spark-sql>
2024-09-30 15:30:07
0
5,213
Cyrus Mohammadian
79,039,958
3,335,606
Getting Tokens Usage Metadata from Gemini LLM calls in LangChain RAG RunnableSequence
<p>I would like to have the token utilisation of my RAG chain each time it is invoked.</p> <p>No matter what I do, I can't seem to find the right way to output the total tokens from the Gemini model I'm using.</p> <pre class="lang-py prettyprint-override"><code>import vertexai from langchain_google_vertexai import Vert...
<python><langchain><google-cloud-vertex-ai><retrieval-augmented-generation>
2024-09-30 15:04:06
1
1,659
Matheus Torquato
79,039,949
14,463,396
Pandas pct_change but loop back to start
<p>I'm looking at how to use the pandas pct_change() function, but I need the values 'wrap around', so the last and first values create a percent change value in position 0 rather than NaN.</p> <p>For example:</p> <pre><code>df = pd.DataFrame({'Month':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'Value':...
<python><pandas>
2024-09-30 15:00:45
3
3,395
Emi OB
79,039,864
3,907,561
Why (x / y)[i] faster than x[i] / y[i]?
<p>I'm new to <code>CuPy</code> and CUDA/GPU computing. Can someone explain why <code>(x / y)[i]</code> faster than <code>x[i] / y[i]</code>?</p> <p>When taking advantage of GPU accelerated computations, are there any guidelines that would allow me to quickly determine which operation is faster? Which to avoid benchmar...
<python><cuda><cupy>
2024-09-30 14:37:26
1
1,167
huang
79,039,724
3,564,164
Push all dependencies to a private python package index
<p>I am building my own python package and uploading it to a private python package index using <code>devpi</code>.</p> <p>At the moment, I am installing my package this way: <code>pip install --index-url &lt;my-index-url&gt; --extra-index-url &lt;pypi-index&gt;</code>.</p> <p>The reason I am using the <code>--extra-in...
<python><pip><python-packaging><devpi>
2024-09-30 14:04:14
1
1,919
ryuzakinho
79,039,709
5,462,743
Databricks custom keep alive cluster
<p>I've upgraded my databricks cluster to 10.4 LTS to 12.2 LTS and I have a breaking change in the way we use the cluster.</p> <p>For some context, we deploy python code on Azure Machine Learning VMs that will connect to Databricks clusters.</p> <p>We have one cluster that we share between algorithms. So that all pytho...
<python><pyspark><databricks><azure-databricks><databricks-connect>
2024-09-30 14:00:47
1
1,033
BeGreen
79,039,539
10,866,453
How to use FastAPI-Cache2 package in the application
<p>I want to implement Redis caching using <a href="https://pypi.org/project/fastapi-cache2/0.1.3.3/" rel="nofollow noreferrer">FastAPI-Cache2</a> and I have implemented the caching based on the <a href="https://github.com/long2ice/fastapi-cache?tab=readme-ov-file#quick-start:%7E:text=Usage-,Quick%20Start,-from%20colle...
<python><caching><fastapi><fastapi-cache2>
2024-09-30 13:18:44
1
2,181
Abbasihsn
79,039,426
22,258,429
Is it possible to perform conditional unpacking in python?
<p>I'm currently doing an interface between several API in a python project.</p> <p>really basically, at some point, I have to call a method from a &quot;Builder&quot; object. There are two types of builders, a GetBuilder and an AggregateBuilder (I'm using the Weaviate API for people wondering). They both allow me to s...
<python><conditional-statements><unpack>
2024-09-30 12:51:00
1
422
Lrx
79,039,231
629,960
How to read async stream from non-async method?
<p>I use FastAPI to create the app. One of features is upload of files with PUT request. Fast API supports uploading files with POST requests (multipart form). But I need the PUT request where a file is just a body of a request.</p> <p>I have found that I can use a Request object and there is the stream() method to acc...
<python><asynchronous><async-await><python-asyncio><fastapi>
2024-09-30 11:48:34
1
2,113
Roman Gelembjuk
79,039,151
10,509,418
ParserError when reading csv file from github
<p>I'm getting a <code>ParserError</code> when I try to read a csv file directly from github:</p> <pre><code>import pandas as pd url = 'https://github.com/marcopeix/AppliedTimeSeriesAnalysisWithPython/tree/main/data/jj.csv' df = pd.read_csv(url) ParserError: Error tokenizing data. C error: Expected 1 fields in line 41...
<python><pandas>
2024-09-30 11:28:30
2
441
locus
79,039,087
6,438,779
How do I update an azure monitor LogSearchRuleResource using the python sdk?
<p>I'd like to use the python sdk to retrieve and then update alerts in azure monitor. However, there seems to be an issue with the sdk where it will not understand that I'm updating an existing alert - as apposed to creating a new one. Here is my example:</p> <pre><code>from azure.core.credentials import AccessToken, ...
<python><azure><rest><azure-monitor>
2024-09-30 11:10:02
1
3,561
PaulG
79,039,069
17,721,722
Cancelling All Tasks on Failure with `concurrent.futures` in Python
<p>I am using Python's <code>concurrent.futures</code> library with <code>ThreadPoolExecutor</code> and <code>ProcessPoolExecutor</code>. I want to implement a mechanism to cancel all running or unexecuted tasks if any one of the tasks fails. Specifically, I want to:</p> <ol> <li>Cancel all futures (both running and un...
<python><error-handling><concurrency><multiprocessing><concurrent.futures>
2024-09-30 11:03:24
3
501
Purushottam Nawale
79,038,972
11,638,153
How to find integer index of a string in a column in pandas dataframe?
<p>I am importing a csv file in pandas containing data like this. Referring to following code, I want to get integer index of row containing <code>name_to_search</code> in column <code>name</code> in <code>df1</code>.</p> <pre><code>name, ColB, ColC, ColD P1, 1,1,1 P2, 0,1,0 P3, 1,1,0 ... df1 = pd.read_csv(filepath_o...
<python><pandas><string><dataframe>
2024-09-30 10:37:36
3
441
ewr3243
79,038,753
1,516,331
Coroutines are stopped in asyncio.gather(*aws, return_exceptions=False) when exception happens
<p>My question is from this <a href="https://python-forum.io/thread-21211.html" rel="nofollow noreferrer">post</a>. I'll describe it here.</p> <p>I have the following Python code:</p> <pre><code>import asyncio, time async def fn1(x): await asyncio.sleep(3) print(f&quot;fn1 is called with x={x}&quot;) retu...
<python><asynchronous><async-await><python-asyncio>
2024-09-30 09:36:48
1
3,190
CyberPlayerOne
79,038,720
216,681
SQLAlchemy Many-to-Many using PostgreSQL's on_conflict_do_update doesn't get committed
<p>I'm trying to use a many-to-many relationship in SQLAlchemy with PostgreSQL. I want to take advantage of the <code>on_conflict_do_update</code>, so I have to use <code>insert</code> statements instead of creating an ORM object, adding it to the session, and committing.</p> <p>I've discovered that when an object is ...
<python><postgresql><sqlalchemy>
2024-09-30 09:29:17
1
305
Mike Benza
79,038,696
9,918,920
what input should I use to predict rl model? will it be scaled or inv scaled?
<p>I am using sb3 DQN to train stock data where my obs is last 120 candle with 7 feature i.e open high low close hour min rsi etc... . so obs shape would be (120,7) output would be discrete with 3 int 0, 1, 2 (Hold, buy, sell respectively).</p> <p>My questions are:</p> <ol> <li>I am only scaling obs using minmaxscaler ...
<python><machine-learning><artificial-intelligence><reinforcement-learning><stablebaseline3>
2024-09-30 09:24:12
0
958
manan5439
79,038,628
9,213,069
How do I set .env file using poetry in Google Colab?
<p>I'm using Google Colab for my Python project. I have created <code>pyproject.toml</code> using <code>!poetry init</code>.</p> <p>Can you please help me to load environment variable using poetry? I have <code>.env</code> file.</p>
<python><python-poetry>
2024-09-30 09:03:51
1
883
Tanvi Mirza
79,038,582
14,450,325
FFMPEG unable to stream videos frame by frame to RTMP Youtube Live stream using Python
<p>I need to open a locally stored video, process it frame by frame and send it to YouTube live RTMP stream. I am able to do it using FFMPEG in command line terminal but unable to do it using Python. In Python on console, it shows stream is properly sent but on YouTube Live control room it shows no data. I tried all ot...
<python><ffmpeg><youtube><rtmp><live-streaming>
2024-09-30 08:47:40
0
567
YadneshD
79,038,483
21,185,825
Replace Tokens - 'init' not found - name not supplied
<p>I need to replace a particular file tokens, so I have set the sources to</p> <pre><code>src/some_folder/somes_cript.py </code></pre> <p>As the pipeline is launched, the template is called and ran properly</p> <p>but I get these errors:</p> <pre><code>token pattern '__\s*((?:(?!__)(?!\s*__).)*)\s*__' transform patter...
<python><azure-devops><azure-pipelines><pipeline>
2024-09-30 08:16:21
1
511
pf12345678910
79,038,328
511,302
Why are Image Fields not being created in Django Factory Boy?
<p>I tried to follow the standard recipe for image fields in django factory boy:</p> <pre><code>class ConfigurationSingletonFactory(DjangoModelFactory): class Meta: model = Configuration django_get_or_create = (&quot;id&quot;,) id = 1 custom_theme = ImageField(color=&quot;blue&quot;, width...
<python><django><unit-testing><factory-boy>
2024-09-30 07:29:15
0
9,627
paul23
79,037,962
4,983,469
Read excel with same column names with pandas
<p>I am trying to convert an excel to csv. The excel has the following headers -</p> <pre><code>DATE,FIELD1,FEEDER BRANCH,50,100,200,500,1000,2000,FIELD2,50,100,200,500,1000,2000,FIELD3,50,100,200,500,1000,2000 </code></pre> <p>As seen, some columns are repeated. On loading the excel using pandas, it appends an index n...
<python><excel><pandas><csv>
2024-09-30 05:04:03
2
1,997
leoOrion
79,037,945
1,870,832
Visual Studio Code trying, but failing to use my uv venv
<p>I have the following code in file <em>main.py</em> file:</p> <pre class="lang-py prettyprint-override"><code>import pymupdf print(f&quot;pymupdf version is: {pymupdf.__version__}&quot;) </code></pre> <p>I can create a Python 3.12 environment with <code>pymupdf</code> installed and run it from my (<a href="https://e...
<python><visual-studio-code><uv>
2024-09-30 04:51:13
0
9,136
Max Power
79,037,841
6,293,886
nested dicts processing with irregular nesting hierarchy
<p>How can one process a pair of nested dicts with partial key overlap?</p> <pre><code>dict1 = { 'A': {'a': 1}, 'B': 2, 'C': {'c': 3}, 'D': {'d': {'dd': 4}} } dict2 = { 'A': {'a': 1}, 'D': {'d': {'dd': 4}} } </code></pre> <p>the desired output should be:</p> <pre><code>dict1 + dict2= { 'A':...
<python><dictionary>
2024-09-30 03:37:39
2
1,386
itamar kanter
79,037,822
3,667,142
Pytest equivalent for unittest-style base/derived class tests
<p>I have an older <code>Python</code> test suite that used a <code>unittest</code> class-based setup for testing, and I'm trying to convert it over to use <code>pytest</code>. An example of which is shown below where a base class with generalized tests is defined and then derived classes set class attributes that are ...
<python><pytest>
2024-09-30 03:14:58
1
1,183
wandadars
79,037,592
2,487,988
Pyplot Printing All Bars Overlapping in First Position in Grouped Bar Chart
<p>I'm generating a grouped bar chart showing what orders are ordered to arrive on what day of the week. My code is as follows:</p> <pre><code>plt.figure(1) x = np.arange(7) width = .1 for j in range(9): print(pdChart[j]) plt.bar((j-4)/10, pdChart[j], width, label=list(flavors.keys())[j]) plt.xticks(x,daysOWe...
<python><matplotlib>
2024-09-29 23:55:35
1
503
Jeff
79,037,326
235,267
Raspberry Pi (Python) - button press (and hold) to run a script loop
<p>I am trying to write a program which will flicker LEDs (and eventually - hopefully - flicker a small strip of LEDs). It's meant to look like lightning - or flickering electricity (for an electric chair halloween prop)</p> <p>I've cobbled together the following from MANY sources. The script should have the bulb start...
<python><python-3.x><raspberry-pi><raspberry-pi3>
2024-09-29 20:29:55
1
3,105
Matt Facer
79,037,283
22,407,544
Django ` [ERROR] Worker (pid:7) was sent SIGKILL! Perhaps out of memory?` message when uploading large files
<p>My dockerized Django app allows users to upload files(uploaded directly to my DigitalOcean Spaces). When testing it on my local device(and on my Heroku deployment) I can successfully upload small files without issue. However when uploading large files, e.g. 200+MB, I can get these error logs:</p> <pre><code> [2024-0...
<python><django><docker><gunicorn>
2024-09-29 20:06:14
0
359
tthheemmaannii
79,036,931
22,407,544
Why does my Celery task not start on Heroku?
<p>I currently have a dockerized Django app deployed on Heroku. I've recently added Celery with <code>redis</code>. The app works fine on my device, but when I try to deploy it on Heroku, everything works fine up until the Celery task is started. However, nothing happened, and I don't get any error logs from Heroku. I ...
<python><django><docker><heroku><redis>
2024-09-29 16:57:38
1
359
tthheemmaannii
79,036,867
1,658,617
Implementing a context-switching mechanism in asyncio
<p>I wish to create something similar to a context switching mechanism, that allows using a shared resource one at a time.</p> <p>In my case it's a single session object connecting to a website, and each context would be the current account connected to the website. As a system constraint - no two accounts can be conne...
<python><concurrency><architecture><python-asyncio><context-switch>
2024-09-29 16:36:33
1
27,490
Bharel
79,036,853
6,293,886
how to apply function on nested dictionary values
<p>I have a nested <em>dict</em> with different levels of nesting</p> <pre><code>dict1 = { 'A': {'a': 1}, 'B': 2, 'C': {'c': 3}, 'D': {'d': {'dd': 4}} } </code></pre> <p>I want to perform (for instance) key-wise multiplication. With flat dict this is straightforward:</p> <pre><code>{k: v * 2 for k, v in...
<python><dictionary>
2024-09-29 16:29:41
1
1,386
itamar kanter
79,036,744
5,544,691
Type hinting to return the same type of Sized iterable as the input?
<p>The following code works, but depending on how I fix the type hinting, either PyCharm or mypy complains about it. I've tried Sized, Iterable, and Collection for the type of S.</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar(&quot;T&quot;) S = TypeVar(&quot;S&quot;, bound=Collection[T]) def limit(i...
<python><pycharm><python-typing><mypy>
2024-09-29 15:33:49
2
503
cjm
79,036,641
8,543,025
Plotly Image ignores alpha channel
<p>I'm attempting to display a (semi) transparent image using plotly's <code>go.Image</code> object. I use <code>cv2</code> to load the image from disk and convert it to <code>rgba</code> format. Following <a href="https://github.com/plotly/plotly.py/issues/3895" rel="nofollow noreferrer">this issue</a>, I manually set...
<python><plotly>
2024-09-29 14:38:42
0
593
Jon Nir
79,036,519
4,375,983
Cannot seem to parse dates correctly in spark 3
<p>I'm trying to write a utilitary that &quot;evaluates&quot; the well formatting of dates. I cannot seem to suceed in this because I keep getting errors like :</p> <pre><code>Exception has occurred: Py4JJavaError (note: full exception trace is shown but execution is paused at: &lt;module&gt;) An error occurred w...
<python><apache-spark><date><pyspark>
2024-09-29 13:42:40
1
2,811
Imad
79,036,307
6,115,317
Python ctypes: How to raise exception when my "Material" class goes out of scope without freeing resources in C level?
<p>I'm writting a Graphics Rendering API with a &quot;Material&quot; class containing resources allocated by calling a &quot;create_material&quot; function in my C DLL, which should be accompanied by a respective &quot;destroy_material&quot; call.</p> <p>I want to raise an exception when the Material class gets destroy...
<python><memory-management><dll><ctypes><raii>
2024-09-29 11:49:57
0
409
Emanuel Kozerski
79,036,219
7,266,996
Python being sourced from multiple environments
<p>So I am using this framework called <code>frappe</code> which seems to have messed Python environment initialization.</p> <p>To provide some context, there is a command line tool named <code>bench</code> which is used to control the framework.</p> <p>The command <code>bench start</code> works with a <code>Procfile</...
<python><virtualenv><frappe>
2024-09-29 11:04:46
1
2,684
Amol Gupta
79,036,141
12,291,425
convert mouse cursor image to left-handed (horizontally flip) using python
<p>Recently I find that Windows mouse cursor is not very friently for left-handed people. Because it point from right to left.</p> <p>So I wonder if there is a way to change it to &quot;left to right&quot;. I searched the internet but havnen't found one.</p> <p>Further search give me a message that the &quot;cur&quot; ...
<python><mouse-cursor>
2024-09-29 10:11:44
0
558
SodaCris
79,036,069
2,440,692
Pandas boxplots - styling props with colors not working
<p>I would like to style all aspects of my boxplots via style sheets and apply the defined styles via plt.style.use(&quot;my_style&quot;). So the goal is to &quot;out source&quot; all the styling attributes of the chart via code and define them inside the style.</p> <p>Unfortunately not all colors are recognized. <a hr...
<python><pandas><matplotlib>
2024-09-29 09:35:03
1
1,229
neuralprocessing
79,035,737
696,836
How do I get a callback for QListWidgetItem becoming visible in PyQT5
<p>I created a simple MediaBrowser using a <code>QListWidget</code> in PyQT5:</p> <pre><code>class MediaBrowser(QListWidget): def __init__(self, database: Database, viewtab, dir_path): QListWidget.__init__(self) self.log = logging.getLogger('mediahug') self.database = database self....
<python><pyqt5><qt5>
2024-09-29 06:33:30
1
2,798
djsumdog
79,035,687
4,105,475
Unable to Trigger Lambda function in AWS using Python code from my local setup
<p>I am trying to trigger a Lambda function using Python code as follows:</p> <pre><code>import boto3 from botocore.exceptions import NoCredentialsError, PartialCredentialsError def get_lambda_client(): return boto3.client('lambda') def invoke_lambda(): lambda_client = get_lambda_client() if lambda_client...
<python><python-3.x><amazon-web-services><aws-lambda><amazon-iam>
2024-09-29 05:42:14
2
753
Humble_PrOgRaMeR
79,035,623
2,698,972
How do I remove escape characters from a JSON value in Python?
<p>I have a big JSON data with one of the keys having escape characters like :</p> <pre><code>{&quot;key&quot;:{&quot;keyinner1&quot;:&quot;\&quot;escapeddata\&quot;&quot;,&quot;keyinner2&quot;:&quot;text&quot;}} </code></pre> <p>I want to convert it to :</p> <pre><code>{&quot;key&quot;:{&quot;keyinner1&quot;:&quot;esc...
<python><json><dictionary>
2024-09-29 04:42:57
1
1,041
dev
79,035,429
18,091,627
How to install packages installed in a python Virtual Environment into a new Virtual Environment?
<p>It is as simple as the title says. I've tried:</p> <pre><code>pip install --no-index --find-links=&quot;.../another-venv/Lib/site-packages/&quot; django </code></pre> <p>but I got the error:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching ...
<python><pip><python-packaging>
2024-09-29 00:53:38
0
371
42WaysToAnswerThat
79,035,416
777,081
Can Django identify first-party app access
<p>I have a Django app that authenticates using allauth and, for anything REST related, dj-rest-auth.</p> <p>I'm in the process of formalising an API</p> <ul> <li>My Django app uses the API endpoints generally via javascript fetch commands. It authenticates with Django's authentication system (with allauth). It <em>doe...
<python><django><rest>
2024-09-29 00:42:26
1
420
gmcc051
79,035,273
1,857,915
Is there any way to catch and handle infinite recursive functions that create Tkinter windows?
<p>I have a student that submitted a function like this:</p> <pre><code>def infinite_windows(): window = tkinter.Tk() infinite_windows() </code></pre> <p>I already test things inside a try-except block. My code reports the RecursionError, but then it freezes my desktop the next time it asks for user input and ...
<python><python-3.x><tkinter><recursion>
2024-09-28 22:06:55
1
584
Kyle
79,035,217
7,106,581
How to play a mp3 file with PyScript?
<p>I want to play an mp3 file using the HTML tag like so:</p> <pre><code> &lt;audio controls&gt; &lt;source id=&quot;player&quot; src=&quot;sounds//ziege.mp3&quot; type=&quot;audio/mpeg&quot;&gt; &lt;/audio&gt; </code></pre> <p>Playing the mp3 file trough the player UI works of course but not within PyScr...
<python><pyscript>
2024-09-28 21:18:05
1
948
Peter M.
79,034,910
25,413,271
Python 2.7: difference between codecs.open(<f>, 'r', encoding=<enc>) and <string>.encode(<enc>)
<p>What is the difference between code like this:</p> <pre><code>with codecs.open(&lt;file path&gt;, 'r', encoding='my_enc') as f: json.load(f) string = json['key'] </code></pre> <p>and code like this:</p> <pre><code>with open(&lt;file path&gt;, 'r') as f: json.load(f) string = json['key'].encode('my_enc') </co...
<python><python-2.7><encoding>
2024-09-28 18:27:47
0
439
IzaeDA
79,034,526
315,168
Performance optimal way to serialise Python objects containing large Pandas DataFrames
<p>I am dealing with Python objects containing Pandas <code>DataFrame</code> and Numpy <code>Series</code> objects. These can be large, several millions of rows.</p> <p>E.g.</p> <pre class="lang-py prettyprint-override"><code> @dataclass class MyWorld: # A lot of DataFrames with millions of rows samples: pd.D...
<python><pandas><numpy><pickle>
2024-09-28 15:16:48
4
84,872
Mikko Ohtamaa
79,034,296
6,762,755
Filter a LazyFrame by row index
<p>Is there an idiomatic way to get specific rows from a LazyFrame? There's two methods I could figure out. Not sure which is better, or if there's some different method I should use.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;x&quot;: [&quot;a&quot;, &quot;b&quot;...
<python><python-polars>
2024-09-28 13:20:27
1
28,795
IceCreamToucan
79,034,285
7,123,797
Are there any practical uses for the copy() method of the frozenset objects?
<p>In Python the <code>frozenset</code> type is the only built-in immutable type that has a <code>copy()</code> method. And it looks like this method always returns <code>self</code>:</p> <pre><code>&gt;&gt;&gt; f1 = frozenset({1,2,3}) &gt;&gt;&gt; f2 = f1.copy() &gt;&gt;&gt; f1 is f2 True </code></pre> <p>I don't see ...
<python><frozenset>
2024-09-28 13:15:17
0
355
Rodvi
79,034,098
1,654,229
How to create a decorator for a FastAPI route that is able to capture the path param value?
<p>I have a FastAPI route like so:</p> <pre><code>@router.put(&quot;/{workflowID}&quot;, response_model=WorkflowResponse) async def update_workflow_endpoint( workflowID: int, workflow: WorkflowUpdateRequest, db: AsyncSession = Depends(get_db) ): ... // Remaining code </code></pre> <p>I want to write a...
<python><fastapi><decorator>
2024-09-28 11:42:11
1
1,534
Ouroboros
79,033,942
4,451,315
How to type function which returns associated type so that it works in subclass?
<p>I have a class <code>Foo</code> which has a <code>to_bar</code> method which returns <code>Bar</code>. I also have a subclass <code>MyFoo</code> for which <code>to_bar</code> returns <code>MyBar</code> (a subclass of <code>Bar</code>). <code>Foo</code> has quite a lot of methods which can return <code>Bar</code>, an...
<python><python-typing><mypy>
2024-09-28 10:16:59
0
11,062
ignoring_gravity
79,033,878
2,595,216
Make symbolic link as admin with New-Item and subprocess
<p>I got PS working CmdLet:</p> <pre class="lang-bash prettyprint-override"><code>New-Item -ItemType SymbolicLink -Path &quot;C:\Users\user1\Saved Games\Scripts\BIOS&quot; -Target &quot;C:\Users\user1\Saved Games\bios\Scripts\BIOS&quot; </code></pre> <p>I need run as Admin (of course) so wrap around <code>Start-Process...
<python><powershell><subprocess>
2024-09-28 09:36:37
0
553
emcek
79,033,795
9,592,585
Google GenerativeAI unable to load video files
<p>I was building a small Flask app with HTML templates where a user could upload a video and I would use an LLM to describe the video.</p> <p>I receive the file URL through an HTML form, which I then save to a local folder.</p> <pre><code>file_url = request.form[f'media-url-{i}'] extension = file_url.split('?')[0].spl...
<python><flask><google-generativeai>
2024-09-28 08:52:39
1
343
Shubhankar Agrawal
79,033,777
16,611,809
How to query a large file using pandas (or an alternative)?
<p>I want to query a large file that I generated from the <a href="https://ftp.ncbi.nih.gov/snp/organisms/human_9606/VCF/00-All.vcf.gz" rel="nofollow noreferrer">dbSNP VCF (16GB)</a> using this shell command:</p> <pre><code>gzcat 00-All.vcf.gz | grep -v ## | awk -v FS='\t' -v OFS='\t' '{print $3, $1, $2, $4, $4}' | gzi...
<python><pandas>
2024-09-28 08:42:02
2
627
gernophil