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,483,077
2,615,236
python is hard crashing with a simple mp3 play call
<p>The following code is hard crashing. It was working fine then suddenly something changed and I don't know what, so I created this mini test app, and it's still crashing python in the call to play. The try isn't getting caught, it's a hard crash of the python interpreter. It does correctly play the audio, then cra...
<python><audio><mp3><text-to-speech>
2023-11-14 18:38:18
0
551
Quadgnim
77,483,016
6,141,238
In IDLE, what is the simplest way to limit the number of lines displayed by a pprint call?
<p>I am working with large nested dictionaries in Python and would like to quickly check their structure in IDLE. The <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow noreferrer"><code>pprint</code></a> module nicely displays this structure, but leads IDLE to hang due to the size the variables. I...
<python><dictionary><large-data><python-idle><pprint>
2023-11-14 18:26:37
3
427
SapereAude
77,482,903
401,173
What is the proper way to build and reference an editable local Python module?
<p>I am trying to build a module that will be shared among more than one Python application in a project.</p> <p>I have a folder with a <code>pyproject.toml</code> with the following content.</p> <pre class="lang-ini prettyprint-override"><code>[project] name = &quot;data_audit_shared&quot; version = &quot;0.0.1&quot; ...
<python><pip><python-module><pyproject.toml>
2023-11-14 18:07:55
0
3,241
Josh Russo
77,482,831
5,529,155
SMTP.starttls() got an unexpected keyword argument 'keyfile'
<p>I'm trying to send email with this code:</p> <pre><code>send_mail( subject='Restore password', message='Restore password for ' + email, from_email=os.environ.get('GMAIL_EMAIL', ''), html_message=html_message, recipient_list=[email] ) </code></pre> <...
<python><python-3.x><django>
2023-11-14 17:56:07
5
467
Yuriy
77,482,825
8,560,600
Can I add a Python compiler/interpreter in a NextJS application, for user to run and test small Python code?
<p>I am building an educational application in NextJS (v13), where I would like to allow user to write and run/test small Python code. I want to build somewhat like an online compiler/interpreter. Is that possible? If so, could someone point me in the right direction and/or resources?</p> <p>Thanks!</p>
<python><next.js>
2023-11-14 17:55:15
1
1,608
Stefan Radonjic
77,482,714
2,056,201
cv2_imshow in Google Colab causes images to be stacked on top of each other instead of displaying them in the same feed
<p>Im not sure if this is a limitation of Colab, Im trying to implement a pong game with opencv, Im using modified code from a tutorial <a href="https://github.com/darthdaenerys/Pong-Game/blob/master/game.py" rel="nofollow noreferrer">https://github.com/darthdaenerys/Pong-Game/blob/master/game.py</a></p> <p>My code mod...
<python><user-interface><jupyter-notebook><google-colaboratory>
2023-11-14 17:38:28
1
3,706
Mich
77,482,602
9,997,212
How to create a chunked list of lists with almost-equal lengths?
<p>I need to split a number into 3 parts. The following function (<a href="https://stackoverflow.com/a/53117390/9997212">source</a>) does that correctly:</p> <pre class="lang-py prettyprint-override"><code>def parts(num: int, div: int) -&gt; list[int]: &quot;&quot;&quot;Split a number into equal parts.&quot;&quot;&...
<python><function><python-3.8>
2023-11-14 17:20:34
2
11,559
enzo
77,482,582
8,006,721
Pandas compare columns and consider NULLS equal
<p>I used Pandas to joined two dataframes together and want to compare if column values are equal.</p> <p>However, whenever I encounter NULLs (or NA ?) values, my comparison returns <code>False</code></p> <pre><code>import pandas as pd # create test dataframes df_1 = pd.DataFrame({'key': [1, 2, 3, 4, 5], 'field1': ['f...
<python><pandas><dataframe>
2023-11-14 17:18:32
2
332
sushi
77,482,580
11,426,624
merge to dataframes on first part of a string
<p>I have two dataframes</p> <pre><code>df1 = pd.DataFrame({'id':['XYZ', 'ABC1', 'CDS'], 'col1':[1,2,3]}) df2 = pd.DataFrame({'id':['XYZ1', 'XYZ2', 'ABC1', 'ABC11', 'CDSS', 'CDS', 'ABC2', 'ABC', 'XYA'], 'col2':[1,2,3,4,5,6,7,8,9]}) </code></pre> <pre><code> id col1 0 XYZ 1 1 ABC1 2...
<python><pandas><dataframe><merge>
2023-11-14 17:18:20
3
734
corianne1234
77,482,489
10,951,092
How to remove a row of a Dataframe if more than one value is zero?
<p>I am analyzing data from an accelerator. It returns acceleration in the x, y, and z directions as well as a timestamp. These values are stored in a Pandas DataFrame. Sometimes the accelerator returns bad data. In this case, at least two of the values (x, y, or z) will be zero. How do I find and remove rows from a da...
<python><pandas><dataframe>
2023-11-14 16:59:43
1
382
PetSven
77,482,416
308,827
Convert Dekad to start and end date in Python
<p>I have a pandas dataframe containing a column with Dekad (10-day) information e.g. Dekad 1 is Jan 1 to jan 10th, Dekad 2 is Jan 11th to jan 20th and so on.</p> <p>Is there a way to get start and end day information given the dekad number? I can do this by hardcoding but a more pythonic solution would be better.</p> ...
<python><pandas><datetime>
2023-11-14 16:47:33
1
22,341
user308827
77,482,375
1,016,065
Python fuzzy string search with `regex`
<p>Trying to understand fuzzy pattern matching with <a href="https://pypi.org/project/regex/" rel="nofollow noreferrer">regex</a>. What I want: I have a string, and I want to find identical or similar strings in other, perhaps larger strings. (Does one field in a database record occur, perhaps as a fuzzy substring, in...
<python><regex><fuzzy-search>
2023-11-14 16:41:30
1
3,912
RolfBly
77,482,299
5,627,023
Docker build with python-3.10-alpine
<p>I am facing compatability issue with python-3.10-alpine when building the docker image.</p> <p>Requirements.txt</p> <pre><code>numpy==1.21.2 dask==2021.9.1 pandas==1.4.4 pyrrow==8.0.0 </code></pre> <p>Dockerfile</p> <pre><code>FROM python:3.10-apine COPY requirements.txt . RUN pip install -r requirements.txt </code>...
<python><dockerfile>
2023-11-14 16:31:20
0
305
Anji
77,482,271
10,143,378
Multi variable in multi processing with one common
<p>I have a script in python and a function that I need to execute with multiprocessing, however, one of the parameter (df) of this function is the same for each call. Let me explain with the code :</p> <pre><code>def main(): for country in all_countries: df = SqlManager().sql_query('MyDb', &quot;SELECT * ...
<python><sql><multiprocessing><arguments>
2023-11-14 16:27:20
1
576
kilag
77,482,223
6,544,849
How to make shamrock image
<p>I am trying to make a shamrock crystal for later fabrication, and am using nazca design tool for doing it.</p> <p>How can I place the trapezoid so that the sides of the trapezoid are parallel to the cyrcles and are always at the end of the sharp corners.</p> <pre><code>import nazca as nd import numpy as np # Define ...
<python><matplotlib><geometry><trigonometry>
2023-11-14 16:20:51
1
321
wosker4yan
77,482,207
10,438,528
Is there a way to encrypt two messages into a single string?
<p>How do I encrypt two strings into one so that I can use two keys to get two different messages from a single string?</p> <p>I need a method that should work kind of like this:</p> <pre><code>key1 = &quot;asdf&quot; key2= &quot;xcvb&quot; encrypted_message = &quot;qpoweiurtz&quot; decrypt(encrypted_message, key1) de...
<python><cryptography>
2023-11-14 16:18:51
0
482
LGR
77,481,897
2,149,718
Capture a video stream from rtsp camera and write it to a file
<p>I am trying to capture a video stream coming from an rtsp camera and write it to a file. Using Jetson Xavier AGX with Jetpack 4.5 [L4T 32.5.0]</p> <p>I am using below python app to perform the task:</p> <pre><code>cap = cv2.VideoCapture(&quot;rtspsrc location=rtsp://10.34.134.1/Streaming/channels/1/ user-id=myuser u...
<python><opencv><video-streaming><gstreamer><nvidia-jetson>
2023-11-14 15:30:53
1
72,345
Giorgos Betsos
77,481,878
2,586,950
Is there any relation between classes which use the same type variable?
<p>The <a href="https://docs.python.org/3/library/typing.html#typing.TypeVar" rel="nofollow noreferrer"><code>typing.TypeVar</code></a> class allows one to specify reusable type variables. With Python 3.12 / <a href="https://docs.python.org/3/whatsnew/3.12.html#pep-695-type-parameter-syntax" rel="nofollow noreferrer">P...
<python><mypy><typing>
2023-11-14 15:28:36
1
711
JHK
77,481,842
190,887
kivy buildozer UrlRequest fails on android with Python3
<p>I've read and tried out the solution from <a href="https://stackoverflow.com/questions/51300399/kivy-buildozer-android-https-request-fail">kivy buildozer android https request fail</a>, but possibly Python3 changes things?</p> <p>I'm trying to run a <code>UrlRequest</code>; it works fine when I run it on my laptop w...
<python><android><python-3.x><kivy>
2023-11-14 15:23:47
2
14,105
Inaimathi
77,481,795
5,753,145
Why am i getting S3 Access error AmazonS3Exception in this AWS Glue Job
<p>I am running an AWS Glue Job, and the job is doing what it should, it takes the records from Kinesis stream and is putting it into the data lake. But it ends with a failure and error is as given below:</p> <pre><code> StreamingQueryException: com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS...
<python><amazon-web-services><amazon-s3><aws-glue>
2023-11-14 15:17:27
1
475
manu muraleedharan
77,481,743
3,973,175
adding figure legend outside of the box
<p>I am attempting to make a scatterplot, with a figure legend outside of the box, as suggested by <a href="https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot">How to put the legend outside the plot</a>, but am also plotting multiple sets of data <a href="https://stackoverflow.com/questi...
<python><python-3.x><matplotlib>
2023-11-14 15:11:42
1
6,227
con
77,481,634
13,023,224
Pandas groupby count unique non cumulative
<p>I have this toy data set</p> <pre><code>df=pd.DataFrame({'user':['John','Steve','Steve','Steve','Jane','Jane','Jane','Jane','Alice','Alice','Alice'], 'days':[1,1,2,3,1,2,3,4,1,2,3]}) </code></pre> <p>yielding</p> <pre><code>user days John 1 Steve 1 Steve 2 Steve 3 Jane 1 Jane 2 Jane...
<python><pandas><count><cumulative-sum>
2023-11-14 14:58:50
2
571
josepmaria
77,481,523
7,497,912
What is the most effective way to flatten a nested json response structure with PySpark?
<p>Given a json array from an API response like the below:</p> <pre><code>[ { &quot;id&quot;: 1, &quot;collection_name&quot;: &quot;gym_equipment&quot;, &quot;total_price&quot;: 5400, &quot;lineitems&quot;: [ { &quot;item_no&quot;: 1, &quot...
<python><apache-spark><pyspark><apache-spark-sql>
2023-11-14 14:45:02
1
417
Looz
77,481,362
1,106,951
How to filter Excel data before loading to Pandas
<p>I want to load only users who their status are <code>&quot;Disabled&quot;</code> in <code>Status</code> column into Pandas data frame. My initial code is like this</p> <pre><code>import pandas as pd df = pd.read_excel('Users.XLSX', sheet_name='WebUsers', usecols=&quot;A,B&quot;) print(df) </code></pre> <p>Which is...
<python><pandas>
2023-11-14 14:23:37
2
6,336
Behseini
77,481,307
2,411,173
Cover the surface of a polygon with rectangles
<p>I am struggling with a python challenge. I have a polygon that is defined by a list of corners. Each corner is 90 degrees.</p> <p>I am trying to partition the surface of the polygon with the smallest possible number of rectangles. How can I do it?</p> <p>Example:</p> <pre><code>corners = [[91570, 49055], [91...
<python><algorithm><computational-geometry>
2023-11-14 14:16:39
1
17,747
Donbeo
77,480,943
446,347
Nginx/Guicorn 502s under load
<p>I have an application serving WebSockets that proxies to Gunicorn using Nginx. I am seeing when a bunch of clients (say 30) are already busy interacting with the server, new attempts to connect to the proxy are failing with 502 errors.</p> <p>I understand this could just be load, but what is strange is these 502s ha...
<python><nginx><websocket><gunicorn>
2023-11-14 13:25:22
0
634
LiteWait
77,480,789
15,263,719
Can I Sort work with Ruff formatter? (not linter)
<p>I am migrating my project to RUFF. The migration was kind of straightforward, but for some reason, ISort rules are not being applied when I do this commands on VSCode: <code>Format code with &gt; Ruff</code></p> <p>I see this when I have my imports usorted:</p> <p><a href="https://i.sstatic.net/qVg7q.png" rel="nofol...
<python><formatter><isort><ruff>
2023-11-14 12:57:40
1
360
Danilo Bassi
77,480,740
2,523,635
I am getting ValueError when running any pip command in my windows machine
<p><strong>Background</strong></p> <p>I have installed python 3.10.11 on my Windows 10 machine using installer 'python-3.10.11-amd64.exe'. But whenever I try to run any 'pip' command it shows error now.</p> <p>Error comes as below</p> <pre><code>C:\WINDOWS\system32&gt;pip -version Traceback (most recent call last): F...
<python><visual-studio-code><pip>
2023-11-14 12:49:54
2
665
KBNanda
77,480,719
1,538,701
Can I exit an "as_completed" pool executor loop (cancelling all remaining tasks)?
<p>The idea is to run a set of tasks, process them as they finish, and as soon as one returns the desired result, cancel the remaining tasks. I don't mind waiting for tasks already started to finish, but starting new tasks should be forbidden.</p> <p>I've tried calling <code>pool.shutdown(cancel_futures=True)</code>, b...
<python><python-multiprocessing><concurrent.futures>
2023-11-14 12:46:29
1
2,714
Jellby
77,480,495
4,575,197
How to clean a long text from repetitive (duplicate) Paragraphs?
<p>So i have 100000 rows in a dataframe, all containing a text column. which i want to clean before further analysis. i found this <a href="https://stackoverflow.com/a/62333168/4575197">answer</a> which gave me a lot of information. However still i have duplicated sentences even in clean list. It's important to note th...
<python><text><nltk><data-cleaning>
2023-11-14 12:09:50
2
10,490
Mostafa Bouzari
77,480,317
17,487,457
Mean absolute value along all columns of a 3D Numpy array
<p>I always get find myself in state of confusion when dealing with a multi-dimensional array. Imaging having the following array of arrays, where each array contains feature importance scores (3-features), for each class in the dataset (5-classes). The dataset contains 4 samples in all.</p> <pre class="lang-py prettyp...
<python><arrays><numpy><multidimensional-array><numpy-ndarray>
2023-11-14 11:40:20
1
305
Amina Umar
77,480,234
859,141
PySide6 - Color specific row with QTableView QAbstractTableModel and Pandas
<p>This is the first application I have created with Python QT so apologies if I have missed something really fundamental.</p> <p>The following table is populated via a QAbstractTableModel linked to a Pandas Framework. I have an PlayerIDX (e.g. 30, who in the example is running 25th) and want that row to be highlight...
<python><pandas><pyside><qtableview><qabstracttablemodel>
2023-11-14 11:26:47
1
1,184
Byte Insight
77,479,695
4,474,576
Scrapy how to make async request from FSFilesStore/media pipeline?
<p>What I need is to stat file based on head request, instead of downloading entire file. File is video(can be big), always have same name. Can determine update based on size and update change from head.</p> <p>Code:</p> <pre><code>import treq from scrapy.pipelines.files import FilesPipeline from scrapy.pipelines.files...
<python><async-await><scrapy><twisted>
2023-11-14 10:03:46
0
1,660
frenzy
77,479,601
12,133,068
Dask array operation on chunks with no return
<p>I have a dask array of dimension <code>(C, Y, X)</code> (for instance, <code>(100, 50000, 50000)</code>).</p> <p>I want to perform an operation on each chunk that will add some value to a small numpy array, that we will call <code>x</code>. Note that the operation on each chunk doesn't need to return any value, it w...
<python><dask>
2023-11-14 09:50:25
1
334
Quentin BLAMPEY
77,479,584
571,692
Local Azure Function: Customer packages not in sys path. This should never happen
<p>I'm encountering a weird warning with azure functions locally. Whenever I <code>func start</code> my function, I get these error messages:</p> <pre><code>Found Python version 3.10.12 (python3). Azure Functions Core Tools Core Tools Version: 4.0.5455 Commit hash: N/A (64-bit) Function Runtime Version: 4.27.5....
<python><azure-functions><azure-functions-core-tools>
2023-11-14 09:47:27
2
717
Morti
77,479,458
189,336
Python: write dataset as hive-partitioned and clustered parquet files (no JVM)
<p>I would like write a table stored in a dataframe-like object (e.g. pandas dataframe, duckdb table, pyarrow table) in the parquet format that is both hive partitioned <em>and</em> clustered. Here's what I mean</p> <ul> <li><strong>Hive partitioning</strong> i.e., I can specify a set of partitioning columns e.g. <cod...
<python><parquet><pyarrow><duckdb>
2023-11-14 09:26:16
0
13,905
conradlee
77,479,371
573,191
CuDF KeyError: 'Field "None" does not exist in schema'
<p>I am reading in one single file (1.4GB) using CuDF, I am actually using RapidsAI pandas implementation, but since I was getting the same error I tried directly with CuDF. Now the shape is (847942, 4) and dtypes shows:</p> <pre><code>@timestamp object message object syslog_program object sys...
<python><dataframe><pyarrow><cudf>
2023-11-14 09:11:15
0
325
fabio.geraci
77,479,170
4,505,998
Save figure with centered plot
<p>I want to save the figure with an Y axis title and ticks, but keeping the frame of the graph horizontally centered.</p> <pre class="lang-py prettyprint-override"><code>x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.ylabel('Y-axis') plt.savefig('/tmp/test.png') </code></pre> <p>While the displa...
<python><matplotlib>
2023-11-14 08:33:47
0
813
David Davó
77,478,949
7,585,973
NotImplementedError: cannot instantiate 'WindowsPath' on your system when load .pkl file in prod environtment
<p>I try to load a pickle file that initially saved from 'nlp = spacy.load(&quot;en_core_web_md&quot;)' it sucess to load and use in jupyter notebopok, but NotImplementedError: cannot instantiate 'WindowsPath' on your system when load .pkl file in prod environtment</p> <p>This is what I've done:</p> <ol> <li>changing p...
<python><pandas>
2023-11-14 07:50:52
1
7,445
Nabih Bawazir
77,478,821
4,494,781
How to emit a 64 bit unsigned integer with a PyQt signal
<p>I ran into integer overflow issues when using <code>PyQt5.QtCore.pyqtSignal(int)</code> in the past, because it seems that the python int becomes a C int (32 bit signed integer) in the C++ call. This limits the maximum value that the signal can emit to 2,147,483,647.</p> <p>I worked around this issue by emitting a <...
<python><pyqt><pyqt5><integer-overflow>
2023-11-14 07:26:59
0
1,105
PiRK
77,478,792
2,000,548
Why `astype(int)` changes the number?
<p>I am using Python 3.11.</p> <p>I have some data which is nanosecond unix time but in float. I try to convert to int.</p> <pre><code>import pandas as pd df = pd.DataFrame( {&quot;float_time&quot;: [1698873816748837120.0, 1698873795853176060.0]} ) df[&quot;time&quot;] = df[&quot;float_time&quot;].astype(int) </co...
<python><pandas>
2023-11-14 07:21:48
0
50,638
Hongbo Miao
77,478,727
12,242,085
How to create new column in Data Frame to sort values for each id based on date column in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <ul> <li><p>Column my_date is in datetime format.</p> </li> <li><p>In my real DataFrame I have many more columns.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>my_date</th> <th>col1</th> </tr> </thead> <tbody> <tr> <td>111<...
<python><pandas><dataframe><date><datetime>
2023-11-14 07:10:27
1
2,350
dingaro
77,478,698
13,803,549
How to work in development with Discord OAuth2 live
<p>I have a django app with Discord OAuth2 authentication live on the deployed site.</p> <p>With all the redirects leading back to the deployed app, what is the procedure for doing development/debugging when I can’t see the progress on the localhost?</p> <p>Thanks!</p>
<python><django><oauth-2.0><discord.py>
2023-11-14 07:03:17
1
526
Ryan Thomas
77,478,534
11,580,993
MV C++ 14.0 or greater is required
<p>I am trying to install Bloomberg API using <code>python -m pip install --index-url=https://bcms.bloomberg.com/pip/simple blpapi</code> as per their website. But I get an error</p> <pre><code> error: Microsoft Visual C++ 14.0 or greater is required. Get it with &quot;Microsoft C++ Build Tools&quot;: https://vis...
<python>
2023-11-14 06:26:12
0
1,003
Rene Chan
77,478,398
4,281,353
Using list comprehensions in Tensorflow
<p>Can we use Python comprehension in Tensorflow graph (non eager) execution?</p> <pre><code>IOU: tf.Tensor = tf.concat( values=[ intersection_over_union( box_pred[..., j, 1:5], box_true[..., 1:5] ) for j in range(self.B) # &lt;--- pr...
<python><tensorflow><list-comprehension>
2023-11-14 05:47:18
1
22,964
mon
77,478,026
9,747,182
How to compute the moving average over 3D array with a step size?
<p>I need to calculate a moving average over a 3D array with a step size set by me. What I am doing right now is</p> <pre><code> img = np.ones(10,10,50) img_new = bottleneck.move.move_mean(img, window=5, axis=2) </code></pre> <p>While the bottleneck.move.move_mean is fast enough to deal with images, unfortunately it d...
<python><numpy-ndarray><moving-average><array-broadcasting><numpy-slicing>
2023-11-14 03:26:24
1
701
emely_pi
77,477,931
189,247
Compute the order of non-unique array elements
<p>I'm looking for an efficient method to compute the &quot;order&quot; of each item in a numpy array, with &quot;order&quot; defined as the number of preceding elements equal to the element. Example:</p> <pre><code>order([4, 2, 3, 2, 6, 4, 4, 6, 2, 4]) [0 0 0 1 0 1 2 1 2 3] </code></pre> <p>Current solution loops in p...
<python><arrays><numpy>
2023-11-14 02:52:02
1
20,695
Gaslight Deceive Subvert
77,477,648
15,233,792
pkg_resources.DistributionNotFound: The 'pip==20.0.2' distribution was not found and is required by the application
<pre><code>python --version Python 2.7.18 python3 --version Python 3.10.0 </code></pre> <p>After I installed pip3 using <code>sudo apt-get install python3-pip</code></p> <p>I run <code>pip3</code></p> <p>It shows error below:</p> <pre class="lang-bash prettyprint-override"><code>$ pip3 Traceback (most recent call last)...
<python><python-3.x><pip>
2023-11-14 01:02:54
1
2,713
stevezkw
77,477,547
564,709
Specify pydantic model fields from a data source
<p>I have a need for a pydantic model that would dynamically create model fields from another data source. I'd like to do something like this:</p> <pre class="lang-py prettyprint-override"><code>import pydantic import my_data _data = my_data.load() # _data[variable] = value class MyModel(pydantic.BaseModel): # t...
<python><python-typing><pydantic>
2023-11-14 00:23:59
2
3,336
dino
77,477,374
2,518,602
Jupyter Notebook hangs after trying to upgrade to new version of Python
<p>I recently realized that while I have Python 3.12.0 installed, Jupyter notebook was using Python 3.7.3. I thought it would be a good idea to try and get Jupyter to use the same version of Python that <code>python3</code> is referring to. I spent a few hours on this and seem to have completely broken Jupyter. I am us...
<python><jupyter-notebook><jupyter>
2023-11-13 23:19:59
2
2,023
Ari
77,477,353
678,572
How to write to Python dictionary without loading the dictionary into memory?
<p>I have a large table that I want to convert to a Python dictionary but I don't want to load all of the data into memory.</p> <p><strong>Is it possible to actively write to a pickle dump without building the object first?</strong></p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>import gzip f_o...
<python><dictionary><bigdata><pickle><large-data>
2023-11-13 23:12:01
1
30,977
O.rka
77,477,327
377,022
Is there a reason some (all?) libraries don't implement log_softmax via log1p(x) = log(1 + x)?
<p>As I understand it, PyTorch implements <code>log_softmax(x)</code> as <code>x - x.max() - (x - x.max()).exp().sum().log()</code>, for added numerical stability. (See, e.g., <a href="https://stackoverflow.com/a/61568783/377022">here</a>.) However, when the largest value is much larger than the rest of the values (a...
<python><tensorflow><pytorch><numerical-methods>
2023-11-13 23:00:58
0
6,168
Jason Gross
77,477,158
628,228
Is there a natural way to handle values of Enum class in a pandas column?
<p>Enum classes are often defined as a mapping from names to numeric constants. I was looking to take advantage of this mapping to show natural labels in a categorical pandas column, while keeping the numbers for efficiency.</p> <p>Initially I felt this could be achieved naturally by using the <a href="https://pandas.p...
<python><pandas>
2023-11-13 22:12:31
3
4,430
glopes
77,477,006
2,642,356
Poetry & Cython - cross-platfrom / build on install
<p>I'm using Poetry v1.4.1 with Cython 3.0.5. My package contains a <code>.pyx</code> file that I wish to compile. If I'm using <code>pyximport</code> instead of pre-compiling, importing takes a long time. However, if I'm building (with the code below) using <code>poetry build</code>, instead of a version- &amp; platfo...
<python><cython><python-poetry><distutils><cythonize>
2023-11-13 21:33:27
0
1,864
EZLearner
77,476,965
3,219,759
Django / Pytest / Splinter : IntegrityError duplicate key in test only
<p>I know it's a very common problem and I read a lot of similar questions. But I can't find any solution, so, here I am with the 987th question on Stackoverflow about a Django Integrity error.</p> <p>I'm starting a Django project with a Postgres db to learn about the framework. I did the classic Profile creation for u...
<python><django><postgresql><pytest><splinter>
2023-11-13 21:23:18
0
1,222
Ruff9
77,476,750
3,116,231
Issue with upsert: SQLAlchemy insert works, update doesn't
<p>My session manager:</p> <pre><code>from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.exc import SQLAlchemyError import contextlib class DatabaseSessionManager: def __init__(self, connection_string): self.engine = create_engine(connection_string)...
<python><postgresql><sqlalchemy>
2023-11-13 20:43:46
1
1,704
Zin Yosrim
77,476,482
10,326,759
Can I return a dataclass from the forward method of a pytorch Module?
<p>Can I return a dataclass from the forward method of a pytorch Module?</p> <p>It appears to be possible in simple examples, and I can't find any documented obstruction. However, I've not seen it done, and coming from Tensorflow I worry that it will blow up when things get complicated (e.g. in distributed training).</...
<python><pytorch>
2023-11-13 19:47:22
0
497
Andrea Allais
77,476,304
2,983,568
Why does running Python import fails on first run but works on subsequent ones (noisereduce package)?
<p>Working with VS Code and Jupyter notebook extension (among others), in a virtual environment that is properly activated.<br> I am trying to run the following import:</p> <pre><code>import noisereduce </code></pre> <p>The <strong>first</strong> time I run the code, this error is shown:</p> <pre><code>----------------...
<python><visual-studio-code><import><dependencies>
2023-11-13 19:13:50
1
4,665
evilmandarine
77,476,261
19,694,624
How do I reply with mention pycord
<p>I am running a discord bot. But it responds without mentioning.</p> <p>In discord.py I could do something like this:</p> <pre><code>@bot.event async def on_message(message): if message.content == &quot;hi&quot;: await message.reply(&quot;Hello!&quot;, mention_author=True) </code></pre> <p>And it would me...
<python><python-3.x><discord><discord.py><pycord>
2023-11-13 19:05:20
2
303
syrok
77,476,250
9,100,431
Can't upload file to Sharepoint site using Graph API. The resource could not be found
<p>I can see the files in the drive, but supposedly doesn't exist when trying to write one.</p> <p>This is how I look for files:</p> <pre><code>site_url = https://graph.microsoft.com/v1.0/sites get_url = f&quot;{site_url}/{site_id}/drives/{drive_id}/root/children&quot; headers = { &quot;Authorization&quot;: f&quot;...
<python><sharepoint><python-requests><microsoft-graph-api>
2023-11-13 19:03:05
1
660
Diego
77,476,241
1,175,788
Is it possible to rename Pyspark exploded columns all at once?
<p>I have to explode two different struct columns, both of which have the same underlying structure, meaning there are overlapping names. Is it possible to rename/alias the columns that are returned from <code>explode()</code> all at once, and avoid a bunch of <code>alias()</code>?</p> <p>Here's what I have:</p> <pre><...
<python><apache-spark><pyspark><apache-spark-sql>
2023-11-13 19:01:41
1
3,011
simplycoding
77,476,114
11,500,371
In a pandas dataframe where the column names are datetime objects, how can I find the earliest instance of a True value for a given row?
<p>I have a dataframe where the column ids are datetime objects, and the values are True or False</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>2023-10-30 00:00:00</th> <th>2023-11-01 00:00:00</th> <th>2023-11-03 00:00:00</th> <th>2023-11-06 00:00:00</th> <th>2023-11-08 00:00:...
<python><pandas><datetime>
2023-11-13 18:37:47
1
337
Sean R
77,476,044
12,042,094
Azure function unable to install azure-identity dependencies
<p>I am attempting to install and azure function using the <code>WEBSITE_RUN_FROM_PACKAGE = &lt;STORAGE_BLOB_URL&gt;</code> approach with a python runtime and linux os to a dedicated subnet so as to eliminate public internet traffic.</p> <p>the specific required installs are:</p> <pre><code>import logging import os imp...
<python><azure><terraform><azure-functions><azure-blob-storage>
2023-11-13 18:23:14
1
486
RAH
77,475,846
9,112,151
How to mock __next__ magic method?
<p>How to mock <code>Queue.__next__</code> magic method? The code below with <code>side_effect</code> is not working:</p> <pre><code>from unittest.mock import MagicMock class Queue: def __init__(self): self.nums = [1, 2, 3] def __iter__(self): return self def __next__(self): try...
<python><pytest><python-unittest><python-unittest.mock>
2023-11-13 17:49:12
2
1,019
Альберт Александров
77,475,822
1,775,010
Python/Mido crashing without any error message
<p>I'm pretty new to Python and MIDI processing, however what I see does not seem normal to me.</p> <p>In this code, <code>listen_input</code> MIDI callback crashes without any error:</p> <pre class="lang-py prettyprint-override"><code>import mido import time def listen_input(message): print('input:', message) ...
<python><midi>
2023-11-13 17:43:27
1
1,068
theredled
77,475,807
7,827,848
Reponse time for GPT models via openAI API vs internet version
<p>I am making a small time test of the openai API, from my local internet connection and laptop, but I get times that are much larger than expected. With the following code:</p> <pre><code>import openai import time import tiktoken OPENAI_KEY='xxx' openai.api_key=OPENAI_KEY encoding = tiktoken.encoding_for_model(&quo...
<python><openai-api><latency>
2023-11-13 17:41:13
0
331
Thomas
77,475,591
15,412,041
Python modules collection from requirements txt
<p>I just have questions about downloading Python modules based on requirements.txt Let's say I have a bundle of folders A,B. Each folder contains some subdirectories within it.</p> <p>Each folder contains <code>requirements.txt</code>, which contains a specific package:</p> <pre><code>$ cat requirements.txt boto3 </co...
<python><pip>
2023-11-13 17:03:39
0
611
Gowmi
77,475,570
893,254
How can I serialize a Python list as a single line in JSON?
<p>It appears to be that by default Python <code>json</code> module serializes a Python list using new lines between each element, like so:</p> <pre><code>&quot;data&quot;: [ -6.150000000000006, -0.5, 0.539999999999992, 0.5800000000000125, -4.6299999999999955, 12.0, 2.829999999999984, -1...
<python><json>
2023-11-13 17:01:05
2
18,579
user2138149
77,475,508
21,346,793
How to fix vertical naming of endpoints in swagger
<p>I write my project in DRF and for auto-documentation i use drf-spectacular, but i have one problem: <a href="https://i.sstatic.net/ECTz7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ECTz7.png" alt="enter image description here" /></a></p> <p>How can if fix this</p>
<python><django-rest-framework><swagger><drf-spectacular>
2023-11-13 16:52:14
2
400
Ubuty_programmist_7
77,475,285
4,537,160
Pytorch CrossEntropy Loss, getting error: "RuntimeError: Boolean value of Tensor with more than one value is ambiguous"
<p>I have a classification model, producing predictions for 4 classes in a tensor of shape (256, 1, 4)...256 is the batch size, while the &quot;1&quot; for the second dimension is due to some model internal logic and can be removed:</p> <pre><code>preds.shape torch.Size([256, 1, 4]) </code></pre> <p>The corresponding a...
<python><pytorch><cross-entropy>
2023-11-13 16:13:58
1
1,630
Carlo
77,474,965
4,382,305
Implement XOR with Pytorch
<p>I want to implement XOR logical operator. I don't get the optimal answer. I need three output columns for next operations. I have a data.csv file as data file(XOR):</p> <pre><code>in1,in2,in3,in4,out1,out2,out3 0,0,0,0,0,0,0 0,0,0,1,0,0,1 0,0,1,0,0,0,1 0,0,1,1,0,0,0 0,1,0,0,0,0,1 0,1,0,1,0,0,0 0,1,1,0,0,0,0 1,0,0,0,...
<python><pytorch><neural-network>
2023-11-13 15:18:39
1
2,091
Darwin
77,474,923
17,487,457
Calculate the mean of absolute SHAP values across all classes
<p>Suppose I have the following model, built from this synthetic data.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import shap from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split X, y = make...
<python><numpy><shap>
2023-11-13 15:12:00
1
305
Amina Umar
77,474,917
13,423,905
How do I interpolate a missing area in a 2D image in python using Gaussians?
<p>I have been looking for some version of the answer to this question in many places, but I feel like the indexing is just getting the better of me. I have a 2D Gaussian image, which has a grayscale value as appears below</p> <p>#visual examination shows that the area with the slit is row 169 to 185 and column 0 to 17...
<python><image><scipy><interpolation>
2023-11-13 15:11:13
0
369
hex93
77,474,902
17,124,619
Retrieve columns from async oracle sql
<p>I am attempting to retrieve column names from my oracle sql query, but I am using FastAPI with an oracle db database. I know that <code>cx_oracle</code> or <code>oracledb</code> do not have asyncio features yet and its being worked on.</p> <p>Therefore, how do I extract column names from the library <code>cx_Oracle_...
<python><fastapi>
2023-11-13 15:09:10
0
309
Emil11
77,474,676
1,581,090
How to plot times on the x-axis with matplotlib?
<p>Following the example given <a href="https://www.tutorialspoint.com/how-to-show-date-and-time-on-the-x-axis-in-matplotlib" rel="nofollow noreferrer">HERE</a> I want to create a plot that shows just the time on the x-axis, not the date. So I modified the example code to the following:</p> <pre><code>from datetime imp...
<python><matplotlib>
2023-11-13 14:38:59
1
45,023
Alex
77,474,534
1,585,696
"BlockingIOError: [Errno 11] Resource temporarily unavailable" when installing Python 3.10.13
<p>I'm running into a blocking issue when installing Python 3.10.13 on a server running Ubuntu 20.04.6 LTS.</p> <p>I download the source, <code>configure</code> with <code>--prefix</code> specified, <code>make</code>, and then <code>make install</code>. The error occurs during the <code>make install</code> portion, at...
<python><python-3.x><ubuntu><makefile>
2023-11-13 14:17:06
0
594
Tyler D
77,474,487
5,873,325
Compare dataframe columns by another column elements and compute accuracy percentage
<p>Let's say I have two dataframes of unequal lengths, <strong>df1</strong> &amp; <strong>df2</strong>.</p> <p>The first dataframe <strong>df1</strong> looks like this :</p> <pre><code>id | a | b | c | d -------------------------- i1 | 1,2 | 0 | Nan | 3 i2 | 1 | 4 | 2 | 0,3 i3 | 0 | 1 | 2,3 | Nan </...
<python><pandas><dataframe>
2023-11-13 14:10:14
1
640
Mejdi Dallel
77,474,455
11,932,905
Pandas - drop records if on specific column value is equal to previous record
<p>I have a dataframe like following (sorted by id, time and status):</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>status</th> <th>timestamp</th> </tr> </thead> <tbody> <tr> <td>111</td> <td>A</td> <td>29.08.2023 12:39</td> </tr> <tr> <td>111</td> <td>A</td> <td>29.08.2023 12...
<python><pandas><group-by><duplicates>
2023-11-13 14:04:27
1
608
Alex_Y
77,474,360
5,618,856
get text from stdout in subprocess.run without UnicodeDecodeError
<p>I read the output from a windows command line call like so:</p> <pre class="lang-py prettyprint-override"><code>result = subprocess.run([&quot;cmd&quot;, &quot;/c&quot;, &quot;dir&quot;,&quot;c:\mypath&quot;], stdout=subprocess.PIPE, text=True,check=True) </code></pre> <p>The result may contain unexpected characters...
<python><python-3.x><subprocess>
2023-11-13 13:48:16
1
603
Fred
77,474,250
4,399,016
Pandas Pivot Table returning no Values
<p>I have a pandas data <a href="https://stackoverflow.com/a/77446000/4399016">frame</a> <code>df</code> that looks like this.</p> <p><a href="https://i.sstatic.net/5GvGX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5GvGX.png" alt="enter image description here" /></a></p> <pre><code>import pandas as p...
<python><pandas><pivot-table>
2023-11-13 13:28:35
1
680
prashanth manohar
77,474,231
19,672,778
TypeError: string indices must be integers in pandas_datareader.DataReader
<p>I am trying to get facebook stock prices with pandas_datareader but it gives me this error. can anyone help me out?</p> <pre class="lang-py prettyprint-override"><code>company = 'FB' start = dt.datetime(2012, 1, 1) end = dt.datetime.now() data = pdr.DataReader(company, 'yahoo', start, end) </code></pre>
<python><python-3.x><pandas><yahoo-finance>
2023-11-13 13:24:26
1
319
NikoMolecule
77,473,949
10,973,108
It's possible to decrease network consume from Selenium application?
<p>Today I've a scraper that was implemented in Selenium and the target website have a lot of barriers to pass, such as, Cloudflare checks, IP block, etc.</p> <p>The application already pass this barriers but we are using an strategy that have a network with limits usage.</p> <p>It's possible to decrease Selenium netwo...
<python><selenium-webdriver><web-scraping><web-crawler>
2023-11-13 12:38:12
0
348
Daniel Bailo
77,473,922
7,318,488
Casting a Polars pl.Object column to pl.String raises a ComputeError
<p>I got a pl.LazyFrame with a column of type Object that contains date representations, it also includes missing values (None).<br /> In a first step I would like to convert the column from <code>Object</code> to <code>String</code> however this results in a ComputeError. I can not seem to figure out why. I suppose th...
<python><dataframe><casting><type-conversion><python-polars>
2023-11-13 12:33:03
4
1,840
Björn
77,473,880
1,841,839
How to Covert Google analtics API response to Pandas data frame
<p>I have some code which exports data from Google analytics using the Google Analtics data api.</p> <pre><code>def sample_run_report(credentials=None, property_id=&quot;YOUR-GA4-PROPERTY-ID&quot;): &quot;&quot;&quot;Runs a simple report on a Google Analytics 4 property.&quot;&quot;&quot; client = BetaAnalyticsDataCli...
<python><pandas><google-analytics><google-analytics-api><google-api-python-client>
2023-11-13 12:25:55
1
118,263
Linda Lawton - DaImTo
77,473,875
5,224,236
Your Kedro project version 0.17.6 does not match Kedro package version
<p>when running <code>kedro ipython</code> into a cloned repo, I get:</p> <pre><code>_version_mismatch_error(metadata_dict[&quot;kedro_init_version&quot;])) ValueError: Your Kedro project version 0.17.6 does not match Kedro package version 0.18.14 you are running. Make sure to update your project template. See https://...
<python><kedro>
2023-11-13 12:25:31
1
6,028
gaut
77,473,858
9,106,985
How to add bar values, set_ylim, and set_ylabel on secondary_y
<p>Currently have 2 problems with the following script</p> <ol> <li><p>cannot add bar labels to sets 8/9</p> </li> <li><p>set 8 is &quot;off the charts&quot; regardless of what ylim I set.</p> <pre><code> import pandas as pd import numpy as np import matplotlib.pyplot as plt categories = ['Cat1', 'Cat2', 'Cat3', ...
<python><pandas><matplotlib><plot-annotations><grouped-bar-chart>
2023-11-13 12:22:19
1
575
shoggananna
77,473,850
9,434,803
Trying to set up Polyglot notebook to work with Python and R
<p>I recently installed the Polyglot notebook extension for VS Code, and I am trying to set it up to work with Python and R. According to <a href="https://github.com/dotnet/interactive/blob/main/docs/jupyter-in-polyglot-notebooks.md" rel="nofollow noreferrer">the developer's tutorial</a>, it should be a simple matter o...
<python><r><.net><visual-studio-code><polyglot-notebooks>
2023-11-13 12:21:13
1
935
Pål Bjartan
77,473,770
374,437
VSCode not debugging into third side packages
<p>New to vscode and it seems fine, just that it doesn't seem to allow debugging into python packages I didn't write (not under the project folder?), neither does it allow me to add breakpoints to code that wasn't written by me.</p> <p>I tried to set the &quot;justMyCode&quot;: false configuration flag but it seems not...
<python><visual-studio-code><debugging><ide>
2023-11-13 12:05:52
2
974
Veltzer Doron
77,473,693
726,730
python - pyqt5 QScrollBar of QListWidget
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled_1.ui' # # Created by: PyQt5 UI code generator 5.15.7 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know w...
<python><pyqt5><qlistwidget><qscrollarea><qscrollbar>
2023-11-13 11:52:40
0
2,427
Chris P
77,473,528
6,653,602
Is it possible to show only sender name when sending email from Python?
<p>I am trying to send email using Python and <code>smptlib</code>. Is it possible to format message body so that it shows the sender's name only instead of name and email?</p> <p>Currently I am composing the email message like this</p> <pre><code>from email.utils import formataddr from email.message import EmailMessag...
<python><email><smtplib>
2023-11-13 11:24:35
3
3,918
Alex T
77,473,473
2,414,988
How to use mypy with helper functions
<p>I have a function <code>my_function</code> that takes two arguments, <code>x</code> and <code>method</code>. Depending on the value of <code>method</code>, either one of two standalone functions will be used, <code>func1</code> and <code>func2</code>. These two functions take <code>x</code> as argument: <code>func1<...
<python><mypy><python-typing>
2023-11-13 11:15:10
2
715
Biblot
77,473,455
13,184,263
Problems dealing with big dataframes in databricks notebook
<p>I am having problems dealing with a big dataframe in databricks notebook. This is the schema of my dataframe:</p> <pre><code>root |-- PAYMENT_DATE: string (nullable = true) |-- PAYMENT_REFERENCE: string (nullable = true) |-- ACCOUNT_NUMBER: string (nullable = true) |-- ROUTING_NUMBER: string (nullable = true) |...
<python><dataframe><pyspark><databricks>
2023-11-13 11:13:11
0
415
Jenny
77,473,419
7,431,005
output from GridSearchCV to log (with parallel joblib)
<p>I'm running some hyperparameter tuning on a cluster. The cluster automatically kills my job after some time. When this happens, I lose all my preliminary results. It would be great to store the preliminary results from <code>GridSearchCV</code> (the output that is printed to the console) in some file. My plan was to...
<python><logging><scikit-learn>
2023-11-13 11:08:18
0
4,667
user7431005
77,472,990
14,270,305
Using concurrency with python asyncio in requests in Google Cloud Functions
<p>I am trying to send requests to the OpenAI API to translate a list of texts via a Google Cloud Function. Since the API takes a little while to answer and I am trying to translate a few hundred texts per day, I tried speeding up the process by sending the requests concurrently from the GCF to the OpenAI API.</p> <p>S...
<python><google-cloud-platform><concurrency><google-cloud-functions><google-cloud-run>
2023-11-13 09:51:36
1
320
Manuel Huppertz
77,472,784
1,568,919
Making fake DataFrame/TimeDataFrame in Pandas
<p>Just found out that <code>pandas.util.testing.makeDataFrame</code> no longer exists.</p> <p>Where is it moved to? Or if it is completely gone, is there a substitute for easy testing functionality?</p>
<python><pandas>
2023-11-13 09:12:10
0
7,411
jf328
77,472,748
5,868,293
How to add text at barchart, when y is a list, using plotly express
<p>I have the following pandas dataframe</p> <pre><code>import pandas as pd foo = pd.DataFrame({'country': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}, 'unweighted': {0: 18.0, 1: 16.9, 2: 13.3, 3: 11.3, 4: 13.1}, 'weighted_1': {0: 17.7, 1: 15.8, 2: 14.0, 3: 11.2, 4: 12.8}, 'weighted_2': {0: 17.8, 1: 15.8, 2: 14.0, 3: 1...
<python><plotly>
2023-11-13 09:05:44
1
4,512
quant
77,472,746
5,269,892
Python - keep output XML namespace definitions at non-root nodes with ElementTree
<p>I want to generate an output XML from a modified input XML in Python using <em>xml.etree.ElementTree</em> (short: <em>ElementTree</em>). The input XML has multiple namespaces and the output XML should also have these namespaces, <strong>defined at the same nodes as the input XML</strong>; the latter is important fo...
<python><xml><xml-parsing><elementtree>
2023-11-13 09:05:28
0
1,314
silence_of_the_lambdas
77,472,734
13,438,431
asyncio.Task cancel() does not cancel the task if it's not in event loop
<p>I've stumbled upon a rather counterintuitive behavior of Python. Version is 3.10.12, Ubuntu 22.04.</p> <p>Consider this script:</p> <pre><code>import asyncio async def main(): t = asyncio.create_task(asyncio.sleep(5)) t.cancel() print(t.cancelled()) await asyncio.sleep(0) print(t.cancelled()) ...
<python><async-await><task><python-asyncio>
2023-11-13 09:03:31
0
2,104
winwin
77,472,710
15,948,240
Using .loc with on subset of levels from a DataFrame with MultIndex
<p>Given a dataframe with 3 levels of multiindex:</p> <pre><code>import pandas as pd df = pd.concat({'a': pd.Series([1,2,3,1]), 'b': pd.Series([5,4,3,5]), 'c': pd.Series(range(9,13)), 'd': pd.Series(range(13,17))}, axis=1).set_index(['a', 'b', 'c']) &gt;&gt;&gt; ...
<python><pandas><indexing><multi-index>
2023-11-13 08:58:40
2
1,075
endive1783
77,472,315
8,741,562
How to get the actual cost for a resource group in python?
<p>I am working on connecting with the azure portal and fetch informations like resource groups, tags and cost data. In that I can able to fetch resource groups and tags, but I am stuck on getting the cost information from the portal. Particularly I need the actual cost from the azure portal as shown in the image below...
<python><azure><azure-functions><azure-rest-api>
2023-11-13 07:34:12
1
1,070
Navi