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,097,619
3,247,006
save_screenshot() vs get_screenshot_as_file() in Selenium in Python
<p>I took 2 screenshots of Django Admin with <code>save_screenshot()</code> and <code>get_screenshot_as_file()</code> as shown below. *I use <a href="https://github.com/django/django" rel="nofollow noreferrer">Django</a>, <a href="https://github.com/pytest-dev/pytest-django" rel="nofollow noreferrer">pytest-django</a> ...
<python><selenium-webdriver><screenshot><webpage-screenshot>
2023-09-13 13:38:19
1
42,516
Super Kai - Kazuya Ito
77,097,591
1,185,254
How to create a Mixin Enum
<p>I'm trying to create an enum with a <code>pathlib.Path</code> mixin, MCVE:</p> <pre><code>import enum, pathlib class Test(pathlib.Path, enum.Enum): path1 = pathlib.Path('/path1') path2 = pathlib.Path('/path2') </code></pre> <p>which gives a totally cryptic error:</p> <pre><code> 1 import enum, pathlib -...
<python><enums><mixins><pathlib>
2023-09-13 13:35:17
1
11,449
alex
77,097,497
1,548,981
Deploying AWS lambda from a SAM App with AWS Codepipeline & CodeBuild
<p>I'm doing a cross-account pipeline for a  SAM application. The same application uses a lambda function (hello_world) with aws_lambda_powertools  and a simple rest API. This is a sample application deployed with &quot;sam init&quot;  </p> <p>The pipeline works and deploys the resources, but the lambda function is mis...
<python><amazon-web-services><aws-lambda><aws-codepipeline><aws-codebuild>
2023-09-13 13:25:00
2
1,369
Crerem
77,097,490
1,652,219
How to create a cross table in Polars?
<p>I would like to count unique combinations in two Polars columns.</p> <h1>In R</h1> <pre class="lang-r prettyprint-override"><code>df &lt;- data.frame(a = c(2,0,1,0,0,0), b = c(1,1,1,0,0,1)) table(df) 0 1 0 2 2 1 0 1 2 0 1 </code></pre> <h1>In Pandas</h1> <pre class="lang-py prettyprint-override"><code>imp...
<python><dataframe><pivot><python-polars>
2023-09-13 13:24:32
1
3,944
Esben Eickhardt
77,097,432
9,543,830
How to use default values for empty parameters in FastAPI
<p>I've got a task on the project to update some packages versions due to security reasons. I updated <code>FastAPI</code> from 0.63.0 to 0.95.2. But one test started to fail.</p> <p>This test makes a API request in the following format: <code>https://.../api/v2/list/?limit=&amp;offset=12&amp;...</code>.</p> <p>And I'm...
<python><validation><pytest><fastapi>
2023-09-13 13:16:45
1
2,685
voilalex
77,097,290
4,495,790
How to filter dates of time window relative to column value in Pandas?
<p>I have a Pandas data frame <code>df</code> with columns of <code>ID</code>, <code>DATE</code> (continuous year-month dates of the same six-month-long period) and <code>FIX_DATE</code> (constant year-month date per <code>ID</code> always falling in the second half of the given <code>DATE</code> period). Multiple <cod...
<python><pandas><subset>
2023-09-13 12:57:58
2
459
Fredrik
77,097,277
11,334,608
Connection timeout to S3 from a python application running in ECS EC2
<p>I have a python ECS task running via EC2 (not Fargate). In this task, I am setting up a <code>boto3</code> client</p> <pre><code>cls._instance.client = boto3.client( &quot;s3&quot;, region_name=&quot;eu-west-1&quot;, ) </code></pre> <p>and trying to perform a <code>PutObject</code> operation (<code>client.u...
<python><amazon-web-services><amazon-s3><boto3><amazon-ecs>
2023-09-13 12:56:17
1
759
Simeon Borisov
77,097,235
7,346,393
My consumer receives every second message
<p>I'm trying to implement a simple producer and consumer architecture in my application. My base class for all producers is very simple</p> <pre><code>class ProducerBase(metaclass=abc.ABCMeta): QUEUE: str = &quot;default&quot; EVENT: str def __init__(self) -&gt; None: self.channel = None s...
<python><rabbitmq>
2023-09-13 12:49:28
0
869
Hendrra
77,096,982
13,819,183
mypy infer paramspec of function based on paramspec of first input
<p>I'm creating a function which will act as a factory for a class, here's how it will look:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar(&quot;T&quot;) def app_factory(app: Type[T], *args, **kwargs) -&gt; T: ... return app(*args, **kwargs) class App: def __init__(self, a: str, b: bool):...
<python><python-3.x><mypy><typing>
2023-09-13 12:12:27
1
1,405
Steinn Hauser Magnússon
77,096,971
7,064,415
Cut a figure along the x axis while retaining scale
<p>I need to be able to compare graphs that show the progress of several variables over time. I need to do this for different cases, where the time covered is not always the same: now the data visualised covers 5 seconds long, then 10 seconds, then 30 seconds, etc.</p> <p>The problem is that Matplotlib uses the number ...
<python><matplotlib><xticks>
2023-09-13 12:11:10
1
732
rdv
77,096,942
20,088,885
Why does nothing shows in my pycharm terminal when I run my Odoo Dev?
<p>I'm having a trouble in my odoo development right now because after changing some part, my terminal doesn't show anything when I run my <code>odoo config</code>. My models shows when I re-run the program, but when I edit <code>xml</code> files, I don't know if i have an error or anything because no message is being ...
<python><odoo><odoo-10>
2023-09-13 12:07:46
2
785
Stykgwar
77,096,912
1,652,219
How to add a number of months to a date in Polars?
<p>I need to carry out a very simple operation in Polars, but the documentation and examples I have been finding are super convoluted. I simply have a date, and I would like to create a range running from the first day in the following month until the first day of a month twelve months later.</p> <p>I have a date:<br /...
<python><datetime><timedelta><python-polars>
2023-09-13 12:03:47
2
3,944
Esben Eickhardt
77,096,668
9,836,333
Number of metrics allowed in Google Analytics Data API (GA4)
<p>I'm not able to find any (official) documentation saying what's the limit on the number of metrics that can be queried within the same API call. Out of the developer tool (<a href="https://ga-dev-tools.google/ga4/query-explorer/" rel="nofollow noreferrer">https://ga-dev-tools.google/ga4/query-explorer/</a>) I can te...
<python><google-analytics-4>
2023-09-13 11:30:19
1
810
Mike
77,096,518
194,000
ModuleNotFoundError after installing dependency
<p>I'm hoping to contribute to <a href="https://github.com/simonw/llm" rel="nofollow noreferrer">this Python library</a> and am following <a href="https://llm.datasette.io/en/stable/contributing.html" rel="nofollow noreferrer">the contribution instructions</a>.</p> <p>I've followed the instructions to check out the cod...
<python><pytest><python-venv>
2023-09-13 11:08:16
0
66,078
Richard
77,096,464
16,092,107
Why does panda flatten out arrays?
<p>I have some data that looks like this :</p> <pre><code> date temperature 0 2021-6-1 [14.1, 16.5] 1 2021-6-10 [19.0, 18.4] 2 2021-6-11 [24.4, 24.8] 3 2021-6-12 [25.4] </code></pre> <p>That I built with a groupby:</p> <pre class="lang-py prettyprint-override"><code>data = data.groupby(['date'])[...
<python><pandas>
2023-09-13 11:00:37
1
800
LucioleMaléfique
77,095,944
498,690
Why does polars rolling corr produce both null and NaN instead of one or the other?
<p><strong>Update:</strong> Polars no longer produces null in this case. The example now returns 2 NaN values.</p> <hr /> <pre class="lang-py prettyprint-override"><code>import polars as pl ts_count_df = pl.DataFrame([pl.Series(&quot;ts&quot;, [ 1687743109438, 1687831935720, 1687958569223, 168797837606...
<python><correlation><python-polars>
2023-09-13 09:47:52
1
3,818
Capacytron
77,095,905
860,202
Finding multisets of numbers within a defined range, efficiently
<p>The problem consists of a collection of N arrays of positive real numbers. The total amount of numbers in the collection is K. The arrays can be of variable length. All K numbers in the collection must be divided over subsets, each number is drawn once but numbers in the collection can be duplicated (so we are not l...
<python><algorithm><optimization><multiset>
2023-09-13 09:41:45
1
684
jonas87
77,095,777
10,687,907
fill the dataframes with dummies
<p>I have a dataframe that list clients throughout years. I'd like to take all customers that ever appear, groupby year week and make every single one appear, if one is not appearing for a specific week i'd like to add None values to the rest of the row but still create a row for this customer there are multiple years ...
<python><pandas>
2023-09-13 09:23:00
0
807
Achille G
77,095,776
301,513
FastAPI pydantic data validation for put method if body only contains the updated data
<p>I am learning FastAPI and understanding that its data validation using <strong>pydantic</strong> is one of its features. But after reading its put method example from <a href="https://fastapi.tiangolo.com/tutorial/body-updates/" rel="nofollow noreferrer">its tutorial</a> I have a question if I only want to let the p...
<python><fastapi><pydantic>
2023-09-13 09:22:58
1
12,833
Qiulang
77,095,668
12,827,931
Repeating ndarray along axis
<p>Assume an array of size (in general) <code>TxNxM</code></p> <pre><code>arr = np.array([[[0.83, 0.3 , 0.22], [0.17, 0.33, 0.37]], [[0. , 0.28, 0.09], [0. , 0.1 , 0.18]], [[0. , 0. , 0.08], [0. , 0. , 0.05]], [[...
<python><arrays><pandas><numpy>
2023-09-13 09:09:42
3
447
thesecond
77,095,565
2,749,397
plt.pause(0) never returns, even if I close the window
<p>TL;DR How can I return to terminal prompt when my scripts ends with <code>plt.pause(0)</code> ??</p> <hr /> <p>This is my code, a sort of animation w/o <code>matplotlib.anim</code></p> <pre><code>import matplotlib.pyplot as plt from matplotlib.lines import Line2D from sys import exit def websocket(tmax=1000, dt=0.0...
<python><matplotlib>
2023-09-13 08:57:21
1
25,436
gboffi
77,095,370
9,414,470
Django django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
<p>I have an app for surveys. I am trying to import my model in <code>views.py</code> and its giving an error.</p> <p>My code is:</p> <p><code>settings.py</code>:</p> <pre class="lang-py prettyprint-override"><code>INSTALLED_APPS = [ 'survey.apps.SurveyConfig', 'survey.urls', 'django.contrib.admin', 'dj...
<python><django>
2023-09-13 08:32:07
1
896
Jaideep Shekhar
77,095,366
11,277,108
Convert CryptoJS to Python
<p>I'm trying to follow some node.js code and convert it into python. I'm now left with the decryption part and I'm struggling:</p> <pre><code>const CryptoJS = require(&quot;crypto-js&quot;) const ee = &quot;#3vlsc6mdk2k400$&quot; const encrypt_data = &quot;hlXzkPyyhwUYql2Nwl/3AAcRSsZHKf5LyqsAHqSWjP+ZHzfdmQ7bG2cOrf3Yx...
<python><node.js><cryptojs><pycryptodome>
2023-09-13 08:31:24
1
1,121
Jossy
77,095,278
9,753,863
Farneback's optical flow implementation
<p>I want to integrate Farneback's optical flow in my framework and I started with a Python prototype.</p> <p>I tried to follow the steps described in <a href="https://link.springer.com/content/pdf/10.1007/3-540-45103-X_50.pdf" rel="nofollow noreferrer">this paper</a> and I compared to OpenCV's output, but I get far wo...
<python><image-processing><computer-vision><opticalflow>
2023-09-13 08:20:11
0
862
ractiv
77,095,143
8,413,889
is there an option to display a selenium session in website
<p>Is it possible to display a Python selenium session (which run a flow in some website) on my website so that the user can see the session that is running? I'm using the Django library.</p>
<python><django><selenium-webdriver>
2023-09-13 07:59:56
0
441
YosDos
77,095,046
14,688,566
Unable to install python 3.11.4 with tkinter via pyenv on MacOS
<p>I'm receiving the following error trying to install python <code>3.11.4</code> via <code>pyenv</code> on <code>MacOS Ventura 13.5.2 (22G91)</code>:</p> <pre class="lang-console prettyprint-override"><code>foo@bar:~$ pyenv install 3.11.4 python-build: use openssl@1.1 from homebrew python-build: use readline from home...
<python><macos><homebrew><pyenv>
2023-09-13 07:47:32
1
446
absoup
77,094,999
5,507,055
How to merge models to one BaseClass, but is still distinguishable
<p>I have several models:</p> <pre><code>from sqlmodel import SQLModel class Dog(SQLModel, table=true): __tablename__ = &quot;dog&quot; name : str size: int color: str class Cat(SQLModel, table=true): __tablename__ = &quot;cat&quot; name: str size: int color: str </code></pre> <p>and ...
<python><fastapi><pydantic><sqlmodel>
2023-09-13 07:40:00
0
2,845
ikreb
77,094,863
136,725
Forward reference to enclosing class in optional return type, without typing.Optional?
<p>Python 3.10 introduced the <code>Foo | None</code> alternative type annotation syntax for <code>Optional[Foo]</code>. This doesn't seem to work when using forward reference to the enclosing type, like <code>'Foo' | None</code>, which instead results in a runtime error:</p> <pre class="lang-py prettyprint-override"><...
<python><python-typing>
2023-09-13 07:21:38
1
4,117
Tuure Laurinolli
77,094,430
1,242,865
How to check if a python package is installed using poetry
<p>I'm using <a href="https://python-poetry.org/" rel="noreferrer">Poetry</a> to manage my Python project, and I would like to check if a package is installed. This means the package is actually fetched from the remote repository and is located in the <code>.venv/</code> folder. I went through the official documentatio...
<python><python-poetry>
2023-09-13 06:08:53
3
676
guojiubo
77,094,251
4,902,679
Set two different logging levels
<p>I am using a basic logging config where all messages of level <code>INFO</code> are getting displayed to stdout, but I'm looking to set log level of <code>WARNING</code> only for the Kafka related messages, the rest can be at <code>INFO</code> level.</p> <p>I'm not sure how to set two different logging levels with m...
<python><python-3.x>
2023-09-13 05:20:56
1
544
Goku
77,093,865
1,639,594
Cannot run MetaAI's llama2 due to "No module named 'fire'" error
<p>I am trying to run the llama2 model locally on my MacOS (M1 chip).</p> <p>In the <code>example_chat_completion.py</code> file there is an import for the fire module:</p> <pre><code># Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 C...
<python><import><pytorch><large-language-model><llama>
2023-09-13 03:27:40
1
13,424
Cybernetic
77,093,716
15,587,184
Data Wrangling in Python in Chaining Style from R
<p>I'm new to Python and I come from the R environment. One thing that I love in R is the ability to write down code that will make some many transformations on the data in one readable chunk of code</p> <p>But it is very difficult for me to find code in that style in Python and I wonder if some of you can guide as to ...
<python><r><chaining><method-chaining>
2023-09-13 02:40:42
2
809
R_Student
77,093,549
12,684,429
How to label outputs of looping
<p>EDITED to focus on outputs rather than the concat:</p> <p>I am scraping data through an API which requires different codes to scrape various datasets (for example, country codes) - I obviously don't want to copy and paste the same few lines of code to pull the data and manipulate it so was hoping to loop through a l...
<python><pandas><list><loops>
2023-09-13 01:33:51
3
443
spcol
77,093,546
12,427,876
Update InputText in PySimpleGUI
<p>I'm trying to disable &amp; delete all texts in 2 certain inputtext fields (<code>A1</code>, <code>A2</code>), if some fields (<code>B1</code>, <code>B2</code>) have value:</p> <pre><code>import PySimpleGUI as sg def gen_layout() -&gt; list: layout=[ [sg.Text('A1', size=(20, 1)), sg.InputText(key='-INPUT-A...
<python><pysimplegui>
2023-09-13 01:32:18
1
411
TaihouKai
77,093,515
17,653,423
How to check yaml Schema in multiple levels using Python
<p>If the yaml file is valid, the method <code>yaml.safe_load()</code> will convert the file to a dictionary (in the code is represented by the variable <code>CONFIG</code>).</p> <p>After the first validation, it should check each key to see if the type matches.</p> <pre><code>from schema import Use, Schema, SchemaErro...
<python><pyyaml>
2023-09-13 01:20:39
1
391
Luiz
77,093,497
11,821,558
Can not run langchain module , Kernel died while running the script?
<p>I was trying to run python script using jupyter notebook as shown below, am not sure on how to troubleshoot moreover the note freezes,</p> <p>error message</p> <p><code>The kernel appears to have died, it will start automatically</code></p> <pre><code># embeddings using langchain from langchain.embeddings import Sen...
<python><jupyter-notebook><langchain>
2023-09-13 01:12:30
1
1,073
cloudcop
77,093,465
2,148,718
Static type checking with Pydantic data conversion
<p>Pydantic offers the means to transform input data into a final type as part of model initialisation. However, this doesn't integrate nicely with static type checkers. Note, I'm using Pydantic 1.X (currently 1.10.12).</p> <p>For example, consider this model which stores a list of strings. I want the user to be able t...
<python><pydantic><pyright>
2023-09-13 00:59:34
1
20,337
Migwell
77,093,447
6,387,095
Django-cms Type error at admin/cms/page/add-plugin?
<p>I have set up an <code>s3 bucket</code> for the media and static files.</p> <p>Now when I go to edit a page, I can add images, files etc. But when I try to add <code>text</code> I get the following error:</p> <pre><code>TypeError at /admin/cms/page/add-plugin/ unsupported operand type(s) for +: 'NoneType' and 'str' ...
<python><django><django-cms><djangocms-text-ckeditor>
2023-09-13 00:49:23
1
4,075
Sid
77,093,266
19,123,103
How to clear input field after hitting Enter in streamlit?
<p>I have a streamlit app where I want to get user input and use it later. However, I also want to clear the input field as soon as the user hits Enter. I looked online and it seems I need to pass a callback function to <code>text_input</code> but I can't make it work. I tried a couple different versions but neither wo...
<python><widget><user-input><streamlit>
2023-09-12 23:48:27
1
25,331
cottontail
77,093,263
9,571,463
Best Practice on Using a Single SQLAlchemy Engine Across Multiple Async Tasks
<p>I am running a concurrent process using <code>asyncio</code>. To do this, I am constructing a number of orchestrator objects which use this same engine. I am debating if I should be passing this engine or referencing it as a class variable.</p> <p>I understand that the SQLAlchemy engine is thread safe, but if I pull...
<python><sqlalchemy><python-asyncio>
2023-09-12 23:46:53
0
1,767
Coldchain9
77,093,154
7,306,999
Set background color for a specific x-range only
<p>Consider the following example code to generate a simple plot:</p> <pre><code># Import modules import numpy as np import matplotlib.pyplot as plt # Create 1D array with time values t = np.linspace(0, 2, 1000) # Calculate 1D array with acceleration values a = 10 * np.sin(2 * np.pi * t) # Create plot fig, ax = plt....
<python><matplotlib>
2023-09-12 23:13:24
1
8,674
Xukrao
77,093,149
21,575,627
Number of permutation operations to return to original array
<p>I recently solved this in a coding assessment for an application (in C++, Python wasn't allowed).</p> <p>I've re-done the problem (with the same logic) in Python with a problem statement.</p> <p>My brute force solution got 6/15 of the test cases (the rest were time limit exceeded).</p> <p>My optimal got 8/15, with t...
<python><arrays><algorithm><data-structures><graph>
2023-09-12 23:12:11
2
1,279
user129393192
77,092,748
714,077
How Add Intelligent Title to Pandas DataFrame.plot.hist
<p>I have a simple data set of multiple columns, all of which I want to plot against a &quot;quality&quot; score from 1-10. NOTE: this is a group_by plot, not a simple plot of a single column. It yields a series of histogram bars for all the other columns in the dataframe, one histogram for each of the &quot;quality&qu...
<python><pandas><plot><histogram><title>
2023-09-12 21:20:35
1
961
noogrub
77,092,684
5,231,001
How does the x,y,z in `plot_surface` work
<p>I am trying to figure out how to work with the input data for pyplot's <code>plot_surface</code>, as it is quite confusing. For a start the y-axis does not represent height as I am used to with geometrics. There is some documentation for it, but it doesn't make sense to me.</p> <blockquote> <p>The general format of ...
<python><numpy><matplotlib><surface><matplotlib-3d>
2023-09-12 21:04:57
1
1,922
n247s
77,092,571
3,611,472
"granularity argument is invalid " error with Coinbase API
<p>I am writing my own Python script to use the Advanced Trade API of Coinbase.</p> <p>I am trying to use the <code>/api/v3/brokerage/products/{product_id}/candles</code> endpoint to fetch historical data. Authentication works, but I get the following error when I try to get historical data</p> <p><code>{&quot;error&qu...
<python><python-requests><coinbase-api>
2023-09-12 20:41:32
1
443
apt45
77,092,547
1,797,000
How to solve "OperationalError: database is locked" with simultaneous /admin and management command sessions?
<p>I'm using django with sqlite for a web application which executes a long-running management command to update the database (<code>./manage.sh download_company_data</code>). However, while it's running, I'm unable to create a new user in the Django admin interface. I've already increased the timeout option for the da...
<python><django><sqlite>
2023-09-12 20:36:38
1
8,117
hdante
77,092,488
9,855,588
python unique set of unsigned digits using uuid
<p>I need a unique number (max 64-bit) that most likely won't be reused in the future, or potentially regenerated in the future.</p> <p>Could that be achieved using:</p> <pre><code>import uuid uuid.uuid4().node </code></pre> <p>which would yield the last 48 bits of the UUID? Is there a chance this 48 bit value could ge...
<python><python-3.x>
2023-09-12 20:24:52
3
3,221
dataviews
77,092,462
5,823,586
Angular 16 / Flask Browser Refresh - How to Redirect to 'root'
<p>I am new to Angular and have been assigned the development of a SPA UI frontend communicating with a Flask server and everything was going fine until I hit an issue of when the user hits the refresh button.</p> <p>What we want to do is redirect to the application root which in this case is index.html in the template...
<python><angular><flask><browser-refresh>
2023-09-12 20:20:56
1
301
B. Youngman
77,092,392
512,480
Strange version string / number error when using pillow
<p>This simple python program:</p> <pre><code>import pyautogui # Get the screen size screen_size = pyautogui.size() # Capture the screen and save it to a file screenshot = pyautogui.screenshot() screenshot.save(&quot;screenshot.png&quot;) </code></pre> <p>Breaks with a very strange error from pyscreeze:</p> <pre><cod...
<python><versioning><dependency-management><pyautogui>
2023-09-12 20:09:31
2
1,624
Joymaker
77,092,321
7,197,899
Metaclass isinstance not working as expected
<p>I've got the following class hiearchy:</p> <pre class="lang-py prettyprint-override"><code>class Acting: pass class Observing: pass class AgentMeta(type): def __instancecheck__(self, instance: Any) -&gt; bool: return isinstance(instance, Observing) and isinstance(instance, Acting) class Agent(Acting, ...
<python><inheritance><metaclass><isinstance>
2023-09-12 19:56:11
1
1,173
KindaTechy
77,092,237
5,044,921
Simulating a vibrating string: is divergence avoidable?
<p>I am trying to simulate a Gaussian wave traveling down a 1-D string, with some wave velocity 1.0, until it hits x=0, where the string changes to have a wave velocity 0.5.</p> <p>My code currently is as follows:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # Parameters N = 301 x_max = 10.0 x_mi...
<python><numpy><simulation><physics>
2023-09-12 19:43:11
0
4,786
acdr
77,092,189
7,700,802
Creating a custom desribe summary table for a number of columns
<p>I have this dataset:</p> <pre><code>d = {'eue_scanner': [1,2,3,4,5], 'eue_thinclient': [12,1221,2123,1231, 123], 'service_model': ['Gold', 'Bronze', 'Bronze', 'Silver', 'Silver']} df = pd.DataFrame(data=d) </code></pre> <p>I want to create a describe table that will look like this (ignore actual numbers):...
<python><pandas><excel><dataframe>
2023-09-12 19:35:11
1
480
Wolfy
77,092,182
3,543,200
boto3 failing to upload file in subdirectory of existing bucket
<p><code>&lt;EDIT&gt;</code> Closing this, as uninstalling and reinstalling <code>moto</code> from scratch fixed the issue. <code>&lt;/EDIT&gt;</code></p> <p>I am using <code>boto3==1.28.45</code> with <code>moto==1.3.14</code> running locally on port 5353.</p> <p>This has worked for years, but for my machine alone, up...
<python><amazon-s3><boto3><moto>
2023-09-12 19:33:40
1
997
gmoss
77,092,165
14,293,020
Write tifs as a datacube
<p>I have a folder of <code>.tif</code> files, I want to merge them in a datacube. By <em>datacube</em> I mean a <code>netcdf</code> file, or <code>zarr</code> files. The goal is that if I open this datacube in Python, I can access a 3D array representing the stack of <code>tif</code> files.</p> <p><strong>Context:</st...
<python><pandas><dask><ram><python-xarray>
2023-09-12 19:31:08
1
721
Nihilum
77,092,114
5,551,827
numba typeerror on higher dimensional structured numpy datatypes
<p>The following code compiles and executes correctly:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np from numba import njit Particle = np.dtype([ ('position', 'f4'), ('velocity', 'f4')]) arr = np.zeros(2, dtype=Particle) @njit def f(x): x[0]['position'] = x[1]['position'] + x[1]['velocit...
<python><numba>
2023-09-12 19:21:32
1
777
Darren McAffee
77,092,010
5,032,387
Understanding options for kwargs in Python functions API
<p>How do I know all the options for arguments of a function when there is a kwargs argument? I've encountered this many times where the documentation isn't specific enough with respect to what they are. I've never been able to figure out whether this is just lackluster documentation or there is a concept that I'm ig...
<python><documentation>
2023-09-12 19:04:06
0
3,080
matsuo_basho
77,091,968
15,498,094
Update Django model field when auth token expires
<p>I'm using JWT auth in Django, I need to set a field in one of my models to false when the access token expires. Is there anyway to monitor tokens like that?</p>
<python><django><jwt>
2023-09-12 18:57:57
1
446
Vedank Pande
77,091,861
18,739,908
How can I configure ib_insync to run in a FastAPI app?
<p>I already have IB Gateway setup on my local machine. When I run my app I get the error: &quot;RuntimeError: This event loop is already running&quot;. Is it possible to have ib_insync running in a FastAPI app? If so how can I do it? Here is my existing code:</p> <pre><code>from fastapi import FastAPI from fastapi.mid...
<python><fastapi><algorithmic-trading><interactive-brokers><ib-insync>
2023-09-12 18:40:06
1
494
Cole
77,091,765
14,852,106
How to make field readonly based on group and state with _get_view function. Odoo 16
<p>I want to use the _get_view function in the 'purchase.order' to set readonly attribute of some customs fields based on group and state. Here is my code. It works with group condition:</p> <pre><code>@api.model def _get_view(self, view_id=None, view_type='form', **options): arch, view = super()._get_view...
<python><xml><odoo><odoo-16>
2023-09-12 18:24:20
1
633
K.ju
77,091,756
22,407,544
How to get python-magic to identify file type of docx correctly instaead of as application/zip?
<p>I'm developing a website which allows users to submit files and then I use Python to detect the file type. I learned that all MS Office files are actually zip files but how do I determine that it contains a single MS Word(or other MS Office) file? I tried getting the first few bytes with:</p> <pre><code>validator = ...
<python><excel><xml><ms-word><mime-types>
2023-09-12 18:23:08
1
359
tthheemmaannii
77,091,688
5,431,734
relative python imports. What is the difference between single dot and no dot
<p>Thats quite basic but still I am a bit puzzled. I have this toy example where I try to import a function from <code>my_module.py</code> which looks like:</p> <pre><code>## my_module.py def say_hi(): print('Hi!') </code></pre> <p>See attached pic for my project tree <a href="https://i.sstatic.net/CYiCU.png" rel=...
<python>
2023-09-12 18:12:40
1
3,725
Aenaon
77,091,644
16,383,578
How to convert BGR array to LCh array efficiently?
<p>I have a NumPy three dimensional array of shape <code>(height, width, 3)</code> with <code>float</code> data type, the values are between 0 and 1, it represents an BGR image of resolution width*height.</p> <p>And now I want to convert it to a LCh(ab) array and back. So I spent days researching, I have read the Wikip...
<python><c++><image><numpy><image-processing>
2023-09-12 18:04:47
1
3,930
Ξένη Γήινος
77,091,626
5,086,100
Consume data from Yahoo Screener via requests
<p>I ran a query on the Yahoo Screener at:</p> <p><a href="https://finance.yahoo.com/screener/equity/new" rel="nofollow noreferrer">https://finance.yahoo.com/screener/equity/new</a></p> <p>DevTools shows that the data came back as JSON via:</p> <p><a href="https://query2.finance.yahoo.com/v1/finance/screener?crumb=u0eN...
<python><python-requests><yahoo-finance>
2023-09-12 18:02:46
1
2,044
Alfred Wallace
77,091,123
9,620,095
How to make field readonly based on group with XML. Odoo 16
<p>I added a custom field in 'purchase.order' model:</p> <pre><code>class PurchaseOrder(models.Model): _inherit = 'purchase.order' custom_field = fields.Char(string=&quot;Custom Field&quot;) </code></pre> <p>I want to set &quot;readonly&quot; = 0 only for admin group, so I added this form views</p> <pre><code...
<python><xml><odoo><odoo-16>
2023-09-12 16:39:40
1
631
Ing
77,091,002
1,411,376
TypeError: 'cython_function_or_method' object is not subscriptable when parsing pydantic model
<p>I have a pydantic model (using pydantic 1.10.7):</p> <pre class="lang-py prettyprint-override"><code>import re from typing import Literal, Sequence from pydantic import BaseModel, Field ColumnTypeLiteral = Literal[ &quot;BOOLEAN&quot;, &quot;DATE&quot;, &quot;FLOAT&quot;, &quot;INTEGER&quot;, &q...
<python><pydantic>
2023-09-12 16:22:26
1
795
Max
77,090,701
1,914,781
add new rate column base previous column
<p>I would like to add a rate column base on row before current row, just like a diff() but need do some calculation just like below:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.random((5,2)),columns=['v1','v2']) print(df) rate = [] rate.append(0) prev = 0 for index, row in df.ite...
<python><pandas>
2023-09-12 15:44:20
3
9,011
lucky1928
77,090,564
1,203,457
Using Python xmltree to sort child elements by attribute value containing FLOAT values?
<p>This is and example of the XML for Pioneer Rekordbox DJ Software.</p> <ul> <li>Using <strong>Python</strong>, I am trying to re-sort the XML child tags by the <strong>START</strong> attribute for each <strong>POSITION_MARK</strong> tag. The POSITION MARK tag basically represent cue points for the DJ software.</li> <...
<python><xml><sorting><elementtree>
2023-09-12 15:22:48
1
7,061
Jonathan Marzullo
77,090,439
170,243
Using pip to install a package for a previous version of python
<p>I have python3.10 on my desktop but I need 3.7 for work.</p> <p>I follow the <a href="https://www.makeuseof.com/install-python-ubuntu/" rel="nofollow noreferrer">instructions here</a> to install python3.7 alongside my 3.10 and they work great.</p> <p>However, when I run python3.7 on the checked out code I find I nee...
<python>
2023-09-12 15:06:17
1
4,534
Joe
77,090,424
3,482,266
Type hinting for expression of type "Float | ndarray[Unknown, Unknown]"
<p>I'm creating a simple wrapper class for scikit-learn function <code>median_absolute_error</code>.</p> <pre><code>from sklearn.metrics import median_absolute_error class MedAbsError: name:str = &quot;MAE&quot; def compute(self, predictions: np.ndarray, observations: np.ndarray) -&gt; float | np.nd...
<python><types>
2023-09-12 15:03:37
0
1,608
An old man in the sea.
77,090,274
15,341,457
Python Scrapy - (403) status code is not handled or not allowed
<p>I'm trying to scrape reviews from Tripadvisor, more specifically from this <a href="https://www.tripadvisor.it/Restaurant_Review-g187791-d25150423-Reviews-Don_s_Meats_Spirits-Rome_Lazio.html" rel="nofollow noreferrer">address</a>.</p> <p>I'm currently unable to scrape any data and I'm returned the 403 status code. A...
<python><web-scraping><scrapy><user-agent><http-status-code-403>
2023-09-12 14:47:58
1
332
Rodolfo
77,090,120
363,949
Make a single global .so module available in virtualenv
<p>I have a program that needs to use the <code>dbm.gnu</code> module. This requires the external python3-gdbm debian package which is installed globally, but it's not available inside the virtualenv. As far as I can tell, this is not available to install via pip. I tried copying the file from <code>/usr/lib/python3.10...
<python><virtualenv><gdbm>
2023-09-12 14:30:26
0
4,205
Elektito
77,090,038
6,068,731
Python - parallelize sequential composition of functions
<p>I have an array <code>A</code> that has dimension <code>(N, d)</code>. I also have a function <code>f</code> that takes arrays <code>(d,)</code> and returns arrays <code>(d,)</code>. I also have a positive integer <code>M</code>. I want to generate a new array <code>B</code> of dimension <code>(N, M+1, d)</code> as ...
<python><arrays><numpy>
2023-09-12 14:21:25
0
728
Physics_Student
77,089,975
9,528,575
kmeans clustering groups the data vertically rather than horizontally
<p>I have a dataset like this:</p> <pre><code>coupled_series = [(9.752, 0.0005), (9.9792, 0.0008), (9.8571, 0.0036), (10.5017, 0.0038), (10.4808, 0.0038), (10.6975, 0.003), (12.1378, 0.0008), (12.7328, 0.0005), (14.0357, 0.0035), (11.7431, 0.0039), (10.107, 0.0039), (10.4207, 0.0039), (10.563, 0.003), (11.0856, 0.0009)...
<python><machine-learning><scikit-learn><cluster-analysis><k-means>
2023-09-12 14:14:44
1
361
Novic
77,089,875
10,452,700
How can I reproduce animation of Backtesting with intermittent refit over time?
<p>I'm experimenting with 1D time-series data and trying to reproduce the following approach via animation over my own data in GoogleColab notebook.</p> <p>It's about reproducing the animation of this approach: <a href="https://skforecast.org/0.10.0/user_guides/backtesting.html#backtesting-with-intermittent-refit" rel=...
<python><matplotlib><time-series><sliding-window><matplotlib-animation>
2023-09-12 14:03:43
1
2,056
Mario
77,089,826
5,547,553
How to get ascii code of a character in a string column in python polars dataframe?
<br> I'd like to get the ascii code of a character in a column in python polars dataframe. <pre><code>import polars as pl df = pl.DataFrame({'a' : ['apple', 'banana']}) df.select('a').with_columns(pl.col('a').str.slice(0, 1)) </code></pre> <p>Slicing works fine, but how do I apply ord() function to it?<br> Ord() works ...
<python>
2023-09-12 13:57:25
1
1,174
lmocsi
77,089,825
822,942
Python and FastAPI live HTML Interface
<p>I have a Python application that compares two files. if i add something in one file and save it, there is a difference. its just a small helper to develope something different.</p> <p>I would like to show that difference as fast as possible in a html file that i use as an interface. I tried FastAPI and my template i...
<python><fastapi>
2023-09-12 13:57:20
1
317
dichterDichter
77,089,769
11,485,896
tabula-py: java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: org.apache
<p>I'm unsuccessfully trying to read a PDF in Python using <code>tabula-py</code>. I installed Java (both <code>jre-1.8</code> and <code>jdk-20</code>), set up <code>JAVA_HOME</code> path (<code>C:\Program Files\Java\jre-1.8\bin</code> in my case; I also added it to <code>Path</code>) and still cannot run <code>read_pd...
<python><java><tabula><tabula-py>
2023-09-12 13:50:42
0
382
Soren V. Raben
77,089,710
9,072,753
How to typing annotate additional obligatory parameter when using ParamSpec?
<p>I want to wrap a function call with some pre action and post action and also make sure that the caller has set the key parameter. I am trying with the following:</p> <pre><code>from typing import ParamSpec, TypeVar P = ParamSpec('P') R = TypeVar('R') def urlparams_pre(key: str): return key def urlparams_post(...
<python><python-3.x><typing>
2023-09-12 13:43:24
1
145,478
KamilCuk
77,089,623
7,339,624
Running independent `nn.Module` instances in `nn.ModuleList` truly in parallel in PyTorch
<p>I have a PyTorch model that consists of multiple independent <code>FullyConnectedNetwork</code> instances stored inside an <code>nn.ModuleList</code>. Here's the code:</p> <pre><code>import torch.nn as nn class FullyConnectedNetwork(nn.Module): def __init__(self): super(FullyConnectedNetwork, self).__in...
<python><machine-learning><deep-learning><pytorch><parallel-processing>
2023-09-12 13:33:34
1
4,337
Peyman
77,089,531
1,142,881
How can I Case-update based on a multi-index update statement?
<p>Supposing I have a model class:</p> <pre><code>class A(Model): key1 = ... key2 = ... value1 = ... </code></pre> <p>I'd like to:</p> <pre><code>import pandas as pd df = pd.DataFrame(data=..., index=['key1', 'key2'], columns=['value1']) Model.update(value1=Case((A.key1, A.key2)), list(df.items()).where(.....
<python><peewee>
2023-09-12 13:21:53
2
14,469
SkyWalker
77,089,401
2,549,828
Type hinting with cyclic dependency
<p>I am building a Django/DRF application and have the following models:</p> <pre class="lang-py prettyprint-override"><code>class Company(models.Model): some_field = models.TextField() some_method(self, user): pass class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.C...
<python><python-3.x><django><pycharm>
2023-09-12 13:06:01
1
1,148
Phocacius
77,089,361
12,705,481
What do ellipses do when they are the default argument of a function?
<p>In pandas source code, here's a snippet of the <code>to_csv</code> function:</p> <pre><code>@overload def to_csv( self, path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str], sep: str = ..., na_rep: str = ..., float_format: str | Callable | None = ..., </code></pre...
<python>
2023-09-12 13:00:10
1
2,628
Alan
77,089,348
3,980,808
Mojo: "Error: An error occurred in Python."
<p>I am trying out Mojo by Modular and more specifically having a look at the <code>Mandelbrot.ipynb</code> available <a href="https://github.com/modularml/mojo/blob/main/examples/notebooks/Mandelbrot.ipynb" rel="nofollow noreferrer">here</a>. When running the line <code>np = Python.import_module(&quot;numpy&quot;)</co...
<python><modular><mojolang>
2023-09-12 12:58:18
2
973
Ivar Eriksson
77,089,228
188,331
Jieba: Import error, cannot find paddle.fluid and jieba.lac_small.predict module
<p>I am trying to use Jieba (a Chinese text segment tool) with Paddle. Here is the code:</p> <pre><code>import jieba # v0.42.1 import paddle # v2.5.1 paddlepaddle-gpu paddle.enable_static() jieba.enable_paddle() text = '我是一個男生' # means &quot;I am a boy.&quot; seg_list = jieba.cut(text, use_paddle=True) </code></pre>...
<python><paddle-paddle><python-jieba>
2023-09-12 12:41:32
1
54,395
Raptor
77,089,164
1,113,579
pandas: find invalid records where for a given value in one column, another column contains multiple values
<p>In my DataFrame, for a given value in the <code>id</code> column, the value in <code>doc_no</code> column must be a single value. In the below example, the records with <code>id-1</code> are invalid, because they have more than one value for the <code>doc_no</code> column.</p> <pre><code>import pandas as pd def fin...
<python><pandas><dataframe>
2023-09-12 12:34:14
2
1,276
AllSolutions
77,089,116
2,604,247
How to Get the Value of an HTTPBearer Token Passed as Dependency in FastAPI?
<p>Trying to learn the basics of authorisation using java-web-tokens from this <a href="https://github.com/BekBrace/FASTAPI-and-JWT-Authentication" rel="nofollow noreferrer">github repository</a>. Reproducing <a href="https://github.com/BekBrace/FASTAPI-and-JWT-Authentication/blob/main/main.py#L71" rel="nofollow norefe...
<python><jwt><backend><fastapi><bearer-token>
2023-09-12 12:28:55
1
1,720
Della
77,088,952
10,687,907
Openpyxl vs pd.read_excel
<p>So this morning I came across this article <a href="https://saturncloud.io/blog/faster-way-to-read-excel-files-to-pandas-dataframe/" rel="nofollow noreferrer">https://saturncloud.io/blog/faster-way-to-read-excel-files-to-pandas-dataframe/</a> which claimed openpyxl was up to 10x faster than the regular <code>pd.read...
<python><pandas><performance><openpyxl>
2023-09-12 12:06:43
1
807
Achille G
77,088,914
9,501,624
Pycharm autocomplete for undefined class attributes in debug console?
<p>For a general Hardware class, I made optional placeholder-attributes for physical devices which might be required during runtime. This works well with autocomplete when using Pycharm's IDE. However, the debug console's autocomplete seems to know less than the IDE.</p> <p>Question: Is there a way to have both defined...
<python><autocomplete><pycharm>
2023-09-12 12:01:56
1
3,844
Christian Karcher
77,088,788
2,386,113
How to open the .Result file generated by Spyder Profiler?
<p>I used <strong>Spyder's inbuilt profiler</strong> to generate the following profiling results:</p> <p><a href="https://i.sstatic.net/pK9X6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pK9X6.png" alt="enter image description here" /></a></p> <p>...I then pressed the <strong>Save Button</strong> to s...
<python><profiling><spyder>
2023-09-12 11:45:35
0
5,777
skm
77,088,660
4,198,298
Update column in rows with variable for each row
<p>I have a database and have added an additional column 'team' so it looks like this</p> <pre><code>date | forename | surname | team ----------------------------------------- 1/1/01 | james | smith | 2/2/02 | paul | jones | 3/3/03 | steven | bradley | </code></pre> <p>I want to ...
<python><postgresql><psycopg2>
2023-09-12 11:24:20
1
945
CEamonn
77,088,537
13,854,431
I am trying to push an index to Azurecognitive search but this gives an error ServiceRequestError: EOF occurred in violation of protocol (_ssl.c:2427)
<p>I am trying to push a index (with embeddings) to Azure cognitive search. The following code is what pushes the index to cognitive search:</p> <pre><code> #Upload some documents to the index with open('index.json', 'r') as file: documents = json.load(file) search_client = SearchClient(endpoint=ser...
<python><azure><azure-cognitive-search>
2023-09-12 11:05:34
1
457
Herwini
77,088,510
1,470,314
Anaconda and pip
<p>Configuring a <a href="https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-from-an-environment-yml-file" rel="nofollow noreferrer">conda environment.yaml</a>, I can set certain packages to be installed by pip. Are these installations also localized to that cond...
<python><pip><conda>
2023-09-12 11:00:53
1
1,012
yuvalm2
77,088,414
1,305,688
Shift+Enter error at running Selection/Line in python terminal using
<p>After upgrading to VS code version 1.81.0 VS code seem to be activating Python after sending the the code, using Shift+Enter, sending 1+1</p> <pre><code>Microsoft Windows [Version 10.0.19044.3324] (c) Microsoft Corporation. All rights reserved. C:\Users\fail\gitprojects\proj_x&gt;activate (base) C:\Users\fail\gitp...
<python><visual-studio-code>
2023-09-12 10:48:39
1
8,018
Eric Fail
77,088,237
13,506,329
Split a NumPy array of strings into 2 new NumPy arrays based on index positions provided by another NumPy array
<p>This is my NumPy array:</p> <pre><code>og_arr = [['5mm', '45&quot;', '300 mm WT', 'Nan'], ['50mm', '3/5&quot;', 'Nan', 'Nan']] </code></pre> <p>I have written some logic that is able to identify at which index position the <code>mm/inch</code> string starts and this results in the following array.</p> <pre><code> in...
<python><arrays><numpy><numpy-ndarray>
2023-09-12 10:22:59
1
388
Lihka_nonem
77,087,702
738,017
How to find the actual tag of a "latest" Docker image in Docker hub, starting from a container image built months ago
<p>I have a local Docker image built months ago, using a Dockerfile starting with <code>FROM python</code></p> <p>Now that image is still in a server that I can access, and I need to create a new Dockefile to generate a container starting from EXACTLY THE SAME python image used when the image was originally build.</p> ...
<python><docker><dockerfile>
2023-09-12 09:17:25
0
14,614
Vito Gentile
77,087,620
8,726,315
Can't get element with Python Selenium find_element(By.CSS_SELECTOR)
<p>I'm having trouble getting a specific element in the page I want to scrape. The content is wrapped in a weird tag, and not sure if it's an iframe. I also tried with CSS_SELECTOR, but anything coming after the mentioned tag throws an error.</p> <p>The page I want to scrape: <a href="https://connect.echobotsales.de/#...
<python><selenium-webdriver><web-scraping><xpath><css-selectors>
2023-09-12 09:06:18
2
341
Eric Lehmann
77,087,440
7,677,894
What happens if __getitem__ return None to dataloader in Pytorch?
<p>What happens if <code>__getitem__</code> return None to dataloader in Pytorch?</p> <p>In my gussing, the batch size will be reduced and training will continue?</p>
<python><pytorch><nlp><pytorch-dataloader>
2023-09-12 08:46:30
1
983
Ink
77,087,407
5,057,360
SharePoint long path not working in Python
<p>My Organization recently rearranged their SharePoint folder and now my script is not working.</p> <p>I have a Python script that is reading an Excel file from SharePoint. The old path used to look like this:</p> <pre><code>FILE_PATH = &quot;https://company.sharepoint.com/sites/Folder1/Shared%20Documents/Project%20Fi...
<python><sharepoint><path>
2023-09-12 08:42:18
0
317
ybloodz
77,087,356
5,684,214
Debug / log output from dbt python models
<p>Is there any way to view variables / output from python models in dbt? Currently my workaround involves replicating the python model in a jupyter notebook.</p> <p>I found this in the <a href="https://docs.getdbt.com/docs/build/python-models#limitations" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p><strong...
<python><snowflake-cloud-data-platform><dbt>
2023-09-12 08:35:45
2
953
DannyDannyDanny
77,087,197
14,705,072
Is there a way to group_by in polars while keeping other columns?
<p>I am currently trying to achieve a polars group_by while keeping other columns than the ones in the <code>group_by</code> function.</p> <p>Here is an example of an input data frame that I have.</p> <pre class="lang-py prettyprint-override"><code>df = pl.from_repr(&quot;&quot;&quot; ┌─────┬─────┬─────┬─────┐ │ SRC ┆ ...
<python><python-polars>
2023-09-12 08:13:23
1
319
Haeden