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,410,955
2,263,683
Apache beam pipeline function does not run in parallel
<p>I have a <code>Dofn</code> function in my pipeline which is running in GCP dataflow and is suppose to do some process per products in parallel.</p> <pre><code>class Step1(DoFn): def process(self, element): # Get a list of products for idx, item in enumerate(product_list): yield produc...
<python><google-cloud-platform><google-cloud-dataflow><apache-beam>
2023-11-02 15:38:31
1
15,775
Ghasem
77,410,933
7,936,386
ModuleNotFoundError: No module named 'geocube.api'; 'geocube' is not a package
<p>I am unable to import <code>geocube</code> at all in my virtual environment, although I have installed it and my venv is activated.</p> <pre><code>&gt;&gt;&gt; from geocube.api.core import make_geocube Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\User...
<python><conda><python-venv><modulenotfounderror>
2023-11-02 15:34:58
1
619
Andrei Niță
77,410,905
5,344,240
Visual Studio Code terminal shows multiple Conda envs
<p>I have VSCode in Windows 11. I have WSL (Ubuntu 22.04) and launch VSCode from the terminal like <code>code .</code> from the project folder. When I open the built-in terminal it shows two conda (Anaconda) environments in parentheses, so I have no idea which one is active, if any. On subsequent <code>conda deactivate...
<python><visual-studio-code><environment><anaconda3>
2023-11-02 15:31:16
3
455
Andras Vanyolos
77,410,704
10,120,952
Pylance not working autocomplete for dynamically instantiated classes
<pre><code>from typing import Literal, overload, TypeVar, Generic, Type import enum import abc import typing class Version(enum.Enum): Version1 = 1 Version2 = 2 Version3 = 3 import abc from typing import Type class Machine1BaseConfig: @abc.abstractmethod def __init__(self, *args, **kwargs) -&gt...
<python><python-typing><pylance><pyright>
2023-11-02 15:03:40
3
1,104
alexp
77,410,272
726,730
Problems installing Python av in Windows 11
<pre class="lang-py prettyprint-override"><code>C:\Windows.old\Users\chris&gt;pip install av Defaulting to user installation because normal site-packages is not writeable Collecting av Using cached av-10.0.0.tar.gz (2.4 MB) Installing build dependencies ... done Getting requirements to build wheel ... error err...
<python><windows><pip><pyav>
2023-11-02 14:06:31
1
2,427
Chris P
77,410,240
10,750,541
How to obtain a list of [index, column, value] lists where the value is not 0 or not missing?
<p>Assuming that the starting point is a dataframe like <em><strong>df</strong></em>, I am trying to achieve the dataframe <em><strong>from_to_value</strong></em> in a pythonic way, meaning without iterating through the dataframe:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df A B C r1 5 Na...
<python><pandas>
2023-11-02 14:02:26
2
532
Newbielp
77,410,211
409,461
Pythonic way to process a synchronous event (callback) in an async environment
<p>I'm looking for a solution with which I could use the Python socketIO <code>disconnect</code> event and forward this into a fully asynchronous host class.</p> <pre><code> @self._sio.event def disconnect(): ''' Platform disconnected ''' logging.info(&quot;disconnected&quot;) self._deleg...
<python><async-await><python-socketio>
2023-11-02 13:59:09
1
837
decades
77,410,154
471,136
How to format currency column in streamlit for dataframes?
<p>I have the following piece of code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import streamlit as st cashflow = pd.DataFrame(data=[ (2023, 10000), (2022, 95000), (2021, 90000), (2020, 80000), ], columns=['year', 'cashflow']) st.dataframe( data=cashflow, column_config={ ...
<python><pandas><streamlit>
2023-11-02 13:52:09
2
33,697
pathikrit
77,410,125
2,112,406
pybind11 change elements in list in a class from the python side
<p>Suppose I have a class <code>Smol</code>:</p> <pre class="lang-c++ prettyprint-override"><code>class Smol { std::string name; int value; public: Smol(std::string name_, int val){ name = name_; value = val; } void set_name(std::string new_name){ name = new_name; } ...
<python><c++><pybind11>
2023-11-02 13:47:17
0
3,203
sodiumnitrate
77,410,108
11,725,056
How to efficiently get all the valid re-ranked permutations from a list when it has duplicate ranks inside it?
<p>Let's suppose two people got the similar marks or scores. Theoretically you can assign them the same rank but what if there is a constraint that there can't be duplicate ranks.</p> <p>Examples:</p> <ul> <li>Input: [1,1,2] can be written as Output: [1,2,3], [2,1,3]</li> <li>Input: [1,1,1] and can be written as ANY pe...
<python><python-3.x><algorithm><permutation><ranking>
2023-11-02 13:44:44
1
4,292
Deshwal
77,409,954
5,084,560
Polars and Pandas DataFrame consume almost same memory. Where is the advantage of Polars?
<p>I wanted to compare memory consumption for same dataset. I read same SQL query with pandas and polars from an Oracle DB. Memory usage results are almost same. and execution time is 2 times faster than polars. I expect polars will be more memory efficient.</p> <p>Is there anyone who can explain this? And any suggesti...
<python><pandas><dataframe><python-polars>
2023-11-02 13:23:09
2
305
Atacan
77,409,924
9,301,805
Is there a "Highlight selected word" feature for Jupyter Notebook 7?
<p>I recently upgraded my Notebook to Notebook 7 (on a Windows machine with Python 3.11). I would like to have a &quot;Highlight selected word&quot; feature like <a href="https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html" rel="noreferrer">the one in</a> <code>jupyter-contrib-nbextensions</code>...
<python><jupyter-notebook><jupyter-extensions>
2023-11-02 13:19:40
0
1,575
user88484
77,409,918
427,083
In Django admin, how do I manage complex user privileges?
<p>Suppose you have this entity structure in Django with to-many relationships:</p> <pre><code>- Company - Division - Department - Unit </code></pre> <p>Every user is part of a <code>Unit</code>, so I managed the rights to create, edit and delete entities in <em>Django Admin</em> by assigning <em>groups</em...
<python><django><django-models><data-structures><django-admin>
2023-11-02 13:18:45
1
80,257
Mundi
77,409,895
11,049,863
Is it possible to configure my celery periodic tasks outside of the Django settigns file? I can't import my tasks into settings
<p>Here's how my project is organized.<br/></p> <pre><code>electron / ... electron / &lt;----- sources root (pycharm) ... electron / ... celery.py settings.py tasks / tasks.py &lt;----- Here are my tasks </code></pre> <p>celery beat configuration in settings.py</p> <pre><code>fro...
<python><django><django-celery-beat>
2023-11-02 13:14:53
0
385
leauradmin
77,409,881
2,581,506
How to write python INFO logs to the output and DEBUG logs to a file?
<p>I searched multiple similar questions, but I couldn't find an answer.</p> <p>Here is an example:</p> <pre><code>logging.info(&quot;This should show both in a file and the output&quot;) logging.debug(&quot;This should show only in a file&quot;) </code></pre>
<python><logging>
2023-11-02 13:13:24
1
1,249
Eran H.
77,409,748
7,534,658
How to infer a Python class generic based on a method input?
<p>I want to write a pipeline using Python like this:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Callable from typing import Generic, TypeVar T = TypeVar(&quot;T&quot;) U = TypeVar(&quot;U&quot;) V = TypeVar(&quot;V&quot;) class Pipeline(Generic[T, U]): def pipe(self, _cb: Ca...
<python><python-typing>
2023-11-02 12:56:25
0
631
p9f
77,409,729
1,757,224
Unknown character for Turkish character
<p>I have a dataframe consisting of two columns: (1) Turkish cities, (2) corresponding values.</p> <pre><code>dict_ = {'City': {0: 'ADANA', 1: 'ANKARA', 2: 'ANTALYA', 3: 'AYDIN', 4: 'BALIKESİR', 5: 'BURSA', 6: 'DENİZLİ', 7: 'DÜZCE', 8: 'DİYARBAKIR', 9: 'ELAZIĞ', 10: 'GAZİANTEP', 11: 'GİRESUN', 1...
<python><pandas><string><capitalization><capitalize>
2023-11-02 12:54:20
3
973
ARAT
77,409,726
2,876,079
How to generate unit tests for Python using src and test folder structure (preferable with PyCharm integration)?
<p>In my python project I have following folder structure:</p> <pre><code>src foo foo.py baa baa.py test foo baa </code></pre> <p>and would like to <strong>generate a unit test file</strong> <code>test/foo/test_foo.py</code> that tests <code>src/foo/foo.py</code>.</p> <p>In PyCharm I can</p> <ul> <li>go...
<python><unit-testing><pycharm><pytest><code-generation>
2023-11-02 12:54:08
1
12,756
Stefan
77,409,551
3,238,679
How to implement a symmetric autocorelation function?
<p>I am trying to compute these values:</p> <p><img src="https://latex.codecogs.com/gif.image?%5Cdpi%7B110%7D%20R_z%5Bn,t%5D=z%5Bn+t%5Dz%5E*%5Bn-t%5D" alt="enter image description here" /></p> <p><img src="https://latex.codecogs.com/gif.image?%5Cdpi%7B110%7D%20R_z%5Bn,t%27%5D=z%5Bn+t%27%5Dz%5E*%5Bn-t%27%5D" alt="enter ...
<python><signal-processing>
2023-11-02 12:25:38
0
1,041
Thoth
77,409,496
8,588,743
Flipping the x & y axis in diagram resulting from plot_simultaneous() in a Tukey HSD test
<p>I have a data set and I need to check significant differences between 5 groups. The resulting diagram shows test groups on the y-axis and the response on the x-axis. However I want the figure to show the reverse, that is response on the y-axis and test groups on the x-axis. So the confidence interval bars should be ...
<python><statsmodels><tukey>
2023-11-02 12:18:52
0
903
Parseval
77,409,424
386,861
Layout of plot in Altair is not appearing to show conditional colours in time series plot
<p>I've got some data on admissions in long format about obesity-related hospital admissions - you can see the full dataset here: <a href="https://www.dropbox.com/scl/fi/6hu7g556pzcyfkhhp1s5l/sorted_data.csv?rlkey=n1tz0mzddkdinkt14rofjxlj1&amp;dl=0" rel="nofollow noreferrer">https://www.dropbox.com/scl/fi/6hu7g556pzcyf...
<python><pandas><altair>
2023-11-02 12:07:38
0
7,882
elksie5000
77,409,338
5,800,969
How to scrape a page generated using flutter javascript code dynamically
<p>I am trying to scrape page to download a file by clicking on download button image in website below. I couldn't inspect that element to find its id for click using selenium . After looking at source code found that its a javascript flutter code and it can't be inspected. Sharing the screenshot of page and page sourc...
<python><selenium-webdriver><selenium-chromedriver>
2023-11-02 11:52:27
1
2,071
iamabhaykmr
77,409,302
17,795,398
Python logging: is there any way to keep last n log files
<p>I'm new to python logging. I was wondering if there is a way to keep last n log files. This is my config:</p> <pre><code>import logging logging.basicConfig( filename = &quot;logs/log.log&quot;, filemode = &quot;w&quot;, encoding = &quot;utf-8&quot;, force = True, level = logging.INFO, format ...
<python><logging>
2023-11-02 11:46:03
2
472
Abel Gutiérrez
77,409,240
7,599,215
python ftp cant delete file, while lftp can
<p>I'm trying to delete file from FTP server using python's <code>ftp</code> lib (I do have R/W permission):</p> <pre class="lang-py prettyprint-override"><code>from ftplib import FTP ftp = FTP('192.168.1.2') ftp.login(user='admin', passwd=None) ftp.login() ftp.cwd('audio/user_rec/575B62E2') ftp.dir() </code></pre> <...
<python><ftp>
2023-11-02 11:35:32
0
2,563
banderlog013
77,409,013
4,494,781
Clearing (zeroing) all bytes of a sensitive bytearray in memory
<p>After reading the <a href="https://stackoverflow.com/a/51936887/4494781">following answer</a>, I want to make sure a <code>bytearray</code> with sensitive information (password) is correctly cleared in memory prior to garbage collection. I'm assuming garbage collection in python only removes the pointer but does not...
<python><python-bytearray>
2023-11-02 10:56:48
0
1,105
PiRK
77,408,930
12,040,751
Passing an exception type as argument, how to type hint?
<p>I have a function which takes an exception class as an argument, this is the simplified version</p> <pre class="lang-py prettyprint-override"><code>def catch_exception(exception): try: 1/0 except exception: print(&quot;lol&quot;) </code></pre> <pre><code>&gt;&gt;&gt; catch_exception(exception...
<python><exception><python-typing>
2023-11-02 10:43:20
1
1,569
edd313
77,408,785
13,946,204
How to make uWSGI server stop if an application raised exception on load?
<h2>Simple reproducible example:</h2> <ul> <li>project structure:</li> </ul> <pre><code>. ├── app.ini ├── app.py ├── uwsgi.ini └── wsgi_run.py </code></pre> <ul> <li><code>app.ini</code></li> </ul> <pre><code>[app:main] use = call:app:main pyramid.reload_templates = true pyramid.debug_authorization = false pyramid.deb...
<python><uwsgi><pyramid>
2023-11-02 10:23:30
0
9,834
rzlvmp
77,408,717
3,584,765
Using a python ssh session which asks for a password to the private key
<p>I am using an ssh connection to remote server via username and password which works fine. I intended to automate some file transactions from my machine to this remote server and attempted to write a python script which would use ssh connections.</p> <pre><code>from paramiko import SSHClient from scp import SCPClient...
<python><ssh>
2023-11-02 10:13:28
0
5,743
Eypros
77,408,654
17,473,587
Encountering ValueError: not enough values to unpack (expected 3, got 0) with Celery in Django project on Windows 7
<p>I have been working on a Django project on my Windows 7 machine, using VS-Code as my development environment. Recently, I decided to incorporate Celery for handling asynchronous tasks. However, I have been encountering a ValueError: not enough values to unpack (expected 3, got 0) whenever I try to retrieve the resul...
<python><django><redis><rabbitmq><celery>
2023-11-02 10:04:31
1
360
parmer_110
77,408,636
769,449
Inherited Scrapy spider does not store any output from super basic tutorial site
<p>See the full Scrapy project filenames and code below. It creates 2 output files myspecificspider.json AND myspecificspider_items.json (which is weird on its own as I'd expect only the latter), but more importantly neither of the files contain ANY content. I can't figure out what's wrong here. Te debug log shows no e...
<python><web-scraping><scrapy>
2023-11-02 10:02:03
0
6,241
Adam
77,408,589
10,218,291
Python dateparser error, AttributeError: "safe_load()" has been removed, use
<p>Today while I was trying to build my application without any changes made to old code just added logging and found below error by surprise.</p> <pre><code> File &quot;/app/search/parsers.py&quot;, line 9, in &lt;module&gt; import dateparser File &quot;/home/python/.local/lib/python3.8/site-packages/dateparser/...
<python><python-3.x><django>
2023-11-02 09:56:46
0
1,617
Avi
77,408,582
7,812,273
Can we run IDL(Interactive Data Language) in Databricks Notebook (python code)
<p>I am working on a project where we use Azure stack for data engineering and analysis. The main component for computation is Azure Databricks in which most of the code is written in python code.</p> <p>Recently I got a requirement to work in a project where we have to process mf4(Measurement Data Files) files. To pro...
<python><databricks><azure-databricks><idl><idl-programming-language>
2023-11-02 09:55:30
1
1,128
Antony
77,408,581
1,422,096
Pandas weirdly reading dates with read_excel
<p>I have a problem a little bit similar to <a href="https://stackoverflow.com/questions/34156830/leave-dates-as-strings-using-read-excel-function-from-pandas-in-python">Leave dates as strings using read_excel function from pandas in python</a>.</p> <p>When doing:</p> <pre><code>x = pd.read_excel(&quot;example.xlsx&quo...
<python><pandas>
2023-11-02 09:55:29
2
47,388
Basj
77,408,505
9,640,238
Properly unwrap long text with Python
<p>I'm trying to find a way to <em>properly</em> unwrap long text in Python. What I mean by &quot;properly&quot; is that only single occurrences of <code>\r\n</code> should be replaced by a space, and any sequence of two or more should be retained. For instance:</p> <pre class="lang-py prettyprint-override"><code>text ...
<python><text>
2023-11-02 09:45:19
1
2,690
mrgou
77,408,418
9,614,610
QSizeGrip doesn't resize window at all how do i fix that?
<p>I am attempting to create a frameless window to allow for a customizable title bar. However, I've encountered an issue with the <code>QSizeGrip</code> not resizing my window as intended.</p> <p>I've experimented with placing it in different sections of the code, but unfortunately, it hasn't proven effective. I also ...
<python><python-3.x><pyqt><pyqt5><qsizegrip>
2023-11-02 09:33:53
1
417
Vlad
77,408,336
842,693
Is there a way to specify per-feature project.scripts in pyproject.toml using hatch?
<p>I have a small python project &quot;<code>tsdb</code>&quot; using <em>hatch</em> for packaging. The projects develops a python package and includes a demo using Streamlit. Since not everyone needs the demo and since Streamlit has a lot of dependencies, I make it an <em>optional dependency</em> (or a <em>feature</em>...
<python><entry-point><hatch>
2023-11-02 09:22:30
0
1,623
Michal Kaut
77,408,220
7,334,572
How to format a dataframe column wise in pandas?
<p>I used to format the dataframe and output a file by:</p> <pre class="lang-py prettyprint-override"><code>tta = pandas.DataFrame( {'name': ['xx', 'y y', 'z'], 'alter': ['AA', 'BB', 'CCC']}) str1 = tta.to_string(formatters={'name': '{:05s}'.format, 'alter': '{:08s}'.format ...
<python><pandas>
2023-11-02 09:06:45
3
442
cwind
77,408,201
7,745,011
Python custom logging handler tries to log itself during emit()
<p>I am trying to implement a custom logging handler, which should post to a rabbitmq server<sup>1</sup>.</p> <p>A basic setup of this would look something like this:</p> <pre><code>class RabbitMQHandler(logging.Handler): def __init__(self, host: str, port: int, queue: str, level: int = 0) -&gt; None: sel...
<python><logging><rabbitmq><pika>
2023-11-02 09:02:58
1
2,980
Roland Deschain
77,408,116
4,994,781
pytest indirect parametrization fails when mixing it with non-fixture parameters
<p>First of all, sorry for the title, I couldn't think of something better.</p> <p>The code below is fictitious because the real code where this is happening is much longer and this little example shows the same problem.</p> <p>I have this code in my <code>conftest.py</code>:</p> <pre><code>@pytest.fixture() def my_fix...
<python><pytest><parametrized-testing>
2023-11-02 08:50:47
1
580
Raúl Núñez de Arenas Coronado
77,407,990
268,581
Investigating JSON data
<h1>PowerShell</h1> <p>Here's an API call to sec.gov in Windows PowerShell:</p> <pre><code>$result = Invoke-RestMethod &quot;https://data.sec.gov/submissions/CIK0001318605.json&quot; -UserAgent 'company user@abc.com' </code></pre> <p>If you want to try the call, replace <code>company user@abc.com</code> as appropriate....
<python><json>
2023-11-02 08:32:56
1
9,709
dharmatech
77,407,930
1,020,139
How to use Python Poetry as a "lightweight" virtual environment like `python -m venv <venv>`?
<p>I often prefer <code>python -m venv &lt;venv&gt;</code> due to its simplicity and lightweight (no notion of a Poetry &quot;package&quot;), only setting environment variables to direct Python/Pip to use local packages.</p> <p>How can I use Python Poetry like virtual environments created by <code>python -m venv &lt;ve...
<python><python-venv><python-poetry>
2023-11-02 08:19:35
0
14,560
Shuzheng
77,407,811
9,304,534
How to implement RBAC in azure and flask application
<p>I want to implement Azure RBAC in a flask application. How should I do it?</p> <p>Inside the web app, Users can assign and remove roles to other users.</p>
<python><azure><flask><azure-rbac>
2023-11-02 08:01:46
1
1,885
Nitin Raturi
77,407,621
6,807,106
python regular expression greedy capture
<p>I need to replace the entire text between AAA and BBB (not including those) in the following multi-line text with a blank. I tried this pattern =&gt; 'This form.*[^Accuracy.]Accuracy.' But it only captures until first 'Accuracy.' I tried to do a greedy capture but cannot get the right pattern. Please help.</p> <pre>...
<python><regex>
2023-11-02 07:24:31
1
352
Soundar Rajan
77,407,078
696,264
Unable to delete a record in Milvus collection
<p>The below code I have executed to delete a record from Milvus collection. There is no error but the respective record also not deleted.</p> <p>Please recommend solution for this</p> <pre><code>from pymilvus import connections,Collection,db,utility,FieldSchema, CollectionSchema def connectVectorDB(**conStrings): ...
<python><milvus>
2023-11-02 05:11:01
1
1,321
Madhan
77,406,962
435,563
How to type function returning a class decorator? (python3.11)
<p>I know I can type a class decorator as follows:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar('T', bound=Type[Any]) def decorator(cls: T) -&gt; T: ... </code></pre> <p>Which can be used:</p> <pre><code>@decorator class Foo: foo: int </code></pre> <p>And a reference to <code>foo</code> on ins...
<python><generics><python-decorators><mypy>
2023-11-02 04:34:09
1
5,661
shaunc
77,406,961
1,085,068
Merge a SQL table with a dataframe via pyodbc
<p>I'm trying to merge a SQL table to a dataframe object using pyodbc.</p> <p>The merge will delete the rows if there are no matches in the destination (SQL) table, the problem is that it seems pyodbc apply the merge row by row, and by doing so when it reach the last row, all the rows updated or inserted before will be...
<python><pandas><pyodbc>
2023-11-02 04:34:04
1
1,921
Guillaume
77,406,773
1,546,990
Django: getting the value of a serializer's field within the serializer itself
<p>In my Django serializer, I have a validate() method.</p> <p>In it, I want to access the value of one of the serializer's fields. How would I do this?</p> <p>I'm using Python 3.10.2 and Django 3.2.23.</p> <p>Previous answers here have suggested using <code>self.initial_data.get(&quot;field_name&quot;))</code> but tha...
<python><django><django-rest-framework>
2023-11-02 03:32:25
1
2,069
GarlicBread
77,406,710
3,446,927
.python_packages and .venv directories prevent func azure functionapp publish
<p>I am trying to deploy a Python Azure Function using Azure Function Core Tools. When I run the publish command, I receive the following error:</p> <pre><code>PS C:\[..]\func&gt; func azure functionapp publish [function name] --build remote Getting site publishing info... Creating archive for current directory... Perf...
<python><azure><azure-functions>
2023-11-02 03:08:04
1
539
Joe Plumb
77,406,653
4,582,026
Tesseract not recognising text in image
<p>I am trying to use tesseract in python 3.11 to convert some images to text on Windows 11. I have tried preprocessing the images including morphing, enlarging, greyscaling and thresholding but nothing seems to work.</p> <p>I have been chopping and changing my code but the below is where I have got to (path is the loc...
<python><opencv><computer-vision><ocr><tesseract>
2023-11-02 02:48:43
2
549
Vik
77,406,413
2,975,438
How can I speed up an analytic chatbot that's based on Langchain (with agents and tools) and Streamlit and disable its intermediate steps?
<p>I created an analytic chatbot using Langchain (with tools and agents) for the backend and Streamlit for the frontend. It works, but for some users' questions, it takes too much time to output anything. If I look at the output of intermediate steps, I can see that the chatbot tries to print out all relevant rows in t...
<python><chatbot><streamlit><langchain><large-language-model>
2023-11-02 01:10:19
1
1,298
illuminato
77,406,411
11,911,694
TypeError: object AsyncMock can't be used in 'await' expression
<p>I created a pytest for a function but I get the following error when I try to run it:</p> <pre><code>&gt; return await cntrl.get_function_by_topic_by_method(url, method, *args, query_params=query_params, action=action, **kwargs) E TypeError: object AsyncMock can't be used in 'await' expression </...
<python><asynchronous><async-await><python-asyncio>
2023-11-02 01:09:22
1
303
Aastha Jha
77,406,316
11,659,424
How do you safely pass values to SQLite PRAGMA statements in Python?
<p>I'm currently writing an application in Python that stores its data in a SQLite database. I want the database file to be stored encrypted on disk, and I found the most common solution for doing this to be <a href="https://www.zetetic.net/sqlcipher/" rel="nofollow noreferrer">SQLCipher</a>. I added <a href="https://g...
<python><sqlite><sql-injection><sqlcipher>
2023-11-02 00:26:37
2
409
Sam Zuk
77,406,185
3,311,276
How can I get both a rendered template html page and swagger documentation of same flask app with differnt endpoint?
<p>I have written this code:</p> <pre><code>from flask import Flask, render_template, request from flask_restx import Api, Resource app = Flask(__name__) api = Api(app, version='1.0', title='Sample API', description='A sample API', doc='/api') # Sample data config = { 'nodes': ['Node1', 'Node2', 'Node3'], 'fi...
<python><flask><flask-restx>
2023-11-01 23:38:46
1
8,357
Ciasto piekarz
77,406,157
5,274,291
What is the total memory overhead of creating a single byte in python?
<p>When I run the following code in Python:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; mybyte = bytes(1) &gt;&gt;&gt; sys.getsizeof(mybyte) 34 </code></pre> <p>I'd ideally expect something around 1 as size because I created a variable to store a single byte, that I don't wa...
<python>
2023-11-01 23:28:11
0
1,578
João Pedro Schmitt
77,406,003
832,490
Expose interface to pybind11
<p>I am trying to expose a interface (aka a class with no implementation) to Python using pybind11</p> <p>I am not sure if pybind11 was built to this, because everything that I saw in their documentation is about to generate modules for python usage, and not to embedded.</p> <p>I tried this:</p> <pre><code>py::object m...
<python><c++><pybind11>
2023-11-01 22:35:34
1
1,009
Rodrigo
77,405,678
4,338,776
How to use optional parameters from decorated method in decorator method
<p>I have a function with an optional argument. How can I pass this argument into the decorator function?</p> <pre><code> def decorator(self, func: Callable[[Any], Any]) -&gt; Callable[[Any, Any], Any]: def wrapper(*args: Any, **kwargs: Any) -&gt; Any: print(args) # does not contain the &quot;opt...
<python><python-3.x>
2023-11-01 21:21:42
2
847
Zigzagoon
77,405,547
4,439,019
Filtering JSON records - Python
<p>I am trying to filter out the records and just show the JSON formatted records based on a specific column value. In this case <code>displayName</code></p> <pre><code>data = { &quot;count&quot;: 10408, &quot;value&quot;: [ { &quot;id&quot;: 151, &quot;name&quot;: &quot;Test&quo...
<python><json>
2023-11-01 20:52:11
1
3,831
JD2775
77,405,314
4,515,838
multi-boundary API call not working in Python
<p>I have a working API call in Postman and I'm trying to replicate the call in Python. I started with the boilerplate code Postman provided and made some changes, but the API call is not working. I pulled a Wireshark log with a working call via Postman and compared it against my API call, and I think I may have found ...
<python><http>
2023-11-01 20:05:16
1
363
Yitzhak
77,405,230
7,045,589
How can I test if a directory exists, and create a Path object with one line of code?
<p>I'm new to using the Python <code>pathlib</code> library, so please edit this question if I'm using incorrect terminology here and there...</p> <p>I'm using the <code>Path</code> class to both create a directory if it doesn't exist, and then to instantiate a <code>Path</code> object. I currently have this as two li...
<python><pathlib>
2023-11-01 19:49:11
2
309
the_meter413
77,405,100
13,086,128
Immortal Objects in Python: how do they work?
<p>Recently I came across</p> <p><strong>PEP 683 – Immortal Objects, Using a Fixed Refcount</strong></p> <p><a href="https://peps.python.org/pep-0683/" rel="nofollow noreferrer">https://peps.python.org/pep-0683/</a></p> <p>What I figured out that objects like <code>None</code>, <code>True</code>, <code>False</code> wil...
<python><python-3.x><pep><python-3.12>
2023-11-01 19:23:22
3
30,560
Talha Tayyab
77,405,058
10,250,223
Decrypt a string in Python that was encrypted by AES-CBC using crypto.subtle in JavaScript
<p>I am dealing with a case where I need to encrypt the payload at client side using JavaScript via AES-CBC algorithm, but later decrypt it in backend using Python. The module used for encryption in JavaScript is crypto.subtle and works with most of the params being in bytes.</p> <p>In python2 I'm using a module called...
<javascript><python><python-2.7><encryption><cryptography>
2023-11-01 19:14:31
1
533
Neeraj Kumar
77,404,986
10,431,629
Combining rows in Pandas based on a single column when column numbers can change
<p>My problem is something like this:</p> <p>I have a dataframe say: (column names can change and columns can get added too)</p> <pre><code> df-in A B C D E U1 1 24 35 a V1 9 d 65 j ...
<python><pandas><row><grouping><aggregation>
2023-11-01 18:58:05
0
884
Stan
77,404,797
13,100,938
Is there a way to group subplots onto a single row in order to stack them vertically?
<p>I have 3 subplots I need to display like so: <a href="https://i.sstatic.net/wfTRG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wfTRG.png" alt="enter image description here" /></a> I have been successful in creating 2 subplots side by side but I am struggling to find (or describe) a way to get the a...
<python><matplotlib><subplot>
2023-11-01 18:21:12
0
2,023
Joe Moore
77,404,793
5,604,827
Python loop through list, enumerate, and start and end at specific index, but do not modify the index
<p>I have a text file as a list, each line is an item in the list. This list contains multiple start tag and end tag (but otherwise not structured) and I must iterate through the file processing data between the start and end tags. Due to potential errors in the file, I must ignore that section of data if some data bet...
<python><python-3.x><list><slice><enumerate>
2023-11-01 18:20:09
2
407
KyferEz
77,404,706
5,052,482
Is there an Apache Beam function to gather a fixed number of elements?
<p>I am fairly new to Apache Beam and Dataflow, and I want to gather or &quot;batch together&quot; <code>k</code> number of elements from a <code>PCollection</code> that has <code>n</code> elements. In this case <code>n</code> is not a fixed number and <code>n &gt; k</code>. For example, suppose my <code>PCollection</c...
<python><google-cloud-dataflow><apache-beam><apache-beam-io>
2023-11-01 18:06:06
1
2,174
Jash Shah
77,404,689
11,001,783
How to reformat spreadsheet tables by adding an extra column using the cell value
<p>I have a system file with format like this:</p> <pre><code> Col 1 Col 2 Col 3 Row1: Employee Standard Report Row2: Effective Date 11/01/2023 Row3: Employee_ID Name Gender Row4: 0001 A F Row5: 0002 ...
<python>
2023-11-01 18:02:13
0
359
Sandy
77,404,609
11,159,734
Postgres/VectorPG expects string for some reason
<p>Basically I want to adapt this Colab Notebook from Google for my own project: <a href="https://colab.research.google.com/github/GoogleCloudPlatform/python-docs-samples/blob/main/cloud-sql/postgres/pgvector/notebooks/pgvector_gen_ai_demo.ipynb#scrollTo=hZKe_9qeRdMH" rel="nofollow noreferrer">https://colab.research.go...
<python><postgresql><google-cloud-platform>
2023-11-01 17:47:51
0
1,025
Daniel
77,404,571
11,233,365
How to load only chosen frames from TIFF image stack into memory, without having to load everything
<p>I am working with large TIFF image stacks that are equivalent to NumPy arrays on the order of <code>(300, 2048, 2048)</code>. I am interested in writing a function that allows me to quickly pick <code>n</code> chosen slices from the array for plotting and comparison, to see how the image has evolved. However, most o...
<python><matplotlib><multidimensional-array><lazy-loading><scikit-image>
2023-11-01 17:41:40
0
301
TheEponymousProgrammer
77,404,543
945,511
Find whether a float value is within categorical value using polars dataframe
<p>I'm trying to find whether a float value &quot;real_value&quot; is found within the interval &quot;categorical_value&quot; using polars dataframe. first, I tried to cast the &quot;categorical_value&quot; column to categorical datatype and then find the &quot;real_value&quot; within the &quot;categorical_cast&quot;<b...
<python><python-polars>
2023-11-01 17:35:52
2
693
Carlitos Overflow
77,404,459
3,574,603
Python3 + Digital Ocean: No module named 'torch'
<p>I am trying to install torch on a Digital Ocean Ubuntu droplet. I am following <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-pytorch" rel="nofollow noreferrer">this</a>:</p> <pre><code>mkdir ~/pytorch mkdir ~/pytorch/assets cd ~/pytorch python3 -m venv pytorch source pytorch/bin/ac...
<python><pip><torch>
2023-11-01 17:22:05
1
3,678
user3574603
77,404,367
2,100,783
Adding leading zeros to extracted month from date on SQLAlchemy
<p>I'm currently have this code working without issues:</p> <p><code>cast(func.extract('month', cast(metric.table.c[date_field], Date)), String(2))</code></p> <p>What I want to achieve is to have leading zeros on months that are composed of single digits.</p> <p>I tried: .zfill(2) it gave me an error: zfill cannot be a...
<python><python-3.x><sqlalchemy>
2023-11-01 17:05:48
1
582
Alejandro
77,404,317
653,311
Correct way to use multiple inheritance with Qt (pysyde6)
<p>I'm trying to use multiple inheritance with my and Qt-derived classes. But faced with the fact that the <code>__init__()</code> method from my class is not called when I use <code>super()</code> to call <code>__init__()</code> for base classes. I suppose that's because Qt classes do not use <code>super()</code> in t...
<python><python-3.x><pyside><multiple-inheritance><pyside6>
2023-11-01 16:59:51
0
10,221
GrAnd
77,404,283
8,271,728
How to debug a "Connection reset by peer" issue in urllib3 when upgrading from v1 to v2
<p>Does anyone have any pointers or advice on how to get to the bottom of a &quot;Connection reset by peer&quot; issue in Python with urllib3?</p> <p>I have been using using urllib3 version 1 for year but have a project that when I swap from urllib3==1.26.18 to urllib3&gt;=2.0.0 my requests that were working now fail.<...
<python><ssl><https><urllib3>
2023-11-01 16:52:58
0
931
Steve Mapes
77,404,219
13,142,245
Pydantic: custom field constraints
<p>Using Pydantic, how can I enforce custom constraints? For example, suppose the below function determined if an input was valid</p> <pre><code>def valid(x): if typeof(x) != str: return False else: return x.isnumeric() and len(x)==3 </code></pre> <p>Essentially I want strings that only contain nu...
<python><pydantic>
2023-11-01 16:41:10
1
1,238
jbuddy_13
77,404,194
5,662,005
Databricks parallelize file system operations
<p>This question applies broadly but the specific use case is concatenating all fragmented files from a number of directories.</p> <p>The crux of the question is optimizing/inspecting parallelism with with how Databricks performs file system operations.</p> <p>Notes:</p> <ul> <li><p>Cluster has 128 cores for the driver...
<python><databricks><aws-databricks><dbutils>
2023-11-01 16:36:24
0
3,899
Error_2646
77,403,801
2,386,605
Make a httpx GET request with data body
<p>When I do a curl request for GET endpoint of a REST API, I would go it like this</p> <pre><code>curl -X 'GET' \ 'http://localhost:8000/user/?limit=10' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '[ { &quot;item_type&quot;: &quot;user&quot;, &quot;skip&quot;: 0 } ]' ...
<python><curl><python-requests><httpx>
2023-11-01 15:34:48
1
879
tobias
77,403,588
3,783,002
Can't read and query graphml file with lxml
<p>I have an XML (GraphML) file which is loosely defined as follows:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;graphml xmlns:x=&quot;http://www.yworks.com/xml/yfiles-common/markup/3.0&quot; xmlns:y=&quot;http://www.yworks.com/xml/yfiles-com...
<python><xml><graph><lxml><graphml>
2023-11-01 15:01:23
1
6,067
user32882
77,403,583
4,115,031
How do I update the path of a venv in PyCharm?
<p>I moved a project from one directory into another, and now my venv won't work. Is there a way to update where PyCharm looks for the venv? I tried the 'Add existing local interpreter' dialog and it didn't work (after clicking &quot;Ok&quot; the interpreter I selected doesn't show up in the list of available interpr...
<python><pycharm><jetbrains-ide>
2023-11-01 15:00:31
0
12,570
Nathan Wailes
77,403,321
22,466,650
How to make an alias of a DataFrame attribute during the instantiation?
<p>To simplify my problem, let's consider this simple class.</p> <pre><code>import pandas as pd class Report: def __init__(self, t=pd.DataFrame({'col1': [1, 2]}), n=None): self.name = n self.table_as_df = t _df = self.table_as_df _df = _df.rename(columns={'col...
<python><pandas>
2023-11-01 14:21:10
1
1,085
VERBOSE
77,403,139
2,232,418
How to import from one python file to another
<p>I know this question has been asked a million times but for the life of me I just cannot get this.</p> <p>I have a scripts <code>setup.py</code> and <code>utility_functions.py</code> within a folder called <code>utils</code>.</p> <p>utility_functions.py:</p> <pre><code>codeql_language_identifiers = { 'c': 'cpp',...
<python><windows>
2023-11-01 13:52:29
0
2,787
Ben
77,402,704
583,464
search two lists and fill with None for each pair in correct order
<p>This is a continuation from <a href="https://stackoverflow.com/questions/77402021/map-by-searching-in-two-lists/77402100?noredirect=1#77402100">this</a>.</p> <p>Right now, the result is:</p> <pre><code>[{'type': 'POT'}, {'type': 'BOOK'}, {'type': 'GLASS'}] </code></pre> <p>I want, if a key is not found, to insert a ...
<python><python-3.x><list><dictionary>
2023-11-01 12:41:06
3
5,751
George
77,402,633
3,207,874
PDB won't stop inside pytest code, will stop in first function call
<p>If I define a pytest test like so:</p> <pre><code>from my_app.main import some_function def test_example(): breakpoint() foo = 'bar' some_function() </code></pre> <p>Then pdf will stop at the beginning of <code>some_function</code> instead of at <code>foo = 'bar'</code>. How can I get it to stop inside ...
<python><pytest><pdb>
2023-11-01 12:30:42
1
3,847
user3207874
77,402,608
22,674,380
Error in running the pytorch model: Missing key(s) in state_dict
<p>I am trying to run a script from <a href="https://github.com/cxzhou95/XLSR" rel="nofollow noreferrer">this repo</a> which tests a PyTorch model. I simply run it through <code>python test.py</code> using its defaults values (with the correct path to <code>best.pt</code>). But when running, it gives the following erro...
<python><python-3.x><deep-learning><pytorch>
2023-11-01 12:26:30
1
5,687
angel_30
77,402,460
6,320,774
download csv file via a website in pyhton
<p>I want to automatically download via python the csv file provided in <a href="https://www.bankofengland.co.uk/boeapps/database/Bank-Rate.asp" rel="nofollow noreferrer">this</a> website.</p> <p><a href="https://www.bankofengland.co.uk/boeapps/database/Bank-Rate.asp" rel="nofollow noreferrer">https://www.bankofengland...
<python><csv><download>
2023-11-01 12:01:57
2
1,581
msh855
77,402,221
11,113,397
Improving Deployment Time for Django Project on Azure Web App
<p>I have a Django project deployed on an Azure Web App (Linux, P2v2, Python 3.10, Django 4.2), which is functioning as expected. However, the <strong>deployment time is extremely slow</strong>, taking between 15 to 20 minutes to complete even a small change in the code. This is significantly longer than the deployment...
<python><django><azure-web-app-service>
2023-11-01 11:19:20
1
353
btavares
77,402,021
583,464
map by searching in two lists
<p>I want to do a mapping.</p> <p>I have two lists from which to extract the info and do the mapping.</p> <p>If we don't find the available entries from the first list, we check the second list.</p> <p>The first list is <code>a</code> and the second is <code>b</code>.</p> <pre><code>stuff_types = { &quot;spana&quot...
<python><dictionary><mapping>
2023-11-01 10:39:52
1
5,751
George
77,402,006
15,051,310
Smooth clamping a tensor
<ol> <li>Is there a simpler and more performant way to do this?</li> <li>Can it be done for each channel individually instead of having a global max/min, in a single operation?</li> </ol> <p>Essentially &quot;soft clamping&quot; values above/below threshold/-threshold to boundary/-boundary</p> <pre><code>import torch ...
<python><pytorch><tensor>
2023-11-01 10:37:15
1
2,757
Timothy Alexis Vass
77,401,990
11,716,727
How can I solve this error (object of type 'float' has no len()), please?
<p>I am working on the dataset <a href="https://www.kaggle.com/sid321axn/amazon-alexa-reviews" rel="nofollow noreferrer">AMAZON ALEXA REVIEW RATINGS</a></p> <p>When I uploaded my dataset as below</p> <pre><code>df_alexa = pd.read_csv('amazon_alexa.tsv', sep='\t') </code></pre> <p><a href="https://i.sstatic.net/8ELCs.pn...
<python><pandas><jupyter-notebook>
2023-11-01 10:34:18
1
709
SH_IQ
77,401,947
6,836,950
Fill null values with the closest non-null value from other columns
<p>I have the following polars dataframe</p> <pre><code>import polars as pl data = { &quot;product_id&quot;: [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;], &quot;col1&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &...
<python><python-polars>
2023-11-01 10:27:53
1
4,179
Okroshiashvili
77,401,881
7,991,624
Cannot install pytorch3d using conda or pip on windows 11
<p>I'm trying to install pytorch3d, but neither conda or pip can find the pytorch3d package.</p> <p>I followed the pytorch instructions: <a href="https://github.com/facebookresearch/pytorch3d/blob/main/INSTALL.md" rel="nofollow noreferrer">https://github.com/facebookresearch/pytorch3d/blob/main/INSTALL.md</a></p> <p>Th...
<python><pip><pytorch><conda><pytorch3d>
2023-11-01 10:19:58
1
437
sos.cott
77,401,727
1,172,907
How to add brightness to a colorwheel
<p>Using the code from this excellent <a href="https://stackoverflow.com/questions/77396626/how-to-mark-rgb-colors-on-a-colorwheel-in-python/77396970#77396970">answer</a> from <a href="https://stackoverflow.com/users/19090048/mandy8055">mandy8055</a>, I'm able to mark a color on a colorwheel.<br /> But <strong>the info...
<python><matplotlib><colors>
2023-11-01 09:56:44
0
605
jjk
77,401,594
583,464
remove mixed new line characters and digits
<p>Let's say I have this string list:</p> <pre><code>a = ['6306\nHLIAN\nVARIOUS', '10215\nSPINA', '10279\nPIPERI-\nΜYTER', '38003\nCORN\nSWEET', '10234ROKA', '10232\nANTH', '8682PIPER\nYPAITH', '8676\nMAROYL', '10211\nΚAROT\nROOT', '8685AGG\nYPAU'] </code></pre> <p>I want to remove the digits and keep the firs...
<python><string><list>
2023-11-01 09:35:20
2
5,751
George
77,401,247
3,744,043
How to type annotate optionally parametrized decorator, which use third party decorator inside
<p>Faced with problem, when using <code>mypy</code> on my project. At first I use a <code>backoff</code> package to do some retries on some functions/methods. Then I realised, that most of options are just repeated, so I created per-project decorator, with all common values filled for <code>backoff</code> decorator. Bu...
<python><decorator><mypy><python-typing>
2023-11-01 08:25:57
2
656
broomrider
77,401,182
9,363,181
how to get the relative path of a jar file from outside in python
<p>I have a project structure like the one below:</p> <pre><code>└── core ├── lib │ └── some.jar └── src └── main └── main.py </code></pre> <p>Now I am trying to access the <code>some.jar</code> inside the main.py file. It works fine with the absolute path but when I try to do somethin...
<python><python-3.x>
2023-11-01 08:14:25
2
645
RushHour
77,401,175
3,486,675
How to make Flake8 ignore syntax within strings?
<p>I'm suddenly getting flake8 errors for syntax within strings.</p> <p>For example, for the following line of code:</p> <pre><code> tags.append(f'error_type:{error.get(&quot;name&quot;)}') </code></pre> <p>I'm getting this error: <code>E231 missing whitespace after ':'</code>.</p> <p>I don't want to ignore all <cod...
<python><pre-commit><flake8>
2023-11-01 08:13:00
1
11,605
D Malan
77,401,164
17,672,187
OpenCV: Detection of clearly delineated object boundary failing
<p>I have the following image:</p> <p><a href="https://i.sstatic.net/YEoCk.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YEoCk.jpg" alt="enter image description here" /></a></p> <p>I want to detect the edge of the document placed on the table in the image. I tried the following code (the earlier approa...
<python><opencv><computer-vision><edge-detection><canny-operator>
2023-11-01 08:10:00
1
691
Loma Harshana
77,401,162
11,082,866
Add text on image in python
<p>I am creating barcodes in python using Barcode library like the following:</p> <pre><code> barcodes = CompanyBarcodes.objects.filter(asn_id__asn_number=asn_id, company=company, product__asset_category__in=cat_i...
<python><python-imaging-library>
2023-11-01 08:09:44
0
2,506
Rahul Sharma
77,401,153
15,233,792
How to read a jpeg from disk and instantiate it as 'werkzeug.datastructures.FileStorage'?
<pre><code>python 3.10.11 werkzeug 2.3.7 </code></pre> <p>I have a jpeg in <code>/mnt/dragon.jpeg</code></p> <p>I want to write unit test for a method, which has <code>werkzeug.datastructures.FileStorage</code> as input, and behavior is save it to a path.</p> <p>I try to instantiate it with codes below:</p> <pre cla...
<python><file><werkzeug>
2023-11-01 08:08:18
2
2,713
stevezkw
77,401,110
7,334,203
Remove duplicate variables declaration in xslt using Python
<p>Suppose I have this xslt 2.0 code which is generated using altova mapforce</p> <pre><code>&lt;xsl:stylesheet version=&quot;2.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt; &lt;xsl:template name=&quot;SDEV:SDEV_NCTS_down_fillUCRC547&quot;/&gt; &lt;xsl:for-each select=&quot;($var292...
<python><xml><xslt-2.0>
2023-11-01 07:59:26
1
7,486
RamAlx
77,400,918
9,516,820
How to check if multiple variables are of a certain type
<p>I have a program that creates four csv files in pandas. I have them encased in a try except block such that if one of the csv files fail then none of the csv files should be created. To achieve this I declare the variables before the try except block as follows</p> <pre><code>classes, names, extracts, cats = None, N...
<python>
2023-11-01 07:13:37
1
972
Sashaank