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,420,772
992,421
pyspark RDD count nodes in a DAG
<p>I have RDD which shows up as</p> <pre><code>[&quot;2\t{'3': 1}&quot;, &quot;3\t{'2': 2}&quot;, &quot;4\t{'1': 1, '2': 1}&quot;, &quot;5\t{'4': 3, '2': 1, '6': 1}&quot;, &quot;6\t{'2': 1, '5': 2}&quot;, &quot;7\t{'2': 1, '5': 1}&quot;, &quot;8\t{'2': 1, '5': 1}&quot;, &quot;9\t{'2': 1, '5': 1}&quot;, &quot;10...
<python><apache-spark><pyspark><mapreduce>
2023-11-04 04:41:50
2
850
Ram
77,420,395
2,647,447
why does python's panda return differce found when compare two csv files and the cell is empty?
<p><a href="https://i.sstatic.net/oKcac.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oKcac.png" alt="enter image description here" /></a>(1) I am using Python's pandas to compare two csv files. In the both files have exact same data set and should return something like the statement &quot;two files ar...
<python><pandas><dataframe>
2023-11-04 01:07:01
1
449
PChao
77,420,330
1,374,078
How to retain sqlalchemy model after adding `row_number()`?
<p>I'm try to filter rows in some method so I need the output model to be of the same type as input model to the sqlAlchemy query.</p> <p>I followed this answer <a href="https://stackoverflow.com/a/38160409/1374078">https://stackoverflow.com/a/38160409/1374078</a> . However would it be possible to get the original mode...
<python><sqlalchemy>
2023-11-04 00:27:03
1
1,652
phoxd
77,420,311
856,804
Under what condition will `str(float(val)) == val` NOT hold in Python?
<p>For a string <code>val</code> variable like <code>&quot;1.2345&quot;</code>, does <code>assert str(float(val)) == val</code> always hold?</p> <p>I've already found it doesn't always hold</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; str(float('1.2345')) '1.2345' &gt;&gt;&gt; str(float('0.1231412...
<python><floating-point><precision>
2023-11-04 00:19:33
1
9,110
zyxue
77,420,235
1,481,689
Why isn't `repr` calling `__repr__`?
<p>I have a class where a constructor argument is only used in <code>__init__</code> and therefore I didn't want to save it as a field, but I did want a nice <code>__repr__</code>. So I wrote something along these lines:</p> <pre class="lang-py prettyprint-override"><code>from types import MethodType class X: def _...
<python><python-3.x>
2023-11-03 23:51:16
0
1,040
Howard Lovatt
77,420,119
748,742
Python - multiprocessing and multithreading
<p><strong>Question:</strong></p> <p>I am trying to gain a better understanding of Python's multiprocessing and multithreading, particularly in the context of using the <code>concurrent.futures</code> module. I want to make sure my understanding is correct.</p> <p><strong>Multiprocessing:</strong></p> <p>I believe that...
<python><multithreading><multiprocessing>
2023-11-03 23:07:18
1
383
uba2012
77,420,118
11,981,718
how to loop through .py files using importlib
<p>I am trying to use the prefix modl and iterate through .py files that I use as settings. I'd like to stick to python files because it is easy to declare functions and variables and import them. The problem I run into is that the module does not update at the second iteration:</p> <pre><code>for settingsfile in ['set...
<python><python-importlib>
2023-11-03 23:06:52
0
412
tincan
77,420,085
1,285,061
prepopulate numpy array with fixed values
<p>How can I prepopulate while initializing numpy array with fixed values? I tried generating <code>list</code> and using that as a <code>fill</code>.</p> <pre><code>&gt;&gt;&gt; c = np.empty(5) &gt;&gt;&gt; c array([0.0e+000, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323]) &gt;&gt;&gt; np.array(list(range(0,10,1))) array([0,...
<python><arrays><numpy>
2023-11-03 22:56:13
2
3,201
Majoris
77,419,995
266,014
PyLance stops working with an error immediately after VS Code start
<p>I have faced an issue with VS Code Pylance. The following output for the &quot;Python Language Server&quot; is generated immediately after VS Code start:</p> <pre><code>2023-11-04 00:06:42.035 [info] [Info - 12:06:42 AM] (2176) Pylance language server 2023.11.10 (pyright 088ebaa5) starting 2023-11-04 00:06:42.036 [...
<python><visual-studio-code><pylance>
2023-11-03 22:23:42
0
314
Viktor
77,419,978
6,251,742
Fake SMTP server not supporting auth
<h1>Fake SMTP server not supporting auth</h1> <p>I have a function that create a SMTP client, login onto a server, and send mails. I want to create a unit-test with a fake SMTP server that will write the email content into a io stream instead of sending the email.</p> <p>Everything works great except the login part tha...
<python><unit-testing><authentication><server><aiosmtpd>
2023-11-03 22:18:12
0
4,033
Dorian Turba
77,419,973
803,533
FastAPI + Selenium to convert HTML to PDF pages
<p>I'm attempting to develop a REST service that will render HTML to a PDF file on demand. I have explored multiple options but I have yet to find one that renders a PDF document as perfectly as Chrome itself. So I thought to wrap <code>Selenium</code> and <code>Chromedriver</code> in a FastAPI by leveraging the great ...
<python><python-3.x><selenium-webdriver><selenium-chromedriver><fastapi>
2023-11-03 22:15:03
0
479
K997
77,419,948
8,383,726
Python - pandas_datareader Error: "data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]TypeError: string indices must be integers"
<p>I really can't seem to figure out this error that I keep getting from the simple code below. I am using <code>Python 3.9.13</code> and <code>pandas 2.1.2</code> . I appreciate in advance the help in figuring this out.</p> <pre><code>import datetime import pandas_datareader.data as web import requests from bs4 import...
<python><python-3.9><pandas-datareader>
2023-11-03 22:07:35
1
335
Vondoe79
77,419,881
758,614
Create a feature, scenario, and its steps at runtime
<p>I'm using python-behave to run some test. For a &quot;proof-of-concept&quot; project I would like to create a test (feature/scenario) at runtime.</p> <p>I'm gathering the test steps from a web server and try to build a <code>Scenario</code> object. One idea was to use the <code>before_all</code> hook to get the step...
<python><python-behave>
2023-11-03 21:52:24
1
529
Mario
77,419,870
893,254
How to obtain a P-Value from a Python Scipy Optimize Least Squares regression?
<p>I have performed a function minimization using Python <code>scipy.optimize.least_squares</code>.</p> <p>The function minimized is a chi-squared function.</p> <pre><code>solution = scipy.optimize.least_squares(optimize_function, x0, method='lm', \ ftol=1.0e-8, xtol=1.0e-8, \ max_nfev=1000000, args=(bi...
<python><scipy><scipy-optimize><p-value><chi-squared>
2023-11-03 21:49:52
0
18,579
user2138149
77,419,708
1,055,869
Pandas apply row wise access faster
<p>Consider the example where A and B are measurements and T is a threshold left joined in from another dataframe. T_name represents the column for which that threshold applies. I want to only keep the measurements that are above the thresholds.</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,1,4,4],'B':[9...
<python><pandas>
2023-11-03 21:07:41
1
2,740
Shabbir Hussain
77,419,705
8,478,404
All combinations of elements in a vector in a larger vector
<p>I have the following input vector.</p> <pre><code>['a','b','c'] </code></pre> <p>I want to list all possible combinations.</p> <p>There are three restrictions:</p> <ul> <li>The values have to be inserted into an output vector of six positions.</li> <li>One given value from the input vector can only occur once in th...
<python><combinations>
2023-11-03 21:06:38
2
535
petyar
77,419,483
336,114
Broken HTML links in Python error output in Interactive Windows and Notebook outputs in VS Code (circa VS Code 1.84)
<p>After the recent update of vscode my error messages in the python interactive window started to look like this:</p> <pre class="lang-none prettyprint-override"><code>File c:\Users\user\anaconda3\lib\site-packages\pandas\core\internals\construction.py:845, in to_arrays(data, columns, dtype) ref='c:\Users\user\anacond...
<python><visual-studio-code><jupyter-notebook><python-interactive>
2023-11-03 20:18:24
1
393
Philipp
77,418,896
10,452,700
AttributeError: 'GrouperView' object has no attribute 'join'
<p>I'm trying to reproduce this <a href="https://stackoverflow.com/a/42712772/10452700">answer</a> but getting the following error:</p> <blockquote> <p>AttributeError: 'GrouperView' object has no attribute 'join'</p> </blockquote> <pre class="lang-py prettyprint-override"><code>-----------------------------------------...
<python><python-3.x><seaborn><heatmap><attributeerror>
2023-11-03 18:14:38
2
2,056
Mario
77,418,669
1,279,355
Use flattbuffer enum with mypy
<p>Flattbuffer generates python code like this for enums -&gt;</p> <pre><code>class ErrorType(object): ERROR1 = 0 ERROR2 = 1 </code></pre> <p>And i would like to use it as a type in a function -&gt;</p> <pre><code>def my_function(error: ErrorType): pass </code></pre> <p>And if i call it now with</p> <pre><cod...
<python><types><mypy>
2023-11-03 17:36:07
1
4,420
Sir l33tname
77,418,578
4,575,197
How to detect if a request has been redirected and if so dokument it in Dataframe
<p>i'm trying to catch if a request that i send to many websites, has been redirected or not. first let me give you some example Data.</p> <pre><code>redirected_urls = [ &quot;http://www.tagesschau.de/inland/vw-schalte-hapke-101.html&quot;, &quot;http://de.reuters.com/article/deutschland-volkswagen-idDEKCN10V0H...
<python><pandas><http-redirect><python-requests>
2023-11-03 17:16:15
2
10,490
Mostafa Bouzari
77,418,545
2,893,024
Vercel seems to ignore my requirements.txt file so no packages are installed
<p>I'm running a React frontend with a python serverless backend on Vercel.</p> <p>My <code>requirements.txt</code> file contains the following lines:</p> <pre><code>pydantic==2.4.2 openai~=0.28.1 python-dotenv~=1.0.0 </code></pre> <p>And yet, none of these packages are installed upon running.</p> <p>When hitting that ...
<python><vercel>
2023-11-03 17:10:39
0
3,576
Michael Seltenreich
77,418,344
403,425
Reuse logic between frontend (SvelteKit) and backend (Django)
<p>I am building a webshop where we have complicated logic to determine which offers are valid for which products, based on which products you already own, what's in your basket, and a bunch more rules. Up until now this code has always lived in the backend (Django with Django REST Framework), and every time you'd add ...
<python><node.js><sveltekit>
2023-11-03 16:35:16
1
5,828
Kevin Renskers
77,418,144
3,231,250
for each element of 2d array sum higher elements in the row and column
<p>My input dataframe (or 2D numpy array) shape is 11kx12k</p> <p>For each element, I check how many values are higher in the given row and column.</p> <p>For example:</p> <pre><code>array([[1, 3, 1, 5, 3], [3, 7, 3, 2, 1], [2, 3, 1, 8, 9]]) </code></pre> <p>row-wise:</p> <pre><code>3 1 3 0 1 1 ...
<python><pandas><numpy><matrix>
2023-11-03 16:05:18
2
1,120
Yasir
77,417,920
4,397,312
Pytorch 1.13 dataloader is significantly faster than Pytorch 2.0.1
<p>I've noticed that PyTorch 2.0.1 DataLoader is significantly slower than PyTorch 1.13 DataLoader, especially when the number of workers is set to something other than 0. I've done some research and found that this is due to a change in the way that PyTorch handles multiprocessing in version 2.0.1. In PyTorch 1.13, th...
<python><pytorch><dataloader>
2023-11-03 15:30:50
0
717
Milad Sikaroudi
77,417,907
3,480,297
Filter queryset from filename field based on two words that appear one after the other Django
<p>I have a <code>Files</code> table, which contains various fields, one of which is a <code>filename</code>. Within each one of the files in this table, there is a specific file that I'd like to retrieve, which is basically a terms and conditions. This filename will always have the words 'terms' and 'conditions' withi...
<python><django><regex><django-rest-framework><drf-queryset>
2023-11-03 15:28:58
1
2,612
Adam
77,417,902
9,137,547
How to map scipy.sparse.lil_array?
<p>I have a starting <code>lil_array</code> of boolean values. (<a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_array.html" rel="nofollow noreferrer">Docs</a>)</p> <p>Eg dimensions 3,5 and values:</p> <pre><code> (0, 2) True (0, 4) True (1, 0) True (1, 1) True (1, 3) ...
<python><scipy>
2023-11-03 15:27:58
3
659
Umberto Fontanazza
77,417,898
268,581
Combine two charts (U.S. Treasuries data and $SPX)
<h1>Chart 1</h1> <p>This program creates a chart of the ratio of bills to (notes + bonds) issued by the U.S. Treasury.</p> <pre><code>import requests import pandas as pd from bokeh.plotting import figure, show from bokeh.models import NumeralTickFormatter, HoverTool # ------------------------------------------------...
<python><pandas><bokeh>
2023-11-03 15:27:30
1
9,709
dharmatech
77,417,774
5,740,734
How to iterate every two elements of a list in an Ansible loop?
<p>I have list variable with disks names which сan be off variable amount - 4, 8, 16 etc. elements, but even and I want to print every two disks in loop at all iteration. How I can do this?</p> <pre class="lang-yaml prettyprint-override"><code>--- - hosts: all vars: disks: - sdc - sdd - sde ...
<python><ansible><jinja2>
2023-11-03 15:11:17
1
655
mocart
77,417,662
3,815,773
How do you get the UTC time offset in Python now that utcnow() is deprecated?
<p>I need the time difference in sec between my current location and UTC. It worked so well with (example timezone Berlin, UTC+1h) :</p> <pre><code>import datetime datetime.datetime.utcnow().timestamp(): 1699017779.016835 datetime.datetime.now().timestamp(): 1699021379.017343 # 3600 sec larger, correct! </code></pre...
<python><datetime><unix-timestamp>
2023-11-03 14:56:32
1
505
ullix
77,417,608
2,386,113
How to create a square-shaped plot with same number of ticks on x and y axis
<p>I am plotting an ellipse, which could become a circle if the values of the major and minor axis are the same. Therefore, I would like to have a square shape plot with the same number of ticks on the x and y-axes. I am already compting the maximum range for ticks in my program but still, the plot is not square-shaped...
<python><matplotlib>
2023-11-03 14:49:42
0
5,777
skm
77,417,474
7,240,233
plotly sunburst + datapane : bug with markers shape
<p>I have sunburst figure made with plotly that I'd like to include into a datapane report. However, some of the levels are hatched, and the hatching is not displayed in datapane (works fine in a standard html file with the figure only). I joined a code example for allow testing, taken from <a href="https://plotly.com/...
<python><plotly><sunburst-diagram><datapane>
2023-11-03 14:30:30
0
721
Micawber
77,417,274
521,347
Error in connecting to AlloyDB database with IAM user
<p>For Postgre Cloudsql, we have to use google cloud-sql-python-connector to connect to DB. When we establish a connection using IAM user, we don't have to pass any password if we pass a flag <code>enable_iam_auth</code> as true . I confirmed this by looking at source-code of this connector that password is optional ...
<python><google-cloud-sql><google-alloydb>
2023-11-03 14:04:56
1
1,780
Sumit Desai
77,417,218
583,464
parallelize file processing (in loop)
<p>I am trying to parallelize processing files.</p> <p>I am using this code:</p> <pre><code>import pandas as pd import glob from tqdm import tqdm from multiprocessing import Process, Pool SAVE_PATH = './tmp/saved/' data_path = './tmp/data/' def process_files(data_path): for idx_file, file in tqdm(enumerate(glob.g...
<python><parallel-processing><multiprocessing>
2023-11-03 13:58:34
2
5,751
George
77,417,118
2,292,133
Pydantic 2 - Editing alias after object generation
<p>I want to edit the alias value on a Pydantic model after it has been created:</p> <pre><code>class MyModel(BaseModel): name: str age: int obj = MyModel(age=8, name='Brian') field = obj.model_fields['name'] field.alias = 'full_name' [IN] obj.model_dump(by_alias=True) [OUT] { 'name': 'Brian', ...
<python><pydantic>
2023-11-03 13:44:18
1
767
Tom Hamilton Stubber
77,416,929
3,190,076
Can I use the same lock on multiple threads if they do not access the same variable?
<p>Imagine I have two threads, each modifying a different variable. Can I pass the same lock object to them, or shall I use two separate locks? In general, when shall I use multiple locks?</p> <p>Here is a toy example:</p> <pre><code>from threading import Thread, Lock from time import sleep def task(lock, var): w...
<python><multithreading><locking>
2023-11-03 13:11:57
1
10,889
alec_djinn
77,416,883
9,494,140
what is the proper way to use aggregate in a complicated structured Django models
<p>I have a Django app that represents a football league and should show scores points and other stuff, I need to create a function based on the models in this app to get the sum of goals, points, matches won, and positions in the current season, here are my models :</p> <p><strong>models.py</strong></p> <pre class="la...
<python><django><aggregate>
2023-11-03 13:05:23
2
4,483
Ahmed Wagdi
77,416,832
7,089,239
Proper exception handling when interleaving context managers
<p>I need to lock the <code>__enter__</code> of a context manager but release the lock right after the context has been entered. How can this be done cleanly? Note that both contexts are provided in libraries, so I cannot move the first context into the enter of the second. (In my case the first is an async lock and th...
<python><concurrency><contextmanager>
2023-11-03 12:57:00
0
2,688
Felix
77,416,739
14,649,310
Chain tasks without passing the previous results in Python Celery
<p>I want to create a chain of async event to be executed one after the other but I am not interested in passing the result of the previous one to the next one, just execute them in a chain. I am have something like this:</p> <pre><code>tasks = [] for document_id in document_ids: tasks.append( utils.task( ...
<python><celery><celery-task>
2023-11-03 12:39:32
1
4,999
KZiovas
77,416,725
5,132,860
Unable to launch Selenium, encountering DeprecationWarning and WebDriverException errors
<p>Suddenly today, Selenium could not be launched in my project. The error messages are as follows:</p> <pre><code>main.py:11: DeprecationWarning: executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(options=options,executable_path='drivers/chromedriver-linux64/chromedriver')...
<python><python-3.x><selenium-webdriver><selenium-chromedriver>
2023-11-03 12:37:05
1
3,104
Nori
77,416,517
9,318,323
How to query subset of data from a file on azure datalake
<p>My datalake has json files. Each file is a pandas dataframe represented as a json. So a file may have this inside:</p> <pre><code>[ { &quot;col1&quot;:&quot;1&quot;, &quot;col2&quot;:&quot;3&quot; }, { &quot;col1&quot;:&quot;2&quot;, &quot;col2&quot;:&quot;4&quot; } ] </code></pre...
<python><pandas><azure><azure-data-lake-gen2>
2023-11-03 12:01:23
1
354
Vitamin C
77,416,375
4,726,173
Import locally installed python package from elsewhere
<p>Yet another stupid question about Python packaging. I've searched stackoverflow but am unable to find an answer, or, the answers I find do not work.</p> <p>The task: Load a package, locally installed (with or without the -e editable flag), from another .py file somewhere else, or from python on the command line.</p>...
<python><pip><setuptools><python-packaging>
2023-11-03 11:37:31
0
627
dasWesen
77,416,240
7,988,415
`ipympl` interactive plots are not interactive, no navigation bar or buttons, in jupyter notebook in pycharm
<p>I am running the example on <code>ipympl</code> homepage in a jupyter notebook in pycharm:</p> <pre><code>%matplotlib ipympl import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 100) y = np.sin(3*x) ax.plot(x, y) </code></pre> <p>And I am not getting interactive to...
<python><matplotlib><jupyter-notebook><ipympl>
2023-11-03 11:17:51
0
1,054
Alex
77,416,182
6,541,082
Pyspark Json Extract Values
<p>I am working with a PySpark DataFrame that has a JSON column from CSV file <code>budgetthresholdaction</code>. The JSON structure looks like this:</p> <pre><code>{ &quot;budgetThresholdAction0threshold0&quot;: { &quot;thresholdValue&quot;: 80, &quot;action&quot;: &quot;promotionsetup.BudgetThresholdPercent...
<python><json><pyspark><explode>
2023-11-03 11:07:49
0
553
pkd
77,416,106
3,153,443
How do I wrap a byte string in a BytesIO object using Python?
<p>I'm writing a script with the Pandas library that involves reading the contents of an excel file.</p> <p>The line currently looks like this:</p> <pre><code>test = pd.read_excel(archive_contents['spreadsheet.xlsx']) </code></pre> <p>The script works as intended with no issues, but I get a future warning depicting the...
<python><pandas><object><byte><bytesio>
2023-11-03 10:54:37
2
583
user3153443
77,416,013
2,123,706
Why does .to_sql() return a -1 or 1 after appending to table?
<p>I have the following set up</p> <pre><code>import sqlalchemy import pandas as pd server = 'server' database = 'database' driver = 'driver' database_con = f'mssql://@{server}/{database}?driver={driver}' engine = create_engine(database_con, fast_executemany=True) con = engine.connect() df = pd.DataFrame({'col1':[1,2...
<python><sql-server><pandas><sqlalchemy>
2023-11-03 10:43:05
1
3,810
frank
77,415,861
2,245,633
File open and apostrophes in file names
<p>I have some simple code [CentOS 7 &amp; python 3.6, because... stuck with a VM image]:</p> <pre class="lang-py prettyprint-override"><code>with open(filename, &quot;r&quot;) as read_file: # do stuff </code></pre> <p>Which is grand &amp; wonderful - does the self-closing thing, and has no problems with spaces in ...
<python><python-3.x>
2023-11-03 10:18:57
1
923
CodeGorilla
77,415,449
1,802,826
Force flush Python-part of Bash-script?
<p>I have a simple Bash-script that spend more than 99 % of its time on executing a Python application (the script is just a wrapper that feeds this Python script files in a for-loop and renames the output files). I have the same problem as described <a href="https://stackoverflow.com/questions/1429951/force-flushing-o...
<python><bash><shell><buffer><flush>
2023-11-03 09:16:47
1
983
d-b
77,415,274
3,337,089
Clear all the GPU memory used by pytorch in current python code without exiting python
<p>I am running a modified version of a third-party code which uses pytorch and GPU. I run the same model multiple times by varying the configs, which I am doing within python i.e. I have a wrapper python file which calls the model with different configs. But I am getting <code>out-of-memory</code> errors while running...
<python><memory-management><pytorch><memory-leaks><out-of-memory>
2023-11-03 08:50:12
2
7,307
Nagabhushan S N
77,415,114
1,142,881
How to make the int values of an Enum to match the corresponding database record id?
<p>I have a database table that contains specific companies that are accessed &quot;statically&quot; throughout the code and for which would be great to have a &quot;static&quot; way to refer to them, for example:</p> <pre><code>from enum import Enum, auto() class CompanyEnum(Enum): APPLE = auto() AMAZON = a...
<python><enums><peewee>
2023-11-03 08:20:20
1
14,469
SkyWalker
77,415,040
2,517,880
Python difflib.SequenceMatcher comparison issue
<p>I'm trying to compare two large text strings. Each can contain approximately 15 thousand characters. I need to find replace, insert, delete, and equal with their start and end characters by comparing two strings so that further operations can be done properly.</p> <p>I've also tried the difflib library, but it is no...
<python><diff>
2023-11-03 08:07:28
1
1,114
Vaibhav
77,414,951
15,175,771
Sparql query returns undesired results when using blank nodes (rdflib)
<p>I use <code>rdflib</code> python library to model a graph of contacts, and perform <code>sparql</code> queries to retrieve who knows who. This works fine when people as added as <code>URIRef</code>, but not when using <code>BNode</code>.</p> <p>The example graph can be represented as follow:</p> <pre><code>bob - k...
<python><sparql><rdf><rdflib><blank-nodes>
2023-11-03 07:47:15
1
340
GabrielGodefroy
77,414,802
10,573,543
Using python client for Kubernetes I am not able to increase the number of replicas for a specific pod?
<h4>Details:</h4> <hr /> <p>I am using AWS EKS service to manage my application in a K8 cluster. In one of the pod which is called <code>my-core-pod</code> in the namespace <code>mytenantspace</code>, I have a python flask app running. I have created an endpoint <code>create_infra</code>, What it does is, it takes a PO...
<python><kubernetes><flask><amazon-eks>
2023-11-03 07:17:39
1
1,166
Danish Xavier
77,414,787
1,757,224
Column names do not appear using druiddb
<p>I am running Apache Druid datastore locally. I am loading data from a Kafka stream.</p> <p>On Druid, I can see the column names:</p> <p><a href="https://i.sstatic.net/bMfID.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bMfID.png" alt="enter image description here" /></a></p> <p>And then using druidd...
<python><pandas><druid>
2023-11-03 07:14:59
2
973
ARAT
77,414,702
5,897,478
Wyze SDK: How do I use the refresh token properly?
<p>I'm trying to understand how the refresh_token() function works in the Wyze python SDK: <a href="https://github.com/shauntarves/wyze-sdk/blob/master/wyze_sdk/api/client.py" rel="nofollow noreferrer">https://github.com/shauntarves/wyze-sdk/blob/master/wyze_sdk/api/client.py</a></p> <p>Let's say I want to access the W...
<python><authentication><sdk><access-token><refresh-token>
2023-11-03 06:56:44
1
488
Aran Bins
77,414,343
5,675,288
How can I format a python logger which is defined in one class but calls itself from another class?
<p>I have an internal logging library which I consume to run my service. The library provides 2 logging capabilities, one for standard and one for debug. I want to log the filename and function name for the logger as well. Since the library does not provide that functionality, I modified the formatter. But I noticed th...
<python><logging><python-logging>
2023-11-03 05:19:37
1
915
scientific_explorer
77,414,325
14,365,042
Join two floats with trailing 0 together
<p>I wrote a function:</p> <pre><code>def main_table(data, gby_lst, col): df = data.groupby(gby_lst)[col].describe() df = df.reset_index() for i in ['25%', '50%', '75%', 'std', 'min', 'max', 'mean']: df[i] = df[i].apply(lambda x: float(&quot;{:.2f}&quot;.format(x))) df['Mean ± SD'] = (df[['mean'...
<python><string><f-string>
2023-11-03 05:13:44
1
305
Joe
77,414,316
13,142,245
FastAPI: 'value_error.missing' when parameter present in query
<p>Here is my FastAPI method</p> <pre class="lang-py prettyprint-override"><code>class Student(BaseModel): name: str age: int year: str ... @app.post('/create-student/{student_id}') def create_student(student_id : int, student : Student): db = connect_ddb() try: response = db.put...
<python><fastapi><pydantic>
2023-11-03 05:09:34
1
1,238
jbuddy_13
77,414,306
12,175,228
Show transparent image with openCV python
<p>im working with opencv and when showing the image it has a black background even its already transparent, (sometimes white) but that depends on the image, in this case the eye image when showing it appears with black background, dont know how can i show it complety transparent:</p> <pre><code> while True: recor...
<python><opencv><image-processing><alpha><alpha-transparency>
2023-11-03 05:08:19
1
365
plus
77,414,212
4,297,413
Efficiently partition Pandas DataFrame rows such that the sum of a column is at least X in each partition
<p>Suppose we have the following DataFrame with a single <code>weight</code> column.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; pd.DataFrame(dict(weight=[1, 3, 5, 6, 8, 9, 5, 6, 5, 5, 4, 9])) weight 0 1 1 3 2 5 3 6 4 8 5 9 6 5 7 6 8 ...
<python><pandas><dataframe>
2023-11-03 04:31:17
1
652
Erp12
77,414,097
4,399,016
Extracting URLs from website using Pyquery and requests
<p>I have this code:</p> <pre><code>from pyquery import PyQuery as pq import requests url = &quot;https://www.mba.org/news-and-research/forecasts-and-commentary&quot; content = requests.get(url).content doc = pq(content) Latest_Report_MO = doc(&quot;#ContentPlaceholder_C012_Col01&quot;) print(Latest_Report_MO) </cod...
<python><python-requests><pyquery>
2023-11-03 03:52:05
1
680
prashanth manohar
77,413,945
3,685,918
How to display the x-axis in as yy.m only for the first month of the year and the rest as m
<p>This is my example code and output.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # Create a DataFrame with a date column and another column with the data you want to plot data = {'Date': ['2023-01-01', '2023-02-01', '2023-03-01', '2024-01-01', '2024-02-01'], ...
<python><pandas><matplotlib><datetime><xticks>
2023-11-03 02:56:11
1
427
user3685918
77,413,726
4,582,026
How to sharpen an image using openCV in Python
<p>I have applied the following adjustments to the original image:</p> <ul> <li>resized</li> <li>changed the colour scale</li> <li>greyscaled</li> <li>thresholded</li> <li>inverted the colours</li> </ul> <p>This results in the following image</p> <p><a href="https://i.sstatic.net/fTunf.png" rel="nofollow noreferrer"><i...
<python><ocr><tesseract><image-preprocessing><game-automation>
2023-11-03 01:35:40
1
549
Vik
77,413,634
13,142,245
Storing map types in DynamoDb, is "M" declaration required?
<p>Using Boto3, how can I store python dictionaries as non-PK attributes in DynamoDb?</p> <p>My CDK</p> <pre class="lang-js prettyprint-override"><code>... this.table = new Table(this, `myTable`, { partitionKey: { name: 'id', type: AttributeType.STRING, }, }); ... </code></pre> <p>Wh...
<python><amazon-dynamodb><fastapi>
2023-11-03 00:53:11
1
1,238
jbuddy_13
77,413,598
3,891,431
Dynamic keys in Pydantic v2
<p>Trying to use pydantic to model a json file like this:</p> <pre><code>{ &quot;people&quot;: { &quot;Jack&quot;: {&quot;age&quot;: 32, &quot;postcode&quot;: 1223}, &quot;Robert&quot;: {&quot;age&quot;: 23, &quot;postcode&quot;:2354}, &quot;Sarah&quot;: {&quot;age&quot;: 55, &quot;postcode&...
<python><python-3.x><pydantic>
2023-11-03 00:35:31
1
4,334
Rash
77,413,591
1,552,837
How to plot axline within each subplot
<p><strong>I'm trying to add an <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.axline.html" rel="nofollow noreferrer"><code>axline</code></a> with <code>slope=1</code> to each of a series of subplots.</strong></p> <ul> <li>I'm following <a href="https://matplotlib.org/stable/gallery/specialty_p...
<python><matplotlib>
2023-11-03 00:32:22
1
4,907
alexwhitworth
77,413,587
4,930,914
Capital words between words - Regex
<p>I am trying to find capital words occurring between words using Regex. I want to ignore capital words after.?! and starting of paragraph.</p> <p>Currently using the code below to find capital letters</p> <p>[A-Z][^\s]*</p> <pre><code>Example A sentence containing Capital letters. How to Extract only capital letter...
<python><regex>
2023-11-03 00:30:55
4
915
Programmer_nltk
77,413,572
219,153
How do I get backslash marker in matplotlib?
<p>I was hoping for this Python 3.11 script to render <code>\</code> markers:</p> <pre><code>import numpy as np, matplotlib.pyplot as plt plt.scatter([1, 2, 3], [3, 1, 4], marker='$\textbackslash$', c='b') plt.show() </code></pre> <p>but it renders <code>-</code> instead. How do I get <code>\</code> or similar marker?...
<python><matplotlib><scatter-plot>
2023-11-03 00:21:45
1
8,585
Paul Jurczak
77,413,440
7,086,220
why does dataframe.interpolate with spline create unexpected wave
<p>I'm trying to use dataframe.interpolate to fill missing data. Here is my test:</p> <pre><code>from itertools import product df=pd.DataFrame.from_dict({ 1.5 :[np.nan ,91.219 ,np.nan ,np.nan ,102.102 ,np.nan ,np.nan ], 2.0 :[np.nan ,np.nan ,np.nan ,np.nan ,10...
<python><interpolation><missing-data><spline><extrapolation>
2023-11-02 23:34:45
1
343
jerron
77,413,431
5,662,005
ZipFile thread-safe across multiple output files?
<p>It's well covered that writing multiple source files to a single target is not thread safe i.e M:1</p> <p>reference question</p> <p><a href="https://stackoverflow.com/questions/9195206/is-python-zipfile-thread-safe">Is python zipfile thread-safe?</a></p> <p>Does this same limitation hold M:M?</p> <pre><code>file_1.t...
<python><python-3.x><python-zipfile>
2023-11-02 23:30:57
1
3,899
Error_2646
77,413,364
2,805,482
OpenCV: How to copy text from one image and super impose on another
<p>I have a image with only text(always in white color) in it and i want to copy the text from it to another image.</p> <p>Below is the image with logo and image. Currently I am taking a screenshot of this text and superimposing it over another images however as you can see I get the black rectangle along with the text...
<python><opencv><image-processing>
2023-11-02 23:08:46
1
1,677
Explorer
77,413,350
8,297,745
How to return a query using `join` from SQLAlchemy to use it as a Flask result, using Flask SQLAlchemy Session?
<p>I have the following situation:</p> <p>I want to create a route that will return all rows that a column on both <code>models</code> (Tables) have the same values, using <code>join</code> function from SQLAlchemy.</p> <p>The method I created inside my service is like this, which also contains the pure SQL that works,...
<python><flask><sqlalchemy><flask-sqlalchemy>
2023-11-02 23:04:14
3
849
Raul Chiarella
77,413,254
345,716
How to "Destructure" a dict to create a new one?
<p>Finally getting around to learning python...</p> <p>I have a dict with many keys. I want to create a new one with an added key. This is how I'd do it in JavaScript, &quot;destructuring&quot; <code>obj1</code> to create <code>obj2</code> with a new <code>c</code> key:</p> <pre class="lang-js prettyprint-override"><co...
<python>
2023-11-02 22:38:35
1
16,339
Peter V. Mørch
77,413,169
2,304,735
How to append different length columns to a different pandas dataframe?
<p>I am downloading stock prices dataframe and I want to take one column from the stock prices dataframe and copy it to another dataframe.</p> <pre class="lang-none prettyprint-override"><code>Stock Prices Dataframe (MCD): Date Open High Low Close Adjusted_close Volume 0 2020-01-06 199....
<python><python-3.x><pandas><dataframe>
2023-11-02 22:14:03
2
515
Mahmoud Abdel-Rahman
77,413,013
1,169,096
How to staple Apple notarization tickets manually (e.g. under linux)
<p>Recently (as of 2023-11-01) Apple has changed their notarization process.</p> <p>I took the opportunity to drop Apple's own tools for this process (<code>notarytool</code>) and switch to a Python-based solution using their <a href="https://developer.apple.com/documentation/notaryapi/submitting_software_for_notarizat...
<python><linux><macos><code-signing><notarize>
2023-11-02 21:34:16
2
32,070
umläute
77,412,876
5,568,409
How to set ticklabels in bold on x-axis when using usetex=True
<p>I have the following small program in which I use <code>rc(&quot;text&quot;, usetex = True)</code> in order to allow some formatting.</p> <p>I thought that the line <code>ax.set_xticklabels(ax.get_xticks(), weight='bold')</code> would show in <strong>bold</strong> the numbers showed on the <code>x-axis</code>.</p> <...
<python><matplotlib><xticks>
2023-11-02 21:05:24
0
1,216
Andrew
77,412,858
5,378,816
can each import create a separate object?
<p>Imagine a library of classes supporting different input or output formats. Applications may switch between those formats. I'm using different languages only as an example.</p> <p>A straightforward way to set the format could look like this:</p> <pre><code>import mytimes mytimes.set_input_format(&quot;German&quot;) ...
<python><python-import>
2023-11-02 21:01:44
0
17,998
VPfB
77,412,673
13,142,245
put_item DynamoDb with FastAPI post request
<p>I've set up a backend using FastAPI and Pydantic</p> <pre class="lang-py prettyprint-override"><code>class Student(BaseModel): name: str age: int year: str ... @app.post('/create-student/{student_id}') def create_student(student_id : int, student : Student): db = connect_ddb() #Boto3 instantiate...
<python><amazon-dynamodb><boto3><fastapi>
2023-11-02 20:24:22
1
1,238
jbuddy_13
77,412,666
5,955,479
Airflow - using multiple pod templates
<p>We have deployed airflow using the official helm chart and we are using KubernetesExecutor with git-sync. I already managed to launch a worker pod with a custom pod template using the executor_config parameter as mentioned in <a href="https://airflow.apache.org/docs/apache-airflow/stable/core-concepts/executor/kuber...
<python><kubernetes><airflow>
2023-11-02 20:23:32
1
355
user430953
77,412,625
1,743,837
How do I set up a Django user for use in a Selenium test case with the setUp method?
<p>I am working to create Selenium unit tests for my code. I have a simple login form:</p> <pre><code>&lt;form method=&quot;POST&quot;&gt; &lt;input type=&quot;hidden&quot; name=&quot;csrfmiddlewaretoken&quot; value=&quot;f00b4r&quot;&gt; &lt;div id=&quot;div_id_username&quot; class=&quot;form-group&qu...
<python><django><selenium-webdriver><python-unittest>
2023-11-02 20:15:06
0
1,295
nerdenator
77,412,601
11,145,820
how to configure Qdrant data persistence and reload
<p>I'm trying to build an app with streamlit that uses Qdrant python client.</p> <p>to run the qdrant, im just using:</p> <pre><code>docker run -p 6333:6333 qdrant/qdrant </code></pre> <p>I have wrapped the client in something like this:</p> <pre><code>class Vector_DB: def __init__(self) -&gt; None: self.co...
<python><docker><streamlit><qdrant>
2023-11-02 20:09:42
3
1,979
Guinther Kovalski
77,412,296
494,134
What causes an ImportError to report "(unknown location)"?
<p>Looking at <a href="https://stackoverflow.com/q/77411571/494134">this question</a>, there is this import error:</p> <pre><code>&gt;&gt;&gt; from flask_security import login_user Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ImportError: cannot import name 'login_user'...
<python><python-import><importerror>
2023-11-02 19:11:18
2
33,765
John Gordon
77,412,249
866,082
How to prevent a subprocess from outputting to stdout in Python?
<p>I need to run a process using Python and kill it and then rerun it when it hangs. And I don't want the second process to contaminate my shell stdout. But no matter what I do, the subprocess's output is written to the shell. BTW, I'm using Linux.</p> <p>This is what I have:</p> <pre class="lang-py prettyprint-overrid...
<python><shell><anaconda><subprocess><stdout>
2023-11-02 19:02:30
1
17,161
Mehran
77,412,228
2,573,075
Update pydantic from 1 to 2 field issues:
<p>I have the following code:</p> <pre><code>class _Sub(BaseModel): value1: str | None class _Supra(BaseModel): supra_value1: str | None sub_value2: _Sub = Field(default_factory=_Sub) </code></pre> <p>In pydantic 1 doing <code>foo = _Supra(**{})</code> worked fine and created a model like <code>_Supra(_Sub...
<python><pydantic>
2023-11-02 18:59:10
1
633
Claudiu
77,412,205
15,913,281
Count Number of Values Less than Value in Another Column in Dataframe
<p>Given a dataframe like the one below, for each date in <code>Enrol Date</code>, how can I count the number of values in preceding rows in <code>Close Date</code> that are earlier? Ideally I would like to add the results as a new column.</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th styl...
<python><pandas><dataframe><numpy><datetime>
2023-11-02 18:54:53
3
471
Robsmith
77,412,174
734,748
Cannot use the credentials created by Boto3 createAccessKey API
<p>I want to write a python program that make some API calls using user A's credential and then create an access key for user B. Then I want to use user B's newly created access key to make get caller identity API call. Here are the challenges:</p> <p>when I directly use the keys returned by the createAccessKey api cal...
<python><amazon-web-services><boto3>
2023-11-02 18:50:02
1
3,367
drdot
77,412,120
2,681,662
abstractmethod returns a type of self
<p>I'm having some problems with mypy.</p> <p>I have an abstract class and a class that inherits from it:</p> <pre><code>from __future__ import annotations from abc import abstractmethod, ABC from typing import Union class Base(ABC): @abstractmethod def the_method(self, a_class: Union[Base, float, int]) -&gt...
<python><inheritance><mypy><python-typing>
2023-11-02 18:42:10
2
2,629
niaei
77,412,057
11,163,122
Searching Entrez based on paper title
<p>I am trying to search NCBI's Entrez based on a title. Here are my GET requests's URL and parameters:</p> <pre class="lang-py prettyprint-override"><code>import requests url = &quot;https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi&quot; # SEE: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8021862/ params = ...
<python><biopython><ncbi><pubmed>
2023-11-02 18:31:25
1
2,961
Intrastellar Explorer
77,411,830
1,506,763
Connection to PostgresSQL database closed in cPanel Flask app
<p>I've developed a simple flask website that is using a remote PostgreSQL database. I've used <code>sqlalchemy</code> for defining the database and <code>pyscopg</code> for connecting to the database. I store the database URL, username and password in a .env file which I then load in my <code>app.py</code> file. When ...
<python><postgresql><flask><cpanel><psycopg2>
2023-11-02 17:49:53
1
676
jpmorr
77,411,722
3,078,473
Throwing a custom exception. I want to override the casting error message
<pre class="lang-py prettyprint-override"><code>while True: try: age = int(input('How old are you? ')) if age &lt; 0: raise ValueError('negative age') except ValueError as ve: print(f'{ve}') except: print('Error') else: break </code></pre> <p>I want to...
<python>
2023-11-02 17:31:25
3
419
JackOfAll
77,411,626
5,147,965
How can I deploy and run a python web server in an azure app service via docker
<p>I am trying to get a python web server running in an Azure App Service. The container is created via the Dockerfile and pushed to an Azure Docker Registry. Continuous deployment is configured for the existing Azure App Service so that the changes are applied directly. This step works correctly. In addition to the w...
<python><docker><azure-web-app-service>
2023-11-02 17:15:10
1
487
Gehtnet
77,411,624
4,764,604
ImportError: Using `load_in_8bit=True` requires Accelerate: bitsandbytespip: but I have them in the pip freeze
<p>I am trying to launch a gradio backend but I seem to be missing libraries, although I have them downloaded.</p> <pre><code>(.venv) reply@reply-GP66-Leopard-11UH:~/Documents/chatbot-rag$ python3 gradio-chatbot.py /home/reply/Documents/chatbot-rag/.venv/lib/python3.10/site-packages/langchain/__init__.py:34: UserWarni...
<python><python-3.x><path><libraries><gradio>
2023-11-02 17:14:27
1
3,396
Revolucion for Monica
77,411,607
9,381,985
python reading text file with prefixing FF FE bytes
<p>I have got a file, which can be opened in VSCode editor as a normal text file. But if I try to read it in Python:</p> <pre class="lang-py prettyprint-override"><code>with open(&quot;file.ass&quot;) as f: for line in f.readlines(): ... </code></pre> <p>it will throw an exception:</p> <pre class="lang-py pre...
<python><encoding>
2023-11-02 17:11:56
1
575
Cuteufo
77,411,592
11,163,122
Does collections.abc.Collection have a uniqueness property, like Set?
<p>From <a href="https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes" rel="nofollow noreferrer">https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes</a>, it's clear to me that a <code>collections.abc.Set</code> is a <code>collections.abc.Collectio...
<python><data-structures><set><python-typing>
2023-11-02 17:09:50
1
2,961
Intrastellar Explorer
77,411,480
1,560,414
Inconsistant Docker Images
<p>I have been using the <code>python3.9-slim</code> docker image, and as one of the build steps I install the 3.9 python headers, via <code>RUN apt-get install python3-dev</code>.</p> <p>This worked for years, and then <code>apt</code> has changed so that <code>python3-dev</code> now installs the headers for Python 3....
<python><docker><ubuntu><apt>
2023-11-02 16:50:13
1
1,667
freebie
77,411,477
10,713,813
Pygmo multi-objective optimization with constraints
<p>I want to solve a multi-objective optimization problem with constraints using pygmo and obtain the resulting Pareto front. However, even though my program only contains linear constraints, I obtain an error:</p> <pre><code>what: Non linear constraints detected in &lt;class '__main__.SimpleProblem'&gt; instance. NSGA...
<python><optimization><pygmo>
2023-11-02 16:49:45
1
320
wittn
77,411,452
1,668,622
In Python is it possible to extract and re-use the types of variadic collections?
<p>Is it possible to modify <code>deco_with_params</code> in the following snippet to accept an arbitrary number of sequences of generic types while keeping it fully type hinted?</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Mapping, Callable, Sequence import functools def deco_with_p...
<python><python-3.x><variadic-functions><mypy><python-typing>
2023-11-02 16:45:36
1
9,958
frans
77,411,202
1,117,119
How do I make a REST call over the WireGuard protocol only using UDP?
<p>I need to call a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="nofollow noreferrer">REST</a> API which is inside a <a href="https://en.wikipedia.org/wiki/WireGuard" rel="nofollow noreferrer">WireGuard</a> VPN. The WireGuard VPN is client managed, so I can't modify it. I am just provide...
<javascript><python><go><wireguard>
2023-11-02 16:09:12
2
2,333
yeerk
77,411,176
2,095,569
Given a target aspect ratio, how to crop into image, framing around a found face
<p>I have 800x800 portrait image and want to crop into it, finding the face and &quot;framing it&quot; in the centre, while maintaining a 3:4 aspect ratio (outline select box).</p> <p>So I almost need to calculate some kind of &quot;centre point&quot; of the calculated <code>top</code>, <code>bottom</code>, <code>left<...
<python><numpy><python-imaging-library>
2023-11-02 16:04:46
1
666
Harry Lincoln
77,411,143
4,715,957
Extract Config Context YAML information from NetBox
<p>We have a NetBox instance which we use to store information about virtual machines. The Config Context tab for a virtual machine object is populated with a YAML file structured as such:</p> <pre><code>stuff: - hostname: myserver os: Linux os_version: RHEL 8.1 network: - ip_address: 192.168.2.3 network: A...
<python><netbox>
2023-11-02 16:00:23
1
2,315
dr_
77,411,138
6,887,780
Getting incorrect padding error when connecting to AzureAppConfigurationClient
<p>I am using the following code to get the keyvault value but on running the code i am getting the error raise binascii.Error(&quot;Connection string secret has incorrect padding&quot;) binascii.Error: Connection string secret has incorrect padding</p> <pre><code>from azure.appconfiguration import AzureAppConfiguratio...
<python><azure>
2023-11-02 15:59:39
1
427
Sourav Roy