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
76,307,173
7,509,907
Getting 'unsupported array index type unicode_type' error when selecting a column based on condition in Numba with NumPy structured array
<p>I am trying to select a column of a structured NumPy array. The column to be selected depends on a condition that will be passed to the function. Numba throws the error below when I try to select the column name based on the condition. Otherwise everything works well.</p> <p>Basic example:<br /> This works:</p> <pre...
<python><numpy><numba><structured-array>
2023-05-22 14:22:02
1
950
D.Manasreh
76,307,108
1,841,839
How to set page size with account summitries list in Google analytics admin api
<p>The <a href="https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1beta/accountSummaries/list?apix_params=%7B%22pageSize%22%3A1%7D" rel="nofollow noreferrer">Method: accountSummaries.list</a> method has an optional parm called page size</p> <blockquote> <p>pageSize integer</p> <p>The maximum num...
<python><google-cloud-platform><google-api><google-analytics-api><google-api-python-client>
2023-05-22 14:15:30
1
118,263
Linda Lawton - DaImTo
76,307,021
6,564,294
Shuffle pandas column while avoiding a condition
<p>I have a dataframe that shows 2 sentences are similar. This dataframe has a 3rd relationship column which also contains some strings. This 3rd column shows how similar the texts are. For instance: <br> P for Plant, V for Vegetables and F for Fruits. Also, <br> A for Animal, I for Insects and M for Mammals.</p> <pre>...
<python><pandas><dataframe><shuffle><sentence-similarity>
2023-05-22 14:05:06
2
324
Chukwudi
76,307,018
4,858,605
Integrating custom pytorch backend with triton + AWS sagemaker
<p>I have a custom python backend that works well with AWS sagemaker MMS (multimodel server) using an S3 model repository. I want to adapt this backend to work with Triton python backend. I have a example dockerfile that runs the triton server with my requirements.</p> <p>I also have a model_handler.py file that is bas...
<python><amazon-web-services><amazon-sagemaker><triton>
2023-05-22 14:04:48
1
2,462
toing_toing
76,306,898
1,504,016
Dynamically define class with inheritance and static attributes (sqlmodel / sqlalchemy metaclasses)
<p>I have the following class definition that I would like to make dynamic:</p> <pre><code>class SQLModel_custom(SQLModel, registry=self.mapper_registry): metadata = MetaData(schema=self.schema) </code></pre> <p>I've tried something like that:</p> <pre><code>type('SQLModel_custom', (SQLModel, self.mapper_registry),...
<python><class><dynamic><metaclass><sqlmodel>
2023-05-22 13:51:40
1
2,649
ibi0tux
76,306,842
3,521,180
Why am I not able to pass two status Ids in my GET method?
<p>I have a scenario where in I need to compare two simulation coming from same table, i.e say simulation_1 and simulation_2. For all completed simulation theer would be a unique id generated &quot;sim_sttus_id&quot; in the &quot;__TABLE1&quot; as shown in the code snippet. Below are the code snippet for reference.</p>...
<python><python-3.x><flask><flask-restful><pypika>
2023-05-22 13:45:23
0
1,150
user3521180
76,306,463
20,726,966
How can I deploy a Python script to Heroku for performing dynamic sum, division and multiplication on-demand?
<p>I am trying to deploy a script to Heroku that for example, returns a sum, division and multiplication of two numbers that are dynamically passed.</p> <p>script.py</p> <pre><code>def sum(a, b): ans = a+b print(ans) return ans def mul(a, b): ans = a*b print(ans) return ans def div(a, b): ...
<python><heroku>
2023-05-22 13:00:00
1
318
Homit Dalia
76,306,376
9,488,023
Compare similar spelling in Pandas dataframe column but different value in another column
<p>Let's say I have a Pandas dataframe in Python that looks something like this:</p> <pre><code>df_test = pd.DataFrame(data=None, columns=['file', 'number']) df_test.file = ['washington_142', 'washington_287', 'chicago_453', 'chicago_221', 'chicago_345', 'seattle_976', 'seattle_977', 'boston_367', 'boston 098'] df_test...
<python><pandas><dataframe><compare>
2023-05-22 12:49:44
2
423
Marcus K.
76,306,172
2,928,970
Create numpy array reusing memory of other array
<p>I have following code:</p> <pre><code>a = np.zeros(N) b = np.tile(a, [m, n]) .... a[4] = 5 # just changing some values inside a b = np.tile(a, [m, n]) </code></pre> <p>In the second assignment for <code>b</code>, can the previous memory of <code>b</code> be overwritten during this procedure instead of creating a n...
<python><numpy><memory-management>
2023-05-22 12:23:51
2
1,395
hovnatan
76,306,121
2,473,382
Poetry: build a package with a non-standard directory structure
<p>I created a repo with this non-standard structure:</p> <pre><code>- src - resources -- a.py -- b.py ... </code></pre> <p>I want to make a package out of it (let's call it <code>pack</code>).</p> <p>In my pyproject.toml, the relevant lines are:</p> <pre class="lang-ini prettyprint-override"><code>[tool.poetry] n...
<python><python-packaging><python-poetry>
2023-05-22 12:18:16
1
3,081
Guillaume
76,306,118
10,164,750
Dropping a column based on the value of another pyspark
<p>I am trying to build and a method which takes a dataframe as input and returns the another dataframe as output after checking a certain condition.</p> <p>If the <code>exception_type</code> column contains <code>FILE_REJECT</code>, it <code>drops</code> the <code>file_name</code> column, otherwise it does not.</p> <p...
<python><apache-spark><pyspark>
2023-05-22 12:18:01
1
331
SDS
76,306,096
12,633,371
polars use Expression API with DataFrame's rows
<p>I am a new <code>polars</code> user and I want to apply a function in every <code>polars DataFrame</code> row. In <code>pandas</code> I would use the <code>apply</code> function specifying that the input of the function is the <code>DataFrame</code>'s row instead of the <code>DataFrame</code>'s column(s).</p> <p>I s...
<python><dataframe><python-polars>
2023-05-22 12:15:13
1
603
exch_cmmnt_memb
76,306,054
10,532,894
PytestUnhandledCoroutineWarning: async def functions are not natively supported and have been skipped
<p>I'm building a py project using <code>poetry</code> I have created a test file and using following code from examples to test asynchronously</p> <pre><code> import httpx import respx @respx.mock async def test_async_decorator(): async with httpx.AsyncClient() as client: route = respx.get(&quot;https://...
<python><asynchronous><pytest><python-poetry>
2023-05-22 12:09:41
2
461
krishna lodha
76,305,881
14,125,436
How to set multi-conditions in an If statement for a pytorch tensor
<p>I have a pytorch tensor and want to mask part of it and put the masked section in an if statement. This is my tensor:</p> <pre><code>import torch all_data = torch.tensor([[1.1, 0.4], [1.7, 2.7], [0.9, 0.7], [0.9, 3.5], ...
<python><if-statement><pytorch><conditional-statements>
2023-05-22 11:51:37
1
1,081
Link_tester
76,305,701
3,740,652
Python app passing config file trhough Docker
<p>I created a stand-alone application with Python3 that accepts a file as input, however I am not able to let it work properly. Once installed on my system I run the application as <code>myapp -accounts ./accounts.yaml</code>.</p> <p>Now, I am trying to replicate this behaviour on a Docker container: I would like to d...
<python><docker><parameter-passing><docker-entrypoint>
2023-05-22 11:29:00
0
372
net_programmer
76,305,700
11,974,163
How to extract values from excel worksheets to get desired calculation using python
<p>So I have 3 worksheets in excel, let's call them <code>sheet_a</code>, <code>sheet_b</code> and <code>sheet_c</code>.</p> <pre><code>sheet_a: type formula 0 type_a A+B 1 type_b A 2 type_c A/(A+B) 3 type_d A/B sheet_b: dish ingredient map 0 type_a ...
<python><excel><oop><openpyxl>
2023-05-22 11:28:57
1
457
pragmatic learner
76,305,685
7,796,211
Update many-to-many table with removed duplicates
<p>I have three models: <code>Author</code>, <code>Book</code>, and <code>BookAuthor</code>. The <code>BookAuthor</code> model represents a many-to-many relationship between <code>Author</code> and <code>Book</code>, i.e., a book can have multiple authors and a person can write multiple books.</p> <p>I need to parse a ...
<python><sqlalchemy>
2023-05-22 11:27:46
0
418
Thegerdfather
76,305,578
13,819,183
Calling instance of adapter class plugged into port is causing mypy issues
<p>I'm currently plugging an Adapter into a port in a handler which can help you get an instance of that port. Here is a simple setup to reproduce:</p> <pre class="lang-py prettyprint-override"><code>from typing import Protocol class SomePort(Protocol): def caller(self): raise NotImplementedError class ...
<python><mypy><python-typing><hexagonal-architecture>
2023-05-22 11:13:06
1
1,405
Steinn Hauser Magnússon
76,305,410
8,541,953
Ipywidgets appear separated when displaying them
<p>I am creating two simple widgets with <code>ipywidget</code> and when displaying them, I need them to be close to each other. However the default is not showing them like this.</p> <pre><code>import ipywidgets as widgets label = widgets.Label(value='test:') checkbox = widgets.Checkbox(indent=False) float_text = wid...
<python><widget><ipywidgets>
2023-05-22 10:49:43
1
1,103
GCGM
76,305,333
18,374,898
plotly write_image() runs forever and doesn't produce any static image
<h1>Plotly <code>fig.write_image()</code> takes forever</h1> <h1>and doesn't produce any image</h1> <p>I'm using</p> <pre><code>python 3.10.11 Plotly 5.14.1 kaleido 0.2.1 Win 11 22H2 VSCode 1.78.2 </code></pre> <p>when I try to execute a cell with <code>fig.write_image('filename.png', format = 'png')</code> the cel...
<python><plotly><kaleido>
2023-05-22 10:38:33
3
320
Konstantin Z
76,305,312
4,571,350
How to add another label level to the x-axis
<p>I am trying to put a secondary axis on a plot. The first x axis display the day of the month. I would like the label of the secondary axis to be the month name and to be displayed below.</p> <p>For my first axe I have:</p> <pre><code>plot={} plot['W']=axs[0] plot['W'].xaxis.set_major_formatter(mdates.DateFormatter('...
<python><matplotlib><x-axis>
2023-05-22 10:36:07
1
1,365
Laetis
76,305,257
18,108,367
The INCRBY instruction executed by a Redis pipeline return a reference to the pipeline instead the value of the key modified
<p>I have some problem to use Redis pipeline. I need to execute 2 commands (<code>incr()</code> and <code>set()</code>) by a <em>Redis transaction</em>.</p> <p><strong>Environment info</strong>: redis-py version 3.5.3; the version of the Redis server is v=5.0.5.</p> <p>So I have tried to use the following code (the cod...
<python><redis><transactions><watch><redis-py>
2023-05-22 10:29:07
2
2,658
User051209
76,305,034
11,452,928
How to pass option to python when I'm running a jupyter notebook on VS Code
<p>I've created a virtual environment using <code>venv</code> and I'm using such environment in Visual Studio Code to run a jupyter notebook.</p> <p>Now, my code stops running and from the log I can read 2 warnings: one of which is</p> <pre><code>warning: It seems that frozen modules are being used, which may 0.00s - m...
<python><visual-studio-code>
2023-05-22 10:02:24
2
753
fabianod
76,305,020
1,648,641
pyspark dataframe limiting on multiple columns
<p>I wonder if anyone point me in the right direction with the following problem. In a rather large pyspark dataframe with about 50 odd columns, two of them represent say 'make' and 'model'. Something like</p> <pre><code>21234234322(unique id) .. .. .. Nissan Navara .. .. .. 73647364736 .. .. .. BMW X5 ...
<python><pyspark>
2023-05-22 10:00:57
1
1,870
Lieuwe
76,304,997
1,113,579
Build a dictionary from an object's explicitly declared fields
<p>My table definition:</p> <pre><code>class AppProperties(base): __tablename__ = &quot;app_properties&quot; key = Column(String, primary_key=True, unique=True) value = Column(String) </code></pre> <p>Code for updating an app property:</p> <pre><code>session = Session() query = session.query(AppProperties)....
<python><sqlalchemy>
2023-05-22 09:57:32
1
1,276
AllSolutions
76,304,987
3,849,662
Stacked bar charts with differing x axes
<p>I am using matplotlib to create a stacked barchart.</p> <p>I have multiple arrays to plot but will simplify it to 2 for the sake of this questions.</p> <pre><code>rates = [4, 4.1, 4.2, 4.3, 4.4, 4.5] counts = [12, 17, 22, 9, 12, 18] rates1 = [4.3, 4.4] counts1 = [24, 17] </code></pre> <p>I want to plot a barchart f...
<python><matplotlib>
2023-05-22 09:56:46
1
773
Joe Smart
76,304,851
1,113,579
VSCode Intellisense for SQLAlchemy query result
<p>Below is a code fragment for querying a table using SQLAlchemy and reading the first record:</p> <pre><code>session = Session() customer = session.query(Customer).filter(Customer.name == &quot;John&quot;).first() customer.age = 50 </code></pre> <p>In the 3rd line of code <code>customer.age = 50</code>, the VSCode In...
<python><visual-studio-code><sqlalchemy><intellisense>
2023-05-22 09:40:47
2
1,276
AllSolutions
76,304,808
11,230,924
Python regex to match identical city names but formatted differently
<p>In a Python regex, I am trying to compare identical city names that are formatted differently (uppercase/lowercase, separated by spaces or hyphens, characters with different cases). For example, &quot;Paris&quot; and &quot;paris&quot;, &quot;New York&quot; and &quot;neW-york&quot; should match, but not &quot;Paris&q...
<python><string><compare>
2023-05-22 09:36:07
3
381
Zembla
76,304,798
7,214,344
Finding nearest neighbor pixel from a binary mask
<p>I have a matrix and a binary mask. For example: Matrix is</p> <pre><code>array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) </code></pre> <p>And binary mask is</p> <pre><code>array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1]]) </code>...
<python><opencv><breadth-first-search><flood-fill>
2023-05-22 09:34:42
0
19,734
Miriam Farber
76,304,767
4,266,314
How to retrieve a Hive query as a DataFrame?
<p>I want to connect to a Hive database via ODBC using <code>sqlalchemy</code>. I managed to connect and query using <code>pyodbc</code> instead of <code>sqlalchemy</code>. Here is what I've done:</p> <pre class="lang-py prettyprint-override"><code>import pyodbc import pandas as pd cnxn = pyodbc.connect(&quot;DSN=my_d...
<python><pandas><sqlalchemy><hive><pyodbc>
2023-05-22 09:30:46
1
1,958
der_grund
76,304,601
17,638,206
Importing a module from a different path in the same project
<p>I have the following project structure :</p> <pre><code>-project -src -package1 -script1.py -__init__.py -package2 -script2.py - __init__.py -__init__.py </code></pre> <p>Now <code>script1.py</code> includes two functions :</p> <pre><code>def my funct1(): print(&quot;Hello&q...
<python><python-3.x>
2023-05-22 09:10:20
1
375
AAA
76,304,449
1,497,720
TFAutoModelForSeq2SeqLM requires the TensorFlow library but it was not found in your environment
<p>For code below:</p> <pre><code>from transformers import TFAutoModelForSeq2SeqLM, AutoTokenizer from transformers import pipeline # Load the pre-trained T5 model and tokenizer model_checkpoint = &quot;t5-small&quot; model = TFAutoModelForSeq2SeqLM.from_pretrained(model_checkpoint) tokenizer = AutoTokenizer.from_pretr...
<python><python-3.x><tensorflow><huggingface-transformers><transformer-model>
2023-05-22 08:49:55
1
18,765
william007
76,304,401
12,435,792
Convert to pd.to_timedelta(unit='m') not working
<pre><code>df.loc[i,'time in queue']=datetime.datetime.now()-df.loc[i,'IST DateTime'] actual_time_left=float(sla_dict.get( df.loc[i,'SLA Type'])-df.loc[i,'time in queue'].total_seconds()/60) df.loc[i,'actual time left']=pd.to_timedelta(actual_time_left,unit='m') </code></pre> <p>where,</p> <pre><code>df.loc[i,'IST Date...
<python><pandas><datetime>
2023-05-22 08:40:55
0
331
Soumya Pandey
76,304,343
16,933,406
dataframe to excel with styling (background and color)
<p>I have a data frame as below and want to apply two conditions for the styling and save into excel.</p> <p>I could perform either of the condition at a time but not the both simultaneously.</p> <blockquote> <p><strong>input:</strong> dataframe (2 colums) and a given_list(index numbers)</p> <p><strong>condition_1:</st...
<python><pandas><dataframe><pyexcel>
2023-05-22 08:32:30
3
617
shivam
76,304,330
6,220,759
Splitting on a character which should always be at the beginning of a group
<p>I would like to split a string based on the following rules:</p> <ul> <li>if it contains 0 bullets (•), return the whole string</li> <li>if it contains 1 or more bullets, return the string up until the bullet, and then a new group starting with each bullet.</li> </ul> <p>Example:</p> <pre><code>&quot;Python is: • Gr...
<python><regex>
2023-05-22 08:31:18
0
11,757
Josh Friedlander
76,304,244
10,970,202
Tensorboard profiler tab not showing anything behind corporate firewall
<p>Versions: python3.7, tensorflow 2.9.1, tensorboard 2.9.1, tensorboard-plugin-profile==2.11.2.</p> <p>tb_callback is passed in as follows</p> <pre><code>tb_callback = tf.keras.callbacks.TensorBoard(logdir=path_tologdir, histogram_freq=1, profile_batch=(1,5)) model.fit(train_ds, validation_data=valid_ds, callbacks=[tb...
<python><tensorflow><deep-learning><tensorboard>
2023-05-22 08:18:09
0
5,008
haneulkim
76,304,096
6,330,106
Thread.join() differences between Python2.7 and Python3.x
<p>In a tutorial on threading.Lock, it gives an example of two threads writing the same global variable without any lock. The tutorial doesn't specify which version of Python it uses.</p> <pre><code>import threading num = 0 def add(): global num for i in range(1000000): num += 1 def desc(): gl...
<python><python-multithreading><python-3.10>
2023-05-22 07:59:11
0
31,575
ElpieKay
76,303,957
9,962,007
“Launch Classic Notebook” option is gone from the JupyterLab Help menu
<p>The deprecation of Notebook in favor of Lab is going on and since JupyterLab 4.0.0 the dependency on Notebook and with it also the useful backward compatibility option “Launch Classic Notebook” was removed from JupyterLab Help menu. Any workarounds?</p>
<python><jupyter-notebook><jupyter><jupyter-lab>
2023-05-22 07:40:35
1
7,211
mirekphd
76,303,713
2,000,548
How to add a new column when writing to a Delta table?
<p>I am using <a href="https://github.com/delta-io/delta-rs" rel="nofollow noreferrer">delta-rs</a> to write to a Delta table in the Delta Lake. Here is my code:</p> <pre class="lang-py prettyprint-override"><code>import time import numpy as np import pandas as pd import pyarrow as pa from deltalake.writer import write...
<python><apache-spark><delta-lake><data-lakehouse><delta-rs>
2023-05-22 07:04:26
2
50,638
Hongbo Miao
76,303,698
1,631,414
How do I move to a specific offset in a Kafka consumer without running into a ValueError?
<p>I'm using python 3.9.16 and kafka-python version 2.0.2. I'm running on my Macbook Pro IOS 11.6.5.</p> <p>New to Kafka and just playing around with it for now. I'm not sure what the issue is and I'm not sure why my workaround works.</p> <p>What I'm trying to do is seek to a specific offset on the topic but I routin...
<python><apache-kafka><kafka-consumer-api>
2023-05-22 07:02:23
1
6,100
Classified
76,303,651
4,420,797
Customize accuracy graph with lines and shapes
<p>I wrote a simple code to construct a graph and it works fine. But, I have no idea how I can modify it like below? How to customize lines in matplotlib?</p> <p><strong>Requirement:</strong></p> <p><a href="https://i.sstatic.net/Wl9ix.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Wl9ix.png" alt="enter...
<python><python-3.x><matplotlib>
2023-05-22 06:54:15
1
2,984
Khawar Islam
76,303,563
11,720,193
AWS Lambda import error: Unable to import module "lambda_function"
<p>I am trying to run a simple program in AWS Lambda. However, it is failing with <code>DEFAULT_CIPHERS</code> error. When I run the following program it <strong>fails</strong> with error <code>...unable to import lambda function</code>:</p> <pre><code>import json import boto3 import os import requests def lambda_hand...
<python><amazon-web-services><aws-lambda>
2023-05-22 06:39:33
1
895
marie20
76,303,520
1,780,761
PyQt5 - Move QTcpServer to subprocess
<p>I am trying to run a QtcpServer on a different thread or even better on a subprocess in python using PyQt5.</p> <p>Running it on a different QThread I get this error as soon as the server tries to send something to the client:</p> <p>QObject: Cannot create children for a parent that is in a different thread. (Parent...
<python><pyqt5><subprocess><qthread><qtcpserver>
2023-05-22 06:28:57
0
4,211
sharkyenergy
76,303,325
19,106,705
torch.nn.Parameter to nn.Module
<p>I want to replace the parameters inside a model with a custom nn.Module layer that I created. Below is a very simplified example of the code I desire.</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>import torch import torch.nn as nn class change_to_layer(nn.Module): def __init__(self): super...
<python><pytorch>
2023-05-22 05:46:58
0
870
core_not_dumped
76,303,248
2,966,197
python streamlit sidebar resetting on entry of input
<p>I am creating a <code>streamlit</code> app where on the sidebar I have first a file uploader and a button. Once the file is uploaded and then the button is pressed, it shows more input option and two more buttons for user to finally sumbit. When I am at the second step, after user enters the input, it resets the sid...
<python><streamlit>
2023-05-22 05:28:04
1
3,003
user2966197
76,303,103
4,725,226
how to save a file outside the docker container with python
<p>So I have this structure:</p> <p>myapp</p> <ul> <li>Dockerfile</li> <li>main.py</li> <li>req.txt</li> </ul> <p>this is the content of my Dockerfile:</p> <pre><code>FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r req.txt RUN playwright install RUN play...
<python><docker><docker-volume>
2023-05-22 04:47:48
3
503
Raul Quinzani
76,303,026
3,449,555
create a union of 3 files with different column headers and rows
<p>I have three text files with different number of rows and columns. The column names are different in each file. There are some overlapping rows and many unique rows.</p> <p>file1.txt</p> <pre><code>SNP CHROM POS ref alt GT info sample1 sample2 sample3 sample4 sample5 snp1 1 1 A c . PR 0/0 0/1 0/0...
<python><r><merge>
2023-05-22 04:25:26
0
309
biobudhan
76,302,926
507,852
Python 3.11 - how to detect socket closed by peer when working with Asyncio Streamers?
<p>I'm testing the TCP echo client example script in Python 3.11 Asyncio Streamer official document. It worked as expected, but doesn't seem to detect whether the socket is closed by peer.</p> <p>The client side code:</p> <pre><code>import socket import asyncio async def echo_client(addr,port): r,w = await asyncio...
<python><sockets><python-asyncio>
2023-05-22 03:46:55
1
1,982
RichardLiu
76,302,815
11,198,558
Issue when running win32com on Window 11
<p>I'm now running Python on Window 11 to read Excel File protected with password. the python Script is as below</p> <pre><code> import win32com.client file_path = '&lt;my_file_path&gt;' xlApp = win32com.client.Dispatch(&quot;Excel.Application&quot;) xlwb = xlApp.Workbooks.qOpen(file_path, False, True, None, passwor...
<python><win32com>
2023-05-22 03:06:26
1
981
ShanN
76,302,784
3,394,510
Trouble making mypy and phonenumbers module work, implementation missing
<p>I installed python's <a href="https://pypi.org/project/phonenumbers/" rel="nofollow noreferrer"><code>phonenumbers&gt;=3.12.32</code></a>, which should include the stub files, but when I run <code>mypy</code> it yields:</p> <pre><code>$ mypy -m module module.py:22: error: Cannot find implementation or library stub ...
<python><mypy><python-typing>
2023-05-22 02:51:24
0
840
ekiim
76,302,654
2,326,961
Why does property override object.__getattribute__?
<p>I noticed that contrary to the <code>classmethod</code> and <code>staticmethod</code> decorators, the <code>property</code> decorator overrides the <code>object.__getattribute__</code> method:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; list(vars(classmethod)) ['__new__', '__repr__', '__get__', ...
<python><python-descriptors>
2023-05-22 02:00:35
1
8,424
Géry Ogam
76,302,642
7,530,306
discord.py: sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
<pre><code>Traceback (most recent call last): File &quot;bot.py&quot;, line 55, in &lt;module&gt; send_cal.start() File &quot;python3.8/site-packages/discord/ext/tasks/__init__.py&quot;, line 398, in start self._task = asyncio.create_task(self._loop(*args, **kwargs)) File &quot;/usr/local/Cellar/python@3....
<python><discord><python-asyncio>
2023-05-22 01:56:52
1
665
sf8193
76,302,550
1,469,208
Replace space with a random character (there and back) in Python
<h2>The problem</h2> <p>I have a <em>haystack</em>:</p> <pre><code>source = ''' &quot;El Niño&quot; &quot;Hi there! How was class?&quot; &quot;Me&quot; &quot;Good...&quot; &quot;I can't bring myself to admit that it all went in one ear and out the other.&quot; &quot;But the part of the lesson abou...
<python><replace><unicode><space>
2023-05-22 01:13:47
2
17,573
trejder
76,302,435
5,212,614
How can we merge column headers from multiple CSVs into one dataframe, and list source file names for each file in one column?
<p>Here is the code that I am testing.</p> <pre><code># import necessary libraries import pandas as pd import os import glob # use glob to get all the csv files # in the folder path = 'C:\\Users\\' csv_files = glob.glob(os.path.join(path, &quot;*.csv&quot;)) csv_files df_headers = pd.DataFrame() # loop over ...
<python><python-3.x><pandas><dataframe><loops>
2023-05-22 00:26:18
1
20,492
ASH
76,302,219
2,840,680
Modify the legend placement of a figure
<p>I am using a package program that return me a <code>matplotlib.figure</code> object together with a legend. I want to change the bounding box and placement of the legend. After checking <a href="https://matplotlib.org/stable/api/figure_api.html" rel="nofollow noreferrer">https://matplotlib.org/stable/api/figure_api....
<python><matplotlib><legend>
2023-05-21 22:44:18
1
785
Vesnog
76,302,191
9,506,773
What to tests in ci run vs pytest, and why
<p>I have a python repo in github. If I understood it correctly there are mainly two ways in which tests can be automated:</p> <ul> <li>using <code>run</code> in a <code>ci.yml</code> file</li> <li>using <code>test_...</code> files under a folder called <code>test</code> (at root level) and then execute them in the ci ...
<python><github><testing><pip><continuous-integration>
2023-05-21 22:32:21
1
3,629
Mike B
76,302,149
9,352,077
imshow with twinx that is also aligned with tiles
<p>There <a href="https://stackoverflow.com/questions/48255824/matplotlib-imshow-with-second-y-axis">is a thread</a> where the question was to add an automatically labelled <code>twinx</code> to Matplotlib's <code>imshow</code>. The result was:</p> <p><a href="https://i.sstatic.net/50zmU.png" rel="nofollow noreferrer">...
<python><matplotlib><imshow><twinx><yticks>
2023-05-21 22:17:12
1
415
Mew
76,301,901
1,259,561
Why does timeit results in almost constant time for all memoization runs?
<p>We compute the Fibonacci number:</p> <pre class="lang-py prettyprint-override"><code>def fibo_memo(i, memo={}): if i &lt;= 0: return 0 elif i == 1: return 1 elif i in memo: return memo[i] else: memo[i] = fibo_memo(i-2, memo) + fibo_memo(i-1, memo) return memo[i...
<python><performance><dynamic-programming><memoization>
2023-05-21 20:59:51
1
3,659
THN
76,301,828
3,482,266
How to set a Pydantic field value depending on other fields
<pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Grafana(BaseModel): user: str password: str host: str port: str api_key: str | None = None GRAFANA_URL = f&quot;http://{user}:{password}@{host}:{port}&quot; API_DATASOURCES = &quot;/api/datasources&quot; ...
<python><pydantic>
2023-05-21 20:35:57
1
1,608
An old man in the sea.
76,301,807
12,144,502
Comparison of BFS and DFS algorithm for the Knapsack problem
<p>I am fairly new to python and I have a task which tells me to compare both algorithm time expended and space used in memory.</p> <p>I have coded both algorithms and ran them both. I was able to measure the time used, but wasnt able to look for ways to know how much space was used. I am also not sure if the question ...
<python><python-3.x><algorithm><knapsack-problem>
2023-05-21 20:28:39
1
400
zellez11
76,301,728
7,533,650
Getting around "Enable JavaScript and cookies to continue" error when web scraping w/ Python
<p>I recently wrote a script to scrape the front-end of a website, but recently have run into issues with enabling Javascript and cookies so I can pull the data. I'm not sure if this is a new captcha that was implemented, but have made several attempts at getting around this error, as shown below:</p> <pre><code>Traceb...
<python><python-3.x><web-scraping><python-requests>
2023-05-21 20:07:52
0
303
BorangeOrange1337
76,301,694
6,223,346
TypeError - read csv functionality
<p>I am getting a Type error when reading a csv file with a bell character as a separator. I don't want to use the pandas and need to utilize the csv libraries for this issue.</p> <p>Sample header:</p> <pre><code>[&quot;header1&quot;, &quot;header2&quot;, &quot;header3&quot;] </code></pre> <p>Data types</p> <pre><code>...
<python><python-3.x><csv><delimiter><csvreader>
2023-05-21 19:59:11
1
613
Harish
76,301,661
13,630,719
How to render different UI contexts in a loop within a Django project?
<p>Suppose I have the following code:</p> <pre><code>async def home(request): if request.method == &quot;POST&quot;: number = &quot;3&quot; context = {&quot;number&quot;: number} return render(request, 'home/home.html', context) </code></pre> <p>I want to have a website that returns differen...
<python><django><loops><render>
2023-05-21 19:50:37
0
1,342
ENV
76,301,530
10,266,059
What is os.Mapping and why isn't it in the os documentation?
<p>I am learning python and while using <code>dir()</code> to examine the <code>os</code> module I found an entry called <code>Mapping</code>. I tried to examine it:</p> <pre><code>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import os &gt;...
<python>
2023-05-21 19:15:44
1
1,676
Aleksey Tsalolikhin
76,301,422
9,542,989
Import Classes from Modules of Python Package to __init__
<p>In the Python package that I am working on there is a sub-package within it which contains a bunch of modules. Each module consists of a class.</p> <p>Now, this package is meant to be extensible and there can be new modules introduced anytime. Similar to the existing modules, any new module introduced will also cons...
<python><python-packaging>
2023-05-21 18:48:29
1
2,115
Minura Punchihewa
76,301,261
8,702,633
dotenv install error: "error: invalid command 'dist_info'"
<p>I'm getting an error installing dotenv on macOS:</p> <pre><code>Collecting dotenv Using cached dotenv-0.0.5.tar.gz (2.4 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... error error: subprocess-exited-with-error × pip subprocess...
<python><pip><dotenv>
2023-05-21 18:04:53
3
331
Max
76,301,208
4,019,495
VS Code Python: unable to get auto import suggestions
<p>I'm using VS Code on Linux. <a href="https://code.visualstudio.com/docs/python/editing#_enable-auto-imports" rel="nofollow noreferrer">Auto imports</a> do not work for me.</p> <p>Here is a screenshot:</p> <p><a href="https://i.sstatic.net/ipQKe.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ipQKe.png...
<python><visual-studio-code>
2023-05-21 17:52:53
1
835
extremeaxe5
76,301,163
12,908,701
How to use choices of a Select field of a form, when defined in the view in Django?
<p>I have an issue with a form with a Select input. This input is used to select a user in a list. The list should only contain user from the group currently used.</p> <p>I found a solution, however I am not completely sure of what am I doing in the form definition (I do not fully understand how works the <code>def __i...
<python><django><forms><selectinput>
2023-05-21 17:41:06
1
563
Francois51
76,301,107
20,443,528
How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model?
<p>How to sort a model's objects if the model has foreign key relations and I have to sort based on the properties of the foreign model?</p> <p>Here is my model</p> <pre><code>class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxVal...
<python><django><django-models><django-queryset>
2023-05-21 17:25:47
1
331
Anshul Gupta
76,301,087
4,451,315
polars: list to columns, without `get`
<p>Say I have:</p> <pre class="lang-py prettyprint-override"><code>In [1]: df = pl.DataFrame({'a': [[1,2], [3,4]]}) In [2]: df Out[2]: shape: (2, 1) ┌───────────┐ │ a │ │ --- │ │ list[i64] │ ╞═══════════╡ │ [1, 2] │ │ [3, 4] │ └───────────┘ </code></pre> <p>I know that all elements of <code>'a'</co...
<python><dataframe><python-polars>
2023-05-21 17:21:17
1
11,062
ignoring_gravity
76,300,991
6,640,504
How to assign a constant value to all records of the pyspark dataframe window
<p>I have a pyspark dataframe like this:</p> <pre><code>+-------+-------+ | level | value | +-------+-------+ | 1 | 4 | | 1 | 5 | | 2 | 2 | | 2 | 6 | | 2 | 3 | +-------+-------+ </code></pre> <p>I have to create a value for every group in <strong>level</strong> column and save th...
<python><apache-spark><pyspark>
2023-05-21 16:53:39
0
1,172
M_Gh
76,300,983
8,235,224
How to interpret word2vec train output?
<p>Running the code snippet below report an output (3, 60). I wonder what exactly it is reporting?</p> <p>The code is reproducible..just copy into a notebook cell and run.</p> <pre><code>from gensim.models import Word2Vec sent = [['I', 'love', 'cats'], ['Dogs', 'are', 'friendly']] w2v_model = Word2Vec(sentences=sen...
<python><nlp><word2vec>
2023-05-21 16:52:10
1
2,943
Regi Mathew
76,300,901
6,258,636
Create a Python list with every combination of '+', '-', '*', and '/' strings
<p>I am trying to build a 2d list of test cases that contains all the possible cases ('+', '-', '*', '/') like this:</p> <pre><code>[('+', '+', '+', '+'), ('+', '+', '+', '-'), ('+', '+', '+', '/'), ('+', '+', '+', '*'), ('+', '+', '-', '-'), ('+', '+', '-', '/'), ('+', '+', '-', '*'), ('+', '+', '/', '/'), ('+...
<python>
2023-05-21 16:33:47
1
1,434
Ken
76,300,464
2,876,994
How to be more precise calculation elapsed time using python request?
<p>I'm trying to simulate a SQLMap exploting a SQL injection Time Based.</p> <pre><code>resultado = &quot;&quot; listaCaracteres = string.ascii_letters + string.digits + &quot;._-@/&quot; delay = 5 tamanhoCampo = 30 for i in range(1,tamanhoCampo+1): caracterFound = False for char in listaCaracters: data = { ...
<python><request><sql-injection><elapsedtime>
2023-05-21 14:46:08
0
1,552
Shinomoto Asakura
76,300,455
5,617,608
Welcome emails sent by Frappe framework are missing the port number
<p>When using Frappe framework and changing the Nginx port from 80 to 8002 to avoid conflicts, I get broken URLs in all emails sent by the system. The port was changed using <code>bench set-nginx-port 8002</code>. The ports 80 and 8000 are already busy in the VPS.</p> <p>While I access the system using hostname:port_nu...
<python><nginx><erpnext><frappe>
2023-05-21 14:44:23
1
1,759
Esraa Abdelmaksoud
76,300,404
7,987,455
Why is "requests-html" not rendering all HTML content?
<p>I am trying to scrape data, but the script is not loading all html content, although I changed the rendering time. Please see the code below:</p> <pre><code>from requests_html import HTMLSession, AsyncHTMLSession url = 'https://www.aliexpress.com/w/wholesale-test.html?catId=0&amp;initiative_id=SB_20230516115154&amp...
<python><web-scraping><beautifulsoup><python-requests><html-rendering>
2023-05-21 14:31:50
0
315
Ahmad Abdelbaset
76,300,362
20,220,485
How do you reconcile a list of tuples containing a tokenized string with the original string?
<p>I am trying to reconcile <code>idx_tag_token</code>, which is a list of tuples containing a tokenized string and its label and character index, with the original string <code>word_string</code>. I want to output a list of tuples, with each tuple containing an element of the original string if split on whitespace, a...
<python><string><indexing><tuples><tokenize>
2023-05-21 14:20:24
1
344
doine
76,300,306
5,838,180
How to cross match with python 2 dataframes by (Cartesian) coordinates?
<p>I have 2 astronomical catalogues, containing galaxies with their respective sky coordinates (ra, dec). I handle the catalogues as data frames. The catalogs are from different observational surveys and there are some galaxies that appear in both catalogs. I want to cross match these galaxies and put them in a new cat...
<python><pandas><database><astropy><cross-match>
2023-05-21 14:09:07
1
2,072
NeStack
76,300,212
14,366,549
Problems combining tensorflow with huggingGPT transformers on a python project
<p>This is my code:</p> <pre><code>mport os from dotenv import load_dotenv from database import create_connection import mysql.connector # from user_interface import user_interface from flask import Flask, request, jsonify import pandas as pd import mysql.connector from transformers import BertTokenizer, TFBertForSeque...
<python><tensorflow><huggingface-transformers>
2023-05-21 13:46:32
1
433
thelittlemaster
76,300,143
17,835,656
why the issuer name is reversed when i get it using python?
<p>i have a certificate and when i use python to get the issuer name of the certificate i get the issuer name reversed :</p> <p>the correct issuer name : <code>CN=PEZEINVOICESCA2-CA,DC=extgazt,DC=gov,DC=local</code></p> <p>the issuer name that i get : <code>DC=local,DC=gov,DC=extgazt,CN=PEZEINVOICESCA2-CA</code></p> <p...
<python><cryptography><ssl-certificate><certificate><x509certificate>
2023-05-21 13:28:07
1
721
Mohammed almalki
76,300,038
5,838,180
In python how to cross match sources with a given mask?
<p>I have a dataframe that is a catalogue of astronomical sources (galaxies) spread across most of the sky. I also have a <code>.fits</code> binary mask that covers only some parts of the sky (see below). I want to cross-match the catalogue with the mask to get only the galaxies that fall within the mask. How can I do ...
<python><pandas><astropy><healpy><cross-match>
2023-05-21 13:04:40
1
2,072
NeStack
76,299,972
12,096,670
Accessing a variable of one method inside another method in the same class - Python
<p>Let's say I have class, MandM, as indicated below with different methods. I want all the variables in each method to be accessible to all other methods in the class because I may need them in other methods.</p> <p>So what I am doing is like in the example below, where I call a method within another method and then a...
<python><class><methods>
2023-05-21 12:46:13
1
845
GSA
76,299,903
2,469,105
Using Python Sphinx getting WARNING: duplicate object description of myproject / use :noindex: for one of them
<p>I'm using Sphinx to create HTML documentation for a Python project.</p> <p>TL;DR I cannot get rid of this warning message.</p> <pre><code>WARNING: duplicate object description of myproject, other instance in class-stubs/Bar, use :noindex: for one of them </code></pre> <p>I want the index page to look like this:</p>...
<python><python-sphinx><autodoc>
2023-05-21 12:26:55
2
951
David I
76,299,315
11,801,298
Set place of each bar in matplotlib
<p>This is working code. It creates bars of specific length.</p> <pre><code># creating the dataset data = {'C':20, 'C++':15, 'Java':30, 'Python':35} courses = list(data.keys()) values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # creating the bar plot plt.bar(courses, values, color ='maroon',...
<python><matplotlib>
2023-05-21 10:02:48
2
877
Igor K.
76,299,098
14,950,385
Is it possible to implement a provider method on top of python?
<p>I'm trying to control my laptop fan speed using WMI in python.</p> <p>This is my python code:</p> <pre class="lang-py prettyprint-override"><code>import wmi c = wmi.WMI () cim_fan = c.CIM_Fan() fan_speed = 4000 cim_fan[0].SetSpeed(fan_speed) </code></pre> <p>But it throws this error:</p> <pre><code>Traceback (most ...
<python><winapi><wmi><cim>
2023-05-21 09:08:10
0
2,695
Ali Ent
76,298,985
12,285,101
Reduce pandas data frame to have one column with list of repeating values
<p>I have the following dataframe:</p> <pre><code>index name path 0 Dina &quot;gs://my_bucket/folder1/img1.png&quot; 1 Dina &quot;gs://my_bucket/folder1/img2.png&quot; 2 Lane &quot;gs://my_bucket/folder1/img3.png&quot; 3 Bari &quot;gs://my_bucket/folder1/img4.png&quot; 4 ...
<python><pandas><aggregate>
2023-05-21 08:37:50
2
1,592
Reut
76,298,900
3,646,265
Django CORS issue with VUE
<p>I am running python 3.11.3 with the following packages:</p> <pre><code>Package Version ------------------- ------- asgiref 3.6.0 Django 4.2.1 django-cors-headers 4.0.0 pip 23.1.2 setuptools 67.6.1 sqlparse 0.4.4 whitenoise 6.4.0 </code...
<python><django><vue.js><cors>
2023-05-21 08:12:57
0
383
developthou
76,298,596
2,000,548
How to delete Prefect blocks in Python?
<p>I am using Prefect 2.</p> <p>I am able to create Prefect blocks, for example, AWS Credentials and Kubernetes Job blocks by</p> <pre class="lang-py prettyprint-override"><code>from prefect_aws import AwsCredentials from prefect.infrastructure import KubernetesJob async def create(): await AwsCredentials( ...
<python><prefect>
2023-05-21 06:34:12
2
50,638
Hongbo Miao
76,298,402
7,987,987
how to get league id for players based on data in matches column
<p>I have 2 dataframes for soccer info:</p> <ul> <li><code>matches</code>: info on individual matches. Contains columns for the ID of the league in which the match was played, the date the match was played, the season the match was played, and has 22 columns of player IDs (<code>home_player_1</code>, <code>home_player_...
<python><pandas><dataframe>
2023-05-21 05:22:25
1
936
Uche Ozoemena
76,298,170
8,616,751
Shape of predictors for geospatial 3D CNN
<p>I can't get my mind around how to build a 3D CNN in python to account for spatial features. I have one target variable (binary classification) and say three predictor variables (continuous). All variables have 35 timesteps, 137 latitudes and 181 longitudes. I made a dummy script</p> <pre><code>import numpy as np fro...
<python><keras><conv-neural-network>
2023-05-21 03:26:11
1
303
scriptgirl_3000
76,298,101
19,270,168
Cannot create a client socket with a PROTOCOL_TLS_SERVER context while trying to rank a player in-group
<pre class="lang-py prettyprint-override"><code>import robloxapi async def grouprank(userId, rankName): # omitted rank-name to role id mapping rankId = dic[rankName] client = robloxapi.Client(cookie=NOT_STUPID_ENOUGH_TO_DISCLOSE) grp = await client.get_group(32409863) await robloxapi.client.Group.s...
<python><python-3.x><roblox>
2023-05-21 02:52:20
2
1,196
openwld
76,298,066
11,885,185
How to solve broadcast issue in Deep Learning?
<p>I have an issue with my code, at broadcasting.</p> <p>I got this error at Step 8:</p> <pre><code>ValueError: non-broadcastable output operand with shape (1062433,1) doesn't match the broadcast shape (1062433,2) </code></pre> <p>and I have this code:</p> <p>Step 1: Read the data</p> <pre><code>df = pd.read_csv('file...
<python><tensorflow><scikit-learn><deep-learning>
2023-05-21 02:33:18
1
612
Oliver
76,297,961
6,056,160
Using Selenium to click a input type submit button
<p>Trying to click this</p> <pre><code>&lt;input type=&quot;submit&quot; value=&quot;Log In&quot; class=&quot;btn btn-lg btn-primary btn-block&quot;&gt; </code></pre> <p>I have tried</p> <pre><code>driver.find_element(&quot;class&quot;, &quot;btn&quot;).click() driver.find_element(&quot;class&quot;, &quot;btn btn-lg b...
<python><selenium-webdriver><input><click><submit>
2023-05-21 01:39:04
1
5,241
Runner Bean
76,297,916
5,431,734
compare operation in a pandas rolling window
<p>I want to make a rolling window and compare the elements in this window with the most recent one. In fact I want to subtrack the last value from all the the others. For example if we have the dataframe</p> <pre><code>df = pd.DataFrame([ [2, 3, 5, 7,], [8, 3, 6, 1], [1, 5, 9, 13], [7, 3, 2, 7], [1...
<python><pandas>
2023-05-21 01:11:35
2
3,725
Aenaon
76,297,879
4,115,031
Benchmarks of FastAPI vs async Flask?
<p>I'm a developer without an interest in benchmarking and I'm trying to decide whether I should use Flask or FastAPI to build some Python/Vue projects. I'm seeing stuff online about how FastAPI was faster than Flask because Flask was single-threaded or something like that, whereas FastAPI was async, but apparently mo...
<python><flask><fastapi>
2023-05-21 00:53:26
1
12,570
Nathan Wailes
76,297,824
2,769,240
PyPDF2 unable to compress pdf
<p>I want to show an embed pdf on streamlit app which has a limitation of &lt;2MB pdf size to be displayed.</p> <p>So I am trying to compress the pdf file which a user uploads via st.file_uploader on streamit app using PyPDF2 package. Here's the code I used:</p> <pre><code>from PyPDF2 import PdfReader, PdfWriter from i...
<python><streamlit><pypdf>
2023-05-21 00:22:04
5
7,580
Baktaawar
76,297,696
3,034,686
Can't update a record using flask-restx sqlalchemy mariadb v10.5.20 "(mariadb.NotSupportedError) Data type 'tuple'"
<p><a href="https://github.com/christianbueno1/flask-api" rel="nofollow noreferrer">github repository</a></p> <p>This is a simple REST API, have 2 classes Client, Product.</p> <p><strong>Relationship:</strong> A client can have many products, Client 1---* Product.</p> <p>I can list, create, search by id, with the 2 mod...
<python><flask><sqlalchemy><mariadb><flask-restx>
2023-05-20 23:17:37
1
592
christianbueno.1
76,297,649
2,781,105
Auto ARIMA in Python results in poor fitting prediction of trend
<p>New to ARIMA and attempting to model a dataset in Python using auto ARIMA. I'm using auto-ARIMA as I believe it will be better at defining the values of p, d and q however the results are poor and I need some guidance. Please see my reproducible attempts below</p> <p>Attempt as follows:</p> <pre><code> # DEPENDEN...
<python><data-science><prediction><arima><pmdarima>
2023-05-20 23:02:23
2
889
jimiclapton
76,297,471
3,130,747
How to read a csv file from google storage using duckdb
<p>I'm using duckdb version <code>0.8.0</code></p> <p>I have a CSV file located in google storage <code>gs://some_bucket/some_file.csv</code> and want to load this using duckdb.</p> <p>In pandas I can do <code>pd.read_csv(&quot;gs://some_bucket/some_file.csv&quot;)</code>, but this doesn't seem to work in duckdb. I see...
<python><csv><google-cloud-platform><duckdb>
2023-05-20 21:46:00
2
4,944
baxx
76,297,358
12,436,050
Replace characters and extract substrings from pandas dataframe
<p>I have following pandas dataframe. I would like to replace some characters and extract substrings (there exists more rows in the original dataframe).</p> <p>I am using following regex but I am unable to replace '?' from some rows like row 6, 7, 8.</p> <pre><code>df[['label', 'id']] = df['name'].str.extract(r'\{?\??\...
<python><pandas><regex>
2023-05-20 21:09:43
2
1,495
rshar