QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
78,062,559
1,773,592
In polars how do I count unique rows cumulatively?
<p>My df:</p> <pre><code>data_string= &quot;&quot;&quot; A,B,C,D 0,0,0,0 0,0,0,1 0,0,1,1 1,0,0,0 1,0,0,0 1,0,0,0 1,1,0,0 1,1,0,0 1,1,0,1 1,1,1,0 &quot;&quot;&quot; df = pl.read_csv(StringIO(data_string)) </code></pre> <p>I want a cumulative count of unique rows (the 'actual' column at end of this). I try:</p> <pre><cod...
<python><dataframe><python-polars>
2024-02-26 16:43:51
1
3,391
schoon
78,062,514
4,402,306
How to skip pbr version check in Python packages
<p>I use pbr in my package. I also use readthedocs to host and generate the docs of the package.</p> <p>pbr doesn't seem to have a way to skip the version checking when you add changes for the sake of configuration setting, e.g. if I add a yaml file for readthedocs, if I don't have a tag on that commit and have a versi...
<python><read-the-docs><python-pbr>
2024-02-26 16:37:39
0
633
Corel
78,062,460
1,050,187
Grouping in minutes intervals starting at fixed time regardless the first row time and the date
<p>I have this code intended to count occurrences in 30-minute intervals; the requirement is to have these intervals at fixed starting points, minute 00 and minute 30 of each hour. Regretfully, despite every attempt of mine, the second group is aligned to minute 03 and minute 33.</p> <p>I suspect that both the groups a...
<python><pandas><group-by><time-series><pd.grouper>
2024-02-26 16:28:03
2
623
fede72bari
78,062,451
6,435,921
Most Pythonic and object-oriented way to create a class that collects together other objects?
<p>My real example is different, but I am going to explain it in terms of this made-up example.</p> <p>I have some base abstract class such as <code>AbstractPerson</code>. I then have several specific persons which inherit from this, such as <code>Bob</code> and <code>Alice</code>.</p> <pre><code>class AbstractPerson: ...
<python><class><oop><inheritance>
2024-02-26 16:26:46
1
3,601
Euler_Salter
78,062,394
3,442,125
Debug python program in VSCode remote window with sourced enviroment
<p>I'm developing a ROS2-application in python and the source code is on the robot and needs a specific environment to run/debug. This environment is setup by sourcing a file, so if I run it manually, it boils down to</p> <pre><code>ssh user@robot source foo/setup.bash python3 fancy.py </code></pre> <p>I tried to inte...
<python><visual-studio-code><ros2>
2024-02-26 16:15:56
0
867
FooTheBar
78,062,352
899,578
Unable to create clientid-secret in Azure Active Directory
<p>I am trying to generate a New ClientID and Secret for an Application in Azure Active Directory using <code>client_credentials</code> flow using code below.</p> <p>The application used to run this script has <code>Application.ReadWrite.All</code>, <code>Application.ReadWrite.OwnedBy</code> and <code>Directory.ReadWri...
<python><azure><rest><azure-active-directory>
2024-02-26 16:09:36
1
973
GeekzSG
78,062,295
20,122,390
How can I configure an enum list in FastAPI?
<p>I have a FastAPI endpoint that fetches all database records for an entity, applying a payload. One of the payload fields refers to the order when bringing the data (which can even be by more than one column). So I have this:</p> <pre><code>class PayloadExecution(BaseExecution): init_date__lte: Optional[datetime]...
<python><fastapi>
2024-02-26 16:00:05
0
988
Diego L
78,062,249
5,975,991
Disable NonBrowserUserAgent in AWS CDK Waf
<p>We set up a WAF in AWS CDK with default rules, and it includes a rule that blocks any request with <code>SignalNonBrowserUserAgent</code>. It's tough to get around this when your clients are apps or postman or python requests.</p> <p>I couldn't not find a solution to this and spent a few days figuring it out so I'm ...
<python><amazon-web-services><aws-cdk><web-application-firewall>
2024-02-26 15:54:03
1
412
RooterTooter
78,062,233
4,858,640
Is pip.conf broken? extra-index-url ignored
<p>I'm running <code>pip 24.0</code> on Ubuntu and have the following in <code>~/.pip/pip.conf</code>:</p> <pre><code>[user] extra-index-url https://&lt;MY_TOKEN_NAME&gt;:&lt;MY_TOKEN&gt;@gitlab.com/api/v4/projects/&lt;MY_PROJECT&gt;/packages/py...
<python><pip>
2024-02-26 15:51:34
1
3,242
Peter
78,062,168
6,525,082
what would be in preferred approach to plotting data?
<p>let us assume I have several datasets whose plots I want to compare. One approach would be:</p> <pre><code> paths = ['list', 'of', 'folders'] colors = ['r', 'g', 'b'] # list of colors based on number of folders for i, path in enumerate(paths): sn = create_object_holding_data(path) sn.load_data() sn.pl...
<python><python-3.x>
2024-02-26 15:42:02
0
1,436
wander95
78,062,132
7,657,180
Python function to download zip file
<p>I am trying python function to download zip file <code>https://storage.googleapis.com/chrome-for-testing-public/122.0.6261.69/win32/chromedriver_win32.zip </code> I tried this and the file is downloaded but damaged not complete</p> <pre><code>import os import requests headers = {'User-Agent': 'Mozilla/5.0 (Windows ...
<python><python-requests><zip>
2024-02-26 15:38:29
1
9,608
YasserKhalil
78,062,117
11,061,371
Configuration Error when formatting Python with Black in VSCode
<p>I can't setup black to format when saving in VSCode.</p> <ul> <li>I went through the steps in the black <a href="https://black.readthedocs.io/en/stable/integrations/editors.html#visual-studio-code" rel="nofollow noreferrer">docs</a></li> <li>Installed the VSCode plugins: <a href="https://marketplace.visualstudio.com...
<python><visual-studio-code><pipenv><python-black>
2024-02-26 15:36:04
1
337
0xBradock
78,062,070
8,543,025
plotly: add rectangle with varying fill color
<p>I have an eye tracking dataset consisting of four columns:</p> <ul> <li><code>t</code> is a numpy array of timestamps</li> <li><code>x</code> and <code>y</code> are the pixel-coordinates of the gaze</li> <li><code>e</code> is an array of values <code>{0, 1, 2, 3, 4, 5}</code> marking each sample as a different gaze-...
<python><python-3.x><plotly><eye-tracking>
2024-02-26 15:29:31
2
593
Jon Nir
78,062,016
11,170,350
Unable to split text received as POST request in django
<p>i am facing a weird error. I am trying to split text sent via form in django. Here is my code in django</p> <pre><code>from transformers import AutoTokenizer from langchain.text_splitter import CharacterTextSplitter tokenizer = AutoTokenizer.from_pretrained(&quot;distilbert-base-uncased-finetuned-sst-2-english&quot...
<python><django>
2024-02-26 15:22:08
0
2,979
Talha Anwar
78,061,902
984,621
How to access particular stats ("finish_reason", "elapsed_time_seconds") in Scrapy?
<p>I am playing with Scrapy and I am able to scrape with it data from different URLs. One thing I am trying to obtain, and so far unsuccessfully, is stats data, particularly <code>finish_reason</code> and <code>elapsed_time_seconds</code>.</p> <p>My <code>testspider.py</code>'s structure looks pretty standard:</p> <pre...
<python><scrapy>
2024-02-26 15:06:24
1
48,763
user984621
78,061,810
429,596
Pygame music play start position seems to have a 1 second resolution
<p>I'm using <code>pygame.mixer.music.play</code> to load and play a wav file as follows:</p> <pre><code>from pygame import mixer mixer.init() wavfile = &quot;/my/wav/file.wav&quot; mixer.music.load(wavfile) start = 0.5 mixer.music.play(start=start) </code></pre> <p>However, <code>start</code> seems to have a 1 second ...
<python><pygame><pygame-mixer>
2024-02-26 14:53:02
0
1,268
Fadecomic
78,061,746
15,980,284
Recursion error when combining abstract factory pattern with delegator pattern
<p>I am learning about design patterns in Python and wanted to combine the abstract factory with the delegation pattern (to gain deeper insights into how the pattern works). However, I am getting a weird recursion error when combining the two patterns, which I do not understand.</p> <p>The error is:</p> <pre><code> [P...
<python><design-patterns>
2024-02-26 14:41:53
2
1,303
JKupzig
78,061,465
5,330,527
Save the current user when saving a model in Django admin backend
<p>I'd like to store the user that saved a model for the first time in one of the fields of that model. This is what I have.</p> <p><code>models.py</code>:</p> <pre><code>from django.conf import settings class Project(models.Model): [...] added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,...
<python><django><django-admin><django-authentication>
2024-02-26 13:57:30
1
786
HBMCS
78,061,369
4,389,785
Can not see resource-id attribute in appium with jetpack compose
<p>My android application is built using <code>jetpack compose</code>. Some elements have applied <code>resource-id</code> attributes for elements. But when analyse DOM model on local physical device via Appium Inspector, I can not see that attributes. And when use BrowserStack, I can see <code>resource-id</code> attri...
<python><selenium-webdriver><appium><appium-android>
2024-02-26 13:40:06
1
321
Den Silver
78,061,319
3,647,970
How to make sense of the output of the reward model, how do we know what string it is preferring?
<p>In the process of doing RLHF I made a reward model using a dataset of <code>chosen</code> and <code>rejected</code> string pairs. It is very similar to the example that's there in the official TRL library - <a href="https://huggingface.co/docs/trl/main/en/reward_trainer" rel="nofollow noreferrer">Reward Modeling</a>...
<python><huggingface-transformers><llama><reward>
2024-02-26 13:32:00
1
2,938
jar
78,061,285
3,906,786
Sorting nested dictionaries at two levels from TOML configuration
<p>I have the idea to create a TOML configuration file which defines some sort of job chain to be executed. Those jobs are not executed immediate, there may be a break in between, so there should also be some grouping to have the chance to do something in between the chain.</p> <p>An example TOML file looks like this:<...
<python><python-3.x><dictionary>
2024-02-26 13:27:48
1
983
brillenheini
78,061,250
6,293,886
find the memory usage of lru_cache decorator
<p>I want to track the memory usage of <em>lru_cached</em> class method.<br /> I know how to extract the number of method calls</p> <pre><code>from functools import lru_cache class Exponent: def __init__ (self, base): self.base = base @lru_cache(maxsize=None) def __call__(self, expo...
<python><caching><python-lru-cache>
2024-02-26 13:24:13
2
1,386
itamar kanter
78,061,092
8,365,731
Python curses Textbox.gather() removes empty lines, is there a way to preserve them?
<p>In below code box.gather() removes empty lines from text. Is there a way to collect the text as is including empty lines?</p> <pre><code>from curses import wrapper from curses.textpad import Textbox def main(stdscr): stdscr.addstr(0, 0, &quot;Enter text separated by empty lines: (hit Ctrl-G to send)&quot;) bo...
<python><python-curses>
2024-02-26 12:57:40
1
563
Jacek Błocki
78,061,077
3,602,296
code completion based on a hierarchy of properties
<p>I want to create a class that has the following structure:</p> <pre><code>ClassName UpperLevel Element_A: val_1 = 'example' Element_B: Tuple(str, str) Element_C: Tuple(str, str) LowerLevel Element_D: Tuple(str, str) Element_E: Tuple(str, str) </code></pre> <...
<python><class><code-completion>
2024-02-26 12:55:53
1
314
penfold1992
78,061,044
8,110,961
safely forking a multithreaded process is problematic
<p>source:<a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow noreferrer">https://docs.python.org/3/library/multiprocessing.html</a></p> <p>I am reading python documentation for multiprocessing and noticed sentence</p> <blockquote> <p>Note that safely forking a multithreaded process is proble...
<python><multiprocessing><documentation>
2024-02-26 12:51:18
0
385
Jack
78,060,857
9,135,359
Kaggle's packages missing many essential methods, for instance Kaggle's `Dataset` class has no `from_generator()` method
<p>I have been working on a particular NLP project for a month and have been running into error after error. I built a small model on my potato PC and it works perfectly. I upscaled it to Kaggle and ran into multiple errors, which have frustrated the hell out of me! I've been exploring all individual packages, and lo a...
<python><nlp><kaggle>
2024-02-26 12:18:16
1
844
Code Monkey
78,060,747
4,934,061
How to create a modern Windows "Open Folder" dialog with Python
<p>For several hours now, I have been trying to open the modern folder selection dialog using python.</p> <p>My application is currently using pywebview's <a href="https://pywebview.flowrl.com/examples/open_file_dialog.html" rel="nofollow noreferrer">create_file_dialog</a>. Which works as intended, but it's really not ...
<python><winapi>
2024-02-26 11:59:08
2
3,632
Josef
78,060,727
7,695,845
Parameter validation in Python
<p>I have a function that accepts some parameters that need to be validated. For example:</p> <pre class="lang-py prettyprint-override"><code>def foo(a: int, b: float, c: str) -&gt; None: if a &lt;= 0: raise ValueError(f&quot;'a' must pe positive: {a}&quot;) if not (0 &lt; b &lt;= 1): raise Valu...
<python><validation>
2024-02-26 11:56:54
3
1,420
Shai Avr
78,060,632
386,861
Jupyter notebook: No module named 'notebook.base'
<p>I'm trying to create a simple HTML version of a notebook without the code.</p> <pre><code>jupyter nbconvert &quot;HFB data dashboard.ipynb&quot; --to html --no-input </code></pre> <p>But it returns:</p> <pre><code>line 18, in &lt;module&gt; from notebook.base.handlers import APIHandler, IPythonHandler ModuleNotF...
<python><jupyter-notebook><nbconvert>
2024-02-26 11:38:30
0
7,882
elksie5000
78,060,622
614,443
Building of project won't install correct version of package
<p>I'm trying to build a package and for some reason when it's trying to install setuptools, it's running into issues:</p> <pre class="lang-bash prettyprint-override"><code>$ python -m build * Creating virtualenv isolated environment... * Installing packages in isolated environment... (setuptools&gt;=61.0) Collecting s...
<python><build><pyproject.toml>
2024-02-26 11:36:17
1
2,551
Aram Papazian
78,060,574
2,989,330
How to annotate the type of a list of functions with different output type in Python
<p>The following <code>try_parse</code> method takes as input a value of type <code>T</code> and a series of functions with input type <code>T</code>. The functions do not necessarily have to have the same output type, e.g., it could be <code>int</code>, <code>float</code>, <code>MyCustomClass</code> etc. How would I a...
<python><python-typing>
2024-02-26 11:27:28
1
3,203
Green 绿色
78,060,479
4,582,949
Annotate a Python function so that it narrows down the return type of an union involving a typevar
<p>I'm currently in the process of adding type annotations for a medium-sized library. The library has some quite complex cases that I would like to handle. I managed to simplify these complex cases to the following, much easier, one.</p> <p>Consider the following <em>pseudo-identity</em> function:</p> <pre class="lang...
<python><mypy><python-typing>
2024-02-26 11:10:44
0
2,842
Guybrush
78,060,363
2,794,152
Is it possible to save the save figure in different ranges, without plotting it twice?
<p>Suppose I have one data set which is very big, <strong>it takes a long time to plot</strong>. I want to save two figures of it in different range. In the GUI, I just plot once and zoom in to the desired range, and repeat to get the other range. How to do it in automatically the code?</p> <pre><code>import numpy as n...
<python><matplotlib><plot>
2024-02-26 10:52:29
1
4,904
an offer can't refuse
78,060,302
3,337,089
Can I call prepare() separately on multiple models or should it be a single call when using accelerator with pytorch?
<p>I'm training two deep learning models in tandem, say <code>model1</code> and <code>model2</code> using pytorch. I'm using <code>accelerator</code> to handle distributed training. When calling the <code>prepare()</code> function, can I call it separately as in the below code?</p> <pre><code>model1, dataloader, optimi...
<python><pytorch>
2024-02-26 10:43:43
1
7,307
Nagabhushan S N
78,060,150
14,660,815
AWS S3 script to get versions of object & folder with same name (Version Enabled Bucket)
<p>I am using AWS Cloudshell to execute simple python script to fetch the all versionIds with following hierarchy.</p> <pre><code>AWS S3 &gt; buckets &gt; my-bucket &gt; test_001 KpJEgbcnjMr5QLzOkA2CfG5NMzPBvyqK test_001/ my-obj 4RektV43Cf.HK17BTyVpDVtFSQiLr.yf HGKVjaVDoP...
<python><amazon-web-services><amazon-s3>
2024-02-26 10:20:50
1
373
Dnyaneshwar Jadhav
78,059,960
12,415,855
Getting 403-status response when get requesting from website?
<p>i try to do a site request using the following code:</p> <pre><code>import requests if __name__ == '__main__': headers = { 'x-requested-with':'XMLHttpRequest', 'Cookie': 'sessionid=8tjkos13k0wpd9rzje3xcc8dp1v64kug; __cf_bm=kbWudR66vyTEyth2CjVopfXLfOA167E8Yk9iDbeWj9E-1708936562-1.0-AUMLR7tUp64sdzNeaV...
<python><python-requests>
2024-02-26 09:49:17
0
1,515
Rapid1898
78,059,868
1,100,711
Type hint function accepting union types
<p>The following function with argument of type <code>type</code> accepts both regular types and union types and works as expected. However Pylance treats passing union type as error.</p> <pre class="lang-py prettyprint-override"><code>def foo(t: type): print(t) foo(int) # OK foo(int | str) # Pylance: # Argument ...
<python><python-typing><union-types><pyright>
2024-02-26 09:35:26
1
671
Maksim Zholudev
78,059,845
5,672,961
SQLAlchemy query result doesn't have attribute `_asdict()`
<p>I have this models.</p> <pre class="lang-py prettyprint-override"><code>class Base(DeclarativeBase): pass class PortfolioPerformanceTable(Base): __tablename__ = tn.portfolio_performance clientuid: Mapped[str] = mapped_column(ForeignKey(f&quot;{tn.clients}.clientno&quot;)) clientno: Mapped[str] = ma...
<python><sqlalchemy>
2024-02-26 09:30:40
1
1,090
mandaputtra
78,059,822
9,923,776
Keycloak - Log user without password
<p>Im using Keycloak to manage User Login. I have a Software that redirect to Keycloak Login if user is not Logged. Normal login by username and password works fine.</p> <p>I need to support some &quot;italian identity system&quot; that are not covered with plugins yet. So I was thinking to managed that kind of login w...
<python><keycloak>
2024-02-26 09:26:26
0
656
EviSvil
78,059,445
10,200,497
How to add plus sign for positive number when using to_excel?
<p>This is my DataFrame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame( { 'a': [2, 2, 2, -4, np.nan, np.nan, 4, -3, 2, -2, -6], 'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6] } ) </code></pre> <p>I want to add a plus sign for positive numbers only for column <code>a</code> whe...
<python><pandas><excel><dataframe>
2024-02-26 08:16:08
2
2,679
AmirX
78,059,437
4,568,212
How to schedule Background Task with FastAPI + Uvicorn + Celery in Production for lower response time?
<p>I am running FastAPI + Uvicorn server setup on EC2 instance. I am using 4 Uvicorn workers and 4 celery workers on 8vCPU Ec2 instance. I am performing very simple task. I get data on post API, schedule background task using celery and return response immediately. For this simple task if I send 40 concurrent request a...
<python><machine-learning><celery><fastapi><uvicorn>
2024-02-26 08:15:09
0
4,344
Punit Vara
78,059,436
1,997,852
Why does PyLance show reportArgumentType?
<p>I have the following Python code which works fine (version 3.11). Why does PyLance complain about this?</p> <pre class="lang-py prettyprint-override"><code>import jinja2 templateEnv = jinja2.Environment(loader=jinja2.BaseLoader) template = templateEnv.from_string(my_string) </code></pre> <p>PyLance v2024.2.2 in VS ...
<python><pyright>
2024-02-26 08:15:07
1
1,217
Elliott B
78,059,324
10,200,497
AttributeError: 'Styler' object has no attribute 'style'
<p>This is my DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': [2, 2, 2, -4, 4, 4, 4, -3, 2, -2, -6], 'b': [2, 2, 2, 4, 4, 4, 4, 3, 2, 2, 6] } ) </code></pre> <p>I use a function to highlight cells in <code>a</code> when I use <code>to_excel</code>:</p> <pre><code>def high...
<python><pandas><dataframe>
2024-02-26 07:50:34
1
2,679
AmirX
78,059,279
7,233,155
Restructuring `struct` with generic types for binding with PyO3
<p>If I have used generics in a rust implementation such as the following MWE:</p> <pre class="lang-rust prettyprint-override"><code>#[derive(Debug)] struct A&lt;T&gt; { a: T, } impl&lt;T&gt; A&lt;T&gt; { fn new(a: T) -&gt; A::&lt;T&gt; { A {a} } } </code></pre> <p>This works fine but if I now want...
<python><rust><types>
2024-02-26 07:43:45
0
4,801
Attack68
78,059,252
6,086,295
instagram graph api rate limit execeed
<p>I am using instagram graph api to extract data of my own account and other business accounts' media. During development, I have made couples of api calls to test the api, at first, everything works fine and the api response is returned successfully. All of the sudden, it is prompting request limit reached</p> <pre><...
<python><facebook-graph-api><instagram><instagram-api><instagram-graph-api>
2024-02-26 07:38:16
1
479
Kevin Lee
78,059,194
857,932
Is it possible to add type annotations to a method outside of my code?
<p>Let's suppose I'm writing a Python plugin for a large, legacy codebase not under my control. That codebase exposes an object with several functions that I can call from my plugin code:</p> <pre class="lang-py prettyprint-override"><code>def plugin_entrypoint(ctx: LegacyCodebaseObject): ... </code></pre> <p>One of...
<python><python-typing>
2024-02-26 07:27:56
1
2,955
intelfx
78,059,139
10,341,337
Why python3 dict's get method O(1) time while under the hood it is aclually O(n)?
<p>We all know that python <code>dict.get()</code> has <code>O(1)</code> time complexity because it need to get a hash of the key and get value, corresponding to it's key. The question is, what magic can actually access the value, corresponding to the hash? Looking for the answer I went to <a href="https://github.com/p...
<python><dictionary><hashtable>
2024-02-26 07:15:45
0
456
Ivan
78,058,655
188,331
How to specify additional parameters when using HuggingFace Evaluate's evaluate.combine() method?
<p>I am using the <a href="https://huggingface.co/docs/evaluate/en/index" rel="nofollow noreferrer">HuggingFace Evaluate library</a> to evaluate my results using 2 metrics. Here are the codes:</p> <pre><code>import evaluate metric = evaluate.combine( [&quot;sacrebleu&quot;, &quot;chrf&quot;], force_prefix=True ) <...
<python><bleu><huggingface-evaluate><chrf>
2024-02-26 04:37:21
2
54,395
Raptor
78,058,636
9,983,652
CondaVerificationError when installing PyTorch
<p>I am trying to install pytorch using either of below command and I got a lot of error. I am using windows CPU only.</p> <pre><code>conda install pytorch::pytorch or conda install pytorch torchvision torchaudio cpuonly -c pytorch </code></pre> <p>some of the error are</p> <pre><code>CondaVerificationError: The pac...
<python><pytorch><conda><miniconda>
2024-02-26 04:31:06
1
4,338
roudan
78,058,624
4,367,371
Jupyter Widgets Formatting
<p>I am using the following code:</p> <pre><code>from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets def f(x): return x interact_manual(f, x='Hi there!'); </code></pre> <p>It yields the following widget in the notebook:</p> <p><a href="https://i.sstatic.net/PxPcp.png"...
<python><jupyter-notebook><widget><jupyter><ipywidgets>
2024-02-26 04:24:26
1
3,671
Mustard Tiger
78,058,590
1,277,865
How to fix CppException forward() Expected a value of type 'Tensor' in pytorch android, but the same model works fine in python
<p>How to fix CppException forward() Expected a value of type 'Tensor' in pytorch android, load by Module.load('mel_ptmobile_v2.pt'):</p> <p>android log:</p> <pre><code>mel, melInputTensor = org.pytorch.Tensor$Tensor_float32, [1, 840] Caused by: com.facebook.jni.CppException: forward() Expected a value of type 'Tensor'...
<python><android><deep-learning><pytorch><tensor>
2024-02-26 04:05:51
1
2,207
thecr0w
78,058,404
5,022,913
Python: Execute long-running task in a background process forking off FastAPI app
<h1>TL;DR</h1> <p>In my <code>gunicorn/uvicorn</code>-run FastAPI app, I need to execute some long-running tasks in a completely non-blocking way, so the main <code>asyncio</code> event loop is not affected. The only approach I can think of is spinning off separate processes to fire the tasks and then somehow collect t...
<python><multiprocessing><subprocess><python-asyncio><fastapi>
2024-02-26 02:32:10
1
584
s0mbre
78,057,906
3,241,846
Django Model self reference OneToOne, Can't set link while bulk_create
<p><strong>Context</strong></p> <p>Bare with me as im new to Django. I have model <code>Account</code> which I want to refer to itself, in one-to-one relationship. <code>Account</code> also has a one to Many with <code>Activities</code>.</p> <p><strong>Goal</strong></p> <ol> <li>When saving Account, save linked_account...
<python><django>
2024-02-25 22:26:47
1
677
user3241846
78,057,893
1,609,514
What is the 'u' parameter estimated by Statsmodel's ARIMA fit method?
<p>I'm struggling to find mention of the <code>'u'</code> parameter that is returned by the statsmodels <a href="https://www.statsmodels.org/stable/generated/statsmodels.tsa.arima.model.ARIMA.fit.html#statsmodels.tsa.arima.model.ARIMA.fit" rel="nofollow noreferrer">ARIMA.fit</a> method in the following ARMAX model para...
<python><statsmodels><arima>
2024-02-25 22:19:39
1
11,755
Bill
78,057,740
23,182,657
Chrome 122 - How to allow insecure content? (Insecure download blocked)
<p>I'm unable to test file download with Selenium (python), after Chrome update to the version '122.0.6261.70'.</p> <p>Previously running Chrome with the '--allow-running-insecure-content' arg did a trick. The same is suggested over the net. On some sites one additional arg is suggested: '--disable-web-security'.</p> <...
<python><selenium-webdriver><selenium-chromedriver><ui-automation>
2024-02-25 21:22:00
7
971
sashkins
78,057,716
340,142
Trying to run Gemma on Kaggle and got issue 'keras_nlp.models' has no attribute 'GemmaCausalLM'
<p>I'm trying to run Gemma on Keras with this model <a href="https://www.kaggle.com/models/keras/gemma/frameworks/keras/variations/gemma_instruct_7b_en" rel="nofollow noreferrer">https://www.kaggle.com/models/keras/gemma/frameworks/keras/variations/gemma_instruct_7b_en</a> And I'm reproducing the Example available on &...
<python><kaggle><gemma>
2024-02-25 21:13:02
2
2,126
Marecky
78,057,705
19,077,881
How to access a value in a Polars struct generated from value_counts?
<p>If I have a df such as:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;color&quot;: [&quot;red&quot;, &quot;blue&quot;, &quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;blue&quot;] }) </code></pre> <p>then if I want the count for color = 'red' in Pan...
<python><dataframe><python-polars>
2024-02-25 21:06:16
2
5,579
user19077881
78,057,611
4,751,165
Py installed from scoop can't find installed Python
<p>After installing python using scoop:</p> <pre><code>scoop install python </code></pre> <p>When running <code>py -3 script.py</code>, py.exe, which is the Python Launcher for windows, can't find an installed Python.</p> <pre><code>py -3 script.py No installed Python found! </code></pre>
<python><windows><powershell><scoop-installer>
2024-02-25 20:36:20
1
16,236
Pau
78,057,602
13,101,893
How to draw a curve through an arbitrary number of true waypoints that may double back
<p>I have been exploring many options to do this. The idea is that I will plot points and a curve will be drawn through them in order, however, the curve will not connect the starting and ending points.<br /> This is what I have so far:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matpl...
<python><numpy><matplotlib><scipy><curve-fitting>
2024-02-25 20:35:23
0
303
Xbox One
78,057,573
11,760,835
QFormLayout does not expand width of left column widgets
<p>I'm trying to create a form layout in a Right-to-left application. I think that the expanding fields grow flag is not working because the most common usage is having the input fields at the right side. Some input widgets do not have the expanding width policy working and they look bad. What could I do?</p> <p><a hre...
<python><pyside><qtwidgets>
2024-02-25 20:25:29
1
394
Jaime02
78,057,555
386,861
nbextensions not showing in jupyter notebook: Command `jupyter-contrib` not found
<p>I'm trying to install nbextensions in jupyter notebook so I can hide code from slideshow.</p> <pre><code>pip install jupyter_contrib_nbextensions jupyter contrib nbextension install --user </code></pre> <p>Error.</p> <pre><code>Jupyter command `jupyter-contrib` not found. </code></pre> <p>Any ideas</p>
<python><jupyter-notebook><jupyter-contrib-nbextensions>
2024-02-25 20:17:04
1
7,882
elksie5000
78,057,467
17,800,932
Fluent interfaces with pipelining or method chaining in Python
<p>I am coming to Python from F# and Elixir, and I am struggling heavily in terms of cleanly coding data transformations. Every language I have ever used has had a concept of a pipeline operator and/or method chaining, and so with Python, I am confused on finding an <em>easy</em> way to accomplish this that doesn't str...
<python><functional-programming><pipeline><fluent><method-chaining>
2024-02-25 19:54:31
2
908
bmitc
78,057,400
11,724,014
GnuGPG python without binary and cross-platform
<p>I am looking for a python project to encrypt and decrypt files using the <a href="https://en.wikipedia.org/wiki/GNU_Privacy_Guard" rel="nofollow noreferrer">GNU Privacy Guard</a> protocol.</p> <p>There exists packages like:</p> <ul> <li><a href="https://pypi.org/project/python-gnupg/" rel="nofollow noreferrer">pytho...
<python><gnupg><pgp><python-gnupgp>
2024-02-25 19:36:02
0
1,314
Vincent Bénet
78,057,395
16,728,369
django-tailwind is not rebuilding styles
<p>I'm trying to use tailwind with my django project and i've followed as this documentation (<a href="https://django-tailwind.readthedocs.io/en/latest/installation.html" rel="nofollow noreferrer">https://django-tailwind.readthedocs.io/en/latest/installation.html</a>) when i'm making changes in tailwind classes in my h...
<python><node.js><django><django-tailwind>
2024-02-25 19:33:47
0
469
Abu RayhaN
78,057,362
10,452,700
why it is not possible use matplotlib.animation when data type within pandas dataframe is datetime due to your time stamp?
<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>I faced the problem of re-producing animation from this post when you pass data type of column list values as <code>'datetime'</code> with dataframe when the x-axi...
<python><pandas><sliding-window><matplotlib-animation>
2024-02-25 19:23:37
1
2,056
Mario
78,057,262
823,859
Cannot update llamaindex
<p>After <code>llamaindex</code> introduced v0.10 in February 2024, it introduced a lot of breaking changes to imports. I am trying to update <code>llama-index</code> within a <code>conda</code> environment, but I receive the following error:</p> <pre><code>&gt; pip install llama-index --upgrade ERROR: Cannot install l...
<python><pip><llama-index>
2024-02-25 18:56:36
4
7,979
Adam_G
78,057,145
6,741,482
Object for storing types for use during static analysis
<p>Is there a way/convention in Python (3.10+) to store types defined in a module, within some container/registry class so that static analysis tools like <code>mypy</code> can correctly infer the type of an annotation?</p> <p>Context for this problem:</p> <ul> <li>Format standard that in-house packages should use the ...
<python><python-3.x><mypy><pydantic>
2024-02-25 18:23:27
0
3,878
pstatix
78,056,946
8,223,979
How to read a huge csv faster?
<p>I tried using pyarrow without success. My code:</p> <pre><code>df = pd.read_csv(&quot;file.csv&quot;, engine='pyarrow') </code></pre> <p>I get this error:</p> <pre><code>&quot;pyarrow.lib.ArrowInvalid: straddling object straddles two block boundaries (try to increase block size?)&quot; </code></pre> <p>I cannot find...
<python><pandas><csv><io><pyarrow>
2024-02-25 17:24:49
2
1,097
Caterina
78,056,934
4,451,315
pandas or Polars: find index of previous element larger than current one
<p>Suppose my data looks like this:</p> <pre class="lang-py prettyprint-override"><code>data = { 'value': [1,9,6,7,3, 2,4,5,1,9] } </code></pre> <p>For each row, I would like to find the row number of the latest previous element larger than the current one.</p> <p>So, my expected output is:</p> <pre><code>[None, 0,...
<python><pandas><python-polars>
2024-02-25 17:22:09
6
11,062
ignoring_gravity
78,056,851
934,757
How to leave out all NaNs a pandas dataframe
<p>I'm upgrading some code from python2 to python3 and the modern pandas version (I now have pandas 2.0.3 and numpy version 1.26.4)</p> <p>My dataframe is :</p> <pre><code> N NE E SE S SW W NW H12 NaN NaN NaN NaN NaN NaN NaN NaN H13 0.7 NaN NaN NaN NaN NaN 1.0 1.4 H14 0.3 NaN NaN NaN NaN...
<python><pandas>
2024-02-25 16:53:41
2
437
djnz0feh
78,056,806
9,133,582
Using tf.keras.metrics.R2Score results in an error in Tensorflow
<p>I'm making a regression model with Tensorflow, but when I use <code>tf.keras.metrics.R2Score()</code> as a metric, it fails with <code>ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: &lt;tf.Tensor: shape=(), dtype=float32, numpy=0.0&gt;</code> after the first epoch. (But works fine...
<python><tensorflow><machine-learning><keras>
2024-02-25 16:40:38
1
1,153
Jacques Amsel
78,056,797
1,946,418
"Expected expression" in a single liner "else continue"
<p><code>Python -V =&gt; 3.12.1</code></p> <pre class="lang-py prettyprint-override"><code>value = &quot;abc&quot; # or could be None in some other cases def doSomething(v): print(f&quot;value is {v}&quot;) for v in range(100): doSomething(v) if value else continue </code></pre> <p><a href="https://i.sstatic....
<python>
2024-02-25 16:36:04
3
1,120
scorpion35
78,056,709
11,825,717
PyTorch tensor.sum() performance drops with large tensors vs. NumPy
<p><code>tensor.sum()</code> performance drops once my tensor exceeds a certain size. Why is that?</p> <pre><code>import torch tensor = torch.FloatTensor(200_000, 2_000).uniform_() &gt; 0.8 # random 1's and 0's tensor[:, :1000].sum(dim=0) tensor[:, :2000].sum(dim=0) # 2x wider but 20x slower </code></pre> <p>Profiling...
<python><performance><pytorch>
2024-02-25 16:16:47
1
2,343
Jeff Bezos
78,056,565
3,305,998
How do I get doctest to run with examples in markdown codeblocks for mkdocs?
<p>I'm using mkdocs &amp; mkdocstring to build my documentation and including code examples in the docstrings. I'm also using doctest (via <code>pytest --doctest-modules</code>) to test all those examples.</p> <h2>Option 1 - format for documentation</h2> <p>If I format my docstring like this:</p> <pre><code> &quot;&...
<python><pytest><doctest><mkdocs><mkdocstrings>
2024-02-25 15:36:03
2
318
MusicalNinja
78,056,541
190,887
How do I resolve this LoRA loading error?
<p>I'm trying to run through <a href="https://huggingface.co/docs/diffusers/training/lora#text-to-image" rel="noreferrer">the 🤗 LoRA tutorial</a>. I've gotten the dataset pulled down, trained it and have checkpoints on disk (in the form of several subdirectories and <code>.safetensors</code> files).</p> <p>The last pa...
<python><huggingface-transformers><huggingface>
2024-02-25 15:26:56
2
14,105
Inaimathi
78,056,450
2,502,331
DataBricks PySpark withColumn() Fails After First Success
<p>I'm working in DataBricks with Python/PySpark. I have several output columns that copy a single input column. One of the output columns is the lower-case version of the upper-case or mixed-case input column, which I need to rename this way before I drop it. Because I am also casting its type, I use the <code>with...
<python><pyspark><databricks>
2024-02-25 15:06:30
1
978
StephenDonaldHuffPhD
78,056,249
11,584,327
How to hide or show a canvas line controlled by sliders using Checkbuttom from Tkinter?
<p>With the code below it is possible to control the amplitude and frequency of a triangular signal.<br /> Just starting out with Python, I fail to hide or show a given signal using a <code>Checkbutton</code> from <code>tkinter</code>. The few examples found on Internet apply to label texts or images, but none to canva...
<python><tkinter><canvas><checkbox><tkinter.checkbutton>
2024-02-25 14:08:06
1
902
denis
78,056,243
5,431,734
call functions from a docker image based on a conda python project
<p>I dont quite understand how to make a docker image and then run a basic function please My toy project (running on a conda env) looks like one shown below, at the bottom:</p> <p>The build looks to executed fine <code>docker build --no-cache -t my_docker_img .</code> What I dont understand is how I can load the ima...
<python><docker><conda>
2024-02-25 14:06:45
1
3,725
Aenaon
78,056,148
2,030,532
How to make pytest exceptions cause breakpoint PyCharm?
<p>PyCharm has this handy feature that, if enabled, you can get a breakpoint where the exception happens and debug it. However, when running pytests through PyCharm, when there is an exception it only shows the error in the console and does not cause exception breakpoints. I know pytest handles the exception by itself,...
<python><pycharm><pytest>
2024-02-25 13:40:03
0
3,874
motam79
78,056,001
893,254
Why can't operator.eq be applied to a class map object using functools.reduce?
<p>Why is the following Python code invalid?</p> <pre><code>iterable = [1, 2, 3] mapped = map(operator.eq, iterable) print(type(mapped)) # `class map` functools.reduce(operator.eq, mapped) </code></pre> <p>A class <code>map</code> object is iterable. The following will work,</p> <p><sub>but produces (perhaps) &quot;u...
<python>
2024-02-25 12:51:26
1
18,579
user2138149
78,055,800
3,904,031
Generate a mesh from my polygon geometry to iterate FEM for geometry optimization?
<p>The 2D script below generates polygons in a box, which represent a cross-section of three cylindrical rings parallel to the z axis which will have voltages applied. I'll solve the <a href="https://scicomp.stackexchange.com/a/43810/17869">Laplace equation</a> in cylindrical coordinates using the Finite Element Method...
<python><mesh><finite-element-analysis>
2024-02-25 11:45:58
0
3,835
uhoh
78,055,498
7,045,119
Python date.today() return different date on the same environment & pc?
<p>I have an Odoo server, where the instance have the following condition and <code>date.today()</code> return yesterday. the following condition return true:</p> <pre class="lang-py prettyprint-override"><code>if invoice.invoice_date &gt; date.today(): errors.append(&quot;- Please, make sure the invoice date is se...
<python><odoo>
2024-02-25 09:46:54
1
1,205
kerbrose
78,055,408
5,378,271
TimeoutError when clicking a button in Playwright
<p>I got playwright._impl._errors.TimeoutError with the following code.</p> <pre><code>import asyncio from playwright.async_api import async_playwright async def fb(): async with async_playwright() as p: browser = await p.chromium.launch(args=[&quot;--disable-gpu&quot;, &quot;--single-process&quot;]) page = ...
<python><python-3.x><playwright>
2024-02-25 09:12:07
1
619
nemy
78,055,011
9,999,114
How can i query and efficiently store 50 million REST API records to build a data lake
<p>The problem use case is simple.</p> <p>I want to query more than 50M records from Salesforce through REST API. It is a part of effort to gather data from multiple sources to fuse them together later which can be fed into a ML model. This data i want to store into a database or a parquet file, from where i can perfor...
<python><database><rest><salesforce><psycopg2>
2024-02-25 06:15:58
1
325
Healer77Om
78,054,752
8,935,725
FastAPI, SQLModel - Pydantic not serializing datetime
<p>My understanding is that SQLModel uses pydantic BaseModel (checked the _mro_. Why is it that the bellow fails the type comparison. (err provided).</p> <pre><code>class SomeModel(SQLModel,table=True): timestamp: datetime id: UUID = Field(default_factory=lambda: str(uuid4()), primary_key=True) def test_some_m...
<python><fastapi><pydantic><sqlmodel>
2024-02-25 03:27:47
2
755
Octavio del Ser
78,054,656
3,388,962
What is the difference between the various spline interpolators from Scipy?
<p>My goal is to calculate a smooth trajectory passing through a set of points as shown below. I have had a look at the available methods of <a href="https://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow noreferrer"><code>scipy.interpolate</code></a>, and also the <a href="https://docs.scipy.org/do...
<python><scipy><interpolation><spline>
2024-02-25 02:24:22
1
9,959
normanius
78,054,416
9,135,359
Huggingface tokenizer object has no attribute 'pad'
<p>I am trying to train a model to classify some diseases, following the HuggingFace tutorial to the dot. I used Kaggle to run the code, as I do not have a powerful GPU. There is no way to include all my code, hence I will insert the pertinent lines only:</p> <ol> <li>I created a pandas <code>dataframe</code> and loade...
<python><tensorflow><huggingface-transformers>
2024-02-25 00:06:50
0
844
Code Monkey
78,054,251
1,895,939
Why does my heap size and thread count increase in this recursive Python code?
<p>I'm working on finding a memory leak in my application, and narrowed down suspicious activity to this (simplified) code:</p> <pre class="lang-py prettyprint-override"><code>import time import threading class Work: def by_duration(self, seconds: float, block: bool = True) -&gt; None: if seconds &lt; 0: ...
<python><memory><python-multithreading>
2024-02-24 22:43:13
0
1,736
Cam.Davidson.Pilon
78,054,191
6,068,294
how to use a string variable to define dataarray name when adding to xarray dataset?
<p>I want to add a <code>dataarray</code> to an <code>xarray</code> <code>dataset</code>, and do so by using <code>xarray.assign</code>, but I don't know how to define the name of the dataarray using a string variable (i.e. to call the new entry &quot;myvar&quot;:</p> <pre><code>import xarray as xr varname=&quot;myvar...
<python><python-xarray><keyword-argument>
2024-02-24 22:17:43
1
8,176
ClimateUnboxed
78,054,172
4,949,649
Python - Implement Authentik SSO in web server using requests_oauthlib
<p>I'm trying to implement SSO in a Web Application using OpenID Connect.</p> <h2>What I am using</h2> <ul> <li><strong>python 3.12</strong></li> <li><strong>Authentik</strong> (the Identity Provider <em>aka IdP</em>)</li> <li><strong>flask</strong> (to expose the webserver)</li> <li><strong>requests_oauthlib</strong> ...
<python><flask><oauth-2.0><single-sign-on><openid-connect>
2024-02-24 22:08:33
1
755
Timmy
78,054,007
2,896,638
How to run many threads/procs with global timeout
<p>I'm trying to run many python threads (or separate processes) from the 'run' method of class GetDayMin. I want the threads or processes to run simultaneously, and after 40 seconds the class instance writes it's data (from each thread/proc) and exits. While I can start each thread without waiting on anything to com...
<python><multithreading><multiprocessing>
2024-02-24 21:15:15
1
347
HonestMath
78,053,770
2,612,259
How can I "dry" up this pytest-mock?
<p>I have some test methods that require a mock of a class. The below code works but I am repeating the same mock in several methods. Here is the code that is getting repeated. You can see it used below in the last 3 methods.</p> <pre class="lang-py prettyprint-override"><code>class PyWaves(object): def names(self)...
<python><pytest-mock>
2024-02-24 19:50:41
1
16,822
nPn
78,053,767
4,119,262
Why is every steps printed and not the final string without vowels?
<p>I have seen various questions close to what I am trying to achieve, i.e removing vowels from a string.</p> <p>My code is as follows (I want to avoid function):</p> <pre><code>word_with_whole_alphabet = input(&quot;give me a string bro: &quot;) vowel = [&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &qu...
<python>
2024-02-24 19:50:11
1
447
Elvino Michel
78,053,580
16,459,035
How to get a <a> tag in a nested HTML using BeautifulSoup4
<p>I want to get to access href links. Although my HTML is a nested structure like the image below</p> <p><a href="https://i.sstatic.net/EhRrj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EhRrj.png" alt="enter image description here" /></a></p> <p>I'am trying to do that using BeautifulSoup4, however ...
<python><web-scraping><beautifulsoup>
2024-02-24 18:49:05
2
671
OdiumPura
78,053,503
22,437,609
How to add gif image inside a Kivy Popup?
<p>I have a popup in my app and works great. It shows a Text as well but i want to add a gif inside it, but i could not success.</p> <p>I will share my structure.</p> <p><strong>KV File:</strong></p> <pre><code>&lt;PopupBox&gt;: pop_up_text: _pop_up_text pop_up_image: _pop_up_image background_color: '#38B6...
<python><kivy><kivymd>
2024-02-24 18:21:35
1
313
MECRA YAVCIN
78,053,296
7,019,073
Align multiple overlayed facetted Seaborn cat plots
<p>I'm trying to create a plot similar to <a href="https://stackoverflow.com/questions/76518217/how-to-map-stripplots-onto-boxplots-in-a-facetgrid">this one</a>. A facet grid with strip and boxplots overlapping. The data is stored in a pandas dataframe. My difference to the referenced question is, that on top of distri...
<python><seaborn>
2024-02-24 17:19:50
1
1,040
Seriously
78,052,964
18,572,509
Get the credentials an instance of `Channel` used to authenticate in Paramiko
<p>I've been working with this multi-threaded SSH server that I made and I've encountered an issue. I need a way to get the credentials each channel used for authentication. For example, in <code>handle</code> after I accept a <code>channel</code> from the <code>transport</code>, I'd like to know what credentials that ...
<python><python-3.x><ssh><paramiko>
2024-02-24 15:22:06
1
765
TheTridentGuy supports Ukraine
78,052,958
11,462,274
How to monitor in real time all the Python files that are running on the computer including files started from subprocess?
<p>I have 4 Python files that are executed separately and uninterruptedly on my computer throughout the day via cmd. Within the codes, there are <code>subprocess</code> that execute other Python files in the background.</p> <p>To keep track of which files are currently being executed, I added a function to the code of ...
<python>
2024-02-24 15:16:31
0
2,222
Digital Farmer
78,052,918
474,491
GAE is very slow loading a sentence transformer
<p>I'm using Google App Engine to host a website using Python and Flask.</p> <p>I need to add text similarity functionality, using sentence_transformers. In requirements.txt, I add a dependency to the cpu version of torch:</p> <pre><code>torch @ https://download.pytorch.org/whl/cpu/torch-2.2.1%2Bcpu-cp311-cp311-linux_...
<python><google-app-engine><pytorch><sentence-transformers>
2024-02-24 15:03:22
2
2,695
Pierre Carbonnelle
78,052,906
5,640,517
Digit OCR using Tesseract
<p>I'm trying to ocr some numbers:</p> <p><a href="https://i.sstatic.net/SeGXC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SeGXC.png" alt="enter image description here" /></a> <a href="https://i.sstatic.net/wLZqG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wLZqG.png" alt="enter ima...
<python><ocr><tesseract><image-preprocessing>
2024-02-24 14:59:37
2
1,601
Daviid