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,353,175
9,940,188
Flask / Pytest error: AssertionError: The setup method 'before_request' can no longer be called
<p>first up, this is NOT a duplicate of <a href="https://stackoverflow.com/questions/76434519/assertionerror-the-setup-method-route-can-no-longer-be-called-on-the-blueprin">this</a> or <a href="https://stackoverflow.com/questions/74195757/flask-pytest-userwarning-the-setup-method-route-can-no-longer-be-called-on-th">th...
<python><flask><pytest>
2023-10-24 14:55:15
1
679
musbur
77,352,946
1,020,139
How to send data over SSH connection created by AWS SSM Session Manager without using plugin?
<p>I want to send data over the SSH connection created by AWS SSM Session Manager in Python without using the <strong>Session Manager Plugin</strong>.</p> <p>The following answer describes how to do it using the plugin, but I want a pure Python approach, with a local port that's forwarded to a target host.</p> <p>Any i...
<python><amazon-web-services>
2023-10-24 14:22:12
0
14,560
Shuzheng
77,352,821
7,064,415
place a PNG right above an axes object
<p>I have a Matplotlib figure with three axes, placed above one another. Above the top <code>axes</code> object I want to place an image that I enclose in an <code>inset_axes()</code> 'box'. The image should as be as wide as the <code>axes</code> object (and its height should be scaled accordingly compared to its origi...
<python><matplotlib><axis>
2023-10-24 14:06:25
1
732
rdv
77,352,615
19,500,571
Extracting elements from a long list of dictionaries efficiently
<p>I have a (long) list of dictionaries, but for the sake of this example I represent them as</p> <pre><code>d = [{'a':1}, {'a':2}, {'a':3}] </code></pre> <p>I need to extract the same element from these dictionaryes, i.e.,</p> <pre><code>[i['a'] for i in d] </code></pre> <p>What is the most efficient way to do this in...
<python><performance><dictionary><vectorization>
2023-10-24 13:41:42
4
469
TylerD
77,352,588
3,364,859
How to catch a package-specific exception?
<p>When I try to read a table from an SQL database with pandas using <code>pandas.read_sql</code>, the package pyodbc throws an <code>DataError</code> (pyodbc.DataError) that I would like to catch. The <code>DataError</code> is caused by an unexpected nvarchar value, causing an conversion failure when pyodbc attempts t...
<python><pandas><exception><pyodbc>
2023-10-24 13:37:54
2
356
marianoju
77,352,551
4,415,502
Why does the ABC has to be placed in the left most position in python abstract class?
<p>Is there any difference in class A and class B in the following code?</p> <pre><code>from abc import ABC class Base: ... class A(ABC, Base): ... class B(Base, ABC): ... </code></pre> <p>I see that most of the code online uses the first version (class A), why is that so?</p>
<python>
2023-10-24 13:33:45
0
2,473
Mox
77,352,344
10,462,461
Filter dataframe for value that exists in all dates
<p>Say I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({ 'PortDt': ['2022-01-31', '2022-02-28', '2022-02-28', '2022-03-31', '2022-03-31'], 'loannum': ['111', '111', '222', '111', '333'] }) </code></pre> <p>I want to filter the dataset so that I am left with only records who appear in every distin...
<python><pandas><dataframe>
2023-10-24 13:10:19
1
340
gernworm
77,352,103
5,576,536
How to use langchain RetrievalQA with asyncio?
<p>I want to parallelize <code>RetrievalQA</code> with <code>asyncio</code> but I am unable to figure out how.</p> <p>This is how my code works serially:</p> <pre><code>import langchain from langchain.chat_models import ChatOpenAI from langchain import PromptTemplate, LLMChain from langchain.chains import RetrievalQA f...
<python><python-asyncio><langchain><large-language-model>
2023-10-24 12:36:37
1
4,793
Abhishek R
77,351,940
12,769,783
python performs a deepcopy of a weakref.proxy's content. Why? Which entity owns the reference?
<p>I wanted to double check my assumption, that the content of a <code>weakref.proxy</code> is not deepcopied when performing a deepcopy of it. To that end, I wrote the following code snippet:</p> <pre class="lang-py prettyprint-override"><code>import copy import weakref class A: def __init__(self, val=3): ...
<python><python-3.x><deep-copy><weak-references>
2023-10-24 12:11:59
0
1,596
mutableVoid
77,351,890
3,831,934
Scipy sparse matrix multiplication using to much RAM
<p>I have two csr sparse matrix 136095x136095 : X and A with dtype Bool</p> <p>I want to calculate <code>X @ A @ X</code></p> <p>But I hit this error :</p> <pre><code>Unable to allocate 93.3 GiB for an array with shape (12525785139,) and data type int64 </code></pre> <p>it happens at the line (from scipy code not my co...
<python><scipy>
2023-10-24 12:02:55
0
1,329
Hugo
77,351,885
558,738
Getting correct path to current script when running from exec()
<p>When I run one python file from another python file by using exec(), the __file__ attribute is the caller's path not the callee:</p> <p>file caller.py:</p> <pre><code>with open(&quot;callee.py&quot;, &quot;r&quot;) as callee: exec(callee.read(), globals(), locals()) </code></pre> <p>file callee.py:</p> <pre><co...
<python><exec>
2023-10-24 12:01:02
0
1,797
Periodic Maintenance
77,351,878
13,000,229
Is it possible to make the box bigger on Swagger UI?
<h2>Environment</h2> <ul> <li>Python 3.11.6</li> <li>flask 2.2.5</li> <li>connexion 2.14.2</li> <li>swagger-ui-bundle 0.0.9 (installed by <code>pip install connexion[swagger]</code>)</li> </ul> <h2>Problem</h2> <p>I would like to know how to make this box bigger. I checked Swagger UI website (e.g. <a href="https://swag...
<python><flask><swagger><connexion>
2023-10-24 11:59:31
0
1,883
dmjy
77,351,719
10,133,797
Override numpy array string representation
<p><code>with np.printoptions</code>'s <a href="https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html" rel="nofollow noreferrer"><code>formatter</code></a> argument allows controlling formatting of individual array elements. Is there something for the entire array?</p> <p>I'm looking for somethin...
<python><numpy>
2023-10-24 11:36:12
0
19,954
OverLordGoldDragon
77,351,504
3,416,774
No module named 'pydantic.v1' even though pip list see it
<p>I install <code>obsei[all]</code> in a venv, then run <code>python .\example\facebook_example.py</code>. I get:</p> <p><a href="https://github.com/obsei/obsei/issues/310" rel="nofollow noreferrer" title="[BUG] pydantic.errors.PydanticImportError: `BaseSettings` has been moved to the `pydantic-settings` package · Iss...
<python><pydantic>
2023-10-24 10:58:06
1
3,394
Ooker
77,351,471
4,666,912
Finding the largest time gap in a list of years
<p>I have a huge dataframe (around 100 million rows) in the following manner:</p> <pre><code>ID Years 1 [1990,1991,1995,2000,2001,2006] 2 [1990,1990] 3 [1980,1981,1990,1995] </code></pre> <p>I want it to return the first occurrence of <em>the largest gap between two consecutive years</em> as the following da...
<python><pandas><dataframe>
2023-10-24 10:53:44
5
2,343
BKS
77,351,273
661,589
how to merge two multi-depth objects in python
<p>I am building some app that needs configuration with lots of similarities and some differences. I'd like to be able to use some base config and override it with the specific values where needed.</p> <p>Each config element is a list of configurations, and each configuration is a dict that can have dict or array as va...
<python><json><list><dictionary><merge>
2023-10-24 10:21:29
1
19,251
Gavriel
77,351,190
22,326,950
How to check for mouse movement outside of tkinter GUI mainloop?
<p>To understand threadding better I try to write a clicker with a small tkinter GUI, which only clicks when you don't move the mouse. I have created a working script without noise (labels that show duration, clicks, settings etc.) that runs a deamon permanently in the background to detect mouse movements:</p> <pre cla...
<python><multithreading><tkinter>
2023-10-24 10:08:25
0
884
Jan_B
77,351,073
4,979,809
How to automate my sources? (Python and SqlServer)
<p>In my .pbix, my data consists of 4 queries: <a href="https://i.sstatic.net/I7Jpv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/I7Jpv.png" alt="enter image description here" /></a></p> <p>One query is a <strong>Python.Execute</strong>, the other 3 are <strong>Sql.Database</strong>.</p> <ul> <li>T...
<python><powerbi><powerbi-desktop><gateway>
2023-10-24 09:51:47
1
706
Chicago1988
77,350,880
9,318,372
match-case: Bind keyword attribute to variable
<p>When matching against a <a href="https://peps.python.org/pep-0622/#class-patterns" rel="nofollow noreferrer">class-pattern</a> with keyword attributes, is it possible to bind the attribute to a variable directly?</p> <p>For positional arguments, it is possible via walrus operator: <a href="https://peps.python.org/pe...
<python><mypy><python-typing><structural-pattern-matching>
2023-10-24 09:23:01
1
1,721
Hyperplane
77,350,706
13,874,745
How to only execute partial codes of a method of super class in python?
<p>I know how to call the method of super class by using <code>super()</code>, like these:</p> <pre><code>&gt;&gt;&gt; class A: &gt;&gt;&gt; def func1(self): &gt;&gt;&gt; print(&quot;1&quot;) &gt;&gt;&gt; print(&quot;2&quot;) &gt;&gt;&gt; print(&quot;3&quot;) &gt;&gt;&gt; class B(A): &gt;&g...
<python><inheritance><super>
2023-10-24 08:54:21
1
451
theabc50111
77,350,602
10,564,566
Cannot open Pycharm (Process 5,540 is still running)
<p>When I am trying to open Pycharm on Ubuntu (22.04) I am getting the following error from time to time (around 50% of cases): <code> Cannot connect to already running IDE instance. Exception: Process 5,540 is still running</code> Killing process: <code>sudo kill -9 5540</code> helps, but it is quite annoying and it w...
<python><linux><ubuntu><pycharm><ide>
2023-10-24 08:36:04
1
539
Matmozaur
77,350,263
9,718,879
How to detect requested urls in Javascript or Python
<p>I would like to know whether there's a javascript or python package that could help monitor the requests performed by an application. Let's say for example in my browser I click on a document. The package should be able to grab the requested link for that document. I know packet analysis can be done with wireshark b...
<javascript><python><request><network-programming>
2023-10-24 07:38:12
1
1,121
Laspeed
77,350,048
4,380,515
Retrieve a redis-py Lock name from a LockError?
<p>I have an application that uses <a href="https://redis-py.readthedocs.io/en/v4.1.2/lock.html" rel="nofollow noreferrer"><code>redis.lock.Lock</code></a> (from the official <a href="https://github.com/redis/redis-py" rel="nofollow noreferrer">redis-py</a> package) a lot. It's either used directly by what I'm developi...
<python><redis><redis-py>
2023-10-24 06:54:53
1
3,854
Blusky
77,349,979
1,895,611
Is there any alternative to brute force matching binary images?
<p>This opencv/numpy code works, but is 1000x too slow. basically I have a white square, and another image that is slightly rotated and translated. The code recovers the pose by brute force trying all angles and translations within 10 degrees and 10 pixels.</p> <p>I tried find homography but got terrible results. This...
<python><optimization><computer-vision><gpu><homography>
2023-10-24 06:41:03
1
8,256
AwokeKnowing
77,349,929
1,186,991
Python claims my venv doesnt have requests module but i have pip3 installed it
<p>Im sure for some of you this will likely be a stupid question but ive spent the last 3 hrs trying to get my first virtual environment working and i still cant seem to get it to work. Ive successfully completed the following.</p> <ol> <li>Installed an older version of Python 3.10.10</li> <li>Created a virtual environ...
<python><visual-studio-code><pytorch>
2023-10-24 06:30:28
1
3,631
Hans Rudel
77,349,903
14,661,648
How to configure Nginx server for Flask-Sock?
<p>I am not talking about Socket-IO but just regular Websocket, I am using this library: <a href="https://flask-sock.readthedocs.io/en/latest/web_servers.html" rel="nofollow noreferrer">https://flask-sock.readthedocs.io/en/latest/web_servers.html</a></p> <p>How do I configure my Nginx configuration for <code>wss://</co...
<python><nginx><flask><flask-sockets>
2023-10-24 06:23:34
1
1,067
Jiehfeng
77,349,823
8,523,868
How to select the date from the calender box as same from the spreadsheet
<p>Thanks in advance for my reply. I want to select the calendar from the calendar box. I tried to send the code using selenium with python. It is not able to select the correct date. It is getting displayed as 21 -- ju--l- 22 instead of 21-JUL-2023 Below i have given the code and screenshot. Please help me to select t...
<python><selenium-webdriver>
2023-10-24 06:02:54
2
911
vivek rajagopalan
77,349,733
754,136
Best way to pass configuration with ranges
<p>I have a plotting function that I use for multiple things. The way I plot curves is the same, but I need to customize the limits and the label depending on the data I am plotting. Right now I define the settings in dictionaries and then read them like</p> <pre class="lang-py prettyprint-override"><code>for d in data...
<python><json><arguments><fb-hydra>
2023-10-24 05:37:19
2
5,474
Simon
77,349,670
3,685,918
how to get bloomberg index data using blpapi and xbbg on python
<p>I'd like to pull data from <code>blpapi</code> and <code>xbbg</code>.</p> <p>It works well on Excel as belows.</p> <pre><code>=BDS(&quot;YCGT0025 Index&quot;,&quot;CURVE_TENOR_RATES&quot;, &quot;CURVE_DATE=20230930&quot;,&quot;headers=t&quot;) </code></pre> <p>But not working on python as bleows.</p> <pre><code>blp...
<python><blpapi>
2023-10-24 05:18:41
1
427
user3685918
77,349,582
9,983,652
why feature importance from decision tree model is different each run?
<p>I am working on stratified kfold cv with decision tree model. The feature importance from decision model is different each time running the model. The accuracy is different as well each time. Can anyone help me understand why the result is different each time?</p> <p>Also,below has 10 fold CV, so which fold do I use...
<python><scikit-learn>
2023-10-24 04:49:47
1
4,338
roudan
77,349,560
4,582,026
Do you always need to call the library when running a python function in command line?
<p>The following line works in command prompt to call my function</p> <pre><code>python -c &quot;from foo import xyz; xyz.aFunction(n)&quot; </code></pre> <p>However, I want to continue calling the function by changing the variable n and also call other functions from xyz. Do I always need to import xyz before call...
<python>
2023-10-24 04:42:23
1
549
Vik
77,349,540
10,990,958
How would I set a background Image in customtkinter?
<p>I want to set a png as the background image in a custokinter UI I have this code</p> <pre><code>import customtkinter import random from PIL import Image import PIL customtkinter.set_appearance_mode(&quot;light&quot;) # Create a list to track the names that have already been chosen chosen_names = [] def button_cal...
<python><user-interface><background><customtkinter>
2023-10-24 04:36:14
1
349
Pandas INC
77,349,206
3,350,050
Shabang Line For Python Script With Conda
<p>I'm trying to write my Python script to run in a particular <em>conda</em> environment without relying on the user to do it correctly. If the environment is named <em>MyEnv</em>, for example, the following <a href="https://unix.stackexchange.com/questions/399690/multiple-arguments-in-shebang">shabang line</a> will ...
<python><pip><conda>
2023-10-24 02:33:31
0
573
Jim
77,349,149
15,781,591
Unable to change barplot width
<p>I have the following code trying make a bar plot in python using seaborn, based simply on a two-column dataframe, with a &quot;Category&quot; column, and &quot;Value&quot; column with float values:</p> <pre><code>dataplot = sns.barplot(x = 'Category', y = 'Value', data = df, hue='Category') <...
<python><pandas><seaborn><bar-chart>
2023-10-24 02:10:33
1
641
LostinSpatialAnalysis
77,349,120
6,394,617
Example of SimPy event that is triggered but not processed
<p>Just like <a href="https://stackoverflow.com/q/76421544/6394617">this question</a>, I don't understand what triggered means for a SimPy event. The only answer posted does not clarify it for me.</p> <p>The docs say an event:</p> <ul> <li>might happen (not triggered),</li> <li>is going to happen (triggered) or</li> <l...
<python><simpy>
2023-10-24 01:58:34
2
913
Joe
77,349,083
10,990,958
How would I remove the CTKLabel from a label using customtkinter?
<p>I have this code:</p> <pre><code>import customtkinter import random customtkinter.set_appearance_mode(&quot;light&quot;) # Create a list to track the names that have already been chosen chosen_names = [] def button_callback(): # Create a list of names names = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Car...
<python><tkinter><while-loop><label><customtkinter>
2023-10-24 01:49:19
1
349
Pandas INC
77,349,031
2,955,541
Using subs for PolyElement
<p>After creating a <code>sympy</code> <code>PolyElement</code>:</p> <pre><code># This is just a simple example x, P = sympy.symbols('x:3'), sympy.symbols('P') K = ZZ[x+(P,)] model = K.from_sympy(P*(x[1]+x[2])) </code></pre> <p>I expected to be able to, say, substitute <code>P=1</code> into the <code>model</code>:</p>...
<python><sympy>
2023-10-24 01:25:47
2
6,989
slaw
77,348,920
8,869,570
numpy.nan_to_num equivalent in sql?
<p>I am trying to rewrite a set of python operations in SQL. Specifically, I have a python script that queries from a sqlite3 connection from a table <code>table_name</code> for the column <code>vals</code> and note that <code>vals</code> is a nullable column.</p> <p>It then filters the return values using <code>numpy....
<python><sqlite><null><nan>
2023-10-24 00:27:12
1
2,328
24n8
77,348,874
301,584
why serv.bind in this tutorial expected to always returns exception?
<p>I got the code below from multiple sources after googling &quot;port scanner using python&quot;</p> <pre><code>import socket s = socket.socket() host = socket.gethostname() for port in range(65535): try: serv = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # create a new socket serv.bi...
<python>
2023-10-24 00:06:18
0
4,598
imin
77,348,872
12,170,032
why does applying probability distributions and transformations result in the same value?
<p>I'm applying multiple Beta, Gamma and HalfNorm Transforms to each column of my pandas dataframe. The dataframe consists of marketing spend; each row indicates spend per week and each column indicates type of spend: <a href="https://i.sstatic.net/6luLJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6l...
<python><pandas><probability-distribution>
2023-10-24 00:06:06
1
495
Erin
77,348,858
11,922,765
Python Pandas Dataframe convert julian day column to date column
<p>I have a column full of julian days. I want to convert them to date format.</p> <pre><code>df1.shape() (638765, 94) df1['DAY'] = 0 2022216 # Format = year (2022),day of the year (216) 1 2022216 2 2022216 3 2022216 4 2022216 from datetime import datetime </code></pre> <p>Sol...
<python><pandas><dataframe><datetime><julian-date>
2023-10-24 00:00:34
1
4,702
Mainland
77,348,806
2,547,556
Override a class attribute of the type of a generic type via a mixin so mypy won’t say it’s incompatible
<p>I have a generic base class <code>A</code> that has an attribute containing the generic type <code>TK</code>.</p> <pre class="lang-py prettyprint-override"><code>import typing class K1: pass TK = typing.TypeVar(&quot;TK&quot;, bound=K1) class A(typing.Generic[TK]): k: type[TK] </code></pre> <p>Then I h...
<python><generics><mypy><python-typing><mixins>
2023-10-23 23:40:38
0
749
Yushin Washio
77,348,770
1,802,826
Why does my shell script register a successful exit when it fails?
<p>I have a shell script that executes <a href="https://github.com/openai/whisper/" rel="nofollow noreferrer">whisper</a> on all files in a directory on a network device, and then stores the resulting transcript on the same volume. Sometimes something happens with the network (the volume is disconnected) that makes the...
<python><bash><shell><exit-code>
2023-10-23 23:24:05
1
983
d-b
77,348,764
3,507,584
Python or R Context aware fuzzy matching
<p>I am trying to match two string columns containing food descriptions [<code>foods1</code> and <code>foods2</code>]. I applied an algorithm weighting the word frequency so less frequent words have more weight but it fails as it does not recognise objects.</p> <p>For instance, <code>foods1</code> item &quot;Bagel with...
<python><r><fuzzy-comparison>
2023-10-23 23:21:35
1
3,689
User981636
77,348,634
7,102,718
Is it possible to query the last element of an array using MongoEngine?
<p>I'm trying to query the last element of a list in a Mongo document using MongoEngine. I can write a raw query to do this but I'm wondering if it's possible to do it without resorting to that.</p> <p>So for example, while <code>X.objects(some_list__val='Test Value')</code> would return any objects which have some lis...
<python><mongodb><pymongo>
2023-10-23 22:30:45
1
332
ScriptSurfer
77,348,585
2,854,555
How to await for a job multiple times in trio?
<p>This is similar to <a href="https://stackoverflow.com/questions/71970942/can-i-await-the-same-task-multiple-times-in-python">Can I await the same Task multiple times in Python?</a>, but for trio (instead of asyncio). Basically, in trio, how can I <code>await</code> for (the result value of) an <code>async</code> fun...
<python><async-await><python-trio>
2023-10-23 22:15:09
2
691
renyuneyun
77,348,582
2,954,547
Psycopg 3 & SQLAlchemy 2: what would cause DuplicatePreparedStatement in normal operation?
<p>We are using SQLAlchemy in our application to interact with a TimescaleDB database with Psycopg as the database driver.</p> <p>Recently we started seeing this error every time the application tries to select from the database:</p> <pre><code>psycopg.errors.DuplicatePreparedStatement: prepared statement &quot;_pg3_3&...
<python><postgresql><sqlalchemy><timescaledb><psycopg3>
2023-10-23 22:15:02
0
14,083
shadowtalker
77,348,561
3,245,998
How does the AWS CLI open a browser and wait for a response before proceeding?
<p>I'm trying to build a golang cli tool for my company and as part of that build login and some other features into the tool. For the life of me I can't figure out how AWS is able to open a browser window and wait for a few button clicks before proceeding from the CLI.</p> <p><a href="https://docs.aws.amazon.com/singl...
<python><go><aws-sdk><aws-cli><aws-sdk-go>
2023-10-23 22:08:31
1
876
JacobW
77,348,500
19,694,624
Can't log into instagram using instaloader: incorrect password
<p>I'm trying to gather a list of my instagram followers using instaloader python module, but I get the error:</p> <pre><code>instaloader.exceptions.ConnectionException: Login error: &quot;fail&quot; status, message &quot;Sorry, your password was incorrect. Please double-check your password.&quot;. </code></pre> <p>But...
<python><instagram-api><instagram-graph-api><instaloader>
2023-10-23 21:49:00
1
303
syrok
77,348,189
13,231,896
How to send html email to multiple recipients using python3 smtplib
<p>I am trying to send an Email with HTML content to multiple recipients using python-3.10 I have read the documentation and came up with the following code, but, although the email it's been send to all recipients, the message is not showing the html correctly. The message I receive has no html format, nor line breaks...
<python><smtplib>
2023-10-23 20:36:32
0
830
Ernesto Ruiz
77,348,033
12,734,203
SQLAlchemy: QueryableAttribute missing arguments
<p>I have a SQLAlchemy model mapped as a dataclass (single class example below)</p> <pre><code>class Base(DeclarativeBase): pass class Players(Base, MappedAsDataclass): __tablename__ = &quot;players&quot; player_uid: Mapped[str] = mapped_column(String(128), primary_key=True) first_name: Mapped[str] = ...
<python><class><sqlalchemy>
2023-10-23 20:05:33
1
305
DECROMAX
77,347,779
2,494,795
Error when Trying to Load Data Into Azure Cognitive Search Index (AttributeError: 'str' object has no attribute 'get')
<p>I am trying load data (with embeddings) into my Azure Cognitive Search index. This is my process after adding the embedding fields to my Pandas dataframe:</p> <pre><code>input data = df.to_json() # Where DF is the Pandas dataframe with embedding fields # Use SearchIndexingBufferedSender to upload the documents in b...
<python><azure><azure-cognitive-search>
2023-10-23 19:14:46
1
1,636
Irina
77,347,777
9,795,817
Checkpoint multiple pyspark dataframes
<p>I have some code that wraps a while loop inside another while loop (the algorithm it implements requires this structure unfortunately).</p> <p>The dataframes used in the loops have super long lineages, so I'd like to use <a href="https://stackoverflow.com/questions/67916597/dataframe-checkpoint-example-pyspark"><cod...
<python><apache-spark><pyspark>
2023-10-23 19:14:31
0
6,421
Arturo Sbr
77,347,740
1,930,402
Joining 2 dataframes in pyspark where one column can have duplicates
<p>I have a pyspark dataframe with 2 columns, <code>ID</code> and <code>condition</code>. ID corresponds to a user, the user can have multiple conditions. I want to find out those users who have condition A and condition B, how to do that?</p> <p>Sample dataframe:</p> <div class="s-table-container"> <table class="s-tab...
<python><pyspark>
2023-10-23 19:07:36
1
1,509
pnv
77,347,618
758,836
Sentence Transformers Segmentation fault
<p>I get a <code>Segmentation fault</code> error when calling <code>model.encode</code> on a <code>SentenceTransformer</code> model:</p> <pre class="lang-bash prettyprint-override"><code>Segmentation fault root@0ac58308616e:/app# /usr/local/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_t...
<python><pytorch><huggingface-transformers><sentence-transformers>
2023-10-23 18:44:49
0
16,321
loretoparisi
77,347,403
1,547,004
How to handle QComboBox wheel-events with an event-filter?
<p>In Qt6, many widgets (QComboBox, QSpinBox) will steal mouse wheel events that should be handled by their parent widget (like a QScrollArea), even when they don't have focus, and even when the <code>focusPolicy</code> has been set to <code>StrongFocus</code>.</p> <p>I can subclass these widget classes and re-implemen...
<python><events><mousewheel><pyside6><qcombobox>
2023-10-23 18:05:28
1
37,968
Brendan Abel
77,347,287
6,231,968
What components of spaCy Pipeline can be disabled so that the sentence tokenization can still work and the pipeline be faster?
<p>I want to use the spaCy pipeline only for sentence tokenization as it's the best for my language but I want it to be as minimal as possible.</p> <p>So far I figured I could get rid of tagger and ner components:</p> <p><code>nlp = spacy.load(&quot;pl_core_news_sm&quot;, disable=['tagger', 'ner'])</code></p> <p>I noti...
<python><nlp><spacy>
2023-10-23 17:40:34
1
525
Karol
77,347,083
9,640,238
Print formula in plot
<p>Sympy returns a print of an expression in Jupyter in mathematical notation. E.g.:</p> <pre class="lang-py prettyprint-override"><code>from sympy import symbols from sympy.plotting import plot x = symbols(&quot;x&quot;) 2 + 3 * x**2 </code></pre> <p>will print: <a href="https://i.sstatic.net/UjYag.png" rel="nofollo...
<python><jupyter><sympy>
2023-10-23 17:01:54
1
2,690
mrgou
77,347,024
492,191
self-reference model in pydantic
<p>I would like to serialize a structure with has self-references:</p> <pre class="lang-py prettyprint-override"><code>class FileSystemEntry(BaseModel): id: str path: str | None = None mime_type: str | None = None is_directory: bool parent: FileSystemEntry | None = None children: List[FileSyste...
<python><recursion><filesystems><pydantic>
2023-10-23 16:52:42
1
350
stuudent
77,346,958
308,827
Converting days in pandas dataframe to other categories
<p>I have the following dataframe:</p> <pre><code> country Duration 0 Afghanistan 0 days 1 Afghanistan 4 days 2 Afghanistan 0 days 3 Afghanistan 22 days 4 Afghanistan 6 days ... ... 316813 Zim...
<python><pandas>
2023-10-23 16:41:42
1
22,341
user308827
77,346,904
14,111,512
Django-Python: You must set settings.ALLOWED_HOSTS if DEBUG is False
<p>I am trying to deploy a Django-Python based web application in Kubernetes. I'm also trying to setup OpenTelemetry so that I could capture the application metrics and visualise it using prometheus and Grafana.</p> <p>However, when I try to instrument the application data to the OpenTelemetry collector, I am getting t...
<python><python-3.x><django><kubernetes>
2023-10-23 16:33:12
0
385
arjunbnair
77,346,557
19,130,803
read row for given id from pickle file without loading all data
<p>I have a dataframe with 2 columns (ID, Contents) which I am saving in <code>pickle</code> format. Say for example, I have 10 rows(ie 0 to 9 ID). I am trying to load a single row by passing <code>ID</code> (valid ID between 0-9) from the <strong>pickle file without loading the entire file</strong>.</p> <pre><code>imp...
<python><pandas>
2023-10-23 15:41:48
4
962
winter
77,346,314
6,087,667
Assign axes to the chart in xlwings
<p>By using the script below I can generate the chart but it assigns columns to abscissa. How can I assign the rows to it, i.e. x,y,z as abscissa and A,B,C as ordinates.</p> <p><a href="https://i.sstatic.net/G4E1B.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G4E1B.png" alt="enter image description her...
<python><excel><charts><xlwings>
2023-10-23 15:04:12
1
571
guyguyguy12345
77,346,244
4,451,315
How to resolve "Incompatible return value type (got "FancyCat", expected "Self")"
<p>Here's a minimal example I've written:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from typing import Protocol from typing_extensions import Self class Cat(Protocol): def add(self, other: Self) -&gt; Self: ... def sub(self, other: Self) -&gt; Self: ...
<python><mypy><python-typing><self-type>
2023-10-23 14:54:13
1
11,062
ignoring_gravity
77,346,241
5,005,808
python cv2.CAP_PROP_FRAME_COUNT get wrong result, and also the cv2.CAP_PROP_FPS get wrong fps
<p>I want to use <code>cv2</code> to extract frames from a <code>.mkv</code> video file. The following is my code. I get wrong results for fps and frame count. I tried opencv versions 4.7.xx and 4.8.xx but still get the same problem. How shall I deal with this? The actual fps of my video file is 30 and the total frame ...
<python><opencv>
2023-10-23 14:54:07
0
1,930
pfc
77,346,210
2,584,772
Getting module names from unittest tests in python
<p>Is there a way to get test module names programmatically, from a test suite, when using python unittest?</p> <p>Python <code>unittest.loader.TestLoader</code> has a discover method that returns all test modules but I can't figure out a way to get only the test modules names.</p> <p>What I did:</p> <pre><code>import ...
<python><testing><python-unittest>
2023-10-23 14:49:28
2
1,684
Caco
77,345,810
3,238,679
Speed up matching between a sliding window and a list
<p>I have an odd length window and a array and I need to find the index of the array where the window is centered and matches more. So far I am doing it with the following code. Is it possible to speed up these computations?</p> <pre><code>import numpy as np import time def find_best_match_position(lst, window): m...
<python><algorithm><numpy><sliding-window>
2023-10-23 13:52:14
1
1,041
Thoth
77,345,420
10,133,797
Print numpy arrays truncated
<p>Something like</p> <pre class="lang-py prettyprint-override"><code>print({n: np.random.randn(50, 50, 50) for n in 'abcd'}) </code></pre> <p>prints a big mess. In MATLAB, it shows</p> <pre class="lang-matlab prettyprint-override"><code> &quot;a&quot; ⟼ {50×50×50 double} &quot;b&quot; ⟼ {50×50×50 double} &q...
<python><numpy><formatting>
2023-10-23 12:58:47
2
19,954
OverLordGoldDragon
77,345,288
4,405,942
Comparing JPEG images in PIL
<p>I am trying to assert equality between JPEG Images using PIL: Currently, I'm relying on exact comparison using the following:</p> <pre><code>from PIL import Image, ImageChops img1 = Image.open(&quot;tmp_img.jpg&quot;) img2 = Image.open(&quot;tmp_img.jpg&quot;) ImageChops.difference(img1, img2).getbbox() is None </co...
<python><python-imaging-library><jpeg><image-comparison>
2023-10-23 12:39:52
0
2,180
Gerry
77,345,242
9,973,879
How to test for a raised Exception in the exit of a context manager?
<p>I am using pytest to test my program. I want to test for an Exception of type <code>Foo</code> being raised when a context manager exits. Using</p> <pre><code>with pytest.raises(Foo): with my_context_mngr(): pass </code></pre> <p>works but with the caveat that it will silently succeed if <code>Foo</code> is ra...
<python><pytest>
2023-10-23 12:32:45
2
1,967
user209974
77,345,136
2,123,706
Convert list of dictionaries to dictionary of dictionaries
<p>I have a list of dictionaries</p> <pre><code>ls1 = [{'AccountBalance': '78', 'Status': '0'}, {'AccountBalance': '56', 'Status': '1'}, {'AccountBalance': '34', 'Status': '0'}, {'AccountBalance': '12', 'Status': '0'}] </code></pre> <p>I would like to convert this to a dictionary of 2 dictionaries</p> <pre><code>dic...
<python><dictionary>
2023-10-23 12:14:58
3
3,810
frank
77,345,121
20,830,264
Azure OpenAI LangChain - (InvalidField) The vector field 'content_vector' must have the property 'vectorSearchConfiguration' set
<p>I'm trying to create an embedding vector database with some .txt documents in my local folder. In particular I'm following this tutorial from the official page of LangChain: <a href="https://python.langchain.com/docs/integrations/vectorstores/azuresearch" rel="nofollow noreferrer">LangChain - Azure Cognitive Search ...
<python><azure-cognitive-search><langchain><azure-openai><openaiembeddings>
2023-10-23 12:12:47
1
315
Gregory
77,344,919
5,955,479
Airflow - importing DAG with dependencies
<p>I deployed airflow on kubernetes using the official helm chart. I'm using KubernetesExecutor and git-sync.<br /> I am using a seperate docker image for my webserver and my workers - each DAG gets its own docker image. I am running into DAG import errors at the airflow home page. E.g. if one of my DAGs is using <code...
<python><kubernetes><airflow>
2023-10-23 11:46:38
1
355
user430953
77,344,749
2,726,900
PythonVirtualenvOperator gives error: No module named unusual_prefix_***_dag
<p>I'm using airflow 2.5.3 with Kubernetes executor and Python 3.7.</p> <p>I've tried to make a simple DAG with only one <code>PythonVirtualnvOperator</code> and two context variables (<code>{{ ts }}</code> and <code>{{ dag }}</code>) passed into it.</p> <pre><code>from datetime import timedelta from pathlib import Pat...
<python><kubernetes><airflow><pickle><dill>
2023-10-23 11:22:08
1
3,669
Felix
77,344,656
1,661,465
Testing concurrent.futures.TimeoutError and logging in a threaded function using Pytest
<p>I've come across a testing challenge in my Python project and I'm hoping to get some insights from the community. I have a utility module containing a function <code>threaded_execute</code> which utilizes the <code>concurrent.futures</code> module to execute a function in a separate thread. If a <code>concurrent.fut...
<python><testing><pytest><concurrent.futures>
2023-10-23 11:06:26
1
3,421
serghei
77,344,570
12,415,855
Writing only part of the text in a cell as bold?
<p>i am writing / changing a cell-value in an existing excel-sheet using openpyxl and formating the cell as bold using the following code:</p> <pre><code>import openpyxl from openpyxl.styles import Font workbook = openpyxl.load_workbook(&quot;try.xlsx&quot;) worksheet = workbook.active worksheet['C1'] = &quot;this is s...
<python><openpyxl>
2023-10-23 10:51:20
1
1,515
Rapid1898
77,344,373
2,074,697
Importing data from Excel; set values in Merged Cells to be the same
<p>I'm importing some hundred Excel files into a SQL Database and I need to have an import procedure which is very general, in the sense that I don't need to adjust any variables depending on the structure of the Excel file.</p> <p>Thus I cannot use column names explicitly in the code and I cannot refer to cells with t...
<python><pandas><excel>
2023-10-23 10:18:11
1
1,242
Cenderze
77,344,296
2,725,810
PCA affects similarity comparisons even when keeping all the dimensions
<p>Consider:</p> <pre class="lang-py prettyprint-override"><code>from sklearn.decomposition import PCA import numpy as np from sklearn.metrics.pairwise import cosine_similarity def do_pca(X, n_components): print(f&quot;Doing PCA from {X.shape[0]} vectors&quot;) pca = PCA(n_components=n_components) X_pca = ...
<python><scikit-learn><pca>
2023-10-23 10:03:45
1
8,211
AlwaysLearning
77,344,291
1,841,839
Wrong type of credentials for creating tuning model in quickstart
<p>I am trying to set up a tuning model for Palm api.</p> <p>It requires authorization so I am following the <a href="https://developers.generativeai.google/tutorials/oauth_quickstart" rel="nofollow noreferrer">Oauth quick start</a></p> <p>I have configured the consent screen and created the desktop app credetials as s...
<python><machine-learning-model><palm-api>
2023-10-23 10:03:20
1
118,263
Linda Lawton - DaImTo
77,344,277
4,194,079
Cross dimensional segmented operation
<p>Say you have the following <code>a</code> array</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a = np.arange(27).reshape((3,3,3)) &gt;&gt;&gt; a array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 2...
<python><numpy><jax>
2023-10-23 10:01:13
2
6,705
keepAlive
77,343,917
13,793,478
Navigating in flask using JS
<p>I am trying to use JavaScript function to navigate to another flask route.</p> <p>this is the function</p> <pre><code>dateClick: function(info) { alert('Date: ' + info.dateStr); alert('Resource ID: ' + info.resource.id); } </code></pre> <p>instead of alet I want it to navigate to ...
<javascript><python><flask>
2023-10-23 09:02:34
1
514
Mt Khalifa
77,343,863
5,730,859
Pandas table convert to word with repeated columns
<p>I want the columns and the data arrange nicely as the below format in the word</p> <pre><code>Name: Sam Age: 14 Weight: 45 Name:Andrea Age: 25 Weight: 88 Name:Alex Age: 55 Weight: 56 Name:Robin Age: 8 Weight: 15 Name:Kia Age: 21 Weight: 71 </code></pre> <p>However,my code below unable to get teh desired output a...
<python><python-docx>
2023-10-23 08:54:16
1
934
bkcollection
77,343,814
2,725,810
pca.tranform(data) vs. data @ pca.components_.T
<p>Given the matrix X, suppose we did:</p> <pre class="lang-py prettyprint-override"><code>from sklearn.decomposition import PCA pca = PCA(n_components=5).fit_transform(X) </code></pre> <p>Given a data matrix <code>data</code>, I would expect that the reduction to 5 dimensions is given by:</p> <pre class="lang-py prett...
<python><scikit-learn><pca>
2023-10-23 08:46:30
1
8,211
AlwaysLearning
77,343,501
859,227
Dividing two columns of pandas daraframe and keep the header name
<p>With the following data frame</p> <pre><code>ID,WEIGHT,I1,I2,I4 1,0.2,839,1664,3266 2,0.1,851,863,858 3,0.4,1018,1999,3982 4,0.3,878,1724,3447 </code></pre> <p>I want to iterate over I1..I4 and create new data frames by joining the <code>WEIGHT</code> column and <code>I_i/I1</code>. The following code works fine</p>...
<python><pandas>
2023-10-23 07:54:18
5
25,175
mahmood
77,343,471
4,402,282
Pytorch: CUDA error: invalid configuration argument
<p>I am attempting to run some third-party Pytorch code, and am seeing the following error:</p> <pre><code> File &quot;D:\Testing\OFFLINE\PSFM\particle-sfm\motion_seg\core\network\traj_oa_depth.py&quot;, line 48, in extract_feature output_feat = self.transformer_model(input_traj, input_traj, \ File &quot;C:\Users...
<python><pytorch>
2023-10-23 07:49:24
1
3,165
anti
77,343,422
17,128,041
Connect CloudSQL Postgres Db using Python
<p>So I am DevOps engineer please excuse for my lack of knowledge in python development. I am trying to connect a CloudSQL Postgres 14 Db using Python. So that I can insert data and read data from my application. Can someone help me understand why I am getting error when I try to run the python script.</p> <p>Reference...
<python><postgresql><google-cloud-platform><google-cloud-sql>
2023-10-23 07:40:27
2
1,599
sidharth vijayakumar
77,343,330
1,780,761
Customize a class of a library
<p>I am using a Python library that has one function that I would need to customize.</p> <p>That is not a problem, since I can make my own edited version like this:</p> <pre><code>from coolLibrary import originalclass class myclass(originalclass): whatever... </code></pre> <p>The problem that I am facing now, is t...
<python>
2023-10-23 07:24:16
2
4,211
sharkyenergy
77,343,078
9,501,624
How to close a Navbar Dropdownmenu when opening another one?
<p>I added multiple <a href="https://dash-bootstrap-components.opensource.faculty.ai/docs/components/dropdown_menu/" rel="nofollow noreferrer">dropdownmenus</a> to a <a href="https://dash-bootstrap-components.opensource.faculty.ai/docs/components/navbar/" rel="nofollow noreferrer">navbar</a>. When activating both one a...
<python><bootstrap-5><plotly-dash>
2023-10-23 06:40:07
1
3,844
Christian Karcher
77,343,073
11,182,916
Find points that are equidistant from 4 points
<p>This code needs a very long time to find a point. Is there any better way to find a point that is equidistant from 4 given points? A tolerance of 0.5 is fine.</p> <pre><code>import numpy as np # Define the four 3D points as (x, y, z) coordinates point1 = np.array([1, 2, 3]) point2 = np.array([3, 4, 5]) point3 = np....
<python><numpy>
2023-10-23 06:38:05
4
405
Binh Thien
77,343,000
1,159,290
can python multiprocessing do semaphores between "unrelated" processes?
<p>I am looking at the multiprocessing python module to protect some hardware (memory mapped) resources which requires atomic access (to do some stuff). (The hardware is an FPGA implementing some finite state machine, and that machine should be returned to idle before any other access could start...)</p> <p>The SW whic...
<python><multiprocessing>
2023-10-23 06:21:56
2
1,003
user1159290
77,342,992
11,855,904
How can I order a Django query by a field of a related model?
<p>I have these two models, <code>ChatRoom</code> and <code>ChatMessage</code>, which are related. My goal is to order the <code>ChatRoom</code> queries in a way that the room with the most recent message, as determined by the <code>sent_timestamp</code>, appears at the top of the results.</p> <p>While I've found some ...
<python><django><django-models><django-queryset>
2023-10-23 06:20:46
3
392
cy23
77,342,988
988,279
Sort a list of dictionaries...(Itemgetter)
<p>I want to group a list of dictionaries by a key. The following code is working.</p> <pre><code>from itertools import groupby from operator import itemgetter user_dict = {123: [ {'the_id': 1, 'title': 'Title1'}, {'the_id': 1, 'title': 'Title1'}, {'the_id': 3, 'title': '...
<python>
2023-10-23 06:19:45
3
522
saromba
77,342,624
5,104,777
How to log arbitrary request headers in Flask?
<p>How do you log headers such as <code>X-Request-ID</code> (or <code>X-Amzn-Trace-Id</code>) in Flask v3?</p> <p>(Apparently in version 1 Flask needed an extension to provide this functionality but <a href="https://github.com/Workable/flask-log-request-id" rel="nofollow noreferrer">that project</a> was orphaned and is...
<python><http><flask><logging>
2023-10-23 04:21:38
1
5,062
benjimin
77,342,593
395,857
How can I call with Postman a RESTful API deployed with Gradio?
<p>I'm following the basic Gradio interface from the <a href="https://www.gradio.app/docs/interface" rel="nofollow noreferrer">Gradio documentation</a>:</p> <pre><code>import gradio as gr def greet(name): return &quot;Hello &quot; + name + &quot;!&quot; demo = gr.Interface(fn=greet, inputs=&quot;text&quot;, outpu...
<python><rest><postman><gradio>
2023-10-23 04:08:54
2
84,585
Franck Dernoncourt
77,342,177
5,924,264
How to locate object that cannot be pickled inside complex object
<p>Related to my earlier question: <a href="https://stackoverflow.com/questions/77341161/how-to-i-change-import-statements-in-a-pickle-file">How to I change import statements in a pickle file?</a></p> <p>I am trying to change an import statement inside a serialized file. It ended up causing some unexpected issues when ...
<python><serialization><cursor><pickle>
2023-10-23 00:48:05
0
2,502
roulette01
77,342,049
7,306,999
Make tkinter widgets expand to fill up horizontal space
<p>I have the following code that generates a GUI window with <code>tkinter</code>:</p> <pre><code>from tkinter import ttk import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self._create_widgets() def _create_widgets(self): self.columnconfigure(0, wei...
<python><tkinter>
2023-10-22 23:41:21
1
8,674
Xukrao
77,341,790
2,386,605
Create multi-column Postgresql trgm index and filter based on that in sqlalchemy
<p>Assume we install the <code>pg_trgm</code> extension</p> <pre><code>create extension pg_trgm; </code></pre> <p>And then create an index on the <code>user</code> table</p> <pre><code>CREATE INDEX user_search_idx ON user USING gin (first_name gin_trgm_ops, last_name gin_trgm_ops); </code></pre> <p>How would I crea...
<python><postgresql><indexing><sqlalchemy><full-text-search>
2023-10-22 21:38:43
0
879
tobias
77,341,666
4,557,607
How to convert gguf to bin?
<p>Trying to follow the LangChain documentation about Llama.cpp but I do not understand how to obtain the <code>.bin</code> file from a <code>.gguf</code>, i.e.: I downloaded <code>llama-2-7b-chat.Q8_0.gguf</code>.</p> <p>Note that the docs only show how to convert the old format.</p> <p>Here is the Llama.cpp doc link:...
<python><langchain><large-language-model><py-langchain>
2023-10-22 20:52:51
0
1,020
Edv Beq
77,341,580
3,433,875
Convert an animation into an in-memory file or a function
<p>I am creating a matplotlib animation to be displayed on a flask app based on user input. The matplotlib script is similar to this:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # Horizontal bar plot with gaps fig, ax = plt.subplots() ax.get_yaxis().set_vi...
<python><matplotlib><flask><matplotlib-animation><bytesio>
2023-10-22 20:25:41
1
363
ruthpozuelo
77,341,479
13,526,701
Open and execute command on visual terminal on startup raspberry pi
<p>I have a python script that includes a webserver and i want to run it on a terminal when the rpi boots. Before that I also have to use iptables to do some routing, dependent on the configuration. All that works with python code already and it can also be run on startup. In case that an error occurs, i would want to ...
<python><linux><raspbian>
2023-10-22 19:51:51
1
419
NoBlockhit