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
75,722,182
12,297,666
How to sum the values of a series into a dataframe based on a mask numpy array
<p>I have the following variables:</p> <pre><code>import pandas as pd import numpy as np y = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['A', 'B', 'C']) mask_y = np.array([[True, False, False], [False, False, True], [False, False, False]]) dist_y = pd.Series([0.222, 0.333, 0.444]) </code></pre> <p>I need ...
<python><pandas><numpy>
2023-03-13 12:59:09
3
679
Murilo
75,721,741
2,131,621
Building an AMI using Packer with Python & Python modules (using pip) installed via powershell script
<p>Using Packer, I am trying to create a Windows AMI with Python + the cryptography module installed. Here is the installation command I'm using for Python:</p> <pre><code>Invoke-Expression &quot;python-3.6.8-amd64.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0&quot; </code></pre> <p>Standalone that works fi...
<python><amazon-web-services><powershell><amazon-ami><packer>
2023-03-13 12:14:56
1
535
Jay
75,721,736
3,561,433
Plot Angular Grid with filled cells based on Color Map
<p>I would like to do a transformation between two coordinate systems and also like to show filled cells accordingly as shown below:-</p> <p><a href="https://i.sstatic.net/sZfxr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sZfxr.png" alt="enter image description here" /></a></p> <p>I have been able to...
<python><matplotlib><colors>
2023-03-13 12:14:24
1
522
Manish
75,721,623
8,176,763
airflow cannot return io.stringIO from a simple dag definition
<p>Given the following dag definition:</p> <pre><code>import datetime import pendulum import io from airflow.decorators import dag, task @dag( dag_id=&quot;my_beauty&quot;, schedule_interval=&quot;0 0 * * *&quot;, start_date=pendulum.datetime(2023, 3, 13, tz=&quot;UTC&quot;), catchup=False, dagrun...
<python><airflow>
2023-03-13 12:02:54
1
2,459
moth
75,721,613
11,688,559
Access the parameters names of a Scipy distribution that has not yet been instantiated
<p>This question has been asked before <a href="https://stackoverflow.com/questions/47449991/how-to-programatically-get-parameter-names-and-values-in-scipy">here</a>. However, the solution does not seem to work with the current version of Scipy any more.</p> <p>To review, I would like to know what parameters some arbit...
<python><scipy>
2023-03-13 12:01:51
1
398
Dylan Solms
75,721,585
3,152,686
Response failing in httpx but not in requests
<p>I am making a POST request to a URL using '<strong>httpx</strong>' library. However, I get a <em><strong>401 unauthorized error</strong></em> with my below request</p> <pre><code>cert = os.path.realpath('./certs/certificate.pem') key = os.path.realpath('./certs/key.pem') context = ssl.create_default_context() contex...
<python><post><python-requests><httpx>
2023-03-13 11:59:11
1
564
Vishnukk
75,721,548
13,971,651
No module named 'debug_toolbar.urls' : version 3.1.1 installed
<p>settings.py</p> <pre><code>INSTALLED_APPS = ( 'debug_toolbar', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) </code></pre> <p>urls.py</p> <pre><code>if DEBUG: import debug_toolbar urlpatterns += url('__debug__/', inclu...
<python><django><django-debug-toolbar>
2023-03-13 11:55:00
1
373
puranjan
75,721,540
9,472,066
PySpark - how to set up environment variables (not Spark config)?
<p>On production cluster I am running Spark via <a href="https://github.com/GoogleCloudPlatform/spark-on-k8s-operator" rel="nofollow noreferrer">Spark Operator</a>, which allows me to set environment variables for driver and executors, so I can access them like in my PySpark script:</p> <pre><code>db_table = os.getenv(...
<python><docker><apache-spark><pyspark>
2023-03-13 11:54:35
1
1,563
qalis
75,721,229
6,761,328
Only list-like objects are allowed to be passed to isn()
<p>I have a dropdown menu:</p> <pre><code> dcc.Dropdown( id=&quot;select&quot;, options = list(all_df['Device'].unique()), value = list(all_df['Device'].unique()[0]) ...
<python><pandas><plotly-dash><isin>
2023-03-13 11:24:16
1
1,562
Ben
75,721,094
428,666
How to merge almost touching polygons
<p>How can I merge polygons that are almost touching, using Python? For example, given these polygons and some distance threshold T:</p> <p><a href="https://i.sstatic.net/SSFrI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SSFrI.png" alt="Input polygons" /></a></p> <p>The algorithm would produce someth...
<python><geometry><shapely>
2023-03-13 11:10:38
4
825
anttikoo
75,720,913
6,609,896
Collections.Counter add zero count elements
<p>I have this code to analyse the <code>node.properties</code> json dict for my data:</p> <pre><code>def summarise_all_model_properties( all_nodes: list ) -&gt; defaultdict[str, Counter[str]]: propdicts = defaultdict(Counter) for node in all_nodes: propdicts[node.model_type].update( k ...
<python><python-3.x><counter>
2023-03-13 10:53:26
2
5,625
Greedo
75,720,848
14,269,252
How to plot multiple category on the same y-axis using plotly express?
<p>I wrote the code as follows for visualization, I have DATE, CODE which I am showing as a scatter chart using plotly and color it based on source.</p> <p>X axis shows the time, Y axis shows the CODE (categorical variable)</p> <p>1- How to show each different source on the same Y axis but their Y axis defined?? curren...
<python><plotly>
2023-03-13 10:47:48
0
450
user14269252
75,720,784
6,213,883
How to provide hive metastore information via spark-submit?
<p>Using Spark 3.1, I need to provide the hive configuration via the <code>spark-submit</code> command (<strong>not</strong> inside the code).</p> <hr /> <p>Inside the code (which is not the solution I need), I can do the following which works fine (able to list database and select from tables. Removing the &quot;enabl...
<python><apache-spark><spark3><apache-spark-3.0>
2023-03-13 10:42:24
0
3,040
Itération 122442
75,720,635
11,630,148
Remove %20 from urls
<p>My urls in django have <code>%...</code>. How can I change that? At first this was ok but suddenly changed at some point in my day. My views, models and urls are as follow:</p> <pre class="lang-py prettyprint-override"><code>class Rant(UUIDModel, TitleSlugDescriptionModel, TimeStampedModel, models.Model): catego...
<python><django><django-urls>
2023-03-13 10:28:10
1
664
Vicente Antonio G. Reyes
75,720,582
10,207,281
Concurrency settings of my RedisSpider doesn't performance as expected
<p>I wrote a spider with scrapy-redis and python3.7.<br /> I set <strong>CONCURRENT_REQUESTS</strong> to 10.<br /> Here is my settings of the spider:</p> <pre><code> custom_settings = { &quot;DOWNLOADER_MIDDLEWARES&quot;: { &quot;projects.middlewares.MediaFileCheckMiddleware&quot;: 300, }...
<python><concurrency><scrapy>
2023-03-13 10:23:18
0
920
vassiliev
75,720,575
774,133
EOF in reading pickle in Jupyter notebook, but not in python interpreter
<p>I have a problem in opening a pickle in a Jupyter notebook. Unfortunately, I cannot share the data file, so I cannot provide a working example.</p> <p>For my data analysis I use a single conda environment <code>ai</code>. The same environment is used in a Jupyter notebook.</p> <p>I have a pickle that is 67M in size....
<python><jupyter-notebook>
2023-03-13 10:22:34
0
3,234
Antonio Sesto
75,720,310
784,433
broadcasting for matrix multiplication
<p>Consider the following</p> <pre class="lang-py prettyprint-override"><code>np.random.seed(2) result = SC @ x </code></pre> <p>SC is <code>nn x nn</code> and x is <code>nn x ns</code>.</p> <p>now consider we have a 3D SCs <code>ns x nn x nn</code>.</p> <pre class="lang-py prettyprint-override"><code>ns = 4 nn = 2 S...
<python><array-broadcasting>
2023-03-13 09:55:44
1
1,237
Abolfazl
75,720,210
429,476
Float storage precision in hardware only to 13 decimals
<p>There are many similar questions related to floating point, and I have read all of them that came up. Still, I am not able to grasp what I am doing wrong.</p> <p>Python3 Cython reference interpreter on 64-bit x86 machine stores floats as double precision, 8 bytes, that is 64 bits</p> <p>CPython implements float usin...
<python><floating-point>
2023-03-13 09:45:28
2
6,310
Alex Punnen
75,720,122
3,878,398
What is the correct way to pass a csv file using requests in python?
<p>If I wanted to push a csv file to an endpoint in Python, what is the correct way to do this?</p> <pre><code>with open(&quot;foo.csv&quot;) as f: endpoint = 'some-url' headers = {} r = requests.post(endpoint, ...., headers = headers) </code></pre> <p>What would be the next steps?</p>
<python><rest><python-requests>
2023-03-13 09:36:10
2
351
OctaveParango
75,719,888
10,617,728
How to fix '/bin/sh: 1: mysql: not found' in cloud function
<p>I have cloud function that restores mysql dump into cloud mysql db. When the function is executed, i get an error</p> <blockquote> <p>/bin/sh: 1: mysql: not found</p> </blockquote> <p>my <code>requirements.txt</code> has</p> <pre><code>google-cloud-storage mysql-client </code></pre> <p>my main.py is as follows</p> <...
<python><mysql><google-cloud-platform><google-cloud-functions>
2023-03-13 09:15:45
0
1,199
Shadow Walker
75,719,852
3,099,733
Does PyInstaller support installing dependent packages via pip on first use?
<p>I am trying to use PyInstaller to distribute a Python app building with pywebview, tensorflow, etc. However, when I create a Python executable with PyInstaller, I find that the package is larger than my expectation. I am not sure if it just packs everything into installer which leads to the large package size.</p> <...
<python><pyinstaller><cx-freeze>
2023-03-13 09:11:00
0
1,959
link89
75,719,826
9,524,065
Installing gluonnlp results in an ImportError undefined symbol _PyGen_Send
<p>I hope this is not an incredibly dumb issue, but googling did not produce any useable results. I installed <code>gluonnlp 0.10.0</code> using <code>pip</code> on a Ubuntu 22.04.1 LTS server under Python 3.10.6. When I try to import gluon, I get the following error:</p> <pre><code>Traceback (most recent call last): ...
<python><pip><cython><gluon><mxnet>
2023-03-13 09:07:32
1
1,810
Max Teflon
75,719,802
12,967,353
Test code and branch coverage simultanously with Pytest
<p>I am using pytest to test my Python code.</p> <p>To test for code coverage (C0 coverage) I run <code>pytest --cov</code> and I can specify my desired coverage in my <code>pyproject.toml</code> file like this:</p> <pre><code>[tool.coverage.report] fail_under = 95 </code></pre> <p>I get this result with a coverage a 9...
<python><testing><pytest><coverage.py>
2023-03-13 09:04:40
1
809
Kins
75,719,800
9,399,492
Importing local module from an embedded installation of Python
<p>I'm trying to make a little program that sets up a portable python 3 with specific packages, with no admin rights required.</p> <p>(The point of this is to execute some specific scripts with more ease and in a way that could be distributed to other people easily)</p> <p>So I have downloaded the latest <a href="https...
<python><python-3.x><module><python-embedding>
2023-03-13 09:04:37
0
1,344
RedStoneMatt
75,719,726
18,221,164
Python Invoke module fails
<p>I am trying to understand how the <code>invoke</code> module works in Python. I have installed the package using the <code>pip install</code> and I am trying to invoke a script in the following manner.</p> <p>I create a <code>tasks.py</code> as <code>invoke</code> is on the search for it, and created a small task as...
<python><python-3.x><invoke>
2023-03-13 08:57:02
1
511
RCB
75,719,665
320,437
In Python issubclass() unexpectedly complains about "Protocols with non-method members"
<p>I have tried the obvious way to check my protocol:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, Protocol, runtime_checkable @runtime_checkable class SupportsComparison(Protocol): def __eq__(self, other: Any) -&gt; bool: ... issubclass(int, SupportsComparison) </code></pre...
<python><python-3.x><protocols><python-typing>
2023-03-13 08:50:50
1
1,573
pabouk - Ukraine stay strong
75,719,399
5,387,794
Kafka consumer error: failed to deserialize - the unknown protocol id
<p>I am running Kafka locally, and sending a &quot;hello, world!&quot; message using the kafka-console-producer.sh using the following command:</p> <pre><code>kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092 &gt; hello, world! </code></pre> <p>I have a Kafka consumer running using t...
<python><apache-kafka>
2023-03-13 08:17:37
1
5,429
kovac
75,719,357
2,348,684
Docker conda multistage image, error with conda-pack
<p>I am trying to create a multistage docker image for a python conda project using conda-pack with the following Dockerfile on MacOS:</p> <pre><code>### build stage FROM continuumio/miniconda3 AS build COPY environment.yaml . # Create the conda environment and install conda-pack RUN conda env create -f environment.ya...
<python><docker><pip><conda><conda-pack>
2023-03-13 08:11:32
1
371
user2348684
75,719,141
9,124,096
Why python request works, but not the when make the same request in curl it does not
<p>I am trying to make a request from a saved session of my LinkedIn account to send a message however when I use the &quot;curl&quot; request, it does not work. Yet, when I use the python requests version it works right away. I am unsure of what is wrong with my &quot;curl&quot; request.</p> <h3>Python Code:</h3> <pre...
<python><http><curl>
2023-03-13 07:44:03
0
1,451
foragerDev
75,719,072
3,336,412
Dynamically set sql-default value with table-name in SQLModel
<p>I'm trying to create a base-class in SQLModel which looks like this:</p> <pre class="lang-py prettyprint-override"><code>class BaseModel(SQLModel): @declared_attr def __tablename__(cls) -&gt; str: return cls.__name__ guid: Optional[UUID] = Field(default=None, primary_key=True) class SequencedBa...
<python><sqlalchemy><alembic><sqlmodel>
2023-03-13 07:35:01
1
5,974
Matthias Burger
75,718,285
12,724,372
Pandas : join 2 tables and compare the fields having the same name except for suffix
<p>I have joined 2 tables having same fields on a key and using a suffix int and prod for each.</p> <p>`int</p> <pre><code>id measure1 measure2 123 45 23 134 09 12 </code></pre> <p>prod</p> <pre><code>id measure1 measure2 123 16 45 134 65 01` </code></pre> <pre><code>df=prod.merge(int,on='id',...
<python><pandas><dataframe>
2023-03-13 05:24:03
1
1,275
Devarshi Goswami
75,718,202
1,114,872
typechecking for compose funcion in python does not seem to work
<p>I am trying to annotate the type of a 'compose' function, and I can't get mypy to tell me I am wrong.</p> <p>In the code below, the definitions of first and eval work as expected, changing the return type to (say) int gives me an error.</p> <p>However, the definition for compose does not. I can change the return val...
<python><mypy>
2023-03-13 05:06:00
1
1,512
josinalvo
75,718,164
4,508,962
Python : cannot call static method on run-time retrieved type
<p>I have a base class:</p> <pre><code>class MyBaseClass: @abstractmethod def from_list(list_float: List[float]) -&gt; Self: pass @staticmethod @abstractmethod def fn() -&gt; int: pass </code></pre> <p>All children of that class implement <code>from_list</code> and static <code>fn<...
<python><reflection><static>
2023-03-13 04:57:09
1
1,207
Jerem Lachkar
75,718,114
11,922,765
Python Identify US holidays in a timeseries dataframe
<p>I have a dataframe with years of data. I want to detect, assign True/False or 1/0 if it is a Holiday.</p> <p>My code:</p> <pre><code>df = pd.DataFrame(index=['2004-10-01', '2004-10-02', '2004-10-03', '2004-10-04', '2004-10-05', '2004-10-06', '2004-10-07', '2004-10-08', '2004-10-09', '2004-10-10', '2018...
<python><pandas><dataframe><numpy><python-holidays>
2023-03-13 04:44:38
2
4,702
Mainland
75,717,900
188,331
FastText Unsupervised Training only detects small number of Chinese words
<p>I'm using FastText to unsupervised train the model (the <code>data.train</code> file is a text file that contains 50,000 lines/1.7 million Chinese characters):</p> <pre><code>import fasttext model = fasttext.train_unsupervised(input='data.train', model='cbow', dim=300, epoch=10, neg=10, minn=2, minCount=20) model.sa...
<python><fasttext>
2023-03-13 03:46:45
0
54,395
Raptor
75,717,821
940,158
Debugging python running unreasonably slow when adding numbers
<p>I'm working on an NLP and I got bitten by an unreasonably slow behaviour in Python while operating with small amounts of numbers.</p> <p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>import random, time from functools import reduce def trainPerceptron(perceptron, data): learningRa...
<javascript><python><performance><nlp>
2023-03-13 03:25:44
0
15,217
alexandernst
75,717,777
5,405,813
Running yolov8 pre-trained model on a free GPU on a CPU for detection for a single class
<p>As a newbie trying object detection for a single class i will be using a free GPU. Can the yolov8 trained model on a free GPU to detect a single class after i have downloaded it on a CPU?</p>
<python><yolo>
2023-03-13 03:12:16
1
455
bipin_s
75,717,593
12,144,502
Reading Sudokus from text file and applying backtracking
<p>I have just begun with python, so excuse me if these are noob questions or if the questions are already answered. I am trying to read multiple sudoku puzzles and apply the algorithm I found online. The code utilizes a grid(<code>list[list[int]]</code>) setup. I have tried looking for a solution online, but all I fou...
<python><json><algorithm><artificial-intelligence>
2023-03-13 02:25:08
2
400
zellez11
75,717,408
11,922,765
Python Dataframe isocalendar() Boolean condition not producing desired result when ISO year is different from Gregorian year
<p>I am surprised that my simple boolean condition was producing a complete year result when I wanted only the first week's data of that year only.</p> <p>My code:</p> <pre><code># Some sample data df1 = pd.DataFrame([1596., 1537., 1482., 1960., 1879., 1824.],index=['2007-01-01 00:00:00', '2007-01-01 01:00:00', ...
<python><pandas><dataframe><matplotlib>
2023-03-13 01:33:41
3
4,702
Mainland
75,717,293
6,676,101
What is a pythonic way to create a factory method?
<p>I have a class, and I would prefer that people call a factory method in order to create instance of the class instead of instantiating the class directly.</p> <p>One of a few different reasons to use a factory method is so that we can use <code>functools.wrap</code> to wrap un-decorated callable.</p> <pre class="lan...
<python><python-3.x><factory><factory-pattern>
2023-03-13 00:56:56
1
4,700
Toothpick Anemone
75,717,172
5,407,050
How to use one_hot on a pytorch_directml tensor on privateuseone device?
<p>Does anyone know how to use Torch_directml one_hot? It seems to fail, while one_hot on 'cpu' device works. See the following snippets:</p> <pre><code>import torch import torch_directml import torch.nn.functional as F a_tensor = torch.tensor([[ 4, 3, 17, 0, 0], [ 1, 0, 13, 13, 0], ...
<python><tensorflow><pytorch>
2023-03-13 00:21:36
1
334
Daniel Lema
75,717,075
2,143,578
wbgapi: resolve country name
<p>I'd like to use the <code>wbgapi</code> to get a list of countries with GDP per capita for 2021, with &quot;normal&quot; country names.</p> <pre><code>import wbgapi as wb gdppercap=wb.data.DataFrame('NY.GDP.PCAP.CD', wb.region.members('WLD')) # how do I pass the coder function to the rename method here, so that it...
<python><function><iterator>
2023-03-12 23:47:06
1
1,593
Zubo
75,717,066
11,922,765
Python dataframe first week with complete 7 days data
<p>I have data frame containing years of data. I want to plot the first week's data that has all seven days.</p> <p>My code:</p> <pre><code># Extract first week data from the dataframe first_week_index=df1.loc[(df1.index.isocalendar().week==1)].index DatetimeIndex(['2005-01-03 00:00:00', '2005-01-03 01:00:00', ...
<python><pandas><dataframe><numpy><datetime>
2023-03-12 23:43:07
2
4,702
Mainland
75,717,005
2,112,406
neovim cannot autocomplete numpy (omni completion not found)
<p>I'm trying to get autocomplete to work, but it doesn't work with numpy. I have a script with numpy imported:</p> <pre><code>import numpy as np </code></pre> <p>and I'm typing <code>np.</code>, and nothing shows up. Instead I get an error that says <code>Omni completion (^O^N^P) Pattern not found</code>. It does work...
<python><numpy><autocomplete><neovim>
2023-03-12 23:26:06
1
3,203
sodiumnitrate
75,716,950
14,729,820
How to install specific python version required by TensorFlow?
<p>I have the following <strong>operating system</strong> :</p> <pre><code>NAME=&quot;Ubuntu&quot; VERSION=&quot;20.04.5 LTS (Focal Fossa)&quot; ID=ubuntu ID_LIKE=debian PRETTY_NAME=&quot;Ubuntu 20.04.5 LTS&quot; VERSION_ID=&quot;20.04&quot; HOME_URL=&quot;https://www.ubuntu.com/&quot; SUPPORT_URL=&quot;https://help.ub...
<python><tensorflow><installation><command-line><operating-system>
2023-03-12 23:16:05
1
366
Mohammed
75,716,873
16,665,831
Pandas API on spark runs too slow according to pandas
<p>I am making transform on my dataframe. while the process takes just 3 seconds with pandas, when I use pyspark and Pandas API on spark it takes approximately 30 minutes, yes 30 minutes! my data is 10k rows. The following is my pandas approach;</p> <pre><code>def find_difference_between_two_datetime(time1, time2): ...
<python><pandas><pyspark><pyspark-pandas>
2023-03-12 22:55:53
1
309
Ugur Selim Ozen
75,716,861
7,259,176
How can I generate example versions that match a PEP 440 Version specifier in Python?
<p>I have a PEP 440 Version specifier, such as <code>&quot;&gt;=1.0,&lt;2.0&quot;</code>, that defines a range of valid versions for a Python package. I would like to generate a list of example versions that match this specifier.</p> <p>For example, if the specifier is <code>&quot;&gt;=1.0,&lt;2.0&quot;</code>, some va...
<python><regex><version><packaging><pep>
2023-03-12 22:54:09
1
2,182
upe
75,716,668
3,943,868
How to sort list of strings based on alphabetical order?
<p>For example, I have a list of strings:</p> <pre><code>How to make pancakes from scratch How to change a tire on a car How to install a new showerhead How to change clothes </code></pre> <p>I want to it be sorted as in the new list:</p> <pre><code>How to change a tire on a car How to change clothes How to install a n...
<python>
2023-03-12 22:09:05
1
7,909
marlon
75,716,634
2,697,954
Automatic1111 > ControlNet API sending 500 server error
<p>I am using Automatic1111 and it is working fine on my local machine and txt2img API is also working fine but when I try to use controlNet it always gives me the server 500 response, any help or guide to where should I look for solution?</p> <pre class="lang-py prettyprint-override"><code>import requests import base6...
<python><stable-diffusion>
2023-03-12 21:59:51
2
4,971
Imran Bughio
75,716,257
5,191,069
Why can I update the .data attribute of a pytorch tensor when the variable is outside the local namespace
<p>I'm able to access and update the .data attribute of a pytorch tensor when the variable is outside a functions namespace:</p> <pre><code>x = torch.zeros(5) def my_function(): x.data += torch.ones(5) my_function() print(x) # tensor([1., 1., 1., 1., 1.]) </code></pre> <p>When I (attempt to) update x in the r...
<python><pytorch>
2023-03-12 20:40:59
2
630
jstm
75,716,145
2,523,581
pivot wider but keep repeating the index
<p>I have a dataframe in pandas of the sort</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ &quot;id&quot;: [1, 1, 1, 1, 2, 2, 2, 2], &quot;column&quot;: [&quot;a&quot;, &quot;b&quot;,&quot;a&quot;, &quot;b&quot;, &quot;a&quot;, &quot;b&quot;, &quot;a&quot;, &quot;b&quot;], &quot;val...
<python><pandas><pivot><pivot-table>
2023-03-12 20:18:05
4
630
Nikola
75,716,069
12,501,684
Why doesn't this way of checking a type work?
<p>I am creating a Python object from its string representation:</p> <pre class="lang-py prettyprint-override"><code>obj = ast.literal_eval(obj_text) </code></pre> <p>Now, I want to make sure that the object has an appropriate type. In this case, I want it to be a list of strings. This can be done, <a href="https://sta...
<python><string><list><types><python-3.10>
2023-03-12 20:06:25
2
5,075
janekb04
75,715,755
2,778,405
.dt accessor fails, but python functions work
<p>For some reason the .dt accessor is having funny results compared to regular datetime functions in pandas. This screen shot is the best example:</p> <p><a href="https://i.sstatic.net/GoUDt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GoUDt.png" alt="enter image description here" /></a></p> <p>As y...
<python><pandas><datetime>
2023-03-12 19:18:16
1
2,386
Jamie Marshall
75,715,657
925,913
Getting tox to use the Python version set by pyenv
<p>I can't seem to wrap my head around managing Python versions. When I run <code>tox</code>, I can immediately see that it's using Python 3.7.9:</p> <pre class="lang-bash prettyprint-override"><code>$ tox py39: commands[0]&gt; coverage run -m pytest =====================================================================...
<python><pytest><virtualenv><pyenv><tox>
2023-03-12 19:01:19
4
30,423
Andrew Cheong
75,715,537
10,093,446
Do you replicate type hints of function within the docstring of the function? PEP Guidelines?
<h1>Background</h1> <p>Propose that there is function:</p> <pre class="lang-py prettyprint-override"><code>def do_product(a: int, b: int) -&gt; int: return a * b </code></pre> <p>And I start documenting my function:</p> <pre class="lang-py prettyprint-override"><code>def do_product(a: int, b: int) -&gt; int: &q...
<python><python-sphinx><python-typing><docstring><pep>
2023-03-12 18:41:10
1
548
Pieter Geelen
75,715,491
19,491,471
pandas merge or join on multiple columns
<p>I am trying to join two tables based on two columns. Let's say we have:</p> <pre><code>df1 = key atTime c d e 1 3 4 a 100 23 8 3 g 230 ... df2 = xkey xatTime z 30 2 p 1 3 l ... </code></pre> <p>Now I want t...
<python><pandas>
2023-03-12 18:35:45
0
327
Amin
75,715,460
17,082,611
NotFittedError (instance is not fitted yet) after invoked cross_validate
<p>This is my minimal reproducible example:</p> <pre><code>import numpy as np from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import cross_validate x = np.array([ [1, 2], [3, 4], [5, 6], [6, 7] ]) y = [1, 0, 0, 1] model = GaussianNB() scores = cross_validate(model, x, y, cv=2, sc...
<python><machine-learning><scikit-learn><cross-validation>
2023-03-12 18:31:29
1
481
tail
75,715,426
2,592,835
pathfinding algorithm bug in python
<p>I have been using python's pathfinding module from pip but its not working it seems to find a path that goes through obstacles (which is unacceptable for my videogame).</p> <p>Here's the sample code:</p> <pre><code>from pathfinding.core.diagonal_movement import DiagonalMovement from pathfinding.core.grid import Grid...
<python>
2023-03-12 18:26:44
0
1,627
willmac
75,715,376
1,595,865
Set the formatting style for logging - percent, format style / bracket or f-string
<p>Python has multiple string formatting styles for arguments:</p> <ul> <li><p>Old-style/percent/<code>%</code>: <code>&quot;The first number is %s&quot; % (1,)</code></p> </li> <li><p>New-style/bracket/<code>{</code>: <code>&quot;The first number is {}&quot;.format(1)</code></p> </li> <li><p>F-string: <code>one = 1; f...
<python><python-logging>
2023-03-12 18:21:35
2
23,522
loopbackbee
75,715,274
1,484,601
python singledispatch with several arguments
<p>for example:</p> <pre class="lang-py prettyprint-override"><code>@singledispatch def f( a: str, ...
<python><functools><single-dispatch>
2023-03-12 18:05:43
0
4,521
Vince
75,714,883
7,256,554
How to test a FastAPI endpoint that uses lifespan function?
<p>Could someone tell me how I can test an endpoint that uses the new <a href="https://fastapi.tiangolo.com/advanced/events/" rel="noreferrer">lifespan</a> feature from FastAPI?</p> <p>I am trying to set up tests for my endpoints that use resources from the lifespan function, but the test failed since the dict I set up...
<python><testing><fastapi>
2023-03-12 17:08:07
3
2,260
lux7
75,714,781
1,857,373
Fit Error OneVsOneClassifier, OneVsRestClassifier Logistic Regression for digits recognition multilabel classifier model fit error
<p><strong>Problem</strong></p> <p>New error on problem:</p> <pre><code>UserWarning: X has feature names, but LogisticRegression was fitted without feature names warnings.warn(UserWarning: X has feature names, but LogisticRegression was fitted without feature names </code></pre> <p>Goal is to use RandomisedSearchCV f...
<python><scikit-learn><logistic-regression><multilabel-classification><gridsearchcv>
2023-03-12 16:54:59
1
449
Data Science Analytics Manager
75,714,718
9,078,185
Keras Sequential: constrain weights based on other weights
<p>I am new to using Tensorflow, and am trying to make a model that essentially dictates how to apportion a budget across some number of options. Hence I need to constrain the weights on each variable not only be positive but also that all of the weights add to the budget (e.g., 100% or similar).</p> <p>I know I can co...
<python><tensorflow><keras>
2023-03-12 16:46:08
0
1,063
Tom
75,714,609
17,158,703
Calculus of two 2D arrays on different dimensions
<p>I have two 2D arrays which I have to subtract, but not on the same dimension, and the arrays have different sizes. If I understood correctly there is something called broadcasting to do what I need and I think this post (<a href="https://stackoverflow.com/questions/72616936/add-arrays-of-different-dimensions">Link</...
<python><numpy><numpy-ndarray>
2023-03-12 16:31:13
1
823
Dattel Klauber
75,714,478
648,045
Splitting text based on a delimiter in Python
<p>I have just started learning python. I am working on netflix_tiles dataset downloaded from Kaggle. Some of the entries in the director column have multiple director names separated by column, i was trying to separate director names using the split function</p> <p>The following is one of the original values loaded f...
<python><pandas>
2023-03-12 16:10:52
2
4,953
logeeks
75,714,426
19,130,803
on/off the logging based on flag python
<p>I have implemented the logging using python standard module(I refered python offical docs). I have created a separate logger.py file and return logger from this. In different modules I have imported and used for logging purpose.</p> <p>Now I want to have a functionality that will enable/disable or on/off the logging...
<python>
2023-03-12 16:04:20
1
962
winter
75,714,415
10,407,102
Displaying images blobs on Django html templates using SaS token
<p>I'm currently trying to get blob images displayed in the HTML of Django templates using the SaS token but I don't see any online implementation examples. I currently have the SaS token but don't know how to implement it in Django.</p> <p>I tried to manually add the token to the end of the URL:</p> <p>https://{accoun...
<python><django><azure-storage>
2023-03-12 16:02:50
1
799
Karam Qusai
75,714,362
1,797,139
PyCharm /. VSCode - how to use global python installation
<p>Recently did a clean install of Linux Mint on an old laptop.</p> <p>Tried writing a python script to use pyaudio. From inside PyCharm, I tried the usual method to add pyaudio using the project preferences screen, but that just kept &quot;loading&quot;. When I tried to install it via pip inside a terminal in PyCharm,...
<python><pycharm>
2023-03-12 15:55:17
1
1,341
Monty
75,714,294
333,403
dynamically determine height of widget in python-textual
<p>I develop a simple app using <a href="https://textual.textualize.io/" rel="nofollow noreferrer">Textual</a> framework. I have two widgets W1 and W2. W1 has a fixed height of <code>20</code> (lines). Now I want W2 to take up the rest of the vertical space. In css for a browser I would use <code>calc(100vh - 20)</code...
<python><css><textual-framework>
2023-03-12 15:44:32
1
2,602
cknoll
75,714,164
2,998,077
How to show only the first and last tick labels on the x-axis with subplots
<p>To show only the first and last tick on x-axis, of both a line chart and bar chart side-by-side, produced by matplotlib and pandas.GroupBy, I have below lines.</p> <p>However only the bar chart shows what's wanted. The line chart has the latest month on the left upmost (it shall be on the right upmost), and missing ...
<python><pandas><matplotlib>
2023-03-12 15:20:59
1
9,496
Mark K
75,714,139
8,176,763
csv.DictReader to skip first two rows of data
<p>I have a buffer that looks like that:</p> <pre><code>some_random_info another info here that i dont want to parser column1,column2,column3 a,b,c </code></pre> <p>I want to read this that using python csv built-in module using the <code>DictReader</code> class, but from the docs it says:</p> <pre><code> class csv....
<python>
2023-03-12 15:17:40
1
2,459
moth
75,714,112
236,081
How do I configure pdm for a src-based Python repository?
<p>I have previously arranged a Python repository without a <code>src</code> folder, and got it running with:</p> <pre><code>pdm install --dev pdm run mymodule </code></pre> <p>I am failing to replicate the process in a repository <em>with</em> a <code>src</code> folder. How do I do it?</p> <p><strong>pyproject.toml</s...
<python><pyproject.toml><python-pdm>
2023-03-12 15:14:01
1
17,402
lofidevops
75,713,995
4,186,989
Find all yaml keys matching string and change their values using python
<p>I've been trying to...</p> <ol> <li>load yaml file</li> <li>find all keys named &quot;top&quot; in a yaml file</li> <li>get the values one by one, which is a percentage</li> <li>add 5 to the percentage number</li> <li>save the file</li> </ol> <p>So far I've written the following python:</p> <pre><code>import sys fro...
<python><yaml><ruamel.yaml>
2023-03-12 14:53:52
1
425
danededane
75,713,993
17,973,259
Python pylint "warning error uncreachable code"
<p>I have this method in my game and I'm getting the &quot;<em>Unreachable code</em>&quot; warning from <em>pylint</em>.</p> <pre><code>def _check_buttons(self, mouse_pos): &quot;&quot;&quot;Check for buttons being clicked and act accordingly.&quot;&quot;&quot; buttons = { self.play_button.rect.collidepoint...
<python><pylint>
2023-03-12 14:53:18
1
878
Alex
75,713,961
13,802,418
Python requests returns 403 even with headers
<p>I'm trying to get content of website but my requests return me an 403 ERROR.</p> <p>After searching, I found Network&gt;Headers section to add headers before GET request and tried these headers.</p> <pre><code>from bs4 import BeautifulSoup as bs import requests url = &quot;https://clutch.co/us/agencies/digital-marke...
<python><python-requests>
2023-03-12 14:47:47
1
505
320V
75,713,948
2,280,178
How can I use a mermaid Flowchart LR for describing a Pyhton code line?
<p>I want to describe a python code line in a quarto document for further description with a mermaid flowchart LR diagram.</p> <p>It should look like this:</p> <p><a href="https://i.sstatic.net/qzDx4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qzDx4.png" alt="enter image description here" /></a></p> ...
<python><diagram><mermaid>
2023-03-12 14:46:20
1
517
SebastianS
75,713,913
11,703,015
Group a DataFrame by months and an additional column
<p>I have the next DataFrame:</p> <pre><code>data={ 'date':['02/01/2023', '03/01/2023', '12/01/2023', '16/01/2023', '23/01/2023', '03/02/2023', '14/02/2023', '17/02/2023', '17/02/2023', '20/02/2023'], 'amount':[-2.6, -230.0, -9.32, -13.99, -12.99, -50.0, -5.84, -6.6, -11.95, -20.4], 'concept':['FOOD', 'REPAIR', 'HEALT...
<python><pandas><dataframe><group-by>
2023-03-12 14:41:15
1
516
nekovolta
75,713,821
295,155
Minimize ||Ax|| on the non negative region of the unit sphere: ||x|| = 1, x ≥ 0
<p>Having a non-square matrix A, I need to find the direction (versor) x ≥ 0 which is &quot;most perpendicular&quot; to all rows of A (in a least sum of squares sense).</p> <p>I tried with SVD: if A = U Σ V*, the &quot;most perpendicular&quot; vector is the last column in V. But it is not guaranteed to be ≥ 0, so I nee...
<python><linear-algebra><linear-programming><scipy-optimize><svd>
2023-03-12 14:30:35
0
919
Amenhotep
75,713,804
9,003,381
On Plotly Python, my widgets don't work : the graphs don't remove when I uncheck the box
<p>I tried to use widgets by simply displaying a graph depending on checkboxes.</p> <p>It shows the number of births along the years, for 2 cities (Grenoble and Vizille).</p> <p>I want to display the evolution lines for 0, 1 or 2 cities depending on checkboxes.</p> <p>At the beginning it's ok : it displays 0 lines, and...
<python><plotly><ipywidgets>
2023-03-12 14:27:57
2
319
Elise1369
75,713,782
9,795,265
Unable to Run container ( Path error for executable )
<p><strong>DockerFile</strong></p> <pre><code>FROM python:3.12.0a6-bullseye RUN mkdir /app WORKDIR /app COPY . . RUN apt-get update &amp;&amp; apt-get upgrade -y RUN apt-get -y autoremove RUN apt install python3 -y \ &amp;&amp; apt install python3-pip -y \ &amp;&amp; apt install python3-venv -y ENV PYTH...
<python><docker><docker-compose><dockerfile><virtualenv>
2023-03-12 14:24:29
0
1,194
Atif Shafi
75,713,598
11,546,773
Numpy array to list of lists in polars dataframe
<p>I'm trying to save a dataframe with a 2D list in each cell to a parquet file. As example I created a polars dataframe with a 2D list. As can be seen in the table the dtype of both columns is <code>list[list[i64]]</code>.</p> <pre><code>┌─────────────────────┬─────────────────────┐ │ a ┆ b ...
<python><dataframe><numpy><parquet><python-polars>
2023-03-12 13:55:08
1
388
Sam
75,713,427
13,132,728
How to merge rows that have multiple levels for specific columns in pandas
<h2>My data</h2> <p>I am working with the following data from the <a href="https://www.ncei.noaa.gov/" rel="nofollow noreferrer">National Centers for Environmental Information (NCEI)</a> - obtained simply by using pandas' <code>read_html()</code>.</p> <pre><code>df = pd.read_html('https://www.ncei.noaa.gov/access/monit...
<python><pandas><data-cleaning><data-wrangling>
2023-03-12 13:26:47
1
1,645
bismo
75,713,161
1,739,325
Finetuning Vision Encoder Decoder Models with huggingface causes ValueError: expected sequence of length 11 at dim 2 (got 12)
<p>Input code that causes code failing:</p> <pre><code>from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer, ViTFeatureExtractor, AutoTokenizer from transformers import ViTImageProcessor, BertTokenizer, VisionEncoderDecoderModel, default_data_collator from datasets import load_datase...
<python><huggingface-transformers>
2023-03-12 12:37:08
1
5,851
Rocketq
75,713,078
7,483,509
sounddevice.PortAudioError: Error querying host API -9979
<p>I am trying to do python audio with <code>python-sounddevice</code> on a macOS 13.2.1 with M1 chip but I can't get it to work. I installed portaudio and libsndfile with brew, then created a conda environment with sounddevice and soundfile packages then ran:</p> <pre class="lang-bash prettyprint-override"><code>❯ pyt...
<python><portaudio><apple-silicon><python-sounddevice><soundfile>
2023-03-12 12:24:30
1
1,109
Nick Skywalker
75,713,049
18,749,472
Stop Django cache clearing on server refresh
<p>In my Django project I want to stop the cache from clearing whenever the server is restarted. Such as when I edit my views.py file, the cache is cleared and I get logged out which makes editing any features exclusive to logged in users a pain.</p> <p><em>settings.py</em></p> <pre><code>SESSION_ENGINE = &quot;django....
<python><django><session><caching><django-settings>
2023-03-12 12:19:13
3
639
logan_9997
75,713,039
13,194,245
Python script runs fine locally but get a JSONDecodeError when running in Github Actions
<p>I have the following code:</p> <pre><code>import requests import boto3 import os # Fetch data from API response = requests.get('https://api.example.com') data = response.json() # Upload data to S3 bucket s3_client = boto3.client('s3',aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=os.e...
<python><python-requests><github-actions>
2023-03-12 12:16:14
0
1,812
SOK
75,712,871
39,242
How do I batch a request to Compute Engine using the Python Google Cloud Client Libraries?
<p>In the older Google API Client Libraries, you could batch a request to label many instances at once, using <code>googleapiclient</code>, <code>discovery.build(&quot;compute&quot;, &quot;v1&quot;).new_batch_http_request(...)</code></p> <p>With the new, <a href="https://github.com/googleapis/google-api-python-client#o...
<python><google-cloud-platform><google-compute-engine><google-client>
2023-03-12 11:41:21
1
19,885
Joshua Fox
75,712,777
10,967,961
Forming a symmetric matrix counting instances of being in same cluster
<p>I have a database that comprises cities divided into clusters for each year. In other words, I applied a community detection algorithm for different databases containing cities in different years base on modularity. The final database (a mock example) looks like this:</p> <pre><code>v1 city cluster year 0 &quot;city...
<python><r><matrix><cluster-analysis>
2023-03-12 11:25:07
2
653
Lusian
75,712,609
7,848,740
Get value of clipboard from a Selenium Grid via Python
<p>I'm using Selenium for Python to connect to my Grid and command a browser. No, I'm trying to get the data of the clipboard of my Browser of the grid and copy them into my Python code.</p> <p>I've tried to use <code>from tkinter import Tk</code> and <code>clipboard = Tk().clipboard_get()</code> but it clearly copy th...
<python><selenium-webdriver><selenium-grid>
2023-03-12 10:52:01
1
1,679
NicoCaldo
75,712,595
19,257,035
How to add concurrency to my asyncio based file downloader script without hitting server
<p>Below is my code to download file as fast as possible using asycio Trying to implement, multiple server connection with multi chunk, multi threded downlad just like idm and aria2</p> <pre><code>import asyncio import os.path import shutil import aiofiles import aiohttp import lxml.html as htmlparser import cssselect...
<python><python-asyncio>
2023-03-12 10:49:34
2
367
Tathastu Pandya
75,712,503
7,624,179
Workaround to using pip in virtual python 2.7 32-bit environemnt
<p>I am currently using Anaconda to setup a virtual environment of python 2.7.1 32-Bit. My project require several packages to be downloaded. However, when I try</p> <pre><code>&gt;pip install numpy </code></pre> <p>It gives me the following error.</p> <pre><code>DEPRECATION: Python 2.7 reached the end of its life on J...
<python><python-2.7><pip><conda><32bit-64bit>
2023-03-12 10:29:12
0
859
Kenta Nomoto
75,712,497
1,036,903
PyPDF2:Creating EncodedStreamObject is not currently supported
<p>The following code tries to edit part of text in a PDF file:</p> <pre><code>from PyPDF2 import PdfReader, PdfWriter replacements = [(&quot;Failed&quot;, &quot;Passed&quot;)] pdf = PdfReader(open(&quot;2.pdf&quot;, &quot;rb&quot;)) writer = PdfWriter() for page in pdf.pages: contents = page.get_contents().get_...
<python><pdf><pdf-generation><wkhtmltopdf><pypdf>
2023-03-12 10:27:57
1
396
Vinod
75,712,458
2,355,176
Disable postgres index updation temporarily and update the indexes manually later for insert statement performance
<p>i have about 1300 CSV files with almost 40k of rows in each file, i have written a python code to read the file and convert all the 40k entries into single insert statement to insert in Postgres database.</p> <p>The psudocode is following</p> <pre><code>for file in tqdm(files, desc=&quot;Processing files&quot;): ...
<python><python-3.x><postgresql><csv>
2023-03-12 10:19:36
3
2,760
Zain Ul Abidin
75,712,275
20,589,631
Is there a way to compare a value against multiple possibilities without repetitive if statements?
<p>I have a function with an input that can be of multiple possibilities, and each one triggers a different function.</p> <p>The example code here works, but it's very bad and I don't want to use this sort of code:</p> <pre><code>def start(press_type): if press_type == &quot;keyboard&quot;: function1() ...
<python><if-statement>
2023-03-12 09:45:13
3
391
ori raisfeld
75,712,094
12,298,276
How to make UNIX-Python-executable work in VS Code via "select interpreter" on a Windows machine?
<p>I was forced to use <a href="https://learn.microsoft.com/en-us/windows/wsl/install" rel="nofollow noreferrer">WSL on Windows 10</a> to install the Python library <a href="https://pypi.org/project/Cartopy/" rel="nofollow noreferrer">Cartopy</a> on my Windows machine correctly. It is way easier in a Linux-distribution...
<python><visual-studio-code><windows-subsystem-for-linux><pythoninterpreter>
2023-03-12 09:10:45
1
4,731
Andreas L.
75,712,057
15,724,084
python extracting values from lists inside a list
<p>With Selenium Webdriver I search for input value in google search. Then take links one by one, run them and take emails from each URL.</p> <p><code>[[], [], [], [], ['info@neurotechnology.com', 'support@neurotechnology.com', 'support@neurotechnology.com'], ['info@neurotechnology.com', 'support@neurotechnology.com', ...
<python><list><selenium-webdriver>
2023-03-12 09:05:09
1
741
xlmaster
75,712,029
12,863,331
Capturing any character between two specified words including new lines
<p>I need to capture the title between the words TITLE and JOURNAL and to exclude a scenario in which the captured string is <code>Direct Submission</code>.<br /> for instance, in the the following text,</p> <pre><code> TITLE The Identification of Novel Diagnostic Marker Genes for the Detection of Beer...
<python><regex>
2023-03-12 08:58:12
1
304
random
75,711,922
4,865,723
Dataclasses and slots causing ValueError: 'b' in __slots__ conflicts with class variable
<p>I don't understand the error message and also couldn't find other SO questions and answers helping me to understand this. The MWE is tested with Python 3.9.2. I'm aware that there is a <code>slots=True</code> parameter in Pythons 3.10 dataclasses. But this isn't an option here.</p> <p>The error output:</p> <pre><cod...
<python><python-3.9><python-dataclasses><slots>
2023-03-12 08:34:35
2
12,450
buhtz
75,711,859
859,141
Django Group By Aggregation works until additional fields added
<p>I'd like to group the following track variations at the given circuit so on an index page I only have a single entry for each circuit. On a subsequent circuit detail page I will show the various configurations.</p> <p><a href="https://i.sstatic.net/sm72E.png" rel="nofollow noreferrer"><img src="https://i.sstatic.ne...
<python><django><django-models><django-queryset><django-orm>
2023-03-12 08:21:33
2
1,184
Byte Insight
75,711,757
5,870,471
FastAPI GET endpoint returns "405 method not allowed" response
<p>A <code>GET</code> endpoint in FastAPI is returning correct result, but returns <code>405 method not allowed</code> when <code>curl -I</code> is used. This is happening with all the <code>GET</code> endpoints. As a result, the application is working, but health check on application from a load balancer is failing.</...
<python><rest><fastapi><http-status-code-405>
2023-03-12 07:55:38
2
548
toing