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,899,656
10,107,805
Use reticulate to create plot using a pandas function within an R script
<p>The below code creates a scatter plot in python using pandas plotting functions</p> <pre><code>import pandas as pd data = {'col1': [1,2,3,4,5], 'col2': [6,7,8,9,10]} df = pd.DataFrame(data) df.plot.scatter(x='col1', y='col2', alpha=0.3) </code></pre> <p>I am trying to recreate the plot function using reticulate. S...
<python><r><reticulate>
2024-01-29 12:15:23
1
1,006
Basil
77,899,556
6,387,095
Requests - Cannot download xls file from a link, stuck in loop or timeout?
<p>I am trying to download a file from the following link:</p> <pre><code>url = &quot;https://nsearchives.nseindia.com/content/fo/qtyfreeze.xls&quot; </code></pre> <p>I have tried setting the <code>timeout</code>, <code>stream</code>, <code>headers</code>, <code>allow-redirects</code>. When I don't set the timeout, the...
<python><python-requests>
2024-01-29 11:57:32
1
4,075
Sid
77,899,537
10,972,079
ASK-SDK Python - How do I use multiple permissions in ASK-SDK simultaneously (i.e. reminders and postal code)?
<p>Essentially, I have a skill which already has code for reminders in it: and to check for permissions and ask for them I have the following code:</p> <pre><code> ... permissions = request_envelope.context.system.user.permissions if not (permissions and permissions.consent_token): # ...
<python><json><alexa-skills-kit><ask-sdk>
2024-01-29 11:53:52
1
1,338
CauseYNot
77,899,471
8,541,953
Google App Engine does not find pip package
<p>I am deployging a python app in Google App Engine and I am facing an error when running <code>google cloud deploy</code></p> <p>My requiremetns.txt file includes the followign python packages and versions:</p> <pre><code>requests==2.31.0 ipyleaflet==0.18.0 ipywidgets==8.1.1 ipyfilechooser jupyterlab==4.0.9 shapely==...
<python><google-cloud-platform><google-app-engine>
2024-01-29 11:44:27
2
1,103
GCGM
77,899,264
10,161,091
Call functions within a method with slightly different inputs
<p>I have a py file with multiple functions inside.</p> <pre class="lang-py prettyprint-override"><code># methods.py def method_a(input_1, input_2) ... def method_b(input_1, input_2, input_3) ... </code></pre> <p>I want to call the functions in <code>methods.py</code> in my main by the method name as string.</p> <pre c...
<python>
2024-01-29 11:07:30
0
2,750
SaTa
77,899,220
7,920,004
Python module not found when importing existing one
<p>I'm getting module not found error despite having <code>__init_.py</code> files where required. My structure is the same as in other sample project where <code>test_...</code> files work as expected.</p> <p>Error that I'm getting appears in <code>test_cicd_in_aws_stack.py</code></p> <p>When doing <code>from cdk_code...
<python>
2024-01-29 11:01:54
0
1,509
marcin2x4
77,899,196
6,681,932
harvesine vectorization for vector list
<p>I have a code snippet that computes a distance matrix between two lists of coordinates using the haversine function. While the current implementation works, it involves nested loops and can be time-consuming for large datasets. I am looking for a more efficient alternative that avoids the use of a for loop.</p> <pre...
<python><performance><vectorization>
2024-01-29 10:56:57
1
478
PeCaDe
77,899,090
14,640,064
Why can not I see logs in Azure Function app?
<p>I am working on Azure Function App (Python on Linux), but I am unable to view the logs.</p> <p>When I go to web portal to the Function App - tab Log Stream, the page never loads. There is just a spinning circle.</p> <p>The same happens when I open the Function itself and go to &quot;<em>Code + Test</em>&quot;. The c...
<python><azure><logging><azure-functions><azure-application-insights>
2024-01-29 10:39:29
1
705
herdek550
77,899,043
7,027,964
How to catch DateParseError in pandas?
<p>I am running a script that uses <code>pd.to_datetime()</code> on inputs that are sometime not able to be parsed.</p> <p>For example if I try to run <code>pd.to_datetime('yesterday')</code> it results to an error</p> <p><code>DateParseError: Unknown datetime string format, unable to parse: yesterday, at position 0</c...
<python><pandas><python-datetime>
2024-01-29 10:31:54
2
2,474
kosnik
77,898,940
2,473,382
Alias a type to be specialised later
<p>(Using python 3.12, so the <code>type</code> syntax is available to me.)</p> <p>During testing, I might abuse types (the examples here are contrived. In real life, I am using a custom class subclassing lists, and I would like to give a list instead of the subclass while testing using pydantic validators to avoid a l...
<python><python-typing><python-3.12>
2024-01-29 10:16:28
1
3,081
Guillaume
77,898,906
10,232,932
Use the first positive number of a row if a certrain condition in another column is valid, using pandas
<p>I want to have the first non-negative number in a new column, based on three columns (<code>valueA, valueB, valueC</code>).</p> <p>If a condition in <code>columnA</code> is valid. The condition is that <code>columnA!=None</code>.</p> <p>An example of a dataframe (df):</p> <pre><code>columnA valueA valueB valueC Non...
<python><pandas>
2024-01-29 10:11:37
3
6,338
PV8
77,898,765
2,386,930
Schedule a member function to run periodically
<p>I'm trying to schedule a member function to run periodically.</p> <pre><code>class Array: def __init__(self): self.array = [] # run every 10 seconds def periodic(self): [print(a) for a in self.array] def insert(self, a): self.array.append(a) </code></pre> <p>Most of the libr...
<python><scheduled-tasks>
2024-01-29 09:51:43
0
1,587
janovak
77,898,735
8,248,194
Calculate distance matrix for list of coordinates in numpy
<p>I've got a list of coordinates:</p> <pre class="lang-py prettyprint-override"><code>l_coords = [(1, 2), (1.1, 2.2), (1.05, 1.9)] </code></pre> <p>how can I calculate the distance matrix using a vectorized experession in numpy?</p>
<python><numpy>
2024-01-29 09:46:28
1
2,581
David Masip
77,898,710
12,544,391
ginstall: cannot stat 'Modules/_blake2.cpython-312-darwin.so':
<p>I was trying to install python 3.12.1 with asdf on macOS 14.2.1 (Sonoma)</p> <pre><code>python-build 3.12.1 /Users/dorianmariefr/.asdf/installs/python/3.12.1 python-build: use openssl@3 from homebrew python-build: use readline from homebrew Downloading Python-3.12.1.tar.xz... -&gt; https://www.python.org/ftp/python/...
<python><macos>
2024-01-29 09:42:54
1
9,411
Dorian
77,898,671
13,023,478
not able to install bist in python3
<p>I'm trying to install the blist module in python3 but I'm getting the below error I have tried everything like upgrading the setuptools, pip, wheel, and everything but nothing seems to be working Please help. I'm trying to install elastalert but the blist is the dependency I have to install.</p> <pre><code> Γ— pytho...
<python><python-3.x><elastalert>
2024-01-29 09:34:52
1
1,218
iamdhavalparmar
77,898,498
126,833
Download file uploaded to Azure Storage in Python
<p>I got the code to upload a document to Azure storage.</p> <pre class="lang-py prettyprint-override"><code>container_client = blob_service_client.get_container_client(container_name) blob_client = blob_service_client.get_blob_client(container_name, blob_name) blob_client.upload_blob(file_content, overwrite=True) abso...
<python><azure><azure-storage>
2024-01-29 09:08:53
1
4,291
anjanesh
77,898,398
1,581,090
Why does `scipy.optimize.minimize` always return the initial value?
<p>I have a complete working code that uses <code>scipy.optimize.minimize</code> but always returns the initial value as the optimized scalar parameter. Here is the complete code:</p> <pre><code>import sys import random import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt # Define the real ...
<python><scipy>
2024-01-29 08:47:39
1
45,023
Alex
77,898,325
14,721,356
Filter queryset based on values in the other queryset
<p>I have the following model in django:</p> <pre class="lang-py prettyprint-override"><code>class EmailSubscriber(BaseSubscriber): email = models.EmailField() name = models.CharField() </code></pre> <p>Now let's say I made a queryset from <code>EmailSubscriber</code> Like below:</p> <pre class="lang-py pretty...
<python><django><django-queryset>
2024-01-29 08:34:13
2
868
Ardalan
77,898,119
2,469,032
how to properly incorporate early stopping validation in sklearn Pipeline with ColumnTransformer
<p>I want to setup a lightGBM model with early stop validation. I also want to follow the best practice of using Pipeline to combine preprocessing and model fitting and prediction. Code below:</p> <pre><code>coltransformer = ColumnTransformer([ ('cat', OneHotEncoder(sparse_output = False), cat_invar), ('num', '...
<python><scikit-learn><pipeline>
2024-01-29 07:50:04
3
1,037
PingPong
77,898,085
7,800,726
How to obtain structured results with YOLOv8 similar to YOLOv5's results.pandas().xyxy method?
<p>I am currently working with YOLOv8 and I'm wondering if there is a method similar to <code>results.pandas().xyxy</code> available in YOLOv5 to obtain structured results in tabular form. With YOLOv5, it's possible to get results easily using the following code:</p> <pre class="lang-py prettyprint-override"><code>resu...
<python><pandas><yolov8>
2024-01-29 07:43:15
1
558
Ian Gallegos
77,898,061
6,502,077
Problem moving lines (one by one) from one text file to another
<p>I try to create a program that moves the first line in a text file to another and then remove said line in the first file (i.e. they are moved one by one). This should continue until there aren't any more lines in the first file to be moved to the second file.</p> <p>The problem I have is that the program freezes an...
<python><python-3.x>
2024-01-29 07:37:48
2
702
Lavonen
77,897,936
1,447,071
How can I prevent or mitigate pybel erroneous addition of hydrogens to a CSO3 group
<p>I read a PDB with a CSO3 group into pybel (The example was edited in Maestro Schrodinger to obscure the original chemistry). Note that since I use a lot of non natural amino acids and other molecule building blocks the amino acid name is inaccurate but easily read by Pymol and Schrodinger. Schrodinger also adds impl...
<python><jupyter><openbabel><pybel>
2024-01-29 07:09:51
1
3,723
Rubber Duck
77,897,621
17,729,094
Map each row into a list and collect all
<p>I have a dataframe:</p> <pre><code>df = pl.DataFrame( { &quot;t_left&quot;: [0.0, 1.0, 2.0, 3.0], &quot;t_right&quot;: [1.0, 2.0, 3.0, 4.0], &quot;counts&quot;: [1, 2, 3, 4], } ) </code></pre> <p>And I want to map each row into a list, and then collect all values (to be passed into e....
<python><python-polars>
2024-01-29 05:38:02
2
954
DJDuque
77,897,467
2,975,438
Adding thumbs up/down buttons and user's feedback into Streamlit based chatbot
<p>I am trying to add thumbs up/down buttons and user's feedback into Streamlit based chatbot. I use st.chat_message to create chatbot with Streamlit. For thumbs up/down buttons and user's feedback I use <a href="https://github.com/trubrics/streamlit-feedback" rel="nofollow noreferrer">streamlit-feedback</a> python pac...
<python><chatbot><streamlit><langchain><large-language-model>
2024-01-29 04:37:51
0
1,298
illuminato
77,897,371
721,998
combinations of list of lists using python
<p>I am given an n-list-of-lists:</p> <pre><code>[ [a, b, c], [p, q, r], .., .., [x, y, z] ] </code></pre> <p>I am supposed to create a result by choosing one element from each lists. For example, the result for the above example should look like:</p> <pre><code>[ [a, p, .., x], [a,...
<python><recursion><combinations><depth-first-search>
2024-01-29 04:00:25
1
6,511
Darth.Vader
77,897,370
146,077
Building tabular report in Pandas with index aligned concat
<p>I have two DataFrames that I want to merge or concat to build a report.</p> <pre><code>&gt;&gt;&gt; df1 class item value 0 A _1 10 1 A _2 11 2 B _3 12 3 X _4 13 &gt;&gt;&gt; df2 class item value 0 A _5 20 1 B _6 21 2 B _7 22 3 C _8 ...
<python><pandas><dataframe>
2024-01-29 04:00:18
1
28,876
Kirk Broadhurst
77,897,298
16,220,410
storing and retrieving hashed password in postgres
<p>I am watching a tutorial on FastAPI, where it switched the database from SQLite to PostgreSQL, before generating a token. It was working before but now it has an error, shown below</p> <p><code>return bcrypt.checkpw(password=password_byte_enc, hashed_password=hashed_password) TypeError: argument 'hashed_password': '...
<python><postgresql><fastapi><bcrypt>
2024-01-29 03:25:51
1
1,277
k1dr0ck
77,897,286
1,224,363
simple python program with gmpy2 is crashing (but i can do in scala???) -> overflow in mpz type / Aborted (core dumped
<p>I am running into an issue with the above mentioned library, running a very simple example -- which I can get working using similar libraries in JVM land (using Scala).</p> <p>The Scala code snippet below prints 'good', while the python version dies with the error in the title of the post.</p> <p>Wondering if this i...
<python><largenumber>
2024-01-29 03:22:19
1
2,744
Chris Bedford
77,897,280
13,345,077
Disable linter error of `method is not a known member of module "cv2"` from pylance in VSCode
<ul> <li><p>OS: WSL 2 Ubuntu 20.04.6 LTS</p> </li> <li><p>VSCode version: 1.85.2</p> </li> <li><p>Pylance version: v2023.12.1</p> </li> <li><p>Pyhotn version: 3.10.13</p> </li> <li><p>opencv-python version: 4.6.0.66</p> </li> <li><p>settings.json</p> </li> </ul> <pre class="lang-json prettyprint-override"><code>{ &...
<python><visual-studio-code><pylance>
2024-01-29 03:20:47
1
412
Weber Huang
77,897,033
8,229,029
USing Python selenium to extract attribute with no class, id, or other unique identifier
<p>I need to extract text using Selenium for html inside a table. There are no unique classes, id's or other identifiers I can use. The lines look like this. I need the &quot; Cost Elements&quot; text.</p> <pre><code>&lt;th align=&quot;LEFT&quot; bgcolor=&quot;7DA6CF&quot; width=&quot;350 px&quot; overflow=&quot;HID...
<python><selenium-webdriver><attributes>
2024-01-29 01:29:39
1
1,214
user8229029
77,896,993
13,520,498
Processing time increases with the number of Threads
<p>I'm working with the <code>pymeshlab</code> library. I noticed a weird behavior with <code>multithreading</code> while using one of their filters <code>generate_surface_reconstruction_screened_poisson</code> which can be found here: <a href="https://pymeshlab.readthedocs.io/en/latest/filter_list.html#generate_surfac...
<python><python-3.x><multithreading><pymeshlab>
2024-01-29 01:13:31
0
1,991
Musabbir Arrafi
77,896,948
3,498,864
Formulating a constraint with pyomo
<p>I'm trying to array genes (<code>elements</code>) in a matrix (<code>matrix_a</code>) based on the restriction sites they have (<code>attributes</code>). Restriction sites are recognized by enzymes that cut the DNA at a specific site. This can be represented as a sparse matrix with rows as genes, and columns as rest...
<python><optimization><sparse-matrix><linear-programming><integer-programming>
2024-01-29 00:51:15
0
3,719
Ryan
77,896,944
13,000,229
Difference between df.plot(kind='bar') and df.plot.bar()
<p>I use Python 3.12.1 and pandas 2.2.0.<br /> I find <code>df.plot(kind='bar')</code> and <code>df.plot.bar()</code> work in a similar (or even the same?) way.</p> <ol> <li>Is there any difference between these two?</li> <li>Which is the preferred way?</li> </ol> <p><a href="https://pandas.pydata.org/pandas-docs/stabl...
<python><pandas><dataframe><plot>
2024-01-29 00:49:07
2
1,883
dmjy
77,896,918
3,171,992
Python adding a double backslash when escaping string
<p>I work with devices such as routers and switches. I am trying to set up some banners on the devices based on user input. Since we cant know how the user would give an input(escaped or otherwise), I am trying to add escape characters to ', &quot; and \</p> <pre><code>Input: &quot;switch_mgmt&quot;: { &quot;cli_ba...
<python><escaping>
2024-01-29 00:33:28
0
436
iceyb
77,896,833
5,965,685
Pandas Resample with Linear Interpolation
<p>I have some hourly data, such as below, with odd sample times.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>#</th> <th>Date Time, GMT-08:00</th> <th>Temp, Β°C</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10/31/23 15:51</td> <td>13.41</td> </tr> <tr> <td>2</td> <td>10/31/23 16:51</td...
<python><pandas><pandas-resample>
2024-01-28 23:50:39
1
431
mitchute
77,896,751
11,342,139
How to overcome a class with too many dependencies in the constructor?
<p>I have a Python project where I have a Car class that has a main state machine with multiple states. Moreover, The Car class has multiple systems. These systems are Engine, GearBox, Brakes, Dashboard, Stereo and a few more. During the transition of each state, I have entry and exit action which do something with the...
<python><dependency-injection><constructor><facade>
2024-01-28 23:09:41
1
1,046
Angel Hadzhiev
77,896,439
1,609,514
How do you define a Python package's requirements when an older version of pip and setuptools are needed to install?
<p>I have an old <a href="https://github.com/billtubbs/gym-CartPole-bt-v0/tree/master/gym_CartPole_BT/envs" rel="nofollow noreferrer">Open AI gym environment</a> in a GitHub repo which requires gym==0.21.0 and pyglet==1.5.27. Based on <a href="https://stackoverflow.com/a/77205046/1609514">this answer</a> I found I can ...
<python><pip><package><openai-gym>
2024-01-28 21:08:01
1
11,755
Bill
77,896,279
15,474,507
Get file information to download files generates HttpError 404 googleapis
<p>With this code <strong>I can</strong> download a file from Google Drive, it downloads me into a file without extension and with a random name in a temporary folder. The file size is correct and the same as the original file.</p> <pre><code>@app.route('/download_from_drive', methods=['POST']) def download_from_drive(...
<python><google-apps-script><google-app-engine>
2024-01-28 20:14:18
0
307
Alex Doc
77,896,229
6,871,867
How to color particular cells given row index and column name in pandas?
<p>I have a dataframe df of shape (100,10) and a dictionary columns_to_color for each row.</p> <pre><code>columns_to_color = { 0: ['col1', 'col2', 'col9'], # Columns 1, 2 and 9 should be colored for row 0 1: ['col1', 'col5', 'col8'], # Columns 1, 5 and 8 should be colored for row 1 2: ['col3', 'col4', 'col7'], ...
<python><pandas>
2024-01-28 20:00:08
2
462
Gopal Chitalia
77,895,978
15,494,335
python elegant way to iterate over a buffer whose size is not divisible by the step
<p>Let's say I have a buffer buf=b&quot;...&quot; of length 953. I want to iterate over it using a step size of 33. Now 953 is not divisible by 33, so there will be a remainder of 29.</p> <p>I want to iterate over the buffer, but without exceeding the end on the last iteration. I could have used a:</p> <blockquote> <p>...
<python><iterator><buffer>
2024-01-28 18:40:03
2
707
mo FEAR
77,895,908
595,305
Define a class in Python and import into Rust module, but it "cannot be converted"
<p>This may be documented somewhere in the PyO3 documents, but I couldn't find it.</p> <p>I make a class like this in Python:</p> <pre><code>class ProgressData(): def __init__(self): self.start_time_ms = 0 self.last_progress_percent = 0.0 </code></pre> <p>... I instantiate it and pass it to a Rust m...
<python><class><rust><data-conversion><pyo3>
2024-01-28 18:18:49
1
16,076
mike rodent
77,895,517
11,536,058
How to url encode special character ~ in Python?
<p>I am trying to do an url encoding on the following string the following string 'https://bla/ble:bli~' using the urllib standard library on Python 3.10. Problem is that the ~ character is not encoded to %7E as per <a href="https://www.w3schools.com/tags/ref_urlencode.ASP" rel="nofollow noreferrer">url encoding</a>. ...
<python><python-3.x><urllib>
2024-01-28 16:27:54
2
873
Stamatis Tiniakos
77,895,366
10,574,250
Azure data tables python SDK does not work on read. "NotImplemented"
<p>I have a Table within Azure data storage that I am trying to read from. I am able to successfully write to this table but unable to read. I have followed the docs here: <a href="https://learn.microsoft.com/en-us/python/api/overview/azure/data-tables-readme?view=azure-python" rel="nofollow noreferrer">https://learn.m...
<python><azure><azure-table-storage><azure-tablequery><azure-tableclient>
2024-01-28 15:42:36
1
1,555
geds133
77,895,358
9,669,142
Python geneticalgorithm2 bounds with stepsize
<p>I'm using the geneticalgorithm2 module for minimization. I use mixed variables and my code is similar to the example given by them:</p> <pre><code>import numpy as np from geneticalgorithm2 import geneticalgorithm2 as ga def f(X): return np.sum(X) varbound = [[0.5,1.5],[0,100],[0,1]] vartype = ('real', 'int...
<python><python-3.x><genetic-algorithm>
2024-01-28 15:40:04
0
567
Fish1996
77,895,351
14,721,356
How can I fix the metaclass conflict in django-rest-framework Serializer
<p>I've written the following code in django and DRF:</p> <pre class="lang-py prettyprint-override"><code>class ServiceModelMetaClass(serializers.SerializerMetaclass, type): SERVICE_MODELS = { &quot;email&quot;: EmailSubscriber, &quot;push&quot;: PushSubscriber } def __call__(cls, *args, **...
<python><django><django-rest-framework>
2024-01-28 15:38:31
1
868
Ardalan
77,895,327
12,285,101
remove duplicates from sorted array - trying to understand an answer (leetcode)
<p>I'm trying to answer the Leetcode question &quot;<a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/?envType=study-plan-v2&amp;envId=top-interview-150" rel="nofollow noreferrer">Remove duplicates from sorted array</a>&quot; , and I am not sure I understand the logic. This is the challenge :</...
<python><list><duplicates>
2024-01-28 15:32:15
2
1,592
Reut
77,895,261
13,987,643
How to remove unwanted gap between bars in a grouped bar plot
<p>I'm trying to a create a grouped bar plot using Matplotlib. This is my code to do the same:</p> <pre><code>label_counts = df.groupby(['labels', 'preds']).size().unstack(fill_value=0) # Calculate percentages label_percentages = label_counts.div(label_counts.sum(axis=1), axis=0) * 100 label_percentages = label_percen...
<python><pandas><matplotlib>
2024-01-28 15:09:44
0
569
AnonymousMe
77,895,157
13,000,229
How can I solve "UserWarning: set_ticklabels() should only be used with a fixed number of ticks" in Seaborn?
<p>I faced a warning message when trying to rotate xticks of seaborn.lineplot.</p> <p>At first, I tried to run <code>set_ticks</code>, but <code>ax</code> doesn't seem to have this function. I also checked <code>FixedLocator</code>, but haven't figured out how to use it.</p> <p>Can anyone teach me how to remove this wa...
<python><pandas><matplotlib><seaborn><xticks>
2024-01-28 14:38:30
0
1,883
dmjy
77,895,092
20,771,478
Python: Use Graph API to send mails with Outlook - Get token with microsoft username and password
<p>I am trying to use the <a href="https://github.com/vgrem/Office365-REST-Python-Client/tree/master?tab=readme-ov-file#Working-with-Outlook-API" rel="nofollow noreferrer">office365</a> lybrary for Python to send mails with Outlook. When I was working with SharePoint the authentication was very simple, as in the exampl...
<python><microsoft-graph-api><office365><microsoft-graph-mail><msal>
2024-01-28 14:17:41
1
458
Merlin Nestler
77,895,088
12,894,926
Asyncio with boto and for range?
<p>I'm trying first time the <a href="https://github.com/aio-libs/aiobotocore" rel="nofollow noreferrer">asyncio botocore implementation</a>. However, I'm quite sure I'm not getting the expected asynchronicity, likely due to my own lack of experience with it. :)</p> <p>The goal of the bellow method is to <strong>duplic...
<python><amazon-web-services><asynchronous><python-asyncio><boto>
2024-01-28 14:15:15
1
1,579
YFl
77,894,773
7,959,614
Get numpy array that consists of ones and zeros for x combinations
<p>I want to create a <code>numpy.array</code> that consists of unique series of ones and zeros. A row needs to have a length of <code>2*x</code></p> <p>When <code>x=2</code> the output is expected to look as follows:</p> <pre><code>[[1 0 1 0] [1 0 0 1] [0 1 1 0] [0 1 0 1]] </code></pre> <p>When <code>x=3</code>:</p...
<python><numpy>
2024-01-28 12:30:24
2
406
HJA24
77,894,722
16,259,344
CID encoding of font
<p>I'am trying to extrat text from a pdf with python. None of the packages I tried could read it (PyPDF2,pdfminer,fitz etc.), but some of them could return me the cid encodings. (eg. (cid:3) ).</p> <p>Now I read the file the &quot;brute force&quot; way, meaning I managed to found out the cid decoding from some examples...
<python><pdf><fonts><pdf-extraction>
2024-01-28 12:11:52
2
505
Franciska
77,894,331
15,222,211
How can I disable a pylint message via pyproject.toml for a specific file?
<p>I'm encountering the <code>too-many-instance-attributes</code> pylint error in multiple files and I want to disable this message only for one file <code>my_project/runner/runner.py</code>. Is it possible to do this in the poetry <code>pyproject.toml</code> file?</p> <pre><code>pylint my_project ************* Module...
<python><pylint><pyproject.toml>
2024-01-28 09:54:37
1
814
pyjedy
77,894,086
15,144,596
How to use asyncio.as_completed() with a variable size task list
<h1>Challenge</h1> <p>Suppose I have a list L=30 tasks. Each task takes a variable time to complete and has a 10% chance of failing. If a task T fails, add the task back to a queue and prioritize it's completion. Also I can only process at most N=8 number of tasks.</p> <p>I want to use Python's <code>asyncio.as_complet...
<python><python-3.x><python-asyncio>
2024-01-28 08:31:50
2
549
Shakir
77,894,069
8,414,030
Run python and get result as string in browser
<p>I want to run Python code from a text-area in HTML and save the output in a div. I am using <code>pyodide.js</code> <a href="https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js" rel="nofollow noreferrer">https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js</a> to run Python. I would also like to use a worke...
<javascript><python><pyscript><pyodide>
2024-01-28 08:23:06
0
791
inquilabee
77,894,056
4,451,521
matplotlib.image.imread(): Some images are integers while some others are floats
<p>I am trying a script that works with images in python. The first image was working and the second one did not work at all.</p> <p>The script was</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np image = mpimg.imread('test.jpg') # Grab the x and y size and make a copy ...
<python><image><matplotlib>
2024-01-28 08:12:10
1
10,576
KansaiRobot
77,894,033
4,590,499
How to publish flask web app which runs C++ subprocess
<p><strong>Current Development Build Architecture</strong>:</p> <ul> <li>Single-Page Flask Web App: c:/code/flask_app/app.py</li> <li>C++ Program: c:/code/flask_app/main.exe</li> </ul> <p>I have a fully functional Flask web application that involves a straightforward HTTP POST request from a client to a server (<code>m...
<python><c++><ubuntu><flask><gunicorn>
2024-01-28 08:01:34
1
964
Daqs
77,893,953
23,219,369
Merge dxf files from multiple pages into one page
<p>I tried to merge multiple dxf files into one dxf file.</p> <p>I've used Importer of <a href="https://ezdxf.readthedocs.io/en/stable/addons/importer.html" rel="noreferrer">ezdxf</a> (Python package) but the result was that dxf files were accumulated in layers on one page.</p> <pre><code>def merge(source, target): ...
<python><pdf><merge><dxf><ezdxf>
2024-01-28 07:20:46
1
834
Temunel
77,893,946
5,049,813
Pylance thinks that an index into an H5 file does not create a group
<p>The following minimal example works fine:</p> <pre class="lang-py prettyprint-override"><code>import h5py f = h5py.File(&quot;mytestfile.hdf5&quot;, &quot;w&quot;) f.create_group(&quot;hello&quot;) # Pylance error here f[&quot;hello&quot;].create_dataset(&quot;hello&quot;, data=1) g = f.create_group(&quot;bye&quot...
<python><python-typing><h5py><pylance>
2024-01-28 07:18:18
1
5,220
Pro Q
77,893,912
1,568,590
Python & Beautiful Soup/Requests: request return a byte string - how to decode?
<p><strong>Short version:</strong> Scraping two very similar web pages, but the content of one is returned as a byte stream.</p> <p><strong>Long version:</strong> I am just dipping my toes into Beautiful Soup. And I am testing on two web pages; both being lists of conference papers. One list is &quot;invited papers&q...
<python><beautifulsoup><encoding><python-requests>
2024-01-28 07:03:57
0
1,414
Alasdair
77,893,827
11,280,068
How do you develop the HTML portion of a Jinja2 template, after you've jinja-ified the file?
<p>I have an HTML email template that I've created and converted to a jinja template. This mean that I've:</p> <ol> <li>Changed it to a <code>.j2</code> file extension</li> <li>Added all the necessary jinja expressions like for-loops, if-statements, and expressions, using <code>{{ ... }}</code> and <code>{% ... %}</cod...
<python><python-3.x><templates><jinja2><server-side-rendering>
2024-01-28 06:23:25
0
1,194
NFeruch - FreePalestine
77,893,774
5,976,033
Python Azure Functions Identity-Based Connection for Trigger Bindings
<p>I can't seem to find clear documentation on how to set a System-assigned Managed Identity-based connection for my Queue-triggered Azure Function.</p> <p><strong>Steps taken</strong>:</p> <ol> <li>Enabled System-assigned Managed Identity (SAMI) for the Azure Function</li> <li>On the Queue Storage Account, granted the...
<python><azure><azure-functions><queue>
2024-01-28 05:54:56
2
4,456
SeaDude
77,893,484
3,973,175
Italicizing letters and numbers in matplotlib
<p>I am attempting to italicize text in my plot:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([1,2,3],[1,1,1], label = '$\it{ABC123}$') plt.legend() plt.show() </code></pre> <p>as shown by <a href="https://stackoverflow.com/questions/8376335/styling-part-of-label-in-legend-in-matplotlib">Styling part of lab...
<python><python-3.x><matplotlib>
2024-01-28 02:40:18
1
6,227
con
77,893,416
7,978,112
Empty pandas dataframe with datatypes preserved
<p>I want to make an empty df with preserved datatypes as a template. Code is as follows:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import datetime from dataclasses import dataclass @dataclass class OpenOrder: symbol: str = &quot;Dummy&quot; secType: str = &quot;STK&quot; dt: ...
<python><python-dataclasses>
2024-01-28 02:01:25
1
1,847
reservoirinvest
77,893,374
21,107,707
How to configure pip to install a script to the environment bin/ folder?
<p>I'm writing a package in Python, and I want possible users to install a command to their system by installing with <code>pip</code>. A package that I want to copy the installation behavior of is <a href="https://github.com/wkentaro/gdown/blob/main/pyproject.toml" rel="nofollow noreferrer"><code>gdown</code></a>. Whe...
<python><pip>
2024-01-28 01:26:12
1
801
vs07
77,893,232
651,174
How to properly log an error and then re-raise an exception
<p>Is the following the correct pattern for logging something and re-raising the error -- specifically, just using a blank <code>raise</code> without anything after it? Is there a more explicit way to do that?</p> <pre><code>try: #MySQL conn = pymysql.connect(host=HOST, user=USER, passwd=PASS, db=NAME) except pymys...
<python>
2024-01-27 23:55:56
0
112,064
David542
77,893,163
1,070,833
how to read/write "bits per sample "ifd tag in a tiff file (python)
<p>I'm struggling with IDF tag for &quot;bits per sample&quot;. According to the documentation the type of this field is <code>short</code></p> <pre><code>Code 258 (hex 0x0102) Name BitsPerSample Type SHORT Count N = SamplesPerPixel Default 1 </code></pre> <p>a tag in a valid tiff file looks like this in ...
<python><image-processing><tiff>
2024-01-27 23:23:36
2
1,109
pawel
77,893,107
525,865
Beautiful soup parse the listing of many entries and saving in data frame
<p>At the moment I'll am gathering data from the dioceses of The world.</p> <p>My approach works with bs4 and pandas. I am currently working on the scrape-logic.</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd url = &quot;http://www.catholic-hierarchy.org/&quot; # Send a GET request t...
<python><pandas><beautifulsoup>
2024-01-27 22:56:17
1
1,223
zero
77,893,034
15,048,981
ImportError: Could not import faiss python package
<p>I am getting this error on python3.12 on M1 air</p> <p>ImportError: Could not import faiss python package. Please install it with <code>pip install faiss-gpu</code> (for CUDA supported GPU) or <code>pip install faiss-cpu</code> (depending on Python version).</p> <p>It suggests installing fairs-cpu and gpu and none o...
<python>
2024-01-27 22:27:17
1
569
Andy
77,893,032
1,001,581
a forking service blocks ssh connection even if the main process ends
<p>I have a program that should be run from <code>sshd</code>. It should print few lines to stdout and then fork and exit. The forked program should do its stuff detached from <code>sshd</code> without blocking the program. The thing is that the program below runs correctly when executed from a terminal shell or via s...
<python><ssh><tcp><sshd><setsid>
2024-01-27 22:27:04
1
431
ChewbaccaKL
77,892,981
17,275,588
moviepy introducing weird audio artifacts at end of audio files, when creating videos via Python. Why?
<p>These are not present in the original audio files. They get added to the end during the video creation process somehow. See this screenshot for a before and after comparison of the waveforms:</p> <p><a href="https://i.sstatic.net/ziZWL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ziZWL.png" alt="en...
<python><mp3><mp4><aac>
2024-01-27 22:08:03
2
389
king_anton
77,892,980
11,405,455
count frequencies in the values of dictionary in python
<p>I want to create a dictionary from the following dictionary which takes all the values in each round and make it as index and store its frequency across rounds</p> <p>I am maintaining a dictionary which gets bigger in every iteration</p> <pre><code>list_chosen_each_round {0: ['1', '26', '20', '14', '28', '23'], 1: ...
<python>
2024-01-27 22:08:00
1
443
Khaned
77,892,926
10,380,766
TypeError in Python 3.11 when Using BasicModelRunner from llama-cpp-python
<p>I'm currently taking the <a href="https://www.coursera.org/learn/finetuning-large-language-models-project/" rel="nofollow noreferrer">DeepAI's Finetuning Coursera course</a> and encountered a bug while trying to run one of their demonstrations locally in a Jupyter notebook.</p> <p><strong>Environment:</strong></p> <...
<python><llama><llama-cpp-python>
2024-01-27 21:47:38
2
1,020
Hofbr
77,892,851
17,729,094
How to box a polar plot with a cartesian coordinates axis?
<p>I want the <code>xy</code> axis to perfectly enclose the polar axis without the colorbar. So far I have:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np # Random data r = np.random.randn(1000) theta = np.random.randn(1000) fig = plt.figure() axc = plt.subplot(236) ax = plt.subplot(236, projectio...
<python><matplotlib>
2024-01-27 21:16:51
1
954
DJDuque
77,892,601
1,114,253
Looping over multiple ranges in "BFS" order?
<p>Let's say for <code>k=3</code> and <code>n=4</code>, then one could simply loop over the <code>k</code> different <code>n</code>-ranges like</p> <pre><code>for a in range(4): for b in range(4): for c in range(4): print((a, b, c)) </code></pre> <p>The problem is that this goes all the way through the last...
<python><algorithm><loops><breadth-first-search>
2024-01-27 19:52:23
1
884
chausies
77,892,410
8,285,840
How to use plotly buttons and plotly.express (px), with the color option?
<p>When using <code>px.scatter(color='key')</code> with the color option, using plotly buttons behaves erractic. The data is after clicking on either of the buttons is jumbled up and not what one expect, certainly does not go back to the original plot when clicking on Plength (the button for showing petal_length on the...
<python><plotly>
2024-01-27 18:57:40
1
760
Matthias Arras
77,892,148
1,102,806
Python concurrent.futures.wait job submission order not preserved
<p>Does python's <code>concurrent.futures.wait()</code> preserve the order of job submission? I submitted two jobs to <code>ThreadPoolExecutor</code> as follows:</p> <pre><code>import concurrent.futures import time, random def mult(n): time.sleep(random.randrange(1,5)) return f&quot;mult: {n * 2}&quot; def di...
<python><concurrent.futures>
2024-01-27 17:35:17
2
4,621
DevEx
77,892,031
6,626,093
array(struct) to array(map)β€”PySpark
<p>I have a <code>df</code> with the following schema,</p> <pre><code> g_hut: string date: date arr_data:array element:struct Id:string Q_Id:string Q_Type:string </code></pre> <p>I want to convert the <code>arr_data</code> column from <code>Array(Struct)</code> to <code>Array(Map)</cod...
<python><arrays><apache-spark><pyspark><apache-spark-sql>
2024-01-27 17:00:04
1
3,046
i.n.n.m
77,891,979
4,199,253
add another column as second X axis label in Python
<p>I have a 15minutes interval time series for several camera. each camera can collect 3 types of movement in four different leg. There is a <code>control_factor</code> that was present for an hour for each camera. I want to show the total of counts in each leg for each camera (each camera in separate plots ) for every...
<python><pandas><seaborn><bar-chart><axis-labels>
2024-01-27 16:44:24
1
1,034
GeoBeez
77,891,836
2,213,825
Silence JAX initial messages
<p>I am using JAX with CPU. Everytime I use it I get a message:</p> <pre class="lang-bash prettyprint-override"><code>Platform 'METAL' is experimental and not all JAX functionality may be correctly supported! 2024-01-27 15:56:46.164447: W pjrt_plugin/src/mps_client.cc:563] WARNING: JAX Apple GPU support is experimental...
<python><jax>
2024-01-27 15:58:24
1
4,883
JoΓ£o Abrantes
77,891,386
4,225,430
Get rid of format string conflict when using sympy
<p>When I try to use sympy to find the derivative of the loss function, it raises a conflict with format string.</p> <pre><code>import numpy as np import sympy as sp def predict(X, w, b): return np.dot(X, w) + b def loss(X, w, b, Y): return np.mean((predict(X, w, b) - Y) ** 2) X, Y = np.loadtxt(&quot;code/02...
<python><string><numpy><machine-learning><sympy>
2024-01-27 13:35:43
2
393
ronzenith
77,891,369
9,947,140
Modeling Sigmoid Curve with Time-Dependent Steepness in Python
<p>I have a dataset that follows a sigmoid curve, and I've observed that the sigmoid function becomes steeper over time. I'm looking for guidance on creating a model to fit this curve using Python. This question is similar to <a href="https://stackoverflow.com/questions/55725139/fit-sigmoid-function-s-shape-curve-to-da...
<python><numpy><scipy><curve-fitting><sigmoid>
2024-01-27 13:29:48
1
342
randomrabbit
77,891,032
11,748,924
Create a small control panel on screen for pyautogui monitoring and control purposes
<p>How do I display a small control panel screen that can control and monitoring <code>pyautogui</code> process? I expect there is a pinned window that for monitoring purpose such as displaying current log.txt that has been generated by <code>logging</code> and controlling purpose such as pause and resume button? Actua...
<python><debugging><controls><monitoring><pyautogui>
2024-01-27 11:38:37
1
1,252
Muhammad Ikhwan Perwira
77,891,012
18,493,710
Cannot fetch Camunda job variables in pyzeebe worker
<p>I have written a Python <code>pyzeebe</code> worker that is supposed to interact with my database using the values that the variables of the previous user task in the <code>Camunda BPMN</code> hold. I have defined a user task with a form. I have also created a service task and defined the <code>taskDefinition</code>...
<python><camunda><zeebe>
2024-01-27 11:28:45
1
418
okaeiz
77,890,704
2,737,779
Just installed Python 3.12 but it doesn't work
<p>I'm trying to clone a repo from GitHub and the 3rd step involves running Python3 pip install to install the requirements.</p> <p>I didn't have python installed so I installed it using Winget with the command &quot;Winget install python.python 3.12&quot;</p> <p>However, I'm still getting an error message telling me P...
<python><windows>
2024-01-27 09:44:03
0
315
Nathaniel
77,890,446
14,098,117
How to call via Google places API(New) Text Search (ID Only) in python?
<p>According to documentation <a href="https://developers.google.com/maps/documentation/places/web-service/usage-and-billing#id-textsearch" rel="nofollow noreferrer">here</a> if I ask, just for place_id, the call should be for free. I tried various versions of call, but all of them either did not work or gave me not ju...
<python><google-places-api>
2024-01-27 07:57:52
1
844
Emil Haas
77,890,294
10,342,778
TFDS extract file name
<p>In tfds, we do</p> <pre class="lang-py prettyprint-override"><code>def _generate_examples(self, file_paths): for file_path in file_paths: yield file_path, { 'image': image, 'label': label } </code></pre> <p>I am already yielding file_path, how can I get it when i load the ...
<python><tensorflow><tensorflow-datasets>
2024-01-27 06:42:02
0
2,742
Ahmad Anis
77,890,206
1,029,902
Replacing a row value in csv with a value from a scrape function
<p>I have a script that opens two csv files. It scrapes the links in venues.csv for an <code>id</code> value for a beer from a webpage, then uses that <code>id</code> to find corresponding data from the beer.csv and then writes to a separate csv. One of the columns in beer.csv is rating_score. However, I want to use th...
<python><pandas><list><csv><web-scraping>
2024-01-27 05:59:24
1
557
Tendekai Muchenje
77,889,994
3,765,883
Python example f"{heading:=^30}"
<p>I ran across this in a basic Python tutorial (<a href="https://docs.python.org/3.10/tutorial/controlflow.html" rel="nofollow noreferrer">https://docs.python.org/3.10/tutorial/controlflow.html</a>). The example is:</p> <pre><code>&gt;&gt;&gt; heading = &quot;Centered string&quot; &gt;&gt;&gt; f&quot;{heading:=^30}&q...
<python><operators><centering>
2024-01-27 03:46:33
0
327
user3765883
77,889,973
23,190,147
How do I get the right installation of python?
<p>I'm having trouble finding the right installation of python, and I am on windows.</p> <p>When I first installed python (IDLE) by going to <a href="https://python.org" rel="nofollow noreferrer">https://python.org</a>, and downloading the version, I did not know that there was a version of python in the microsoft stor...
<python><windows><installation><python-idle>
2024-01-27 03:36:55
0
450
5rod
77,889,955
9,095,603
Selenium uc webdriver chrome instances proliferating, eating up all memory and CPU
<p>I have included steps to close the selenium python webdriver, and even restart it regularly to avoid accumulating problems. But my Windows 10 Task Manager shows a steady increase in memory and CPU usage up to the point of saturation and freezing up my computer, and the number of Chrome instances proliferate, despit...
<python><google-chrome><selenium-webdriver><selenium-chromedriver><cpu-usage>
2024-01-27 03:23:09
1
423
ptrcao
77,889,938
3,620,605
Reshaping and Transposing NumPy Array to Match Specific Flattened Order
<p>I have a numpy array of shape <code>(9,768)</code>, it is reshaped into a 3D array and then flattened. I am trying to find the combination of 2D operations like reshaping and transposing that will result in the same order when flattened. Here's an example</p> <pre><code>&gt;&gt;&gt; m = np.random.normal(size=(9,768)...
<python><numpy>
2024-01-27 03:14:33
1
1,158
Effective_cellist
77,889,768
10,107,897
Swift PythonKit with error for no module found
<p>I'm trying to run some python code from Xcode but wasn't sure why it can't find the module. All the tutorial I found only shows importing the simple .py file that contains function only no import on the top. I'm using python3. TIA</p> <pre><code>import SwiftUI import PythonKit struct ContentView: View { va...
<python><swift><swift-pythonkit>
2024-01-27 01:40:58
1
427
14079_Z
77,889,719
7,218,062
With Pandas json_normalize how can I select only some of the dictionary fields?
<p>I'm trying to use Pandas json_normalize to import the cik, entityName, end, fp, and val fields from this json:</p> <pre><code>{ &quot;cik&quot;: 320193, &quot;entityName&quot;: &quot;Apple Inc.&quot;, &quot;facts&quot;: { &quot;dei&quot;: { &quot;EntityCommonStockSharesOutstanding&quot;: { &q...
<python><pandas>
2024-01-27 01:21:49
1
1,591
jmq
77,889,644
1,982,032
How can use higher pandas version when pandas-market-calendars requires lower version?
<p>Upgrade the pandas version:</p> <pre><code>pip install --upgrade pandas Requirement already satisfied: pandas in ./lib/python3.11/site-packages (1.5.3) Collecting pandas Downloading pandas-2.2.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (19 kB) Requirement already satisfied: numpy&lt;2,&...
<python><python-3.x><pandas><pip><dependencies>
2024-01-27 00:46:43
1
355
showkey
77,889,581
1,509,264
Typing Checking for a value to be any string except one literal
<p>The <code>Union[X, Y]</code> type is for when the type can be either <code>X</code> or <code>Y</code>. I want the opposite when the type must be <code>X</code> but never <code>Y</code> so either:</p> <ul> <li>Any <code>X</code> but not <code>Y</code> where <code>Y</code> is a specific sub-class of <code>X</code>; or...
<python><python-typing>
2024-01-27 00:17:14
0
172,539
MT0
77,889,482
1,132,708
Writing a custom Keras layer that returns a vector from a dictionary for a given token
<p>I'm working on a problem where I've tokenized a corpus, but there are specific words that have additional features I want to add to an embedding layer's output. The output dimension needs to be the precomputed vectors dimension + the embedding dimension. I'm storing the specific words in a dictionary where <code>wor...
<python><keras>
2024-01-26 23:34:04
0
470
webb
77,889,447
1,214,800
Make Mypy accept a generic dict type with an empty dict default value
<p>I'm trying to make Mypy accept a generic param that conforms to a dict. No matter what I do, it is always complaining with:</p> <blockquote> <p>Incompatible default for argument &quot;overrides&quot; (default has type &quot;dict[str, Any]&quot;, argument has type &quot;T_Overrides&quot;) [Mypyassignment]</p> </block...
<python><python-typing><mypy>
2024-01-26 23:19:09
0
73,674
brandonscript
77,889,409
8,734,934
Specify browser for login
<p>I am writing a python script to query something from graph. I am using <a href="https://github.com/AzureAD/microsoft-authentication-library-for-python" rel="nofollow noreferrer">MSAL for python</a> to get the login and get the token. When using <em>acquire_token_interactive</em> the login prompt will redirect to my ...
<python><msal>
2024-01-26 23:07:11
1
475
devil_inside
77,889,205
7,087,604
Loading Python joblib package and sharing it in Flask between WSGI (Phusion Passenger) workers
<p>I have a pre-trained <a href="https://radimrehurek.com/gensim/models/word2vec.html" rel="nofollow noreferrer">Gensim Word2Vec</a> model that IΒ use as a global variable in a Flask web app:</p> <pre class="lang-py prettyprint-override"><code>app = Flask(__name__) engine = gensim.Models.load(&quot;search_engine&quot;) ...
<python><flask><multiprocessing>
2024-01-26 22:02:50
0
713
AurΓ©lien Pierre