QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
78,543,027
4,249,338
Polars - How to drop inf rows
<p>I have a polars dataframe containing some rows with infinite values (<code>np.inf</code> and <code>-np.inf</code>) which I'd like to drop.</p> <p>I am aware of<code>drop_nans</code> and <code>drop_null</code> but I don't see a similar <code>drop_inf</code>. As I want to handle nan values separately, I cannot just re...
<python><python-polars>
2024-05-28 09:01:38
1
656
gg99
78,543,026
3,973,269
Azure app function - python, overlapping executions overwrite variables
<p>I have a function app in Azure, in which the app gathers row 0 of a cosmosDB and then sends out some emails with data.</p> <p>When the app function is triggered twice within a short period, I find that content of the first mail is overwritten with data from the 2nd execution, which contains a new row of data.</p> <p...
<python><azure-functions>
2024-05-28 09:01:28
1
569
Mart
78,542,877
1,887,919
Does matrix multiplication time-complexity only apply to large N?
<p>The time complexity of (square, naive) matrix multiplication is O(N<sup>3</sup>), e.g. <a href="https://stackoverflow.com/questions/8546756/matrix-multiplication-algorithm-time-complexity">this answer</a></p> <p>I can run a quick script</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import t...
<python><algorithm><time-complexity><matrix-multiplication>
2024-05-28 08:34:44
2
923
user1887919
78,542,765
7,161,082
Get route within azure function and python
<p>I'm searching for a way to get the route of my azure-function from the <code>app</code> or <code>req</code> object. I assume this should be straight forward. But I'm not able to find it.</p> <pre class="lang-py prettyprint-override"><code> import azure.functions as func app = func.Function(...) app.route(route...
<python><azure-functions>
2024-05-28 08:13:52
1
493
samusa
78,542,760
18,091,040
How to proper "install" the python wrapper of Indy-vdr
<p>I'm following the instructions of <a href="https://github.com/hyperledger/indy-vdr/blob/main/README.md" rel="nofollow noreferrer">Indy-vdr</a> to use its python wrapper. It says:</p> <blockquote> <p>The Python wrapper is located in wrappers/python/indy_vdr. In order for the wrapper to locate the shared library, the ...
<python><python-packaging><hyperledger-indy><indy-node>
2024-05-28 08:12:58
0
640
brenodacosta
78,542,706
955,273
Conflicting instructions between manpages and running help on the command
<p>I was recently trying to understand why running <code>pip install --upgrade</code> wasn't upgrading some packages in my virtualenv.</p> <p>Being on Ubuntu 22.04, I turned to the manpages for help.</p> <p>There I found the following:</p> <pre class="lang-none prettyprint-override"><code>-U, --upgrade Upgrade all ...
<python><linux><pip><manpage>
2024-05-28 08:02:33
1
28,956
Steve Lorimer
78,542,564
5,567,893
(Pytorch) How to get the tensors by matching values in other list?
<p>I want to select the values in a two-dimensional tensor by matching them to the list of values.</p> <pre class="lang-py prettyprint-override"><code>example #tensor([[61078, 51477, 28492, 4290, 86920, 2216], # [26799, 76684, 23785, 18202, 14552, 98301]]) a # Index([61078, 23785, 2216], dtype='int64', length...
<python><pytorch>
2024-05-28 07:37:49
2
466
Ssong
78,542,555
1,670,478
403 Forbidden Error when fetching content from a URL hosted in Zendesk
<p>When I try following python code to fetch content from a URL hosted in Zendesk, I get following 403 Forbidden Error:</p> <p>Python Code:</p> <pre class="lang-python prettyprint-override"><code>url = 'https://support.abc.com/hc...' html_content = fetch_content(url) if html_content: text_content = html_to_text(htm...
<python><fetch-api><zendesk><zendesk-api>
2024-05-28 07:36:38
1
1,956
clint
78,542,549
17,795,398
NumPy: matrix multiplication when coordinates are given separately, is there a shortcut?
<p>I'm working with particle positions in different arrays, something like (three particles):</p> <pre><code>import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 6, 1]) z = np.array([0, 3, 6]) </code></pre> <p>I do it in this way because of matplotlib 3D plots, which require to have the different coordinates in...
<python><arrays><numpy>
2024-05-28 07:35:59
1
472
Abel Gutiérrez
78,542,519
972,647
Add SSL certificate to python requests for all environments
<p>As the title states. Company enabled SSL inspection which blocks every call made by request due to ssl failure. Yes I could go the easy route and just set verify=False but that isn't really a clean and sustainable solution especially for modular code.</p> <p>Anyway from chrome I can easily get the root cert and I ca...
<python><ssl-certificate><conda><certifi>
2024-05-28 07:31:15
1
7,652
beginner_
78,542,389
11,198,558
How to customize style of django-autocomplete-light Forms
<p>I need your help on customizing the style of TextInput Box while using django-autocomplete-light.</p> <p>Specifically, I have a data model <code>TextHeader</code>, <code>UserInputDataSearch</code> then I'm creating a view object as</p> <pre><code># views.py class DataSearchAutocomplete(autocomplete.Select2QuerySetVi...
<python><django>
2024-05-28 07:01:21
0
981
ShanN
78,542,211
53,212
What is wrong with using Element.makeelement?
<p>Why does the Python documentation say this about <code>xml.etree.ElementTree</code>'s <code>Element.makeelement()</code> method?</p> <blockquote> <p>Do not call this method, use the SubElement() factory function instead</p> </blockquote> <p>It's specifically not marked as deprecated and has existed in the docs for s...
<python><elementtree>
2024-05-28 06:13:33
0
117,860
thomasrutter
78,542,042
2,443,377
Cannot install ChromaDB on python:3.12.3-alpine3.19 Docker image
<p>I am trying to install python dependencies on a python:3.12.3-alpine3.19 Docker immage. When the requirements.txt file is processed I get the following error:</p> <pre><code>7.932 ERROR: Ignored the following versions that require a different python version: 0.5.12 Requires-Python &gt;=3.7,&lt;3.12; 0.5.13 Requires-...
<python><docker><onnxruntime><chromadb>
2024-05-28 05:16:44
1
1,743
cw24
78,541,861
1,447,953
Pytest: use reduced parameter matrix unless 'slow' mark is set
<p>I have some pytest tests that run a test using a variety of different parameter combinations, like so:</p> <pre><code>class TestCases: d_prob = [0.1, 0.8] f_dens = [0.001, 0.1] r_scale = [True, False] i_corr = [True, False] # Cartesian product cart = itertools.product(d_prob, f_dens, r_scale...
<python><pytest><pytest-fixtures><pytest-markers>
2024-05-28 03:51:16
1
2,974
Ben Farmer
78,541,706
678,572
How to computing k-nearest neighbors from rectangular distance matrix (i.e., scipy.spatial.distance.cdist) in Python?
<p>I want to calculate the k-nearest neighbors using either sklearn, scipy, or numpy but from a rectangular distance matrix that is output from <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.cdist</code></a>.</p> <p...
<python><numpy><scipy><distance><nearest-neighbor>
2024-05-28 02:33:20
1
30,977
O.rka
78,541,683
11,121,557
Python CFFI `<cdata>` data pointer replace from C land - is it safe?
<p>I am trying to use CFFI to create a python C extension.</p> <p>Suppose I have the following C code:</p> <pre class="lang-c prettyprint-override"><code>void freeSomeType(SomeType_t **ptr) { free(*ptr); *ptr = NULL; } void func(SomeType_t **ptr) { freeSomeType(ptr); *ptr = malloc(...); } </code></pre>...
<python><c><cpython><python-cffi>
2024-05-28 02:22:27
1
376
Slav
78,541,610
5,651,575
Create a column aggregating column names based on boolean state of a row in Python Pandas
<p>I am attempting to scan a Pandas dataframe and identify all the columns that are True for a particular row and aggregate the column names in the output column.</p> <p>Given a sample input as follows:</p> <pre><code>a b c True False True True False False </code></pre> <p>The goal is to accomplis...
<python><pandas>
2024-05-28 01:35:14
3
617
youngdev
78,541,207
5,568,409
Why are colors so strangely showed?
<p>When running the following code, I found the two colors <code>red</code> and <code>blue</code> very strangely displayed in plot; moreover, the legend has the colors mismatched:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns maxs = [35, 31, 35, 31, 34, 30, 31, 29, 30, 33] clrs = ['red', 'blue',...
<python><seaborn><histplot>
2024-05-27 21:52:16
1
1,216
Andrew
78,541,141
896,451
Why does this two-line Python program give variable output under PyCharm?
<p>Using Windows 7, python.exe 3.8.0 and PyCharm 2019.4.5 with:</p> <p><a href="https://i.sstatic.net/JPx3Gh2C.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JPx3Gh2C.png" alt="enter image description here" /></a></p> <p>this (faulty) program</p> <pre><code>print(&quot;hello&quot;, flush=True) garbage; ...
<python><pycharm>
2024-05-27 21:25:46
2
2,312
ChrisJJ
78,541,066
3,391,549
Langchain HuggingFace embeddings no longer loading for Llama-Index?
<p>The following code worked about a week ago:</p> <pre><code>from langchain_community.embeddings import HuggingFaceEmbeddings from llama_index.embeddings.langchain import LangchainEmbedding embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name=&quot;WhereIsAI/UAE-Large-V1&quot;)) </code></pre> <p>Previousl...
<python><langchain><embedding><huggingface><llama-index>
2024-05-27 20:58:32
0
9,883
Adrian
78,540,850
1,189,239
Corner plot in log scale
<p>I am using the <code>corner</code> library to make a corner plot. However, when I set the <code>axes_scale</code> parameter to <code>log</code>, nothing changes. I know that I can put everything in log scale before plotting, but I would prefer to do it inside corner.</p> <pre><code>import numpy as np import matplotl...
<python><matplotlib>
2024-05-27 19:44:54
2
933
Alessandro Peca
78,540,765
2,194,119
How to Use Python Hypothesis in Integration Tests
<p>We've got pretty complex builder and factory classes/methods to build test/domain data for our unit tests using Hypothesis. Now for our integration tests, we'd like to use the same functionality, the only difference is that they should run only once regardless of the result of the test. One solution is to call <code...
<python><python-hypothesis>
2024-05-27 19:19:05
1
5,162
Rad
78,540,702
34,747
Deploying Flet app from a docker container using Uvicorn
<p>I am trying to run my <a href="https://flet.dev" rel="nofollow noreferrer">flet</a> as a web app from a docker container, but I am getting the following error message:</p> <pre><code>RuntimeError: asyncio.run() cannot be called from a running event loop 2024-05-27T18:46:46.450774857Z sys:1: RuntimeWarning: coroutine...
<python><docker><uvicorn><flet><asgi>
2024-05-27 18:58:59
1
6,262
fccoelho
78,540,671
1,473,517
How can I use float128 in Cython 3?
<ul> <li>Cython version: 3.0.10</li> <li>Python 3.10.12</li> </ul> <p>I have a file, <em>sum_array.pyx</em>, which is:</p> <pre><code># sum_array.pyx cimport numpy as np def sum_array(np.ndarray[np.float128_t, ndim=1] arr): cdef int n = arr.shape[0] cdef np.float128_t total = 0 cdef int i for i in rang...
<python><cython>
2024-05-27 18:47:27
2
21,513
Simd
78,540,605
2,153,235
"runfile" not aware of changes to *.py file until I open it in Spyder editor
<p>I have recently started to become familiar with the Spyder editor as a debugger. For purposes other than for debugging, however, I use my favourite external editor (Vim for me, but probably Emacs for others). I am working on a <code>MyScript.py</code> script that is not meant to be a module, in the sense that I do...
<python><ipython><spyder>
2024-05-27 18:29:24
0
1,265
user2153235
78,540,460
2,065,083
Read xml and generate dynamic object properties
<p>Complete the XMLReader class, to which we pass XML document as string to constructor, it converts the XML document into a dynamic object, in which the nodes are accessible as the object's properties and the inner XML is accessible by the text property.</p> <p>Complete the class so that it works recursively for XMLs ...
<python><xml>
2024-05-27 17:43:30
1
21,515
Learner
78,540,435
20,302,906
Can't send json reponse in requests mock
<p>I'm looking for a way to test a function called <code>fetch_options</code> that basically renders a returned JSONResponse from an internal API. My approach to this test is to mock <code>requests</code> because the internal API is located in another app which has already tested in a different test suite.</p> <p>I've ...
<python><django><python-requests><mocking>
2024-05-27 17:36:51
2
367
wavesinaroom
78,540,370
3,155,240
RelatedObjectDoesNotExist when trying to count number of objects in a Query Set
<p>I know that this error is not unique to me. I have come across many posts asking what the error is and how to fix it. One of the answers I saw was to use <code>hasattr</code> on the returned objects in a for loop before you try to get the attribute of the object. The problem is, is that I actually want to <code>coun...
<python><python-3.x><django>
2024-05-27 17:19:16
0
2,371
Shmack
78,540,300
2,335,020
FastAPI - switching out OpenAPI.json after it has been generated - where to put code?
<p>FastAPI generates the &quot;openapi.json&quot; file and provides an interface to it.</p> <p>For an experiment I need to replace this with a third party file.</p> <pre><code>from pathlib import Path import json app.openapi_schema = json.loads(Path(r&quot;myopenapi.json&quot;).read_text()) </code></pre> <p>when I put...
<python><fastapi><openapi><startup>
2024-05-27 17:00:21
1
8,442
576i
78,540,291
3,654,852
Why are similar dataframes showing two different index types?
<p>Updates: 1.I got it to work. I created another unique counter column for both dataframes and then used merge instead of concat</p> <pre><code>terminal_price['counter'] = np.arange(terminal_price.shape[0]) terminal_pnl['counter'] = np.arange(terminal_pnl.shape[0]) pnl_vs_price_df = terminal_price.merge(terminal_pnl, ...
<python><pandas><dataframe>
2024-05-27 16:56:38
1
803
user3654852
78,540,119
6,875,230
Create binary matrix from dataframe of Indices for each pair of Rows
<p>I have the following Dataframe of indexes:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 1: [(), (1, 2), (1, 2, 5, 7), (1, 2), (1, 2, 5), (1, 2)], 2: [(), (1, 2), (1, 2, 5, 7), (1, 2), (1, 2, 5), (1, 2)], 3: [(), (3, 4), (3, 4), (3, 5, 6), (3, 4,...
<python><pandas><dataframe><pyspark>
2024-05-27 16:05:57
2
528
Stefano
78,540,055
10,816,965
Convert asynchronous iterable to non-list iterable
<p>The following code works as expected:</p> <pre><code>import asyncio from collections.abc import AsyncIterable, Iterable # In reality, this is more complicated. async def create_asynchronous_iterable() -&gt; AsyncIterable[int]: for k in range(3): yield k # In reality, this is more complicated. def do_...
<python><python-asyncio><iterable>
2024-05-27 15:51:27
0
605
Sebastian Thomas
78,539,937
6,068,731
Computing effective sample size in tensorflow - Complex128 Warning
<p>When computing the effective sample size of a NumPy array as done below</p> <pre><code>import numpy as np import tensorflow_probability as tfp x = np.random.randn(1000, 2, dtype=np.float64) ess = tfp.mcmc.effective_sample_size(x) </code></pre> <p>I get the following cryptic warning:</p> <pre><code>WARNING:tensorflo...
<python><numpy><tensorflow>
2024-05-27 15:25:18
1
728
Physics_Student
78,539,906
66,473
Logic behind adding keyboard callback in Flet app
<p>The following code feels a bit counterintuitive (you are deleting something defined later in code) but works:</p> <pre><code>import flet as ft def main(page: ft.Page): def on_keyboard(e: ft.KeyboardEvent): page.remove(cntnr) page.update() page.on_keyboard_event = on_keyboard cntnr = ft...
<python><flet>
2024-05-27 15:20:36
1
9,041
Alex Bolotov
78,539,835
1,304,247
Running Python package and unittests do not work at the same time
<p>Error in structuring and running Python code</p> <p><strong>Directory Structure:</strong></p> <pre><code>project ├── library │ ├── __init__.py │ ├── time_calculator.py │ ├── distance_calculator.py │ ├── weight_calculator.py │ ├── calculator.py │ │ │ └── tests │ ├── __init__.py │ └── unittes...
<python><python-3.x>
2024-05-27 15:07:11
2
1,241
wafers
78,539,834
16,436,095
Correct way to mocking of httpx response
<p>I build API with Litestar, and I have several methods that internally call functions with asynchronous network requests.</p> <pre class="lang-py prettyprint-override"><code># routs.py class TokenController(Controller): @post(&quot;/check-token&quot;) async def check_token(self, data: SomeSchema) -&gt; Resp...
<python><mocking>
2024-05-27 15:06:45
0
370
maskalev
78,539,830
8,372,455
Fernet key must be 32 url-safe base64-encoded bytes error despite correct key length
<p>I'm working on a Python project using <code>aiohttp</code> and <code>aiohttp_session</code> with <code>EncryptedCookieStorage</code> for session management. I'm generating a Fernet key in a batch script and passing it to my Python application via an environment variable. However, despite the key being of the correct...
<python><session><cryptography><session-cookies><web-development-server>
2024-05-27 15:06:22
1
3,564
bbartling
78,539,704
850,781
Conda update flips between two versions of the same package from the same channel
<p>This is the continuation of <a href="https://stackoverflow.com/q/78512062/850781">my previous question</a>.</p> <p>Now, with both <code>channel_priority: flexible</code> and <code>channel_priority: strict</code>, every <code>conda update -n base --all</code> flips between</p> <pre><code>The following packages will b...
<python><conda><miniconda>
2024-05-27 14:36:18
1
60,468
sds
78,539,623
1,838,726
How to reorder (re-index) the vertices of a graph in graph-tool - efficiently?
<p>I use graph-tool (I love it for its sheer speed) with python as a basis for developing and running own graph algorithms. Sometimes I want to reorder the vertices of the graph, i.e. the indices of the vertices, like swapping vertex indices, without changing the topology of the graph. This doesn't seem to be a standar...
<python><algorithm><graph><graph-tool>
2024-05-27 14:17:53
0
6,700
Daniel S.
78,539,617
3,765,883
'str' object is not callable error in Python/Selenium web-scraping script
<p>I have a very simple Python/Selenium web-scraping script, as follows:</p> <pre><code>from re import L from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By cService = webdriver.ChromeService(executable_path=&quot;C:\\Users\\Frank\\Documents\\Visua...
<python><selenium-webdriver>
2024-05-27 14:15:18
1
327
user3765883
78,539,509
18,910,865
CLI Tool Fails to Recognize New Arguments During Direct Execution with Python-Fire
<p>I'm working on a CLI in Python and I don't know why the main class of the CLI does not update as new arguments are added, performing the tool using <code>python-fire</code>.</p> <p>I've mainly 2 scripts that rule the CLI: <code>main.py</code> and <code>cli.py</code></p> <p><code>main.py</code> is structured as follo...
<python><arguments><command-line-interface><python-poetry><python-fire>
2024-05-27 13:57:37
0
522
Nauel
78,539,421
2,667,066
Reorder "ragged" numpy array defined by offsets (i.e. contiguous slices)
<p>I have a long 1D numeric data array of bytes (e.g. chars) along with a set of offsets which define a set of contiguous slices along the array (e.g. these could correspond to words). Here's an example, showing the character equivalent of each byte:</p> <pre><code>data = np.array(['h', 'e', 'l', 'l', 'o', 't', 'h', 'e...
<python><numpy><ragged>
2024-05-27 13:39:39
1
2,169
user2667066
78,539,418
5,568,409
Python, scipy, gamma.rvs ans rng
<p>I am trying to sample from the <code>gamma</code> distribution and would like to &quot;fix&quot; the sample I get.</p> <p>What I do is:</p> <pre><code>from scipy.stats import gamma gamma.rvs(a = 20, loc = 0, scale = 1/2, size = 10) </code></pre> <p>and this gives me a different array of values, each time I run the c...
<python><random><scipy><generator>
2024-05-27 13:38:59
0
1,216
Andrew
78,539,135
7,031,021
How to avoid InterpolationResolutionError with hydra config variables in vsCode notebooks
<p>I know that hydra is only limited when it comes to using it in notebooks but the reality is that many projects have at least some notebooks that might need the same set of configurations.</p> <p>I would like to know how to load variables in a notebook that use config variables like:</p> <pre><code>conf.yaml paths: ...
<python><visual-studio-code><jupyter-notebook><fb-hydra>
2024-05-27 12:39:15
2
510
RSale
78,539,092
7,808,647
How to provide additional information on enum values to an LLM in LangChain
<p>I'm trying to extract structured information with an LLM say GPT-4 using LangChain in python. My goal is to classify companies by associating them with tags.</p> <p>My output class is of the type:</p> <pre><code>from langchain_core.pydantic_v1 import BaseModel class Company(BaseModel): industry: list[Industry] ...
<python><enums><large-language-model><py-langchain>
2024-05-27 12:30:36
1
522
antti
78,538,780
12,242,085
How to assign appropriate ZipCode from one table to geographical data from anothr table in PySpark / Python?
<p>I have in PySpark:</p> <p><strong>Input data:</strong></p> <ol> <li>table location_df with columns:</li> </ol> <ul> <li><p>location <code>(values: Canada, Costa Rica, Mexico, Puerto Rico, United States)</code></p> </li> <li><p>answer_label</p> <p>(values: ['Guadalajara', 'San José', 'Heredia', 'Puntarenas', 'Do not ...
<python><pyspark><geolocation>
2024-05-27 11:27:01
1
2,350
dingaro
78,538,536
4,271,491
How to parse a huge amount of json files effectively in pyspark
<p>I'm trying to parse around 100GB of small json files using pySpark. The files are stored in a google cloud bucket and they come zipped: *.jsonl.gz <br> How can I do it effectively?</p>
<python><pyspark><google-cloud-dataproc>
2024-05-27 10:28:24
0
528
Aleksander Lipka
78,538,476
9,134,545
Airflow DockerOperator: argument list too long
<p><strong>The Problem:</strong></p> <p>I've a DAG wherere I basically launch a docker Container with a bunch of volumes and environment variables.</p> <p>One of these Environment variables is a Json String that must be computed with Python Code and then supplied to the DockerOperator. This JSON String serves as a conf...
<python><docker><airflow>
2024-05-27 10:16:08
0
892
Fragan
78,538,178
135,749
Python httpx log all request headers
<p>How can I log all request headers of an httpx request? I use log level DEBUG nad response headers log fine but there are no request headers in the log. If it matters I'm using async api of httpx lib.</p>
<python><httpx>
2024-05-27 09:12:58
1
1,034
Grigory
78,538,094
6,221,742
Poor predictions with phophet
<p>I am trying to make forecasting in my dataset using prophet but my results are very poor. I tried adding seasonality and and seasonality mode but the results on MAE and R-squared are very low. Here's an overview of my dataset</p> <p><a href="https://i.sstatic.net/Lx0x7Kdr.png" rel="nofollow noreferrer"><img src="htt...
<python><time-series><forecasting><facebook-prophet>
2024-05-27 08:55:33
0
339
AndCh
78,538,033
4,340,985
How to turn a df column into a multiindex column?
<p>I have a dataframe with a column multiindex and various data columns:</p> <pre><code> id value1 value2 valuen name date foo 01-2000 No01 324 6575 ... bar 02-2000 No02 964 0982 ... </code></pre> <p>Now I need to turn <code>id</code> into a number (<code>df['id'] = df[id].str[...
<python><dataframe><multi-index>
2024-05-27 08:44:08
0
2,668
JC_CL
78,537,817
1,084,174
ImportError: cannot import name 'DILL_AVAILABLE'
<p>I want to work with IMDB datasets. Trying to load using following command:</p> <pre><code>from torchtext.datasets import IMDB train_iter = IMDB(root='~/datasets', split='train') </code></pre> <p>I am getting following error:</p> <pre><code>ImportError: cannot import name 'DILL_AVAILABLE' from 'torch.utils.data.datap...
<python><pytorch><compiler-errors><dataset><torchtext>
2024-05-27 07:55:39
1
40,671
Sazzad Hissain Khan
78,537,678
3,595,995
Pyspark 3.5.0 fixing vulnerabilities in JAR files
<p>I'm working on a Python project that depends on PySpark 3.5.1.</p> <p>During the CI/CD pipeline, a Nexus scan identified vulnerabilities in PySpark's dependencies:</p> <ol> <li>avro-ipc-1.11.2.jar</li> <li>jackson-mapper-asi-1.9.13.jar</li> </ol> <p>These JAR files are sub-dependencies of PySpark.</p> <p>We use a pl...
<python><pyspark><python-poetry>
2024-05-27 07:23:52
0
445
PremKumarR
78,537,509
1,142,881
Postgres connection URL options stopped working switching from PG11 to PG14
<p>I have a codebase that relies on a connection to Postgres via a full self-contained connection URL. The Python codebase was working while on PG11 but after switching to PG14 the options in the connection URL are no longer recognized:</p> <pre><code>postgresql://username:password@host:port/database?&amp;options=-csea...
<python><postgresql><psycopg2><postgresql-14><postgresql-11>
2024-05-27 06:38:51
1
14,469
SkyWalker
78,537,429
12,091,935
Create multiple modified versions of a script for submission to cluster
<p>I am trying create child scripts from one parent script where a few parameters are modified (48 child scripts, so automation would be preferred). My intention for this is to run different Modelica scripts as individual Slurm jobs. I would normally do this with the Modelica scripting language, but since I need to sub...
<python><text-manipulation>
2024-05-27 06:14:10
1
435
Luis Enriquez-Contreras
78,537,407
2,702,249
Packaging python script with it's dependent packages in single packages
<p>I have a situation:</p> <p>In macOS machine with <code>Python 3.6.8</code>, I wrote single python script called <code>publisher.py</code> which uses <code>pycrypto</code> package. Everything runs as expected.</p> <p>Now, I need to put my code in a shared location of production Linux env, from where hundreds of devel...
<python><pip><package>
2024-05-27 06:06:23
1
7,743
Om Sao
78,537,167
126,833
Exception occurred in file 'chrome.py', line 64: 'NoneType' object has no attribute 'split'
<p>I am using pyhtml2pdf for converting HTML to PDF which has a requirement of Chrome headless.</p> <p>When the server is run as <code>python manage.py runserver</code> there is no issue.</p> <p>But when the django is run as a service it throws and error regarding split with chrome.py :</p> <pre><code>Exception occurre...
<python><django><selenium-chromedriver>
2024-05-27 04:16:39
2
4,291
anjanesh
78,537,131
9,737,855
Dealing with a very large xarray dataset: loading slices consuming too much time
<p>I have a very large netcdf dataset consisting of daily chunks data from April 1985 to April 2024. As the arrays are divided into daily chunks, I often open them by using <code>ds = xr.open_mfdataset(*.nc)</code>. The entire dataset has up to 1.07TB, which is way way far than I can handle loading into memory:</p> <p>...
<python><dask><python-xarray>
2024-05-27 04:01:17
1
311
Gabriel Lucas
78,537,075
2,555,706
Why is "dict[int, int]" incompatible with "dict[int, int | str]"?
<pre class="lang-py prettyprint-override"><code>import typing a: dict[int, int] = {} b: dict[int, int | str] = a c: typing.Mapping[int, int | str] = a d: typing.Mapping[int | str, int] = a </code></pre> <p>Pylance reports an error for <code>b: dict[int, int | str] = a</code>:</p> <pre class="lang-none prettyprint-over...
<python><python-typing><type-theory>
2024-05-27 03:25:43
2
426
keakon
78,536,986
4,451,521
a chat with gradio (how to modify its screen appearance)
<p>I wrote this very simple script</p> <pre><code>import requests import gradio as gr import json def chat_response(message, history, response_limit): return f&quot;You wrote: {message} and asked {response_limit}&quot; with gr.Blocks() as demo: gr.Markdown(&quot;# Data Query!&quot;) with gr.Row(): ...
<python><gradio><gradio-chatinterface>
2024-05-27 02:38:10
1
10,576
KansaiRobot
78,536,915
395,857
How use Gradio's gr.Button.click() so that it passes a local variable that is not a Gradio block to the called function?
<p>Example:</p> <pre><code>import gradio as gr def dummy(a, b): return '{0} {1}'.format(a, b) with gr.Blocks() as demo: a = 'Hello ' txt = gr.Textbox(value=&quot;test&quot;, label=&quot;Query&quot;, lines=1) answer = gr.Textbox(value=&quot;&quot;, label=&quot;Answer&quot;) btn = gr.Button(value=&q...
<python><gradio>
2024-05-27 01:49:19
1
84,585
Franck Dernoncourt
78,536,889
4,348,400
How to implement a mixture of gamma distributions in Python without Bayes'?
<p>I am trying to create examples to compare and contrast <a href="https://en.wikipedia.org/wiki/Bayesian_inference" rel="nofollow noreferrer">Bayesian</a> <a href="https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo" rel="nofollow noreferrer">MCMC</a> (e.g. <a href="https://arxiv.org/pdf/1701.02434" rel="nofollow ...
<python><scipy><statistics><distribution>
2024-05-27 01:36:34
1
1,394
Galen
78,536,748
2,276,054
Or-Tools CP-SAT: how to define goal function to minimize number of unique booked rooms?
<p>I'm starting to learn <code>ortools.sat.python</code> / <code>cp_model</code> and I am confused as how to use <code>model.minimize()/maximize()</code>.</p> <p>Let's take an example simple problem of booking meetings to timeslots and rooms:</p> <pre><code>model = cp_model.CpModel() bookings = {} for m in meetings: ...
<python><or-tools><cp-sat>
2024-05-26 23:59:33
1
681
Leszek Pachura
78,536,720
5,284,054
Python MySQL: DatabaseError: 1364 (HY000): Field 'emp_no' doesn't have a default value
<p>I've installed MySQL on my Windows desktop. The installation was successful. I downloaded the <code>employees</code> data from github and added it to my MySql server. I confirmed that through the <strong>MySQL 8.4 Command Line Client</strong></p> <p>I'm working through the Documentation for the MySQL Connector/P...
<python><mysql><mysql-python>
2024-05-26 23:42:15
2
900
David Collins
78,536,693
4,730,164
change pandas index value base on column condition
<p>I want to change an index value for a specific column condition.</p> <p>Here an example</p> <pre><code>import pandas as pd data = { &quot;Product&quot;: [&quot;Computer&quot;, &quot;Printer&quot;, &quot;Monitor&quot;], &quot;Price&quot;: [120, 25, 40], } df = pd.DataFrame(data, index=[&quot;Item_1&quot;, &...
<python><pandas>
2024-05-26 23:17:31
1
753
olivier dadoun
78,536,595
4,445,584
PySide2 QWebEngineView does not play mp4, mkv, avi, mov and wmv video files
<p>I just write a simple applications for Windows using PySide2 and Python 3.8 that is a reduced web browser (it can not navigate everywhere but only in some specific web pages) and it has to open html pages embedding audio or video files or just pointing to audio and video files. Everything works apart for the major p...
<python><mp4><pyside2>
2024-05-26 22:09:58
0
475
Massimo Manca
78,536,551
845,210
"Variable not allowed in type expression" - how can I create parameterized typing.Annotated types?
<p>I'm not sure if this is possible in Python, but I'd like to create a series of related <code>typing.Annotated</code> referring to the same underlying type, but where each is constrained to a different set of values (ideally using enums, but that isn't crucial), and annotated with metadata about what it accepts. I co...
<python><mypy><python-typing><pyright>
2024-05-26 21:46:41
0
3,331
bjmc
78,536,496
3,765,883
Selenium how to find button that is part of a 'flex flex-col md:grid class
<p>Using Selenium in Python, I want to click on a button with text 'View Active', but Selenium can't find it when searching for 'View Active'. Looking at the code with 'inspect' (see below), I see the following for the 'flex-col' class containing the button. I can see the button text, but I don't know how to access i...
<python><selenium-webdriver>
2024-05-26 21:14:38
3
327
user3765883
78,536,443
20,969,632
Moviepy not updating FFmpeg Version after FFmpeg Install?
<p>I've been toying around with MoviePy, and recently switched a project to a new computer at home to continue messing around with it. However, I tried running what I had previously written (which ran perfectly fine on the other computer) and I get this:</p> <pre><code>OSError: MoviePy error: failed to read the first f...
<python><ubuntu><ffmpeg><moviepy><crostini>
2024-05-26 20:48:40
1
355
The_ Game12
78,536,181
25,091,707
why does my discord tasks start at random times?
<p>I built a bot to ping people at certain time in the day (for fun lol) but the bot seems to randomly ping at random times in the day and doesn't print a message to terminal as it should've if it were a usual ping. This has happened twice already and caused a lot of frustration since obviously people don't really like...
<python><discord><discord.py><bots>
2024-05-26 18:40:31
1
343
Matt
78,536,066
10,426,490
Unable to get Azure Document Intelligence service to process a 1000pg. PDF
<p>I can't find any information on this. Currently using a Premium App Service Plan-hosted Azure Function with <code>functionTimeout</code> set to <code>00:30:00</code> but still timing out.</p> <p><strong>PDF specs</strong>:</p> <ul> <li>1000 pages</li> <li>30MiB</li> <li>Scanned documents, no text</li> </ul> <p><stro...
<python><azure><azure-form-recognizer>
2024-05-26 17:54:26
1
2,046
ericOnline
78,536,048
12,321,900
Is it possible to install only the Scipy stats module with pip?
<p>For my project I am only needing to import the stats and optimize module from Scipy. I would like to know if it is possible to install only these modules with pip? What alternatives do I have?</p>
<python><pip><scipy><pyodide>
2024-05-26 17:47:22
1
307
Sebastian Jose
78,535,999
2,520,186
How to reorganize data to correctly lineplot in Python
<p>I have the following code that plots <code>ydata</code> vs <code>xdata</code> which is supposed to be a circle. The plot has two subplots -- a lineplot with markers and a scatter plot.</p> <pre><code>import matplotlib.pyplot as plt xdata = [-1.9987069285852805, -1.955030386765729, -1.955030386765729, -1.8259096357...
<python><list><matplotlib><plot>
2024-05-26 17:30:42
2
2,394
hbaromega
78,535,743
2,845,095
Two Sample Z-Test on Pandas dataframe
<p>I have a pandas dataframe that looks like this.It is a frequency table.</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>landing_page</th> <th>0</th> <th>1</th> </tr> </thead> <tbody> <tr> <td>new_page</td> <td>128045</td> <td>17264</td> </tr> <tr> <td>old_page</td> <td>127785</td> <td>174...
<python><pandas><z-test>
2024-05-26 15:40:15
2
533
user2845095
78,535,555
7,958,562
Python - Stream file
<p>I want to stream upload a file to a webserver. To achieve this I found this library: <a href="https://github.com/requests/toolbelt#multipartform-data-encoder" rel="nofollow noreferrer">https://github.com/requests/toolbelt#multipartform-data-encoder</a></p> <p>The code looks pretty straight forward:</p> <pre><code>fr...
<python>
2024-05-26 14:34:11
0
437
John
78,535,480
15,648,070
SqlAlchemy Autocommit mode not commiting
<p>Having some issues setting up an autocommit session</p> <p>The create_audit_log function doesn't &quot;create&quot; the new record without having <code>s.commit()</code> afterwards</p> <p>SqlAlchemy version <code>2.0.30</code></p> <p>psycopg2-binary version <code>2.9.9</code></p> <p>My code</p> <pre><code>import log...
<python><sqlalchemy><autocommit>
2024-05-26 14:04:38
1
636
Eyal Solomon
78,535,453
12,358,733
Google ADCs don't seem to work using Python on Windows 11 / Gcloud SDK 475.0.0
<p>So just migrated from a Windows 10 to Windows 11 machine and notice Python scripts don't seem to be picking up Google ADCs. I'm repeatedly getting this error:</p> <p><code>Reauthentication is needed. Please run 'gcloud auth application-default login' to reauthenticate.</code></p> <p>Python code uses <a href="https:...
<python><google-cloud-platform><google-oauth><gcloud>
2024-05-26 13:50:39
1
931
John Heyer
78,535,203
5,790,653
Find one value between two lists of dicts, then find another same value based on first similarity
<p>This is my code:</p> <pre class="lang-py prettyprint-override"><code> from collections import defaultdict ip_port_device = [ {'ip': '192.168.1.140', 'port_number': 4, 'device_name': 'device1'}, {'ip': '192.168.1.128', 'port_number': 8, 'device_name': 'device1'}, {'ip': '192.168.1.56', 'port_number': 14...
<python>
2024-05-26 12:03:28
2
4,175
Saeed
78,535,147
10,542,284
How do I know when a program is waiting for an input and then give the input through Python?
<p>Sorry, this might look very stupid but I have a console <code>C++</code> program and I need to pass input through <code>Python</code>. It is unexpected when this <code>C++</code> program waits for an input and so I hoped I could have done this programmatically. Probably there's a way with <code>Windows API</code> bu...
<python><winapi><stdin>
2024-05-26 11:45:47
0
473
Jugert Mucoimaj
78,534,807
5,686,015
Pandas: Convert rows in a single index datafram to columns in a multilevel index dataframe
<p>I've the following dataframe:</p> <pre><code> month name product category Metric Flipkart Active 0 April Accessories Stock Quantity NaN 1808.00 1 April Accessories Stock Quantity 0.0 NaN 2 May Accessories Sales Quantity NaN ...
<python><pandas><dataframe><pivot-table>
2024-05-26 09:22:45
1
1,874
Judy T Raj
78,534,514
3,184,779
How to solve grpc error in fetching data from GA4 API (google-analytics-data api) by python
<p>I am using this code snippet to get data from GA4:</p> <pre><code> credentials = service_account.Credentials.from_service_account_info(self.credential_info) client = BetaAnalyticsDataAsyncClient(credentials=credentials) offset = 0 # Start at the first row limit = 100000 # Maximum number of rows to return per re...
<python><python-3.x><google-analytics><google-analytics-api><google-analytics-4>
2024-05-26 07:06:52
0
387
Mehdi Mirzaei
78,534,458
2,050,158
How deserialize langchain_core.messages.ai.AIMessage
<p>I would like to reconstruct an object of langchain_core.messages.ai.AIMessage from the dict obtained from an object of type langchain_core.messages.ai.AIMessage.</p> <p>Is there a constructor I can use?</p> <p>The documentation of &quot;langchain_core.messages.ai.AIMessage&quot; seems not to include information on t...
<python><langchain>
2024-05-26 06:34:26
1
503
Allan K
78,534,378
6,915,206
No DATABASE_URL environment variable set, and so no databases setup
<p>While Deploying Django website on AWS EC2 server I am getting error</p> <blockquote> <p>No DATABASE_URL environment variable set, and so no databases setup.</p> </blockquote> <p>I Created a gunicon.service file on my server location <code>/home/ubuntu/lighthousemedia/LightHouseMediaAgency</code> and set <code>Enviro...
<python><django><postgresql><amazon-web-services><gunicorn>
2024-05-26 05:42:00
1
563
Rahul Verma
78,534,257
3,628,240
Scraping a site with embedded Google Maps
<p>I'm taking a look at this site: [redacted]</p> <p>Is there a way to scrape the red pins on Google Maps? When you click on a pin, you get the name, address, and phone number. Ideally I would like to be able to create a list of the locations.</p> <p>Is there a way to do this using APIs? I don't see one when I check th...
<python><selenium-webdriver><web-scraping>
2024-05-26 04:07:52
1
927
user3628240
78,534,246
12,870,750
ezdxf python - How can I set the plot transparency configuration in the plotsettings of a layout?
<p>I have a code that plots a layout created with ezdxf, but I have trouble setting my plot transparency option, because I have a external reference with an image that I want to be 40% transparent.</p> <p>This is the code I use for plotting the whole dxf file, but I dont know how to set the transparency option to True ...
<python><win32com><autocad><ezdxf>
2024-05-26 03:56:55
1
640
MBV
78,534,210
1,107,474
Plotly, convert epoch timestamps (with ms) to readable datetimes?
<p>The below code uses Python lists to create a Plotly graph.</p> <p>The timestamps are Epoch milliseconds. How do I format the x-axis to readable datetime?</p> <p>I tried <code>fig.layout['xaxis_tickformat'] = '%HH-%MM-%SS'</code> but it didn't work.</p> <pre><code>import plotly.graph_objects as go time_series = [171...
<python><plotly>
2024-05-26 03:25:04
1
17,534
intrigued_66
78,534,013
7,498,328
Python code for counting the number of Yahoo emails maxes out at 10,000 emails, how to fix?
<p>I have code that uses Python to programmatically count the number of emails in each of the mailboxes of my Yahoo email account. The issue is that it maxes out at 10,000 even though some of my inboxes have over 80,000 emails. Would anyone have any ideas how this can be fixed? My code is as follows. Thanks!</p> <pre><...
<python><email><yahoo-mail>
2024-05-26 00:35:06
1
2,618
user321627
78,533,984
233,428
Implementing a weighted loss function in SFTTrainer
<p>Currently you can let SFTTrainer teach your models to learn to predict every token in your dataset, or you can let it train on &quot;completions only&quot;, using the <code>DataCollatorForCompletionOnlyLM</code> class.</p> <p>I would like something in between, where certain tokens have a higher weight than others.</...
<python><pytorch><huggingface-transformers><huggingface-trainer>
2024-05-26 00:01:05
0
22,155
Jelle De Loecker
78,533,861
5,306,861
Python silently crashes after building scipy from source code, when `import _ufuncs`
<p>I built scipy from source code according to this <a href="https://docs.scipy.org/doc/scipy/building/index.html#building-from-source" rel="nofollow noreferrer">guide</a> on Windows, the build was successful, The build was with command: <code>python dev.py build --with-scipy-openblas</code>.</p> <p>Now I run Python an...
<python><scipy>
2024-05-25 22:24:49
1
1,839
codeDom
78,533,823
5,053,483
Flattening groups of indices in a numpy array
<p>Suppose I have a four-dimensional array and I would like to flatten the first two indices and the last two indices. For example, with a 2x2x2x2 array, this would yield a (2x2)x(2x2)=4x4 array. How can I do this?</p> <p>In other words, I want to reindex an array in the fashion of</p> <p><code>A_new[2*n+m,2*q+p] = A_o...
<python><numpy><numpy-ndarray>
2024-05-25 22:02:41
2
482
BGreen
78,533,795
12,139,954
Streamlit multipage app crashes on import pandas or import plotly.express statement
<p><strong>EDIT: Solution that worked for me</strong></p> <p>instead of using conda environment, I created environment using pip and it stopped crashing. Don't know what is the issue with conda based environment.<br /> <strong>EDIT End</strong></p> <p>--</p> <p>the code is more or less a copy paste of sample code given...
<python><streamlit>
2024-05-25 21:44:51
0
381
Ani
78,533,683
7,318,120
how to inherit from tkinter
<p>I see two methods for using the <code>tkinter</code> module with python classes.</p> <ul> <li>the first method uses the <code>super()</code> method.</li> <li>the second method does not.</li> </ul> <p>So the example code looks like this:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk class...
<python><class><tkinter>
2024-05-25 20:48:01
1
6,075
darren
78,533,563
1,601,580
How do we dispatch many multiprocessing jobs robustly in Python without memory errors?
<p>I'm working on a Python project where I need to run a large grid search optimization using multiprocessing. My challenge is to dispatch a large number of jobs without running into memory issues.</p> <p>Here's my current approach:</p> <ol> <li>Memory Check Function: Checks if the current memory usage is within a spec...
<python><multiprocessing><scipy-optimize>
2024-05-25 19:50:08
0
6,126
Charlie Parker
78,533,165
8,521,346
Selenium Standalone Chrome Allow Multiple Simultaneous Executions
<p>I have an app that allows users to click a button that performs a webscraping task using selenium. During dev with a webdriver.exe file, this works fine, but we decided to use the <code>selenium/standalone-chrome</code> docker image for production.</p> <p><code>driver = webdriver.Remote(&quot;http://127.0.0.1:4444/w...
<python><docker><selenium-webdriver>
2024-05-25 17:07:25
1
2,198
Bigbob556677
78,533,162
274,579
How to define separator characters for argparse?
<p>Python's <code>argparse</code> module is a powerful tool for parsing script command line arguments. The problem is that it expects the args to be separated by spaces. Is there a way to let <code>argparse</code> know I am using a comma-separated args list instead of space-separated args list, especially for the posit...
<python><python-3.x><command-line-arguments><argparse>
2024-05-25 17:06:35
2
8,231
ysap
78,533,152
1,128,648
Unable to upload file to gdrive using gdrive api with service account
<p>I am using a service account created in Google cloud platform to upload csv files to gdrive using a python script. This script was working file till yesterday but now I am getting below error.</p> <p>Script:</p> <pre><code>scopes = ['https://www.googleapis.com/auth/drive'] gdrive = 'D:/common-modules/gdrive.json' fo...
<python><google-cloud-platform><google-drive-api>
2024-05-25 17:03:21
1
1,746
acr
78,533,132
1,132,175
Ray serve error: serve.run throws utf-8 can't decode byte 0xf8 in position 0 invalid byte
<p>I am trying to run <code>serve.run</code> in my test method but when the test runs, it throws an error in this part of the code:</p> <p><code>serve.run(RayFastApiWrapper.bind(), route_prefix=settings.app_root_url)</code></p> <p>FastApiWrapper looks like this:</p> <pre><code>@serve.deployment(ray_actor_options={&quot...
<python><fastapi><ray>
2024-05-25 16:54:22
1
597
Jorge Cespedes
78,533,107
590,335
ibis: select map on array value works with table object but not with the underscore operation
<p>for a table with a list field i'm trying to call map</p> <pre><code>import ibis from ibis import _ t = ibis.memtable({ 'i': [1,2,3], 'x': [[1,2],[3,5],[6,7] ] }) </code></pre> <p>using the table object works:</p> <pre><code>t.select(t.x.map(_ + 1)) </code></pre> <p>but using the underscore api (<a href="h...
<python><ibis>
2024-05-25 16:47:33
1
8,467
Ophir Yoktan
78,532,969
373,121
How to make Python VSCode Intellisense work with dynamically imported versioned API modules
<p>I have a Python client library that supports multiple versions of a server by dynamically loading a different &quot;API&quot; module depending on which version of the server is connected to.</p> <p>Once that module is loaded, the API content is fully determined. The implementing class has complete comments and even ...
<python><python-typing><pyright>
2024-05-25 15:56:49
0
475
Bob
78,532,840
552,247
Handling Synchronous Socket Reads and Asynchronous Events in Python
<p>As an educational project, I'm working on a Python application that involves multiple threads, each blocked on a synchronous socket read operation. I need these threads to also respond to two types of events: individual thread-specific events and broadcast events that all threads should respond to. The challenge is ...
<python><multithreading><sockets>
2024-05-25 15:06:08
1
1,598
mastupristi