QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,319,132
8,947,889
How do you use custom prompts with LangChains RetrievalQA without specifying from_chain_type?
<p>According to <a href="https://python.langchain.com/docs/use_cases/question_answering/vector_db_qa" rel="nofollow noreferrer">LangChain's documentation</a>,</p> <p>&quot;There are two ways to load different chain types. First, you can specify the chain type argument in the from_chain_type method. This allows you to p...
<python><chatbot><langchain><large-language-model>
2023-10-18 19:33:58
1
677
Stephen Strosko
77,319,016
10,219,001
Pandas extract substring between two characters
<p>I have a dataframe column in pandas which contains a long piece of text</p> <pre><code> Value_column Car:&quot;Ford&quot;,Colour:&quot;Black&quot;, Price:2000, </code></pre> <p>I'd like to split this into three columns</p> <p>So it would look like</p> <pre><code>Car Colour Price Ford Black ...
<python><pandas>
2023-10-18 19:09:57
2
2,155
fred.schwartz
77,318,902
17,653,423
Why using yield instead of return in pytest fixtures?
<p>I see why using <code>yield</code> keyword when we want to run our tests and then clean things up going back to the fixture and running some code after the <code>yield</code> statement. As the code below.</p> <pre><code>@pytest.fixture def sending_user(mail_admin): user = mail_admin.create_user() yield user ...
<python><python-3.x><pytest><pytest-mock>
2023-10-18 18:50:31
1
391
Luiz
77,318,838
14,179,793
How to diagnose docker compose "Attaching to ..." taking a long time?
<p>We have a repo that uses a python subprocess to call docker compose and run a container that processes an input file and produces a new output file. For most files this works as expected, but it appears that as the file grows in size the &quot;Attaching to ...&quot; step takes significantly longer.</p> <p>I am not s...
<python><docker><docker-compose>
2023-10-18 18:38:06
0
898
Cogito Ergo Sum
77,318,785
11,827,673
How do I detect the usage of a ContextManager in Python?
<p>I am trying to refactor the following:</p> <pre class="lang-py prettyprint-override"><code>with MyContext() as ctx: ctx.some_function() </code></pre> <p>...into something more like this:</p> <pre class="lang-py prettyprint-override"><code>with MyContext(): some_function() </code></pre> <p>How can I detect in...
<python><refactoring><contextmanager>
2023-10-18 18:28:28
2
378
JeremyEastham
77,318,623
4,953,820
Check if dataframe or specific string literal was passed to function
<p>I have a function that takes an argument which, among other things, could be either a dataframe or a string literal.</p> <pre><code>def func(could_be_df): if could_be_df=='optionA':data=stuffA() elif could_be_df=='optionB':data=stuffB() else:data=get_data(could_be_df) </code></pre> <p>When a dataframe is...
<python><pandas><equality>
2023-10-18 18:00:40
1
617
Kalev Maricq
77,318,492
13,118,009
Building wheel for pyarrow (pyproject.toml) did not run successfully
<p>Just had IT install Python 3.12 on my Windows machine. I do not have admin rights on my machine, which may or may not be important. During install, the following were done:</p> <ul> <li>Clicked &quot;Add Python 3.n to Path&quot; box.</li> <li>Went into Customize installation and made sure pip was selected, and, sele...
<python><python-3.x><pip><snowflake-cloud-data-platform>
2023-10-18 17:32:50
2
6,494
Isolated
77,318,367
12,888,866
Prevent pandas resample from filling in gap day while downsampling
<p>I have a pandas Series with measurements at a 1 minute interval. I want to downsample this data to a 5 minute interval. <code>series</code> contains measurements from at end of October 18th, none from October 19th and then measurements at the start of October 20th. Using <code>series.resample(&quot;5T&quot;).mean()<...
<python><pandas><datetime><pandas-resample>
2023-10-18 17:10:53
1
377
Timo
77,318,361
4,324,496
ModuleNotFoundError: No module named 'some_module'
<p>Could anyone please point me where I am going wrong ??? I tried all options , I don't want to go with adding sys.path option..</p> <p>Below is my project structure, I am trying to import module</p> <pre><code> from pipeline_modules.pdf2docx_convertor import * Getting error : ModuleNotFoundError: No module named...
<python><module><package>
2023-10-18 17:10:20
1
2,954
ZKS
77,318,322
4,844,359
Python breaks http response status code after trying to alter returned response with a new array or map
<p>I tried to alter a response body in lambda before returning to my front end (Flutter). However I got status code 500 internal server error even though in my cloudwatch log, it shows printing of the newly created response ok.</p> <p>my lambda code where i got <code>sample_json_response</code> and try to rebuild the r...
<python><flutter><http>
2023-10-18 17:05:41
1
1,100
unacorn
77,318,163
22,466,650
How to iteratively merge dfs and increment the suffixes at the same time?
<p>I receive a list of csv files (that varies from 3 to 20) and I need to make an inner merge on the primary key <code>A</code> and grab all the remaining columns and put them next to each other in a consolidated single dataframe.</p> <p>Since I can't share the whole csv files, I made some examples :</p> <pre><code>fro...
<python><pandas>
2023-10-18 16:37:36
1
1,085
VERBOSE
77,318,043
274,460
How to use python zeroconf in an asyncio application?
<p>Here's a minimal reproducible example demonstrating the problem:</p> <pre><code>import asyncio from zeroconf import Zeroconf, ServiceStateChange from zeroconf.asyncio import AsyncServiceBrowser def on_service_state_change(zeroconf, service_type, name, state_change): if state_change == ServiceStateChange.Added: ...
<python><python-asyncio><zeroconf>
2023-10-18 16:19:09
0
8,161
Tom
77,317,546
9,525,983
Caching pip packages in requirements.txt using vercel.json
<p>Whenever I am deploying to Vercel, it takes 10+ minutes to install pip packages. I am digging into Vercel documentation, I cannot locate any caching pip packages articles. Any insight would be greatly appreciated.</p> <p>requirements.txt</p> <pre><code>Flask==2.3.3 Flask-Admin==1.6.1 Flask-BabelEx==0.9.4 Flask-Cors=...
<python><flask><pip><serverless><vercel>
2023-10-18 15:07:36
0
1,231
Wils
77,317,536
1,914,781
atlassian module has been installed but import report not found
<p>I have installed the module with below command in ubuntu2204:</p> <pre><code>$ pip3 install atlassian Requirement already satisfied: atlassian in /home/funny/.local/lib/python3.8/site-packages (0.0.0) </code></pre> <p>But when try below python code in x.py:</p> <pre><code>#!/usr/bin/env python3 from atlassian import...
<python>
2023-10-18 15:06:55
0
9,011
lucky1928
77,317,463
5,561,649
Why doesn't stubgen generate types for literal collections?
<p>For example, on this file:</p> <pre class="lang-py prettyprint-override"><code>MY_DICT = {'a': 0, 'b': 1, 'c': 2} MY_LIST = ['a', 'b', 'c'] MY_TUPLE = ('a', 'b', 'c') </code></pre> <p>It generates:</p> <pre class="lang-py prettyprint-override"><code>from _typeshed import Incomplete MY_DICT: Incomplete MY_LIST: Inco...
<python><mypy><stub>
2023-10-18 14:57:57
0
550
LoneCodeRanger
77,317,418
955,273
pandas.Timestamp.floor gives different results
<p>I am running pandas 1.50</p> <p>Below, I am running the same code for 2 different timestamps, and getting 2 different answers.</p> <pre><code>def test(now): now = pd.Timestamp(now) floored = now.floor(pd.Timedelta(&quot;48 hours&quot;)) diff = now - floored print(f&quot;{now}, {interval}, {floored},...
<python><pandas>
2023-10-18 14:51:26
1
28,956
Steve Lorimer
77,317,412
12,257,924
MarianMTModel stops translating on encountering “-” character
<p>I’m trying to translate simple text from Polish to English:</p> <p>“Życie nigdy się nie kończy – przygotuj się zatem na ciąg dalszy. Zasilany twoją energią zegarek z widocznym mechanizmem dopasuje się do ciebie..”</p> <p>The model behaves strangely, when it encounters the <code>-</code> char it stops translating onl...
<python><machine-learning><deep-learning><nlp><huggingface-transformers>
2023-10-18 14:50:27
0
639
Karol
77,317,144
20,386,689
Trade-offs and considerations for conditional tuple unpacking in Python: primarily performance but also stylistic considerations for maintainability
<p>I have a piece of logic in <strong>Python</strong> that involves tuple unpacking based on conditions.</p> <p>The code instantiates two variables, and assigns to these variables the unpacked values of a tuple.</p> <p>This tuple is defined conditionally: if a conditional_expression is true, then a function executes re...
<python><django>
2023-10-18 14:13:21
1
780
KingRanTheMan
77,317,117
19,024,379
pyparsing how to express functions inside an infixNotation
<p>I'm building a recursive grammar using pyparsing, to express a series of possible operations, but I've hit an issue with how to express functions. I wish to describe an operator that has a name, followed by a comma delimited set of arguments:</p> <pre class="lang-py prettyprint-override"><code>import pyparsing as pp...
<python><pyparsing>
2023-10-18 14:10:40
1
1,172
Mark
77,317,085
14,044,486
How do I make a file "executable" in github actions?
<p>I build a little command-line tool using python, and have been trying to use Github Actions to build it for the various different platforms. To build the project into a standalone binary, I am using the <a href="https://github.com/Nuitka/Nuitka-Action" rel="nofollow noreferrer">Nuitka Action</a>, and then I'm releas...
<python><github><github-actions><nuitka>
2023-10-18 14:07:01
1
593
Drphoton
77,317,072
2,497,309
Download docx file created in Flask using VueJS
<p>I'm trying to figure out how to download a docx file in VueJS. I initially tried to create it in the frontend but the file ends up being corrupt so I'm using flask to create the docx file (which when I save locally opens just fine) and then sending it over to the frontend where I want to download it but the file end...
<javascript><python><vue.js><flask>
2023-10-18 14:05:09
1
947
asm
77,317,045
4,451,521
My dash subplots are too flat. How can I enlarge the Y axis?
<p>I have used python dash to make some subplots but when I run it it is like this</p> <p><a href="https://i.sstatic.net/a1NnU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/a1NnU.png" alt="enter image description here" /></a></p> <p>You can see that the Y axis is too small compared to the X axis. I don...
<python><plotly-dash>
2023-10-18 14:02:39
0
10,576
KansaiRobot
77,317,040
1,034,637
Transform.orient function in python Math3D ver 4.0.0
<p>In python math3d version 4.0.0 which function correspond to the transform.orient function in version 3.4.1?</p>
<python>
2023-10-18 14:02:23
0
10,844
Itay Gal
77,316,817
9,137,547
Python sibling relative import error: 'no known parent package'
<p>I want to import a module from a subpackage so I went here <a href="https://stackoverflow.com/questions/14057464/relative-importing-modules-from-parent-folder-subfolder">Relative importing modules from parent folder subfolder</a> and since it was not working I read all the literature here on stack and found a smalle...
<python><python-import><relative-import>
2023-10-18 13:34:26
3
659
Umberto Fontanazza
77,316,751
512,480
How to Actually pass parameters from API Gateway test screen to Lambda
<p>I am learning API Gateway. I have created an API method that is linked to a lambda function. I can demonstrate that the lambda function is actually called in a timely fashion. However, when I put a query string in the &quot;Query strings&quot; space in the test screen and then press the Test button, the information ...
<python><aws-lambda><aws-api-gateway>
2023-10-18 13:25:29
1
1,624
Joymaker
77,316,603
12,226,377
Extract text from Word document and store in an excel file using python
<p>I have a word document that is a standard template used for our wider meetings. There are two columns in my word document, First Column has all the headers second column holds the actual details of that. I have attached a screenshot of the same to show the structure of the word document.<a href="https://i.sstatic.ne...
<python><ocr><docx><text-parsing>
2023-10-18 13:07:14
1
807
Django0602
77,316,538
19,128,410
How can you format y-axis differently in each subplot?
<p>I have the following piece of code that draws some subplots:</p> <pre><code>from matplotlib import pyplot as plt import seaborn as sns import pandas as pd import numpy as np df = pd.DataFrame(data=[[0, 1], [1, 0]], columns=['prc_col', 'money_col']) fig, axs = plt.subplots(1, 2) fig.tight_layout(pad=5.0) formatting_...
<python><matplotlib><lambda><seaborn>
2023-10-18 12:58:40
0
311
Sanjin Juric Fot
77,316,505
2,110,805
I'm having a bad time installing some modules with poetry
<p><strong>First, a bit of context</strong></p> <p>I have an old project managed with poetry and I wanted to install new modules. I tried installing them with <code>poetry add &lt;mymodule&gt;</code>... but it failed, <code>poetry update</code> failed, everything failed... So, after a big headache time, as always with ...
<python><linux><python-poetry>
2023-10-18 12:55:44
0
14,653
Cyrille
77,316,494
16,383,578
PyQt6 how to update 96 widgets simutaneously as fast as possible?
<p>This is about my GUI application.</p> <p><a href="https://i.sstatic.net/7xH67.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7xH67.png" alt="enter image description here" /></a></p> <p>What you are seeing is the window I have created to let the user customize the style of the application. I don't kno...
<python><asynchronous><python-asyncio><pyqt6>
2023-10-18 12:53:57
2
3,930
Ξένη Γήινος
77,316,382
2,248,271
database locked when using sqlalchemy to_sql method
<p>I have a function to upload a dataframe to a SQL server, defined as follows:</p> <pre><code> def uploadtoDatabase(data,columns,tablename): connect_string = urllib.parse.quote_plus(f'DRIVER={{ODBC Driver 17 for SQL Server}};Server=ServerName;Database=DatabaseName;Encrypt=yes;Trusted_Connection=yes;TrustServerCer...
<python><sql-server><sqlalchemy>
2023-10-18 12:36:55
1
6,020
Wietze314
77,316,349
11,329,736
Send email after Snakemake workflow finishes successfully on SLURM
<p>Is there way to send an email after a <code>Snakemake</code> workflow finished when using the <code>--slurm</code> option? Something like this:</p> <pre><code>onsuccess: email(example@hello.com, title=&quot;Snakemake job xxx finished successfully&quot;) onerror: email(example@hello.com, title=&quot;Snakema...
<python><python-3.x><shell><email><snakemake>
2023-10-18 12:32:54
1
1,095
justinian482
77,316,345
1,581,090
How to use re.split in python but keep the splitting expression?
<p>I have a string</p> <pre><code>a = &quot;Example text 123&quot; </code></pre> <p>which I want to split by the text <code>text</code></p> <pre><code>b = re.split(r&quot;text&quot;, a) </code></pre> <p>which gives</p> <pre><code>['Example ', ' 123'] </code></pre> <p>but I want to keep the text I used in the regex, so ...
<python><regex>
2023-10-18 12:32:32
1
45,023
Alex
77,316,276
16,739,843
How to solve or debug that IPyWidgets are just partially shown?
<p>I have just installed Jupyter Notebooks and a new Python environment using <code>venv</code> on my vanilla Macbook (I have not used Jupyter on this hardware before). Now I am running the Jupyter Notebook, that is using IPyWidgets as input controls, and recognized that only some of the widgets are shown.</p> <p>A min...
<python><macos><jupyter-notebook><ipywidgets>
2023-10-18 12:23:56
1
1,191
Mathias Kemeter
77,315,840
827,927
How to use matplotlib for debugging, without making it a dependency
<p>I am developing a library of algorithms on graphs. During development, I regularly need to plot graphs generated during the algorithms, for debugging. I use matplotlib for this, so in my source code I need to <code>import matplotlib</code>.</p> <p>But, I do not want matplotlib a dependency of the library, because th...
<python><matplotlib>
2023-10-18 11:21:42
1
37,410
Erel Segal-Halevi
77,315,780
13,222,679
How to merge rows in dictionary python using pandas
<p>i have a dataframe like that</p> <pre><code>MV id NAME ADDRESS DOC DOCTYPE PHONE 1 100 Mark Home 299 NI {123,456} 2 100 John Work A123 Pass {789,101} 3 100 Club </code></pre> <p>what i want to do is to merge the columns that has the same id into one cell in dictionary like thi...
<python><pandas><dataframe><dictionary><group-by>
2023-10-18 11:12:14
2
311
Bahy Mohamed
77,315,715
5,775,358
Python subclass of abstract baseclass shows type error
<p>pylance gives an type error while the types of the variables are defined. Below a small example which shows the structure of the code and gives also the error:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass ...
<python><typing><pylance>
2023-10-18 11:03:17
1
2,406
3dSpatialUser
77,315,541
7,052,826
Plotly express bar re-orders the x-axis due to missing data
<p>I have some data which includes dates in a year-quarter format.</p> <p>Sorting the dataframe works fine, however when plotting the data, <code>Plotly</code> automatically re-orders the x-axis, by placing data with missing values at the end, instead of adhering to the desired order.</p> <pre><code># Example data that...
<python><pandas><plotly><plotly-express>
2023-10-18 10:36:30
1
4,155
Mitchell van Zuylen
77,315,369
3,433,875
Import a global variable from an external function into flask app
<p>I am really new to flask and fairly new to python.</p> <p>Here is my issue: I have created a flask app that displays a bunch of matplotlib charts with the following structure:</p> <pre><code>└──app ├──templates | └──index.html ├──assets ├──functions | └──by_continent.py └──app.py </code></pre> <p...
<python><flask>
2023-10-18 10:08:59
2
363
ruthpozuelo
77,315,308
9,997,385
How to convert string to Python object (Flask specific)
<p>If I have this code:</p> <pre><code>from datetime import timezone DEFAULT_TZ = timezone.utc </code></pre> <p>And I want to pass <code>timezone.utc</code> as an input variable from a JSON file:</p> <pre><code>from datetime import timezone app.config.from_file(filename=&quot;config.json&quot;, load=json.load) DEFAULT...
<python><flask>
2023-10-18 10:01:48
1
643
A. Gardner
77,314,901
1,279,355
Strip scripts from pybuild
<p>I need to build a debian package from a python package. The python package is not under my control so i can not easily change the setup.py file.<br /> It is using setuptools and has a very standard setup.py containing scripts. But for my resulting debian package i don't want any of the scripts included.</p> <pre><co...
<python><debian><setuptools><packaging>
2023-10-18 09:01:20
1
4,420
Sir l33tname
77,314,839
12,081,269
How do I connect to Clickhouse locally using sqlalchemy
<p>I am trying to establish a Clickhouse connection from my local machine but I receive an error that <code>sqlalchemy</code> does not know how to deal with clickhouse dialect (<code>Can't load plugin: sqlalchemy.dialects:clickhouse.native</code>). However, everything works in JupyterHub.</p> <p>I cannot use JupyterHub...
<python><sqlalchemy><clickhouse>
2023-10-18 08:52:25
0
897
rg4s
77,314,836
12,590,879
Storing 'formattable' strings in database
<p>I'm working on a project where I need to store certain descriptions in a database. These descriptions need to be strings akin to prepared statements in SQL, where I can later 'inject' my own values wherever necessary. The reason is that the data that goes in the fields needs to be generated by the backend on demand ...
<python><sql><django>
2023-10-18 08:51:36
0
325
Pol
77,314,758
1,306,747
VSCode Python unittest discovery fails: 'utils' is not a package -> sys.path ordering?
<p>since a few days, Visual Studio Code Python unittest discovery no longer works for me in several projects that contain a package called <code>utils</code>:</p> <pre><code>2023-10-18 09:37:36.901 [info] Discovering unittest tests with arguments: /home/phip/.vscode/extensions/ms-python.python-2023.19.12901009/pythonFi...
<python><visual-studio-code><python-unittest><pythonpath>
2023-10-18 08:42:38
2
989
Philipp Burch
77,314,703
7,029,724
QGIS python plugins: How to install python packages, f.e. cx_Oracle
<p>I want to develop a python- plugin for QGIS. For this I need to install packages (f.e. cx_Oracle) on my computer and of course - when deployed on client- computers. Can anyone tell me, how to do this, preferably without the need for admin rights?</p>
<python><plugins><qgis>
2023-10-18 08:36:30
2
371
am2
77,314,656
8,849,071
Maintaning isolation between modules in Django monolith
<p>In our company, we have a monolith. Right now is not that big but we are already seeing some problems with the isolation between the modules we have. Our setup is pretty similar to other Django backends: we have a common User model and another UserProfile model where we store additional information about the user. A...
<python><django><architecture><domain-driven-design>
2023-10-18 08:31:12
1
2,163
Antonio Gamiz Delgado
77,314,581
6,851,715
dynamically add a sequential date column to a data frame with a starting with each date is repeated N times in consecutive rows
<p>I've got the following data.frame:</p> <pre><code>import pandas as pd import random data = { 'Column1': [random.randint(1, 100) for _ in range(9)], 'Column2': [random.uniform(0, 1) for _ in range(9)], 'Column3': [chr(random.randint(65, 90)) for _ in range(9)], 'Column4': [random.choice(['A', 'B', 'C...
<python><dataframe><date><repeat>
2023-10-18 08:20:55
1
1,430
Ankhnesmerira
77,314,559
7,745,011
Is it possible to partially build a pydantic basemodel before validation?
<p>Working on a data access package which handles queries from a database and should return <code>pydantic</code> models.</p> <p><b>Here is the Problem:</b><br> Most of the models are derived from multiple tables. This means after querying a models table, do not yet have all of the models properties (I first have to qu...
<python><validation><pydantic>
2023-10-18 08:17:53
0
2,980
Roland Deschain
77,314,507
972,647
How to pass a constant value (a list) to concurrent.futures.Executor.map?
<p>Related question that doesn't answer my exact use-case:</p> <p><a href="https://stackoverflow.com/questions/6785226/pass-multiple-parameters-to-concurrent-futures-executor-map">Pass multiple parameters to concurrent.futures.Executor.map?</a></p> <p>I have a function that takes 2 arguments. The second argument is a l...
<python><concurrent.futures>
2023-10-18 08:08:51
2
7,652
beginner_
77,314,320
5,079,255
Is there any way to use custom Consumer Tag with pika
<p>I am using pika to work with RabbitMQ. I have a queue with a dozen consumers. I want to map consumer information in Rabbit with my application logs. So is there any way of either getting the attached consumer_tag after a connection was established or using a custom tag generated by my app?</p> <p>Thanks</p>
<python><python-2.7><rabbitmq><pika>
2023-10-18 07:37:53
0
2,148
GhostKU
77,313,860
1,059,860
Ruff doesn't catch undefined argument to function
<p>I'm not sure even if it is ruff's job to catch the undefined argument to a function, but is there a tool that does this? or is there a ruff configuration that I'm missing to add so that ruff can do this?</p> <pre><code>from typing import Optional def my_func(bar: int, baz: int, foo: Optional[int] = None) -&gt; int...
<python><python-3.x><lint><ruff>
2023-10-18 06:16:09
1
2,258
tandem
77,313,849
2,541,276
ModuleNotFoundError: No module named '_tkinter' when installing python 3.12.0 using pyenv in Fedora 38
<p>I'm tryiny to install latest python 3.12.0 in Fedora 38 using pyenv. The command is <code>pyenv install 3.12.0</code></p> <p>I get below error -</p> <pre class="lang-bash prettyprint-override"><code>~ pyenv install 3.12.0 Downloading Python-3.12.0.tar.xz... -&gt; https://www.python.org/ftp/python/3.12.0/Python...
<python><tkinter><pyenv>
2023-10-18 06:12:25
4
10,555
user51
77,313,847
8,523,868
Could not able to click the link from the container
<p>hi all thanks for reading my question. I tried to automate some of my work. I tried to get the path of Add button using xpath finder I found three links below. I tried to click on the add button but its not working. The curser is in the first name box. Below my code is there. Please help me to click the Add button.<...
<python><selenium-webdriver><automation>
2023-10-18 06:12:12
2
911
vivek rajagopalan
77,313,546
1,538,049
Numpy advanced indexing with index arrays
<p>In numpy, I got stuck with an advanced case of indexing problem. Suppose that I have an array <code>A</code> with the shape<code>(D0,D1,...,D(N-1),A,B)</code>. So, the first N dimensions are where I want to query for indices. The last two dimensions (A,B) are holding the actual data. I have a list of tuples of N dim...
<python><arrays><numpy>
2023-10-18 04:48:48
0
3,679
Ufuk Can Bicici
77,313,491
7,636,462
Patching the `__call__()` method of a child class from a parent class in Python
<p>I have the following lines of code in Python:</p> <pre class="lang-py prettyprint-override"><code>from functools import partial class DummyClass: def load_values(self, prompt, num_inference_steps): self = partial(self, prompt=prompt, num_inference_steps=num_inference_steps) class AnotherDummyClass(Dum...
<python><inheritance>
2023-10-18 04:28:53
2
400
S. P
77,313,357
4,451,521
python assigment of dataframes points to the same direction?
<p>I am debugging a python script that uses dataframes and there is a line like this</p> <pre><code>df=myObject.df df[&quot;error_value&quot;] = &quot;&quot; </code></pre> <p>myObject is an object that has a dataframe as a member variable (df)</p> <p>I run it until the first line and sure enough <code>df</code> has the...
<python><pandas><dataframe>
2023-10-18 03:36:22
0
10,576
KansaiRobot
77,313,188
138,776
HTTP request fails in Flask request, succeeds from command line
<p>In trying to write a flask app, I ran into a problem making an outbound HTTP call using <a href="https://requests.readthedocs.io/" rel="nofollow noreferrer">requests</a> to an API while processing the request. If I run the same function from the python command line, it works. <strong>Why?</strong></p> <p><strong>Upd...
<python><flask><ssl><python-requests><gunicorn>
2023-10-18 02:33:35
1
3,429
Doug Harris
77,312,806
14,947,895
Defekt Python-C linking leads code to deviates after relative number of loops and not absolute
<p>For performance reasons I implemented a C function of an (adaptive) Gaussian filter. For a sanity check, I compared it to my old Python implementation. It seems to work well at first, but then starts to break down. Strangely, this does not seem to depend on the absolute number of frequencies evaluated, but somehow o...
<python><c><parallel-processing><simd>
2023-10-17 23:52:45
1
496
Helmut
77,312,801
2,153,235
Spark Row object instantiated differently from overloaded prototypes?
<p>The Spark <code>Row</code> class in <code>pyspark/sql/types.py</code> contains no <code>__init__</code> method, but shows the following overloaded type hints for <code>__new__</code>:</p> <pre><code>@overload def __new__(cls, *args: str) -&gt; &quot;Row&quot; @overload def __new__(cls, **kwargs: Any) -&gt; &quot;Ro...
<python><apache-spark><pyspark><overloading><python-typing>
2023-10-17 23:50:45
1
1,265
user2153235
77,312,694
11,277,108
AttributeError: 'ClassManager' object has no attribute 'obj' when listening for "first_init" event
<p>I'd like to update a table in a standard way when any of a variety of scripts I've written runs. To that end I'd like to use the <code>event.listens_for</code> decorator so I don't need to call my update function at the beginning of each script.</p> <p>I opted to listen for the <code>first_init</code> event using th...
<python><sqlalchemy>
2023-10-17 23:07:00
0
1,121
Jossy
77,312,659
2,805,482
plotting timeseries line graph for unique values in a column
<p>I am trying to plot a timeseries graph for all the unique keys in my dataset, below is my dataset, I have 7 unique keys and I am trying to plot event_date on x-axis and line graph for count on y axis.</p> <p>I am looping through each unique key and trying to plot date vs count however getting below error. Based on ...
<python><pandas><matplotlib><time-series><line-plot>
2023-10-17 22:57:04
1
1,677
Explorer
77,312,571
3,562,088
Numerical implementation of ODE differs largely from analytical solution
<p>I am trying to solve the ODE of a free fall including air resistance.</p> <p>I therefore defined my ODE as:</p> <pre><code>def f(v, g, k, m): return g - k/m * v**2 </code></pre> <p>which in my opinion should represent the system correctly because</p> <pre><code>m*a = m*g -k*v**2 </code></pre> <p>where <code>a=vd...
<python><numerical-methods><differential-equations>
2023-10-17 22:28:10
1
1,485
Axel
77,312,513
2,595,216
infinite generator integers from range with step
<p>I need infinite generator, like:</p> <pre class="lang-python prettyprint-override"><code>def zigzag_iterator(current_value, step, max_val): direction = 1 while True: if current_value &gt;= max_val: direction = -1 elif current_value &lt;= 0: direction = 1 curren...
<python><iterator><generator>
2023-10-17 22:09:02
1
553
emcek
77,312,448
10,364,235
simplejwt token work for all tenants for django-tenants
<p>I just want to mention about my problem. I have already researched many documents but I could not find any solution.</p> <p>I just try to use <code>django-tenants</code>. Everything seems OK. But If any user gets the token after login, <strong>that token works for all tenants.</strong></p> <p>It's a big leak of secu...
<python><django><django-rest-framework><django-rest-framework-simplejwt><django-tenants>
2023-10-17 21:51:54
3
436
kalememre
77,312,382
2,153,235
How to interpret DataFrame[approx_count_distinct(salary): bigint]?
<p>I am simultaneously spinning up on Python and Spark via PySpark by following <a href="https://sparkbyexamples.com/pyspark/pyspark-aggregate-functions" rel="nofollow noreferrer">this tutorial</a>. Here is the minimum working example:</p> <pre><code>&gt;&gt;&gt; from pyspark.sql import SparkSession &gt;&gt;&gt; spark ...
<python><apache-spark><pyspark>
2023-10-17 21:37:37
1
1,265
user2153235
77,312,205
850,781
Merge weighted averages in groupby
<p>I have a <a href="https://pandas.pydata.org/docs/reference/frame.html" rel="nofollow noreferrer">Pandas <code>DataFrame</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;commodity&quot;:[&quot;Potatos&quot;,&quot;Potatos&quot;,&quot;Apples&quot;,&quot;Apples&quot;,&quot;Apples&quot;], ...
<python><pandas><dataframe><group-by><aggregate>
2023-10-17 20:54:30
2
60,468
sds
77,312,008
6,248,790
codebuild stage fails with "Specified key does not exist error"" in AWS CDK 2.63.2
<p>I have the following CDK code that creates a CloudFormation stack with an S3 bucket, codecommit and codepipeline.</p> <pre><code> assets = s3d.BucketDeployment( self, &quot;codeassets&quot;, destination_bucket=pipeline_bucket, role=reader_role, cache_control=[ s3d.CacheControl.from_string( ...
<python><amazon-s3><aws-cdk><aws-codepipeline><aws-codebuild>
2023-10-17 20:14:31
1
1,279
Ashfaq
77,311,966
1,422,096
Find how many events in each 30-minute interval, without looping many times on the events
<p>This works and prints the number of events in each 30-minute intervals:</p> <p>00:00 to 00:30, 00:30 to 01:00, ..., 23:30 to 24:00</p> <pre><code>import time, datetime L = [&quot;20231017_021000&quot;, &quot;20231017_021100&quot;, &quot;20231017_021200&quot;, &quot;20231017_052800&quot;, &quot;20231017_093100&quot;,...
<python><performance><loops><datetime><intervals>
2023-10-17 20:07:46
1
47,388
Basj
77,311,784
16,383,578
How to split a list of integers into two groups of integers with minimal difference of their sums?
<p>I don't know if this is a duplicate, but Google search returns nothing relevant as usual.</p> <p>So I have a list of integers, which represents the lengths of segments. And I want to split the list of integers into two lists of integers, such that the difference between the sum of lengths of the groups is minimal.</...
<python><algorithm><math>
2023-10-17 19:34:33
3
3,930
Ξένη Γήινος
77,311,671
10,565,820
"reportMissingImports" error even though code and import works fine in VSCode
<p>Small question but annoying. In VSCode, it is reporting a &quot;reportMissingImports&quot; error even though the import and the code is working fine. Here is the relevant portion.</p> <pre><code>import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.ssl_ import create_urllib3_c...
<python><visual-studio-code><pylance>
2023-10-17 19:13:21
1
644
geckels1
77,311,656
8,858,832
Access parent object data member from sub-object in Python
<p>I have a setup like the following</p> <pre><code>class decorator: def __init__(self, fn): self.fn = fn @staticmethod def wrap(fn): return decorator(fn) def __call__(self): print(f&quot;decorator {self} function called&quot;) class A: @decorator.wrap def foo(self): ...
<python><decorator><composition>
2023-10-17 19:10:42
1
1,824
Niteya Shah
77,311,649
11,197,796
Fastest way to assign row to dataframe in pandas groupby loop
<p>Ok so I have 2 dataframes:</p> <pre><code>df = pd.DataFrame({'A':['German Shepherd','Border Collie','Golden Retriever','Beagle','Daschund']}) df = df.T df.columns = df.iloc[0] df = df.drop(df.index[0]) A German Shepherd Border Collie Golden Retriever Beagle Daschund df2 = pd.DataFrame({'ID':['A','A','A...
<python><pandas><dataframe><numpy>
2023-10-17 19:09:25
1
440
skiventist
77,311,583
6,423,456
How can I recursively iterate through a directory in Python while ignoring some subdirectories?
<p>I have a directory structure on my filesystem, like this:</p> <pre><code>folder_to_scan/ important_file_a important_file_b important_folder_a/ important_file_c important_folder_b/ important_file_d useless_folder/ ... </code></pre> <p>I want to recursively scan through <cod...
<python><pathlib>
2023-10-17 18:57:38
3
2,774
John
77,311,427
17,653,423
How to mock open file and raise if path does not exists?
<p>I'am facing a problem when testing a function that reads the first line of a file and raises an <code>Exception</code> when the path of the file doesn't exist.</p> <p>Current code:</p> <pre><code>from unittest.mock import patch, mock_open from pytest import raises from os.path import exists def read_from_file(file_...
<python><pytest><python-unittest><python-unittest.mock><pytest-mock>
2023-10-17 18:28:15
1
391
Luiz
77,311,398
12,027,869
optuna: Different Results Even With Same random_state
<p>I am trying to understand why running the below code for hypterparameter tuning using optuna gives me different best parameter values even if I am running the exact same code with the same <code>random_state = 42</code>. Where is the random part coming from?</p> <pre><code>import optuna import sklearn from sklearn.e...
<python><optuna>
2023-10-17 18:24:47
2
737
shsh
77,311,383
8,849,755
Python get element pointed by iterator and not move
<p>Consider the iterator <code>i = iter([1,2,3,4])</code>. I am looking for some <code>current</code> function that does this:</p> <pre><code>first = next(i) # 1 second = next(i) # 2 second_2 = current(i) # 2 third = next(i) # 3 ... </code></pre> <p>I.e., it gives me the current element pointed by the iterator without ...
<python><iterator>
2023-10-17 18:21:21
2
3,245
user171780
77,311,352
9,112,151
How to parse this simple XML?
<p>I'm trying to parse thhis simple XML:</p> <pre><code>import xml.etree.ElementTree as ET data = &quot;&quot;&quot; &lt;ns2:Request xmlns:ns2=&quot;urn://www.example.com&quot;&gt; &lt;ns2:User&gt; &lt;ns2:Name&gt;John&lt;/ns2:Name&gt; &lt;ns2:Surname&gt;Snow&lt;/ns2:Surname&gt; &lt;ns2:Ema...
<python><xml>
2023-10-17 18:16:12
3
1,019
Альберт Александров
77,311,289
2,274,981
Is there a more readable/efficient way of doing this?
<p>I have a bot that process some metadata from a replay file (it reads the binary) I then parse out all the variables I require.</p> <p>Basically due to the game dev the files can be a bit confusing so I've written some code to ascertain the correct result I need (Basically appending player names to a list that is the...
<python>
2023-10-17 18:05:33
1
1,149
Lynchie
77,311,288
11,354,959
Apply a function to all dict elements of an array in python
<p>Hi I am wondering what would be the best way to apply a function to all elements of an array (those elements are dict). I have dict object that contains elements, one of them being another array of dict. I want to avoid doing the following</p> <pre><code>my_array = api.get_elements().json() # return an array of dict...
<python><python-3.x><dictionary><generator>
2023-10-17 18:05:18
2
370
El Pandario
77,311,284
3,319,713
Merge tuples in a list based on their dates items
<p>I have a list of tuples, where the first two items in each tuple are dates and the third one is always some name. I want to check: 1) if any two or more tuples have the name as the third item; 2) if the two dates of the tuple are part of or within the two dates of any other tuple. If 1) and 2) are true then only kee...
<python><python-3.x><pandas>
2023-10-17 18:04:31
3
3,206
Blue482
77,311,257
7,200,174
Check if Dataframe Values are Equal across specific columns
<p><strong>CONTEXT</strong></p> <p>I have two Dataframes and I want to validate that each DataFrame has the same value for each ID. I want to create a dataframe of all the rows/outliers that don't match.</p> <p>The ID's are not in the same order and the dataframes do not have the same amount of rows.</p> <p><strong>SAM...
<python><pandas><dataframe><compare>
2023-10-17 17:59:05
3
331
KL_
77,311,076
10,270,246
How to construct a Python object with multiple inheritance?
<p>I succeeded to construct a Python object with multiple inheritance but I feel like I didn't use the proper way...</p> <p>Here is my code :</p> <pre class="lang-py prettyprint-override"><code>class A: def __init__(self, a): print(&quot;A ctor called!&quot;) self.a_ = a def printa(self): ...
<python><multiple-inheritance>
2023-10-17 17:29:03
0
633
Autechre
77,311,036
13,132,728
How to merge pandas dataframes (on a common key) that are dictionary values
<p>I have a dictionary <code>data</code> where the values are pandas dataframes:</p> <pre><code>{'x': player x1 0 foo x_val 1 bar x_val 'y': player y1 0 foo y_val 1 bar y_val 'z': player z1 0 foo z_v...
<python><pandas><dictionary><merge>
2023-10-17 17:22:28
0
1,645
bismo
77,311,031
6,013,700
CVXPY finds no solution (unbounded) to a problem that definitely has a solution - how to debug
<p>I encountered the following special case where CVXPY was returning a <code>None</code> solution, with status <code>unbounded</code>, for a problem that definitely has a solution.</p> <p>It doesn't seem like I can enter LaTeX, so <code>@</code> signifies matrix multiplication, <code>.T</code> means transpose, small l...
<python><optimization><cvxpy><convex-optimization><quadratic-programming>
2023-10-17 17:22:11
0
1,602
Marses
77,310,945
20,266,647
Issue seeing xticks with subplots
<p>I have a problem to see x-axis description for first subplot (I used Axes.set_xticks). See sample of code:</p> <pre><code>import matplotlib.axes import matplotlib.pyplot as plt y_lst=[100,200,150,500] x_lst=[2,4,8,16] plt.style.use(&quot;bmh&quot;) #&quot;ggplot&quot; &quot;seaborn-v0_8-poster&quot; fig, ax = plt....
<python><matplotlib><subplot>
2023-10-17 17:07:27
2
1,390
JIST
77,310,849
7,457,808
Mesh smoothing/minimal surface algorithm, ideally in python
<p>I am in need of an algorithm for approximating a minimal surface (with some added constraints) starting from an initial triangular 3D mesh. For now, I would be quite satisfied with a reproduction of what is implemented in Blender as &quot;smooth vertices&quot;.</p> <p>I believe that effectively one would move every ...
<python><algorithm><computational-geometry><mesh>
2023-10-17 16:53:01
1
360
Franz
77,310,823
3,878,377
How to extract best parameters from a crossvalidator in pyspark
<p>I have a question regarding extracting the hyperparameters from crossvalidator in PySpark. I have tried every single solution in stackoverflow and none of them work for me. I am not sure either those answers are old or I am making mistake somewhere.</p> <p>I can perform distributed training and prediction successful...
<python><apache-spark><pyspark><scikit-learn><cross-validation>
2023-10-17 16:49:24
0
1,013
user59419
77,310,754
4,655,853
lambda function Runtime.ImportModuleError: Unable to import module 'lambda_function': No module named 'cerberus'
<p>I am trying to use Cerberus in AWS lambda but running into the below error when trying to execute the code. I created a custom layer and pointed it to zip file in S3 downloaded from <a href="https://pypi.org/project/Cerberus/#files" rel="nofollow noreferrer">here</a>. Runtime env for lambda and layer is <code>python...
<python><aws-lambda><cerberus>
2023-10-17 16:35:25
1
387
user0000
77,310,400
6,595,663
Join or concat Polars DataFrames without knowing the matching column names
<p>I am using the polars library in python and have two data frames the look like this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data1 = { 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] } df1 = pl.DataFrame(data1) data2 = { 'B': [4, 5, 6], 'C': [7, 8, 9], 'D': [...
<python><dataframe><python-polars>
2023-10-17 15:40:26
1
3,271
BhanuKiran
77,310,361
10,573,543
Why I am getting blank response from the AWS lambda function even though AWS lambda test works properly?
<h4>Description</h4> <hr /> <blockquote> <p>I am creating an intermediary service between my frontend and my backend using AWS lambda function. The job of the function is to take the payload from the UI and send to the backend, if Backend is live then send the <code>200</code> status (progress of ML model, short poolin...
<python><json><amazon-web-services><aws-lambda>
2023-10-17 15:33:26
2
1,166
Danish Xavier
77,310,349
13,184,183
How to take sample from pyspark dataframe by column?
<p>I have very large pyspark with two columns of interest : <code>date</code> column and <code>id</code> column. Dataframe is partitioned by <code>date</code>. I want to take a sample from that dataset, such that if some <code>id</code> is in the sample, then all rows with that <code>id</code> should be in the sample.<...
<python><pyspark>
2023-10-17 15:32:09
0
956
Nourless
77,310,131
7,211,014
ansible proper way to split an extended variable and create new variable to use in other tasks?
<p><strong>Running ansible 2.10.17</strong></p> <p>I keep getting <code>% Invalid input detected at '^' marker.</code> when trying to run a role. here is my code. Note &quot;filter&quot;, &quot;trust&quot;, and &quot;untrust&quot; are passed in with <code>-e</code> as extra variables.</p> <pre class="lang-yaml prettypr...
<python><variables><split><ansible><cisco>
2023-10-17 15:01:11
1
1,338
Dave
77,310,109
3,015,186
How to check if a datetime value is valid (and not in time gap caused by DST change)?
<p>Daylight Saving Time (DST) changes occur usually twice a year. During fall clocks are moved backwards which creates a fold which means that a given local time has two possible meanings. This is covered in <a href="https://peps.python.org/pep-0495/" rel="nofollow noreferrer">PEP-495</a>. During spring clocks are move...
<python><datetime><timezone><dst>
2023-10-17 14:58:07
1
35,267
Niko Fohr
77,310,098
3,105,520
fit function expected 2D array, got 1D array instead
<p>I am using Linear Regression to predict the 'Value' throughout the years, I have the following data, i imported from a csv file : <code>**df.head()**</code> :</p> <pre><code>LOCATION INDICATOR SUBJECT MEASURE FREQUENCY TIME Value Flag Codes 0 IRL LTINT TOT PC_PA M 1.167610e+18 4.04 NaN 1 ...
<python><pandas><linear-regression><reshape><data-fitting>
2023-10-17 14:57:10
2
421
Najoua
77,310,054
11,665,178
How to authenticate with a service account or OAuth consent automatically for Google Drive API?
<p>I am trying to make a simple POST request as the following :</p> <pre><code>POST https://www.googleapis.com/drive/v3/changes/watch Authorization: Bearer auth_token_for_current_user Content-Type: application/json { &quot;id&quot;: &quot;4ba78bf0-6a47-11e2-bcfd-0800200c9a77&quot;, // Your channel ID. &quot;type&q...
<python><google-drive-api>
2023-10-17 14:51:55
1
2,975
Tom3652
77,310,043
5,924,264
How to prefilter a list of dicts that I want to insert into a sql table where each dict has an extra column
<p>I have a sqlite3 connector, and I would like to insert a list of dicts into the sql table. However, this list of dicts may have an extra column that isn't part of the sql table schema.</p> <p>Obviously, I can pre-filter the list of dicts to remove this column prior to using <code>executemany</code>, and that's what ...
<python><sql><sqlite>
2023-10-17 14:50:33
2
2,502
roulette01
77,309,956
5,231,110
Compare two strings by meaning using LLMs
<p>I'd like to use some of the good large language models to estimate how similar the <strong>meanings</strong> of two strings are, for example &quot;cat&quot; and &quot;someone who likes to play with yarn&quot;, or &quot;cat&quot; and &quot;car&quot;.</p> <p>Maybe some libraries provide a function for comparing string...
<python><neural-network><artificial-intelligence><large-language-model>
2023-10-17 14:37:12
3
2,936
root
77,309,900
4,399,016
Saving multiple Pandas data frames to different work sheets of a Single Excel file
<p>I have this code:</p> <pre><code>import pandas as pd import yfinance as yF import datetime from functools import reduce def get_returns_change_period(tic,com,OHLC_COL1,OHLC_COL2): df_Stock = yF.download(tickers = tic, period = &quot;38y&quot;, interval = &quot;1mo&quot;, prepost = False, repair = False) df...
<python><pandas><excel><dataframe>
2023-10-17 14:29:04
1
680
prashanth manohar
77,309,857
19,299,757
How to pass parameter values to lambda event from API call
<p>I've a lambda function which runs a Docker Image and creates a CSV file. This lambda function expects 5 arguments which are passed from command line when invoking the lambda as given below. These 5 parameters are configured in input.json file and passed to the CLI.</p> <pre><code>aws lambda invoke --function-name de...
<python><aws-lambda>
2023-10-17 14:23:32
1
433
Ram
77,309,717
9,891,565
Version controller in websocket with fastapi
<p>So, I want to use router within the websocket call. This is what I have, at the moment (using dummy data)</p> <p>version-&gt;v1-&gt;<strong>init</strong>.py</p> <pre><code>router.include_router(websocket_controller, prefix=&quot;/ws&quot;) router_without_prefix.include_router(websocket_controller) </code></pre> <p>v...
<python><fastapi>
2023-10-17 14:04:31
1
487
rainbow12
77,309,676
6,423,456
Does Django DRF have a way to do read-only tokens?
<p>I have a Django REST API using Django REST Framework. I want to use <a href="https://github.com/encode/django-rest-framework/blob/f56b85b7dd7e4f786e0769bba6b7609d4507da83/rest_framework/authentication.py#L151" rel="nofollow noreferrer">TokenAuthentication</a>, but I want to have read-only tokens and read-write token...
<python><django><django-rest-framework>
2023-10-17 14:00:03
1
2,774
John